Discover
sfd discover: which local transcripts are read, how each shell call is
classified, how the savings estimates and loop-fit ranking are derived, the text
and --json output, and the diagnostics. Source: src/discover/index.mjs
(discoverOptions, classify, observe, discover, formatReport),
src/discover/loop-fit.mjs (manifest catalog, matchCommandId, rankLoopFit,
formatLoopFit), src/discover/shared.mjs (file selection, streaming lines,
timestamp filter, output sizing, medianOfSorted),
src/discover/claude.mjs, src/discover/codex.mjs and
src/discover/gemini.mjs (readers), src/discover/worker.mjs (one worker thread
per agent), the discover adapter in src/cli/discover.mjs (its runEarly
handles the command before the shared parser), DISCOVER_ARGS in
src/cli/constants.mjs, lex and rewrite
in src/rewrite.mjs, and split in src/shell.mjs (segment boundaries), pluginRoots in
src/plugin/discover.mjs (plugin manifest roots), loadTable in
src/plugin/table-cache.mjs (its read-only mode) and runtimeDirPath in
src/paths.mjs (the measurements.json location).
Tests: test/discover.test.mjs, with fixtures in test/fixtures/discover/.
test/snippet.test.mjs also excludes the discover line when it checks that help output is unchanged.
sfd discoversfd discover --since 12h --agent claude --agent codex --project /path/to/projectsfd discover --allsfd discover --jsonsfd discover never starts or contacts the daemon, needs no org or auth, makes
no network calls and writes nothing. It does not run the commands it finds.
Flags
| Flag | Meaning |
|---|---|
--since <n>d|<n>h |
Window. Default 30d. Any other value is a usage error (exit 2). |
--agent claude|codex|gemini |
Repeatable. Default: all three. Duplicates are ignored. Any other name is a usage error. |
--project <path> |
Keep only records whose working directory is this path or below it. Relative paths resolve from the current directory. |
--top <n> |
Limit each ranked adoption list in text output. Positive safe integer, default 10. |
--all |
Show every loop-fit row in text output. The default is 15 rows. |
--json |
Print the full report object instead of the text summary. |
-h, --help |
Print the usage line. |
Positional arguments are a usage error.
Stores and readers
Each reader is an async generator that yields records shaped as
{ agent, ts, command, cwd, session, durationMs?, outputChars? }. session is
the transcript file path. Missing stores are treated as empty.
| Agent | Store | Shell calls read | Duration | Output size |
|---|---|---|---|---|
| Claude Code | ~/.claude/projects/**/*.jsonl |
tool_use with name: "Bash" and a string input.command |
Result line timestamp minus call line timestamp, paired by id and tool_use_id |
tool_result.content length; a non-string value is measured as its JSON text |
| Codex CLI | ~/.codex/sessions/**/*.jsonl |
response_item function_call named shell, shell_command or exec_command, with JSON arguments |
Output line timestamp minus call line timestamp, paired by call_id |
function_call_output.output length |
| Gemini CLI | ~/.gemini/tmp/**/chats/*.jsonl, ~/.gemini/tmp/**/chats/*.json and ~/.gemini/tmp/**/logs.json |
messages[].toolCalls[] named run_shell_command with args.command |
toolCalls[].timestamp (stamped when the call’s batch completes) minus the message timestamp (recorded when the model’s response ends), only when the message has a single tool call and the difference is positive. Includes approval wait |
toolCalls[].result length |
- Claude: A call with no matching result is still yielded, without a
duration or output size. Only calls that mention
sf,sfdorsfdxare tracked. - Codex:
commandorcmdis accepted. An argv array is joined into one quoted string, except thatbash/shwith-lc/-cand exactly three elements is unwrapped to its script. The working directory isarguments.workdir, or the lastcwdseen in asession_metaorturn_contextline. Custom tools, including JavaScriptexectools, are ignored, sosfcalls made through them are not counted. - Gemini: Current sessions are JSONL: a metadata line, message records
keyed by
id,$setmetadata patches and$rewindTomarkers. A message re-appended under the sameid(for example once a tool call has its result) replaces the earlier copy, and messages listed in$set.messagesare merged byid. Rewinds and$set.messagesreplacements do not drop earlier messages, because their shell calls still ran. Older.jsonsessions are read whole and may be a bare array or an object withmessages. The timestamp istoolCalls[].timestamp, falling back to the message timestamp. The working directory isargs.directory, then the messagecwd, then the sessioncwd(from the JSON document, or the JSONL metadata and$setlines). Gemini’s formats vary, so only the shapes above are supported. Alogs.jsonwith only user messages has no shell calls.
Selection and time filter
- Store files are found recursively. Files with a modification time older than
--sinceare skipped without being opened. - JSONL is streamed line by line, so large files are never held whole. Each record’s timestamp must be at or after the window start. A record with a missing or unparseable timestamp is dropped and counted as malformed.
--projectrequires a stringcwd. Records without one are excluded when the filter is set.
Agents are read in parallel, one worker thread each. The worker classifies every record and returns only aggregate-ready observations to the main thread.
Classification
Each shell tool call is classified once, from its command string:
- Words before the command are skipped: leading
VAR=valueassignments, andenv,rtk,proxyandcommand. Splitting happens at&&,||,;,|, newline and&. - A call’s subcommand is its longest recognized command path. The allowlist in
src/discover/index.mjscovers sf commands and common legacy paths; sfd paths come fromCOMMANDS. Trailing positional values are omitted. Unknown paths use(unrecognized subcommand); a call with no path uses(no subcommand). - The invocation is the first
sforsfdxin the command. If there is none, it is the firstsfd. A compound call is therefore counted once, by its firstsf/sfdx. Its later segments are not counted separately.
Then each call falls into one class:
| Class | Rule |
|---|---|
adopted |
The invocation is sfd. |
legacy |
The invocation is sfdx force:*. Other sfdx calls follow the rewrite engine and are skipped as unsupported invocations. |
rewritable |
rewrite(command) on the whole original command returns a command. The hook would rewrite it. |
unsupported |
rewrite skips with unsupported sf command. |
skipped |
rewrite skips with any other reason. Calls are grouped by that reason, with command values removed and flag names retained. |
Because the classifier is rewrite(), changing a mapping or skip rule in
src/rewrite.mjs changes the counts. docs/agent-hooks.md covers the rewrite
rules.
Loop fit
Loop fit ranks unported sf commands in the selected transcripts. It counts
each sf invocation the shell parser recognizes, including multiple invocations
in a compound call. It finds the longest command prefix before the first flag
that matches an installed oclif.manifest.json command ID or alias. Both
space-separated and colon-separated forms resolve to the canonical colon-separated
ID. Calls without a manifest match and calls to sfdx or sfd are outside
the ranking.
Discover reads manifests from the installed sf CLI and its core plugins,
the sf data directory’s installed and linked plugins, and roots in
SFD_PLUGIN_PATHS. SFD_PLUGIN_PATHS_ONLY=1 skips sf data directory discovery.
The ranking excludes IDs covered by built-in rewrite mappings or by commands
in the merged sfd plugin table. It matches plugin commands by their sf path
when present and their direct command name otherwise. Coverage applies even
when the hook would skip a call because of its flags or shell syntax. Discover
can rebuild a missing or stale table in memory. A row’s plugin indicator says
whether the sf command’s provider has an sfd key in its package.json.
Only sessions using the command contribute to its repeat counts, and a
single call counts as one repeat. Median averages the middle two values
for an even number of sessions. P90 is the count at rank
ceil(0.9 × sessions) after sorting counts from lowest to highest.
The per-command startup estimate defaults to 3 seconds. To provide measured
values, store a JSON object in measurements.json in the sfd runtime directory,
with canonical command IDs as keys and finite nonnegative startup seconds as
values. For example, {"project:deploy:report": 2.4} sets one estimate.
Missing or invalid measurements use the default. Estimated total startup cost
is calls × startup seconds. The ranking score is median repeats per session
× sessions × startup seconds. Ties sort by command ID.
Estimates
- Time saved: the sum over rewritable calls with a duration of
max(0, duration - 300 ms). The 300 ms is the assumed cost of an sfd call. Durations include permission wait, so this is an upper-bound estimate. - Output tokens: the sum of output characters over rewritable calls with an output size, divided by four. This is potential savings before sfd’s own output, which is not measured.
- Unknowns: a missing duration or output size stays unknown and is never
extrapolated. The text output says
time unknownoroutput unknownwhen a total has no samples. It also prints the sample count when it has one. - Medians: each group in
commandsreports a median duration and median output size from its own samples. Output tokens are the median characters divided by four. Groups that are not rewritable have medians but do not feed the totals.
Output
Text
sfd discover: <window>, <agents> agents, <sf calls> sf/sfdx calls in <sessions> sessions rewritable now <n> (~<min> min saved (<samples> samples); ~<tokens> output tokens (<samples> samples)) skipped <n> <reason> <count> · … not in sfd <n> <subcommand> <count> · … (legacy <n>) already sfd <n>Top rewritable: <subcommand> <count> · …Scan: <malformed> malformed, <ignored> ignored entries, <unreadable> unreadable files.Durations include permission wait; savings assume 0.3 s/call. Tokens are chars/4.Output tokens are potential savings before sfd output, which is not measured. Missing samples are not extrapolated.Adoption counts each shell tool call once, using the first sf/sfdx invocation in compound calls.
Loop fit (unported sf commands) Command Sessions Calls Median P90 Startup s/call Total startup s sfd plugin Scoresf callsis every non-adoptedcall.sessionsis every transcript file with at least one observed call, including ones that only usedsfd.- Each ranked adoption list shows the first
--topitems, or(none). Thenot in sfdlist includeslegacysubcommands. - The loop-fit table shows up to 15 rows, or every row with
--all. When rows are hidden, it ends withShowing <n> of <m>. Use --all to show every row.With no unported commands it shows(none). - The time and output parts show
time unknownoroutput unknownwhen there are no samples.
JSON
--json prints the report object, pretty-printed. Its fields are:
since(ISO timestamp),window,agents,project(ornull) andtop.topis echoed back but does not limit any list in the JSON.sfCalls,sessionsandcounts(rewritable,skipped,unsupported,legacy,adopted).estimates:timeSavedMs,durationSamples,outputChars,outputSamplesandoutputTokens. These cover rewritable calls only.diagnostics:malformedEntries,ignoredEntriesandunreadableFiles.commands: one entry per group, keyed by class, subcommand and, for skipped calls, reason. Each hasclassification,subcommand,reason(skipped only),count,medianDurationMs,durationSamples,medianOutputChars,medianOutputTokensandoutputSamples. Medians arenullwith no samples.skipReasons,unsupportedandrewritable: ranked{ name, count }lists, unlimited in JSON.loopFitis the complete ranked array, independent of--topand--all. Each row hascommandId,sessions,calls,medianRepeatsPerSession,p90RepeatsPerSession,startupSeconds,estimatedStartupSeconds,pluginProvides(boolean) andscore.
The report holds no command text, output text, or file contents. Groups are keyed
by subcommand and reason. The only path it contains is the --project value.
Diagnostics
malformedEntries: a JSONL line that does not parse, a Codexargumentsstring that does not parse, a Gemini document with a syntax error, or a candidate call with a missing or invalid timestamp.unreadableFiles: a store directory or file that cannot be read, other than missing. Also a stat failure or a stream error during reading.ignoredEntries: unrelated messages and items, non-shell tools, and results with no pending call. Shell calls that do not mentionsf,sfdorsfdxare not counted here.
A missing store is not a diagnostic.
Known limits
- Codex custom tools, including JavaScript
exectools, are ignored. - Gemini stamps every call in a batch with the batch’s completion time, so calls from a message with several tool calls have no duration. Their output sizes still contribute when present.
- Gemini’s transcript format is only partly verified. The fixtures cover the
documented shapes, and a user-only
logs.jsonhas no shell calls. - Claude calls that never receive a result are counted without a duration or output size.
- Output sizes are character counts, not tokens. Non-string Claude output is measured as JSON, so it can be larger than the text an agent saw.
- Loop fit reads a command ID only from words before the first flag, and it
stops at the first word that is not command-ID-shaped (for example a value
containing
@or/). ThesfCLI rejects flags before the command ID, so loop fit excludes failed invocations such assf --json org list.
Changing this area
- To add an agent, write a reader that yields the record shape above. Then add it
to the
readersmap insrc/discover/index.mjsand to the map insrc/discover/worker.mjs. Both maps must match, anddiscoverOptionsvalidates--agentagainst the first one. Update the--agenttext inDISCOVER_ARGSinsrc/cli/constants.mjs, the README command table and the flag table above. - Keep classification in
rewrite(), and do not copy its rules into the readers. Reader changes should only extract commands and sizes. - Do not add command text, output text or file contents to the report. Keep to
subcommand names and reasons, so
--jsonstays safe to share. - New fixtures go in
test/fixtures/discover/. Add atest/discover.test.mjscase for each new reader shape, malformed line and classification rule.