harnery 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/commands/completion.d.ts.map +1 -1
  2. package/dist/commands/completion.js +48 -10
  3. package/dist/core/agents/rules/claim-conflict.d.ts.map +1 -1
  4. package/dist/core/agents/rules/claim-conflict.js +10 -2
  5. package/dist/core/hooks/cli.js +4 -10
  6. package/dist/core/hooks/guard-path.d.ts +29 -0
  7. package/dist/core/hooks/guard-path.d.ts.map +1 -0
  8. package/dist/core/hooks/guard-path.js +38 -0
  9. package/dist/lib/completion/bash.d.ts +15 -0
  10. package/dist/lib/completion/bash.d.ts.map +1 -1
  11. package/dist/lib/completion/bash.js +35 -0
  12. package/dist/lib/completion/fish.d.ts +10 -0
  13. package/dist/lib/completion/fish.d.ts.map +1 -1
  14. package/dist/lib/completion/fish.js +21 -0
  15. package/dist/lib/completion/index.d.ts +4 -3
  16. package/dist/lib/completion/index.d.ts.map +1 -1
  17. package/dist/lib/completion/index.js +4 -3
  18. package/dist/lib/completion/resolve.d.ts +52 -0
  19. package/dist/lib/completion/resolve.d.ts.map +1 -0
  20. package/dist/lib/completion/resolve.js +171 -0
  21. package/dist/lib/completion/zsh.d.ts +8 -0
  22. package/dist/lib/completion/zsh.d.ts.map +1 -1
  23. package/dist/lib/completion/zsh.js +33 -0
  24. package/dist/lib/docs-lint.d.ts.map +1 -1
  25. package/dist/lib/docs-lint.js +6 -0
  26. package/package.json +1 -1
  27. package/src/commands/completion.ts +62 -9
  28. package/src/core/agents/rules/claim-conflict.ts +10 -2
  29. package/src/core/hooks/cli.ts +4 -8
  30. package/src/core/hooks/guard-path.ts +34 -0
  31. package/src/lib/completion/bash.ts +36 -0
  32. package/src/lib/completion/fish.ts +22 -0
  33. package/src/lib/completion/index.ts +12 -3
  34. package/src/lib/completion/resolve.ts +210 -0
  35. package/src/lib/completion/zsh.ts +34 -0
  36. package/src/lib/docs-lint.ts +5 -0
@@ -1 +1 @@
1
- {"version":3,"file":"zsh.d.ts","sourceRoot":"","sources":["../../../src/lib/completion/zsh.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,WAAW,EAA8B,MAAM,WAAW,CAAC;AAwBzE,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAsGtE"}
1
+ {"version":3,"file":"zsh.d.ts","sourceRoot":"","sources":["../../../src/lib/completion/zsh.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,WAAW,EAA8B,MAAM,WAAW,CAAC;AAwBzE,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAsGtE;AAOD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAyB1D"}
@@ -129,6 +129,39 @@ function truncate(s, n) {
129
129
  return "";
130
130
  return s.length > n ? `${s.slice(0, n - 1)}…` : s;
131
131
  }
132
+ /**
133
+ * DYNAMIC zsh completion: a thin, tree-independent shim that calls
134
+ * `<bin> __complete-line` on every <Tab> (see bash.ts generateBashDynamic for
135
+ * the rationale). Candidate lines are `value\tdescription`; the shim converts
136
+ * the tab to `:` so `_describe` renders descriptions. The trailing `\x1f:<n>`
137
+ * line carries the directive (bit 0 = file fallback → `_files`).
138
+ */
139
+ export function generateZshDynamic(binName) {
140
+ const fn = fnPrefix(binName);
141
+ return `#compdef ${binName}
142
+ # ${binName} zsh completion (dynamic; install once, never stale). Do not edit.
143
+ ${fn}() {
144
+ emulate -L zsh
145
+ local line directive=0
146
+ local -a raw display
147
+ raw=( "\${(@f)$(${binName} __complete-line $((CURRENT-1)) -- "\${words[@]}" 2>/dev/null)}" )
148
+ for line in $raw; do
149
+ [ -z "$line" ] && continue
150
+ if [[ "$line" == $'\\x1f:'* ]]; then
151
+ directive="\${line#$'\\x1f:'}"
152
+ else
153
+ display+=( "\${line//$'\\t'/:}" )
154
+ fi
155
+ done
156
+ if (( directive & 1 )); then
157
+ _files
158
+ return
159
+ fi
160
+ _describe -t values 'completions' display
161
+ }
162
+ compdef ${fn} ${binName}
163
+ `;
164
+ }
132
165
  /**
133
166
  * The driver walks `$words` to determine the current command path, then
134
167
  * dispatches to subcommand / option / value completion. `fn` is the
@@ -1 +1 @@
1
- {"version":3,"file":"docs-lint.d.ts","sourceRoot":"","sources":["../../src/lib/docs-lint.ts"],"names":[],"mappings":"AAYA,wBAAgB,eAAe,CAAC,IAAI,EAAE;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C,GAAG,IAAI,CAIP;AAaD;;;;;;GAMG;AAEH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;AAE3C,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,QAAQ,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAkVD,wBAAsB,OAAO,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAoBlE"}
1
+ {"version":3,"file":"docs-lint.d.ts","sourceRoot":"","sources":["../../src/lib/docs-lint.ts"],"names":[],"mappings":"AAYA,wBAAgB,eAAe,CAAC,IAAI,EAAE;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C,GAAG,IAAI,CAIP;AAaD;;;;;;GAMG;AAEH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;AAE3C,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,QAAQ,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAuVD,wBAAsB,OAAO,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAoBlE"}
@@ -204,6 +204,12 @@ function checkNamingConvention(repoName, _repoPath, files) {
204
204
  // Allowlisted names
205
205
  if (ROOT_FILE_ALLOWLIST.has(name))
206
206
  continue;
207
+ // Leading-underscore files are deliberate templates / meta files
208
+ // (e.g. _template.md), not content. The underscore is a convention
209
+ // marking "copy me, don't read me as a real doc", so exempt them
210
+ // from naming discipline rather than forcing kebab-case.
211
+ if (name.startsWith("_"))
212
+ continue;
207
213
  // Dated files (audits/issues)
208
214
  if (DATED_FILE_PATTERN.test(name))
209
215
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harnery",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Multi-agent coordination + harness adapters + portable CLI utilities for Claude Code / Cursor / Codex.",
5
5
  "license": "MIT",
6
6
  "author": "Ryan Kelly",
@@ -4,9 +4,15 @@ import type { Command } from "commander";
4
4
  import type { EmitContext, HarneryProgramContext } from "../commander.ts";
5
5
  import {
6
6
  type CompletionContextLookup,
7
+ type CompletionProviderRunner,
8
+ encodeResult,
7
9
  generateBash,
10
+ generateBashDynamic,
8
11
  generateFish,
12
+ generateFishDynamic,
9
13
  generateZsh,
14
+ generateZshDynamic,
15
+ resolveCompletions,
10
16
  walkProgram,
11
17
  } from "../lib/completion/index.ts";
12
18
 
@@ -39,27 +45,39 @@ export function registerCompletionCommand(
39
45
  "Shell tab-completion. Emit a script per shell or install to the standard location.",
40
46
  );
41
47
 
48
+ const dynamicHint =
49
+ "Emit a thin shim that calls the binary at tab-time (never goes stale; install once)";
50
+
42
51
  root
43
52
  .command("bash")
44
53
  .description("Emit bash completion script to stdout")
45
- .action(() => {
46
- const out = generateBash(walkProgram(program, lookup), program.name());
54
+ .option("--dynamic", dynamicHint)
55
+ .action((opts: { dynamic?: boolean }) => {
56
+ const out = opts.dynamic
57
+ ? generateBashDynamic(program.name())
58
+ : generateBash(walkProgram(program, lookup), program.name());
47
59
  process.stdout.write(out); // raw bytes: shell completion scripts must be unframed (consumer evals stdout).
48
60
  });
49
61
 
50
62
  root
51
63
  .command("zsh")
52
64
  .description("Emit zsh completion script to stdout")
53
- .action(() => {
54
- const out = generateZsh(walkProgram(program, lookup), program.name());
65
+ .option("--dynamic", dynamicHint)
66
+ .action((opts: { dynamic?: boolean }) => {
67
+ const out = opts.dynamic
68
+ ? generateZshDynamic(program.name())
69
+ : generateZsh(walkProgram(program, lookup), program.name());
55
70
  process.stdout.write(out); // raw bytes: shell completion scripts must be unframed (consumer evals stdout).
56
71
  });
57
72
 
58
73
  root
59
74
  .command("fish")
60
75
  .description("Emit fish completion script to stdout")
61
- .action(() => {
62
- const out = generateFish(walkProgram(program, lookup), program.name());
76
+ .option("--dynamic", dynamicHint)
77
+ .action((opts: { dynamic?: boolean }) => {
78
+ const out = opts.dynamic
79
+ ? generateFishDynamic(program.name())
80
+ : generateFish(walkProgram(program, lookup), program.name());
63
81
  process.stdout.write(out); // raw bytes: shell completion scripts must be unframed (consumer evals stdout).
64
82
  });
65
83
 
@@ -69,6 +87,7 @@ export function registerCompletionCommand(
69
87
  .option("--shell <name>", "bash | zsh | fish (default: auto-detect from $SHELL)")
70
88
  .option("--path <file>", "Override destination path")
71
89
  .option("--print-path", "Print the destination path and exit (no write)")
90
+ .option("--dynamic", `${dynamicHint} (recommended)`)
72
91
  .action(async (opts: InstallOpts) => {
73
92
  await installCompletion(program, opts, lookup);
74
93
  });
@@ -92,12 +111,39 @@ export function registerCompletionCommand(
92
111
  });
93
112
  // Keep TS happy that the variable is used.
94
113
  void hidden;
114
+
115
+ // Hidden internal entry for DYNAMIC completion: the thin shim passes the live
116
+ // command line (cursor index + all words after `--`) and we compute the full
117
+ // candidate set from the live command tree. `--` stops option parsing so
118
+ // words like `-h` reach the variadic instead of being read as our flags.
119
+ const hiddenLine = program
120
+ .command("__complete-line <cword> [words...]", { hidden: true })
121
+ .description("Internal: full-line completion callback for the dynamic shell shim")
122
+ .allowUnknownOption(true)
123
+ .allowExcessArguments(true)
124
+ .action(async (cword: string, words: string[] | undefined) => {
125
+ try {
126
+ const result = await resolveCompletions(
127
+ program,
128
+ words ?? [],
129
+ Number.parseInt(cword, 10) || 0,
130
+ lookup,
131
+ runProvider as CompletionProviderRunner,
132
+ );
133
+ process.stdout.write(encodeResult(result)); // lint-ok-emission: shell callback; the encoded candidate/directive stream is the contract with the shim.
134
+ } catch {
135
+ // Never break the user's tab: emit just the file-fallback directive.
136
+ process.stdout.write("\x1f:1\n"); // lint-ok-emission: shell callback fallback directive.
137
+ }
138
+ });
139
+ void hiddenLine;
95
140
  }
96
141
 
97
142
  interface InstallOpts {
98
143
  shell?: string;
99
144
  path?: string;
100
145
  printPath?: boolean;
146
+ dynamic?: boolean;
101
147
  }
102
148
 
103
149
  async function installCompletion(
@@ -117,16 +163,23 @@ async function installCompletion(
117
163
  return;
118
164
  }
119
165
 
166
+ const name = program.name();
120
167
  let content: string;
121
168
  switch (shell) {
122
169
  case "bash":
123
- content = generateBash(walkProgram(program, lookup), program.name());
170
+ content = opts.dynamic
171
+ ? generateBashDynamic(name)
172
+ : generateBash(walkProgram(program, lookup), name);
124
173
  break;
125
174
  case "zsh":
126
- content = generateZsh(walkProgram(program, lookup), program.name());
175
+ content = opts.dynamic
176
+ ? generateZshDynamic(name)
177
+ : generateZsh(walkProgram(program, lookup), name);
127
178
  break;
128
179
  case "fish":
129
- content = generateFish(walkProgram(program, lookup), program.name());
180
+ content = opts.dynamic
181
+ ? generateFishDynamic(name)
182
+ : generateFish(walkProgram(program, lookup), name);
130
183
  break;
131
184
  default:
132
185
  process.stderr.write(`Unknown shell: ${shell}\n`); // lint-ok-emission: install-time error, see above.
@@ -101,7 +101,15 @@ export function evaluateClaim(coordRoot: string, req: ClaimRequest): VerdictResu
101
101
  const hasFreshPeers = otherPeers.some(
102
102
  (p) => isFresh(p.last_heartbeat) && p.files_touched.length > 0,
103
103
  );
104
- if (hasFreshPeers && myPeer && myPeer.files_touched.length > 0) {
104
+ // Re-editing a path already in our own files_touched acquires no new lock
105
+ // edge, so it can't create a circular wait — the ordering rule must not block
106
+ // it. Without this exemption, an agent that edits a higher-sorting file and
107
+ // then makes a second pass over an already-held lower-sorting file gets a
108
+ // spurious ordering_violation (the dominant friction source under concurrency:
109
+ // both agent-Gibson holding README.md and agent-Ophelia holding AGENTS.md were
110
+ // blocked re-editing those held files after touching a higher path, 2026-07-03).
111
+ const alreadyHeld = myPeer?.files_touched.includes(req.path) ?? false;
112
+ if (hasFreshPeers && myPeer && myPeer.files_touched.length > 0 && !alreadyHeld) {
105
113
  // Only ACTIVE (uncommitted) edits should constrain lock ordering. A claim on
106
114
  // a committed-clean file is a finished edit, not a held lock, so it must not
107
115
  // wall off a lower-sorted acquisition. Without this, a long session
@@ -118,7 +126,7 @@ export function evaluateClaim(coordRoot: string, req: ClaimRequest): VerdictResu
118
126
  allow: false,
119
127
  exit_code: 2,
120
128
  rule: "claim.ordering_violation",
121
- reason: `Cannot acquire ${req.path} while holding ${highest} (claim ordering rule: paths must be acquired in sorted order). Release the higher claim first.`,
129
+ reason: `Cannot acquire ${req.path}: you already hold ${highest}, which sorts after it (claim ordering rule: acquire paths in sorted order to prevent deadlock between concurrent agents). Fix by editing in sorted order, or by committing ${highest} first, since a committed-clean file no longer blocks and is auto-pruned.`,
122
130
  };
123
131
  }
124
132
  // Every blocker is a finished (committed-clean) edit: prune them so they
@@ -42,6 +42,7 @@ import {
42
42
  } from "./effects/index.ts";
43
43
  import { emit } from "./events/emit.ts";
44
44
  import type { Harness } from "./events/schema.ts";
45
+ import { canonicalize } from "./guard-path.ts";
45
46
  import { detectHarness } from "./harness/detect.ts";
46
47
  import {
47
48
  extractBashCommand,
@@ -774,7 +775,9 @@ async function runPreToolUseGuard(
774
775
  harness: Harness,
775
776
  ): Promise<void> {
776
777
  const toolName = (data.tool_name as string | undefined) ?? "";
777
- const targets = collectGuardTargets(toolName, data).map((p) => canonicalize(coordRoot, p));
778
+ const targets = collectGuardTargets(toolName, data)
779
+ .map((p) => canonicalize(coordRoot, p))
780
+ .filter((p): p is string => p !== null);
778
781
  if (targets.length === 0) return;
779
782
 
780
783
  const agentCoordBin = join(coordRoot, "harnery", "bin", "agent-coord");
@@ -822,13 +825,6 @@ async function runPreToolUseGuard(
822
825
  /** Canonicalize a path to monorepo-relative form. Absolute paths under
823
826
  * coordRoot get the prefix stripped; relative paths pass through (assumed
824
827
  * already canonical). */
825
- function canonicalize(coordRoot: string, p: string): string {
826
- if (!p) return p;
827
- if (p.startsWith(`${coordRoot}/`)) return p.slice(coordRoot.length + 1);
828
- if (p === coordRoot) return ".";
829
- return p;
830
- }
831
-
832
828
  /** Pull the candidate path(s) out of a write-tool payload. Empty array when
833
829
  * the tool isn't a write or no path could be derived. */
834
830
  function collectGuardTargets(toolName: string, data: Record<string, unknown>): string[] {
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Canonicalize a write-tool target path for the claim guard.
3
+ *
4
+ * Returns the monorepo-relative path, or `null` when the target lies OUTSIDE the
5
+ * repo (an absolute path not under coordRoot, e.g. a `/tmp` scratchpad or other
6
+ * session-temp file).
7
+ *
8
+ * The claim system is intentionally repo-scoped: it coordinates monorepo files,
9
+ * not arbitrary absolute paths, so the guard skips out-of-repo targets. Skipping
10
+ * them is right on two counts. First, it keeps non-repo paths out of a
11
+ * heartbeat's `files_touched`. Second, the ordering rule compares raw path
12
+ * strings, and an absolute `/tmp/…` sorts before every repo-relative path
13
+ * (`/` = 0x2F < any letter), so without this a scratchpad write would spuriously
14
+ * "block" a legitimately-held repo file. Returning null keeps such paths out of
15
+ * the claim system entirely.
16
+ *
17
+ * Accepted tradeoff: this also means shared out-of-repo files (a user-level
18
+ * memory or plans directory) are not coordinated across agents. The alternative,
19
+ * normalizing every path to one consistent key so those stay coordinated, was
20
+ * rejected as gold-plating a rare, merge-disciplined race in a deadlock-critical
21
+ * path. Coordinate shared state by keeping it in the repo, not out of it.
22
+ *
23
+ * Relative inputs are assumed already-repo-relative (Codex `apply_patch` emits
24
+ * cwd-relative paths). The in-repo check requires the `<root>/` separator, so a
25
+ * sibling dir that merely shares a prefix (`/repo-other` vs `/repo`) is treated
26
+ * as out-of-repo, not stripped.
27
+ */
28
+ export function canonicalize(coordRoot: string, p: string): string | null {
29
+ if (!p) return null;
30
+ if (p === coordRoot) return ".";
31
+ if (p.startsWith(`${coordRoot}/`)) return p.slice(coordRoot.length + 1);
32
+ if (p.startsWith("/")) return null; // absolute + not under coordRoot → out-of-repo
33
+ return p; // relative → treat as repo-relative
34
+ }
@@ -162,6 +162,42 @@ function bashEscape(s: string): string {
162
162
  * to subcommand / option / value completion. `fn` is the function-name prefix
163
163
  * and `binName` is the CLI name used for the `__complete` callback.
164
164
  */
165
+ /**
166
+ * DYNAMIC bash completion: a thin, tree-independent shim. Instead of baking the
167
+ * command tree into case-tables (which go stale on any command/flag change),
168
+ * it hands the live command line to `<bin> __complete-line` on every <Tab> and
169
+ * lets the binary — which always knows its own current tree — answer. Install
170
+ * once; never regenerate. The trailing `\x1f:<n>` line carries the directive
171
+ * bitmask (bit 0 = fall back to file completion).
172
+ */
173
+ export function generateBashDynamic(binName: string): string {
174
+ const fn = fnPrefix(binName);
175
+ return `# ${binName} bash completion (dynamic; install once, never stale). Do not edit.
176
+ # Source via: eval "$(${binName} completion bash --dynamic)"
177
+ ${fn}() {
178
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
179
+ local raw line directive=0
180
+ local -a cands=()
181
+ raw="$(${binName} __complete-line "$COMP_CWORD" -- "\${COMP_WORDS[@]}" 2>/dev/null)" || return
182
+ while IFS= read -r line; do
183
+ [ -z "$line" ] && continue
184
+ if [ "\${line:0:2}" = $'\\x1f:' ]; then
185
+ directive="\${line:2}"
186
+ else
187
+ cands+=( "\${line%%$'\\t'*}" )
188
+ fi
189
+ done <<< "$raw"
190
+ if (( directive & 1 )); then
191
+ COMPREPLY=( $(compgen -f -- "$cur") )
192
+ return
193
+ fi
194
+ local IFS=$'\\n'
195
+ COMPREPLY=( $(compgen -W "\${cands[*]}" -- "$cur") )
196
+ }
197
+ complete -F ${fn} ${binName}
198
+ `;
199
+ }
200
+
165
201
  function bashDriver(fn: string, binName: string): string {
166
202
  return `${fn}() {
167
203
  local cur prev words cword
@@ -67,6 +67,28 @@ function valueAction(
67
67
  return { flag: "-r", arg: "" };
68
68
  }
69
69
 
70
+ /**
71
+ * DYNAMIC fish completion: a thin, tree-independent shim that calls
72
+ * `<bin> __complete-line` on every <Tab> (see bash.ts generateBashDynamic for
73
+ * the rationale). Fish renders `value\tdescription` lines natively, so the
74
+ * helper just strips the trailing `\x1f:<n>` directive line. Note: fish's
75
+ * declarative `complete -a` cannot switch to file completion from inside the
76
+ * helper, so the File directive is a no-op here — use static fish completion
77
+ * (`completion fish`) if you need file fallback on a path-valued positional.
78
+ */
79
+ export function generateFishDynamic(binName: string): string {
80
+ const fn = `__${binName.replace(/[^a-zA-Z0-9_]/g, "_")}_complete`;
81
+ return `# ${binName} fish completion (dynamic; install once, never stale). Do not edit.
82
+ # Source via: ${binName} completion fish --dynamic | source
83
+ function ${fn}
84
+ set -l toks (commandline -opc)
85
+ set -l cur (commandline -ct)
86
+ ${binName} __complete-line (count $toks) -- $toks $cur 2>/dev/null | string match -rv '^\\x1f:'
87
+ end
88
+ complete -c ${binName} -f -a '(${fn})'
89
+ `;
90
+ }
91
+
70
92
  export function generateFish(root: CommandSpec, binName: string): string {
71
93
  const out: string[] = [];
72
94
  out.push(
@@ -1,5 +1,14 @@
1
- export { generateBash } from "./bash.js";
2
- export { generateFish } from "./fish.js";
1
+ export { generateBash, generateBashDynamic } from "./bash.js";
2
+ export { generateFish, generateFishDynamic } from "./fish.js";
3
+ export {
4
+ type Candidate,
5
+ type CompletionProviderRunner,
6
+ type CompletionResult,
7
+ DIRECTIVE_PREFIX,
8
+ Directive,
9
+ encodeResult,
10
+ resolveCompletions,
11
+ } from "./resolve.js";
3
12
  export {
4
13
  type CommandSpec,
5
14
  type CompletionContextLookup,
@@ -7,4 +16,4 @@ export {
7
16
  type PositionalSpec,
8
17
  walkProgram,
9
18
  } from "./walk.js";
10
- export { generateZsh } from "./zsh.js";
19
+ export { generateZsh, generateZshDynamic } from "./zsh.js";
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Runtime completion resolver — the authoritative, in-process answer to
3
+ * "what should I suggest at this cursor position?".
4
+ *
5
+ * The static bash/zsh/fish generators bake the whole command tree into shell
6
+ * case-tables, which go stale the moment a command/flag is added (the script
7
+ * must be regenerated + reinstalled). The DYNAMIC completion path instead
8
+ * installs a thin, tree-independent shim that, on every <Tab>, hands the live
9
+ * command line back to the binary and calls THIS function. Because the binary
10
+ * always knows its own current command tree, a dynamic shim never goes stale —
11
+ * install once, ever.
12
+ *
13
+ * This mirrors the path-walking the static bash driver does, but in one place
14
+ * and in TypeScript, so all three shells share identical behavior. It is
15
+ * deliberately decoupled from Commander internals via the CommandSpec tree
16
+ * (walkProgram), exactly like the static generators.
17
+ */
18
+
19
+ import type { Command } from "commander";
20
+ import { type CommandSpec, type CompletionContextLookup, walkProgram } from "./walk.js";
21
+
22
+ /** Bitmask of post-processing hints for the shell shim (Cobra-style). */
23
+ export const Directive = {
24
+ /** Use the returned candidates as completion values. */
25
+ Default: 0,
26
+ /** No candidates apply here — the shell should fall back to file completion. */
27
+ File: 1,
28
+ } as const;
29
+
30
+ export interface Candidate {
31
+ value: string;
32
+ description?: string;
33
+ }
34
+
35
+ export interface CompletionResult {
36
+ candidates: Candidate[];
37
+ directive: number;
38
+ }
39
+
40
+ /** Provider runner injected by the host CLI (same contract as `__complete`). */
41
+ export type CompletionProviderRunner = (provider: string, partial: string) => Promise<string[]>;
42
+
43
+ interface PathTables {
44
+ subcommandsByPath: Map<string, CommandSpec[]>;
45
+ /** path → flag (long or short) → spec, for both forms. */
46
+ optionsByPath: Map<string, CommandSpec["options"]>;
47
+ positionalsByPath: Map<string, CommandSpec["positionals"]>;
48
+ }
49
+
50
+ function buildTables(root: CommandSpec): PathTables {
51
+ const subcommandsByPath = new Map<string, CommandSpec[]>();
52
+ const optionsByPath = new Map<string, CommandSpec["options"]>();
53
+ const positionalsByPath = new Map<string, CommandSpec["positionals"]>();
54
+ const walk = (s: CommandSpec): void => {
55
+ subcommandsByPath.set(s.path, s.subcommands);
56
+ optionsByPath.set(s.path, s.options);
57
+ positionalsByPath.set(s.path, s.positionals);
58
+ for (const sub of s.subcommands) walk(sub);
59
+ };
60
+ walk(root);
61
+ return { subcommandsByPath, optionsByPath, positionalsByPath };
62
+ }
63
+
64
+ function optionAt(tables: PathTables, path: string, flag: string) {
65
+ const opts = tables.optionsByPath.get(path) ?? [];
66
+ return opts.find((o) => o.long === flag || o.short === flag);
67
+ }
68
+
69
+ function isKnownSubcommand(tables: PathTables, path: string, name: string): boolean {
70
+ return (tables.subcommandsByPath.get(path) ?? []).some((c) => c.name === name);
71
+ }
72
+
73
+ /**
74
+ * Walk the words before the cursor to determine the current command path,
75
+ * skipping options and the values they consume (mirrors the static driver).
76
+ * Returns the resolved command path ("" = root).
77
+ */
78
+ function resolvePath(tables: PathTables, words: string[], cword: number): string {
79
+ let path = "";
80
+ let i = 1; // words[0] is the bin name
81
+ while (i < cword) {
82
+ const w = words[i] ?? "";
83
+ if (w.startsWith("-")) {
84
+ const opt = optionAt(tables, path, w);
85
+ if (opt?.takesValue) i += 1; // skip the option's value
86
+ } else if (isKnownSubcommand(tables, path, w)) {
87
+ path = path ? `${path} ${w}` : w;
88
+ }
89
+ i += 1;
90
+ }
91
+ return path;
92
+ }
93
+
94
+ /** Count positional args consumed at the resolved path (non-option, non-subcommand words). */
95
+ function positionalIndex(tables: PathTables, words: string[], cword: number): number {
96
+ let seen = "";
97
+ let after = 0;
98
+ let j = 1;
99
+ while (j < cword) {
100
+ const w = words[j] ?? "";
101
+ if (w.startsWith("-")) {
102
+ const opt = optionAt(tables, seen, w);
103
+ if (opt?.takesValue) j += 1;
104
+ } else if (isKnownSubcommand(tables, seen, w)) {
105
+ seen = seen ? `${seen} ${w}` : w;
106
+ } else {
107
+ after += 1;
108
+ }
109
+ j += 1;
110
+ }
111
+ return after;
112
+ }
113
+
114
+ /** Resolve the value source (enum / dynamic-provider / file) for a value slot. */
115
+ async function valueCandidates(
116
+ source: { valueChoices?: string[]; dynamicProvider?: string },
117
+ partial: string,
118
+ runProvider: CompletionProviderRunner,
119
+ ): Promise<CompletionResult> {
120
+ if (source.dynamicProvider) {
121
+ try {
122
+ const values = await runProvider(source.dynamicProvider, partial);
123
+ return { candidates: values.map((value) => ({ value })), directive: Directive.Default };
124
+ } catch {
125
+ return { candidates: [], directive: Directive.File };
126
+ }
127
+ }
128
+ if (source.valueChoices && source.valueChoices.length > 0) {
129
+ return {
130
+ candidates: source.valueChoices.map((value) => ({ value })),
131
+ directive: Directive.Default,
132
+ };
133
+ }
134
+ // A value is expected but we have nothing to suggest → let the shell try files.
135
+ return { candidates: [], directive: Directive.File };
136
+ }
137
+
138
+ /**
139
+ * Compute completion candidates for `words` with the cursor at `cword`.
140
+ * `words[0]` is the bin name; `words[cword]` is the (possibly empty) token
141
+ * being completed. The shell shim does the final prefix-filtering against that
142
+ * token, so this returns the full candidate set for the slot.
143
+ */
144
+ export async function resolveCompletions(
145
+ program: Command,
146
+ words: string[],
147
+ cword: number,
148
+ lookup: CompletionContextLookup,
149
+ runProvider: CompletionProviderRunner,
150
+ ): Promise<CompletionResult> {
151
+ const tables = buildTables(walkProgram(program, lookup));
152
+ const path = resolvePath(tables, words, cword);
153
+ const cur = words[cword] ?? "";
154
+ const prev = cword > 0 ? (words[cword - 1] ?? "") : "";
155
+
156
+ // Case 1: previous word is an option that takes a value → complete the value.
157
+ if (prev.startsWith("-")) {
158
+ const opt = optionAt(tables, path, prev);
159
+ if (opt?.takesValue) return valueCandidates(opt, cur, runProvider);
160
+ }
161
+
162
+ // Case 2: completing an option name (cur starts with "-").
163
+ if (cur.startsWith("-")) {
164
+ const opts = tables.optionsByPath.get(path) ?? [];
165
+ const candidates: Candidate[] = [];
166
+ for (const o of opts) {
167
+ if (o.long) candidates.push({ value: o.long, description: o.description });
168
+ if (o.short) candidates.push({ value: o.short, description: o.description });
169
+ }
170
+ return { candidates, directive: Directive.Default };
171
+ }
172
+
173
+ // Case 3: subcommands available at this path → suggest them.
174
+ const subs = tables.subcommandsByPath.get(path) ?? [];
175
+ if (subs.length > 0) {
176
+ return {
177
+ candidates: subs.map((c) => ({ value: c.name, description: c.description })),
178
+ directive: Directive.Default,
179
+ };
180
+ }
181
+
182
+ // Case 4: positional value slot.
183
+ const positionals = tables.positionalsByPath.get(path) ?? [];
184
+ const idx = positionalIndex(tables, words, cword);
185
+ const pos =
186
+ positionals[idx] ??
187
+ (positionals[positionals.length - 1]?.variadic
188
+ ? positionals[positionals.length - 1]
189
+ : undefined);
190
+ if (pos) return valueCandidates(pos, cur, runProvider);
191
+
192
+ // Nothing structured to suggest → file completion.
193
+ return { candidates: [], directive: Directive.File };
194
+ }
195
+
196
+ /** Sentinel prefix for the trailing directive line in the wire protocol. */
197
+ export const DIRECTIVE_PREFIX = "\x1f:";
198
+
199
+ /**
200
+ * Serialize a result for the shell shim: one `value\tdescription` line per
201
+ * candidate, then a final `\x1f:<directive>` line. The \x1f (unit separator)
202
+ * prefix makes the directive line unambiguous against real candidate values.
203
+ */
204
+ export function encodeResult(result: CompletionResult): string {
205
+ const lines = result.candidates.map((c) =>
206
+ c.description ? `${c.value}\t${c.description}` : c.value,
207
+ );
208
+ lines.push(`${DIRECTIVE_PREFIX}${result.directive}`);
209
+ return `${lines.join("\n")}\n`;
210
+ }
@@ -142,6 +142,40 @@ function truncate(s: string, n: number): string {
142
142
  return s.length > n ? `${s.slice(0, n - 1)}…` : s;
143
143
  }
144
144
 
145
+ /**
146
+ * DYNAMIC zsh completion: a thin, tree-independent shim that calls
147
+ * `<bin> __complete-line` on every <Tab> (see bash.ts generateBashDynamic for
148
+ * the rationale). Candidate lines are `value\tdescription`; the shim converts
149
+ * the tab to `:` so `_describe` renders descriptions. The trailing `\x1f:<n>`
150
+ * line carries the directive (bit 0 = file fallback → `_files`).
151
+ */
152
+ export function generateZshDynamic(binName: string): string {
153
+ const fn = fnPrefix(binName);
154
+ return `#compdef ${binName}
155
+ # ${binName} zsh completion (dynamic; install once, never stale). Do not edit.
156
+ ${fn}() {
157
+ emulate -L zsh
158
+ local line directive=0
159
+ local -a raw display
160
+ raw=( "\${(@f)$(${binName} __complete-line $((CURRENT-1)) -- "\${words[@]}" 2>/dev/null)}" )
161
+ for line in $raw; do
162
+ [ -z "$line" ] && continue
163
+ if [[ "$line" == $'\\x1f:'* ]]; then
164
+ directive="\${line#$'\\x1f:'}"
165
+ else
166
+ display+=( "\${line//$'\\t'/:}" )
167
+ fi
168
+ done
169
+ if (( directive & 1 )); then
170
+ _files
171
+ return
172
+ fi
173
+ _describe -t values 'completions' display
174
+ }
175
+ compdef ${fn} ${binName}
176
+ `;
177
+ }
178
+
145
179
  /**
146
180
  * The driver walks `$words` to determine the current command path, then
147
181
  * dispatches to subcommand / option / value completion. `fn` is the
@@ -246,6 +246,11 @@ function checkNamingConvention(repoName: string, _repoPath: string, files: strin
246
246
  const name = basename(rel);
247
247
  // Allowlisted names
248
248
  if (ROOT_FILE_ALLOWLIST.has(name)) continue;
249
+ // Leading-underscore files are deliberate templates / meta files
250
+ // (e.g. _template.md), not content. The underscore is a convention
251
+ // marking "copy me, don't read me as a real doc", so exempt them
252
+ // from naming discipline rather than forcing kebab-case.
253
+ if (name.startsWith("_")) continue;
249
254
  // Dated files (audits/issues)
250
255
  if (DATED_FILE_PATTERN.test(name)) continue;
251
256
  // Changelogs