@spexcode/spec-cli 0.6.5

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 (201) hide show
  1. package/README.md +95 -0
  2. package/bin/spex.mjs +76 -0
  3. package/dist/attach.d.ts +2 -0
  4. package/dist/attach.js +48 -0
  5. package/dist/claude-headless.d.ts +33 -0
  6. package/dist/claude-headless.js +307 -0
  7. package/dist/cli.d.ts +1 -0
  8. package/dist/cli.js +1859 -0
  9. package/dist/client.d.ts +111 -0
  10. package/dist/client.js +476 -0
  11. package/dist/cockpit.d.ts +7 -0
  12. package/dist/cockpit.js +26 -0
  13. package/dist/codex-headless.d.ts +1 -0
  14. package/dist/codex-headless.js +7 -0
  15. package/dist/codex-runtime-generations.d.ts +53 -0
  16. package/dist/codex-runtime-generations.js +686 -0
  17. package/dist/commit-surgery.d.ts +1 -0
  18. package/dist/commit-surgery.js +90 -0
  19. package/dist/contract-filter.d.ts +14 -0
  20. package/dist/contract-filter.js +219 -0
  21. package/dist/dashboard-assets.d.ts +6 -0
  22. package/dist/dashboard-assets.js +50 -0
  23. package/dist/delivery-queue.d.ts +23 -0
  24. package/dist/delivery-queue.js +179 -0
  25. package/dist/doctor.d.ts +9 -0
  26. package/dist/doctor.js +547 -0
  27. package/dist/eval-host.d.ts +1 -0
  28. package/dist/eval-host.js +19 -0
  29. package/dist/execution-trace.d.ts +26 -0
  30. package/dist/execution-trace.js +475 -0
  31. package/dist/file-write.d.ts +2 -0
  32. package/dist/file-write.js +26 -0
  33. package/dist/flat.d.ts +89 -0
  34. package/dist/flat.js +1076 -0
  35. package/dist/gateway-auth.d.ts +56 -0
  36. package/dist/gateway-auth.js +168 -0
  37. package/dist/gateway-hub.d.ts +28 -0
  38. package/dist/gateway-hub.js +361 -0
  39. package/dist/gateway.d.ts +37 -0
  40. package/dist/gateway.js +503 -0
  41. package/dist/graphCache.d.ts +27 -0
  42. package/dist/graphCache.js +716 -0
  43. package/dist/graphSnapshot.d.ts +14 -0
  44. package/dist/graphSnapshot.js +35 -0
  45. package/dist/graphStream.d.ts +85 -0
  46. package/dist/graphStream.js +1195 -0
  47. package/dist/guidance-catalog.d.ts +64 -0
  48. package/dist/guidance-catalog.js +166 -0
  49. package/dist/guide.d.ts +8 -0
  50. package/dist/guide.js +684 -0
  51. package/dist/harness-select.d.ts +18 -0
  52. package/dist/harness-select.js +62 -0
  53. package/dist/harness.d.ts +325 -0
  54. package/dist/harness.js +3026 -0
  55. package/dist/headless-controller.d.ts +9 -0
  56. package/dist/headless-controller.js +47 -0
  57. package/dist/help.d.ts +10 -0
  58. package/dist/help.js +574 -0
  59. package/dist/hook-prompts.d.ts +18 -0
  60. package/dist/hook-prompts.js +122 -0
  61. package/dist/hooks.d.ts +1 -0
  62. package/dist/hooks.js +27 -0
  63. package/dist/host-resources.d.ts +97 -0
  64. package/dist/host-resources.js +795 -0
  65. package/dist/host.d.ts +88 -0
  66. package/dist/host.js +663 -0
  67. package/dist/index.d.ts +1 -0
  68. package/dist/index.js +899 -0
  69. package/dist/init.d.ts +1 -0
  70. package/dist/init.js +284 -0
  71. package/dist/issues-cli.d.ts +6 -0
  72. package/dist/issues-cli.js +334 -0
  73. package/dist/issues.d.ts +69 -0
  74. package/dist/issues.js +189 -0
  75. package/dist/lint.d.ts +34 -0
  76. package/dist/lint.js +476 -0
  77. package/dist/listen.d.ts +7 -0
  78. package/dist/listen.js +24 -0
  79. package/dist/localIssues.d.ts +65 -0
  80. package/dist/localIssues.js +582 -0
  81. package/dist/login-page.d.ts +5 -0
  82. package/dist/login-page.js +86 -0
  83. package/dist/loop-in.d.ts +23 -0
  84. package/dist/loop-in.js +68 -0
  85. package/dist/machine-peer.d.ts +69 -0
  86. package/dist/machine-peer.js +603 -0
  87. package/dist/materialize.d.ts +18 -0
  88. package/dist/materialize.js +468 -0
  89. package/dist/mentions.d.ts +50 -0
  90. package/dist/mentions.js +117 -0
  91. package/dist/opencode-headless.d.ts +4 -0
  92. package/dist/opencode-headless.js +208 -0
  93. package/dist/opencode.d.ts +3 -0
  94. package/dist/opencode.js +142 -0
  95. package/dist/pi-harness.d.ts +3 -0
  96. package/dist/pi-harness.js +129 -0
  97. package/dist/pi-headless.d.ts +25 -0
  98. package/dist/pi-headless.js +196 -0
  99. package/dist/plugin-harness.d.ts +21 -0
  100. package/dist/plugin-harness.js +146 -0
  101. package/dist/pty-bridge.d.ts +10 -0
  102. package/dist/pty-bridge.js +404 -0
  103. package/dist/pty-helper.d.mts +1 -0
  104. package/dist/pty-helper.mjs +101 -0
  105. package/dist/pty-native-helper.d.mts +2 -0
  106. package/dist/pty-native-helper.mjs +23 -0
  107. package/dist/public-graph.d.ts +46 -0
  108. package/dist/public-graph.js +56 -0
  109. package/dist/ranker.d.ts +15 -0
  110. package/dist/ranker.js +188 -0
  111. package/dist/reaper.d.ts +6 -0
  112. package/dist/reaper.js +81 -0
  113. package/dist/reviews.d.ts +189 -0
  114. package/dist/reviews.js +350 -0
  115. package/dist/runtime-guard.d.ts +6 -0
  116. package/dist/runtime-guard.js +37 -0
  117. package/dist/runtime-ownership.d.ts +21 -0
  118. package/dist/runtime-ownership.js +84 -0
  119. package/dist/search.bench.d.mts +1 -0
  120. package/dist/search.bench.mjs +75 -0
  121. package/dist/search.d.ts +20 -0
  122. package/dist/search.js +61 -0
  123. package/dist/session-cursors.d.ts +14 -0
  124. package/dist/session-cursors.js +82 -0
  125. package/dist/session-declarations.d.ts +13 -0
  126. package/dist/session-declarations.js +126 -0
  127. package/dist/session-execution.d.ts +10 -0
  128. package/dist/session-execution.js +70 -0
  129. package/dist/session-files.d.ts +28 -0
  130. package/dist/session-files.js +130 -0
  131. package/dist/session-follow.d.ts +31 -0
  132. package/dist/session-follow.js +179 -0
  133. package/dist/session-reparent.d.ts +10 -0
  134. package/dist/session-reparent.js +33 -0
  135. package/dist/session-timeline.d.ts +51 -0
  136. package/dist/session-timeline.js +233 -0
  137. package/dist/session-web.d.ts +24 -0
  138. package/dist/session-web.js +141 -0
  139. package/dist/sessions.d.ts +412 -0
  140. package/dist/sessions.js +4239 -0
  141. package/dist/sh.d.ts +1 -0
  142. package/dist/sh.js +3 -0
  143. package/dist/shim-runtime.d.ts +1 -0
  144. package/dist/shim-runtime.js +161 -0
  145. package/dist/slash-commands.d.ts +9 -0
  146. package/dist/slash-commands.js +307 -0
  147. package/dist/source-files.d.ts +9 -0
  148. package/dist/source-files.js +113 -0
  149. package/dist/supervise.d.ts +1 -0
  150. package/dist/supervise.js +308 -0
  151. package/dist/tree.d.ts +25 -0
  152. package/dist/tree.js +98 -0
  153. package/dist/tsx-bin.d.ts +3 -0
  154. package/dist/tsx-bin.js +41 -0
  155. package/dist/uninstall.d.ts +3 -0
  156. package/dist/uninstall.js +177 -0
  157. package/dist/uploads.d.ts +36 -0
  158. package/dist/uploads.js +243 -0
  159. package/dist/worktree-sources.d.ts +1 -0
  160. package/dist/worktree-sources.js +47 -0
  161. package/hooks/compat/mark-active-0.5.2-eef1.fixture +53 -0
  162. package/hooks/compat/mark-active-sed-v0.fixture +46 -0
  163. package/hooks/dispatch.sh +105 -0
  164. package/hooks/harness.sh +272 -0
  165. package/package.json +47 -0
  166. package/templates/hooks/commit-msg +14 -0
  167. package/templates/hooks/post-checkout +25 -0
  168. package/templates/hooks/post-merge +34 -0
  169. package/templates/hooks/pre-commit +120 -0
  170. package/templates/hooks/prepare-commit-msg +35 -0
  171. package/templates/hooks/reference-transaction +105 -0
  172. package/templates/spec/project/.plugins/commands/extract/spec.md +66 -0
  173. package/templates/spec/project/.plugins/commands/regroup/spec.md +25 -0
  174. package/templates/spec/project/.plugins/commands/rename/spec.md +11 -0
  175. package/templates/spec/project/.plugins/commands/spec.md +30 -0
  176. package/templates/spec/project/.plugins/commands/supervisor/spec.md +8 -0
  177. package/templates/spec/project/.plugins/commands/tidy/spec.md +43 -0
  178. package/templates/spec/project/.plugins/core/comment-altitude/spec.md +9 -0
  179. package/templates/spec/project/.plugins/core/idle/idle.sh +15 -0
  180. package/templates/spec/project/.plugins/core/idle/spec.md +13 -0
  181. package/templates/spec/project/.plugins/core/mark-active/mark-active.sh +59 -0
  182. package/templates/spec/project/.plugins/core/mark-active/spec.md +22 -0
  183. package/templates/spec/project/.plugins/core/session-fail/fail.sh +12 -0
  184. package/templates/spec/project/.plugins/core/session-fail/spec.md +15 -0
  185. package/templates/spec/project/.plugins/core/spec-first/spec-first.sh +43 -0
  186. package/templates/spec/project/.plugins/core/spec-first/spec.md +17 -0
  187. package/templates/spec/project/.plugins/core/spec-of-file/spec-of-file.sh +66 -0
  188. package/templates/spec/project/.plugins/core/spec-of-file/spec.md +15 -0
  189. package/templates/spec/project/.plugins/core/spec.md +22 -0
  190. package/templates/spec/project/.plugins/core/stop-gate/spec.md +23 -0
  191. package/templates/spec/project/.plugins/core/stop-gate/stop-gate.sh +149 -0
  192. package/templates/spec/project/.plugins/prompts/atomic-landing/spec.md +15 -0
  193. package/templates/spec/project/.plugins/prompts/forge-link/spec.md +10 -0
  194. package/templates/spec/project/.plugins/prompts/memory-hygiene/spec.md +13 -0
  195. package/templates/spec/project/.plugins/prompts/reproduce-before-fix/spec.md +12 -0
  196. package/templates/spec/project/.plugins/prompts/spec.md +24 -0
  197. package/templates/spec/project/.plugins/skills/distill/digest.mjs +136 -0
  198. package/templates/spec/project/.plugins/skills/distill/spec.md +67 -0
  199. package/templates/spec/project/.plugins/skills/spec.md +19 -0
  200. package/templates/spec/project/.plugins/spec.md +23 -0
  201. package/templates/spec/project/spec.md +20 -0
package/dist/sh.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function shQuote(s: string): string;
package/dist/sh.js ADDED
@@ -0,0 +1,3 @@
1
+ export function shQuote(s) {
2
+ return `'${s.replace(/'/g, `'\\''`)}'`;
3
+ }
@@ -0,0 +1 @@
1
+ export declare function shimRuntimeSource(harnessId: string, dispatch: string, spex: string): string;
@@ -0,0 +1,161 @@
1
+ // @@@ shim-runtime - the ONE shared runtime every GENERATIVE per-session shim embeds ([[shim-runtime]]).
2
+ // pi's extension and opencode's plugin (and any future in-process harness shim) are thin hosts: they declare
3
+ // an event-name mapping and bind their host's API; the machinery they share — claude-shaped payload synthesis
4
+ // into dispatch.sh, the block-verdict parse, the rendezvous socket server, tool-input normalization — is THIS
5
+ // module's generated chunk, embedded verbatim by each generator. One source of truth: the deliver-confirm and
6
+ // stop-gate-rejection bugs were each fixed in only one of the two hand-written copies this replaces; a fix
7
+ // here reaches every generative shim at the next materialize.
8
+ //
9
+ // The chunk is PLAIN JavaScript (no type annotations, no non-builtin imports): pi loads its shim as a native
10
+ // .ts extension, opencode as a project plugin, and tests import the generated file directly under node — the
11
+ // lowest common denominator is untyped ESM against node builtins. Identifiers are __spex-prefixed so a host
12
+ // section can never collide with them.
13
+ // the embedded runtime chunk. `harnessId` is baked as dispatch.sh's argv[1] (the deterministic shell-side
14
+ // harness detector); `dispatch`/`spex` are the absolute paths materialize bakes into every shim — the
15
+ // 'dispatch.sh' substring doubles as the identity stamp cleanHarness gates removal on.
16
+ export function shimRuntimeSource(harnessId, dispatch, spex) {
17
+ return `// ---- spexcode shared shim runtime (embedded from spec-cli/src/shim-runtime.ts — edit THERE) ----
18
+ import { spawn as __spexSpawn } from "node:child_process"
19
+ import { createServer as __spexCreateServer } from "node:net"
20
+ import { unlinkSync as __spexUnlink } from "node:fs"
21
+
22
+ const DISPATCH = ${JSON.stringify(dispatch)}
23
+ const SPEX = ${JSON.stringify(spex)}
24
+ const HARNESS = ${JSON.stringify(harnessId)}
25
+
26
+ // cfg: { sessionId: () => string, cwd?: () => string } — the two identity accessors a host binds; everything
27
+ // else is shared machinery.
28
+ const spexShimRuntime = (cfg) => {
29
+ const cwd = cfg.cwd || (() => process.cwd())
30
+
31
+ // feed ONE claude-shaped payload ({ session_id, cwd, hook_event_name, ...extra }) to dispatch.sh, the
32
+ // harness id baked as argv[1]. Payload key order matters for tool events: a host must put agent_id (when
33
+ // present) BEFORE tool_input because harness.sh's hp_is_subagent checks keys only before tool_input. Resolves with the exit
34
+ // code + both streams for the verdict helpers below; never rejects.
35
+ const dispatchEvent = (event, extra) => new Promise((resolve) => {
36
+ let out = "", err = ""
37
+ let child
38
+ try {
39
+ child = __spexSpawn("bash", [DISPATCH, HARNESS, event], {
40
+ cwd: cwd(), env: { ...process.env, SPEX }, stdio: ["pipe", "pipe", "pipe"], timeout: 600_000,
41
+ })
42
+ } catch (e) { resolve({ code: 1, out, err: String(e) }); return }
43
+ child.stdout.on("data", (d) => { out += d })
44
+ child.stderr.on("data", (d) => { err += d })
45
+ child.on("error", (e) => resolve({ code: 1, out, err: err || String(e) }))
46
+ child.on("close", (code) => resolve({ code: code == null ? 1 : code, out, err }))
47
+ // a handler may exit without draining stdin (fast-fail scripts, a missing dispatch file) — the write then
48
+ // EPIPEs; that must never throw into the host's event handler, the child's exit code still answers.
49
+ child.stdin.on("error", () => { /* child exited before consuming stdin — fine */ })
50
+ try { child.stdin.end(JSON.stringify({ session_id: cfg.sessionId(), cwd: cwd(), hook_event_name: event, ...(extra || {}) })) } catch { /* same */ }
51
+ })
52
+
53
+ // the ONE block contract: dispatch.sh signals a block by EXIT 2 (a handler's stdout
54
+ // {"decision":"block","reason":…} JSON is mapped to exit 2 by dispatch itself, stderr staying empty; a
55
+ // bare exit-2 handler writes its reason on stderr instead). codex's stderr bridge is codex's own native
56
+ // protocol and lives in dispatch.sh — not here.
57
+ const blocked = (r) => r.code === 2
58
+
59
+ // the human-readable rejection, extracted in contract order — never the raw wire JSON (an escaped-\\n payload
60
+ // turned the stop-gate's teaching menu into one unreadable line on one harness before this was shared):
61
+ // 1. a decision:block JSON line on stdout, strictly parsed (the designed channel);
62
+ // 2. several handlers' stdout objects can arrive GLUED without separators — regex the reason string out
63
+ // (JSON.parse of the string literal unescapes it);
64
+ // 3. stderr — the channel a bare exit-2 handler writes;
65
+ // 4. the caller's fallback.
66
+ const blockReason = (r, fallback) => {
67
+ for (const line of (r.out || "").split("\\n")) {
68
+ const s = line.trim()
69
+ if (!s.startsWith("{")) continue
70
+ try {
71
+ const o = JSON.parse(s)
72
+ if (o && o.decision === "block" && typeof o.reason === "string" && o.reason) return o.reason
73
+ } catch { /* not a lone JSON line — the glued fallback below */ }
74
+ }
75
+ if (/"decision"\\s*:\\s*"block"/.test(r.out || "")) {
76
+ const m = (r.out || "").match(/"reason"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"/)
77
+ if (m) { try { return JSON.parse('"' + m[1] + '"') } catch { /* malformed escape — fall through */ } }
78
+ }
79
+ return (r.err || "").trim() || fallback
80
+ }
81
+
82
+ // the Stop dispatch with the gate's LOOP-TERMINATION bit. Claude's native Stop payload carries
83
+ // stop_hook_active=true when the stop happens inside a continuation a Stop-hook block itself forced, and
84
+ // the stop-gate's escape paths key on exactly that bit to guarantee the loop ends (auto-declare /
85
+ // downgrade-to-ask instead of a fresh block). A generative host has no native bit, so the runtime supplies
86
+ // it: false on a natural stop, true on the settle that follows a blocked one, reset by the first allowed
87
+ // stop. Without it every settle reads as a FIRST stop and a gate that can never pass (e.g. the commit gate
88
+ // on a 0-commit worktree) blocks forever. On block, the host's inject re-enters the gate's reason as the
89
+ // continuation; an inject that cannot land is caught LOUD on stderr — never thrown into the host, never
90
+ // silent. stopPending exposes whether the
91
+ // last Stop verdict was a block still awaiting its continuation's allow — the state a host's backstop
92
+ // binding (pi's agent_settled) keys on to consume exactly one pending blocked stop, never duplicating a
93
+ // naturally-allowed dispatch.
94
+ let stopBlocked = false
95
+ const stopPending = () => stopBlocked
96
+ const dispatchStop = async (inject, fallback) => {
97
+ const r = await dispatchEvent("Stop", { stop_hook_active: stopBlocked })
98
+ if (blocked(r)) {
99
+ stopBlocked = true
100
+ try { await inject(blockReason(r, fallback)) } catch (e) {
101
+ console.error("spexcode: a blocked stop's continuation could not be re-injected: " + String(e))
102
+ }
103
+ } else stopBlocked = false
104
+ return r
105
+ }
106
+
107
+ // normalize a host tool-input onto the claude accessor shape: mirror the host's file-path spelling onto
108
+ // file_path (the key harness.sh and every claude-family handler read), dropping the host spelling.
109
+ const toolInput = (input, fileAlias) => {
110
+ const args = { ...(input && typeof input === "object" ? input : {}) }
111
+ if (fileAlias && args[fileAlias] !== undefined && args.file_path === undefined) {
112
+ args.file_path = args[fileAlias]
113
+ delete args[fileAlias]
114
+ }
115
+ return args
116
+ }
117
+
118
+ // The per-session rendezvous control socket is a best-effort same-turn poke. The timeline remains the
119
+ // message's durable copy, so this listener only receives reply lines and never confirms or rejects them.
120
+ const serveRendezvous = (inject, opts) => {
121
+ const sock = (process.env.CLAUDE_BG_RENDEZVOUS_SOCK || "").trim()
122
+ if (!sock) return null
123
+ try { __spexUnlink(sock) } catch { /* no stale socket — fine */ }
124
+ const injected = new Set()
125
+ const server = __spexCreateServer((c) => {
126
+ let buf = ""
127
+ c.on("error", () => { /* probes disconnect abruptly — expected */ })
128
+ c.on("data", (d) => {
129
+ buf += d.toString("utf8")
130
+ let nl
131
+ while ((nl = buf.indexOf("\\n")) >= 0) {
132
+ const line = buf.slice(0, nl)
133
+ buf = buf.slice(nl + 1)
134
+ let msg
135
+ try { msg = JSON.parse(line) } catch { continue }
136
+ if (msg && msg.type === "reply" && typeof msg.text === "string") {
137
+ if (opts && opts.canInject && !opts.canInject()) continue
138
+ const mid = typeof msg.mid === "string" ? msg.mid : ""
139
+ if (mid && injected.has(mid)) continue
140
+ if (mid) injected.add(mid)
141
+ try {
142
+ const p = inject(msg.text)
143
+ if (p && typeof p.catch === "function") p.catch(() => { if (mid) injected.delete(mid) })
144
+ } catch { if (mid) injected.delete(mid) }
145
+ }
146
+ }
147
+ })
148
+ })
149
+ server.on("error", (e) => console.error("spexcode: rendezvous socket failed to bind at " + sock + ": " + String(e)))
150
+ server.listen(sock)
151
+ server.unref() // never hold the host process open for our socket; the harness's own loop keeps it alive
152
+ return { close: () => {
153
+ try { server.close() } catch { /* already closed */ }
154
+ try { __spexUnlink(sock) } catch { /* already gone */ }
155
+ } }
156
+ }
157
+
158
+ return { dispatchEvent, dispatchStop, stopPending, blocked, blockReason, toolInput, serveRendezvous }
159
+ }
160
+ // ---- end spexcode shared shim runtime ----`;
161
+ }
@@ -0,0 +1,9 @@
1
+ export type SlashCommand = {
2
+ name: string;
3
+ description: string;
4
+ source: 'built-in' | 'user' | 'project' | 'skill';
5
+ };
6
+ export declare function claudeSlashCommands(): SlashCommand[];
7
+ export declare function piSlashCommands(): SlashCommand[];
8
+ export declare function codexSlashCommands(): SlashCommand[];
9
+ export declare function opencodeSlashCommands(): SlashCommand[];
@@ -0,0 +1,307 @@
1
+ import { readFileSync, readdirSync, existsSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { repoRoot } from '@spexcode/spec-core';
5
+ // captured live from `claude --dangerously-skip-permissions` v2.1.x by typing `/` and paging the dropdown;
6
+ // version-specific — re-capture this block to refresh for a new CC version (the disk-discovered sources don't).
7
+ const BUILT_IN = [
8
+ ['add-dir', 'Add a new working directory'],
9
+ ['advisor', 'Let Claude consult a stronger model at key moments'],
10
+ ['agents', 'Manage agent configurations'],
11
+ ['autofix-pr', 'Monitor and autofix any issues with the current PR'],
12
+ ['background', 'Send this session to the background and free the terminal'],
13
+ ['branch', 'Create a branch of the current conversation at this point'],
14
+ ['btw', 'Ask a quick side question without interrupting the main conversation'],
15
+ ['chrome', 'Open Claude in Chrome (beta) settings'],
16
+ ['clear', 'Start a new session with empty context; previous session stays on disk (resumable with /resume)'],
17
+ ['color', 'Set the prompt bar color for this session'],
18
+ ['compact', 'Free up context by summarizing the conversation so far'],
19
+ ['config', 'Open settings'],
20
+ ['context', 'Visualize current context usage as a colored grid'],
21
+ ['copy', "Copy Claude's last response to clipboard (or /copy N for the Nth-latest)"],
22
+ ['desktop', 'Continue the current session in Claude Desktop'],
23
+ ['diff', 'View uncommitted changes and per-turn diffs'],
24
+ ['doctor', 'Diagnose and verify your Claude Code installation and settings'],
25
+ ['effort', 'Set effort level for model usage'],
26
+ ['exit', 'Exit the CLI'],
27
+ ['export', 'Export the current conversation to a file or clipboard'],
28
+ ['fast', 'Toggle fast mode (Opus 4.8)'],
29
+ ['feedback', 'Submit feedback, report a bug, or share your conversation'],
30
+ ['focus', 'Toggle focus view: just your prompt, summary, and response'],
31
+ ['fork', 'Spawn a background agent that inherits the full conversation'],
32
+ ['goal', 'Set a goal Claude checks before stopping'],
33
+ ['help', 'Show help and available commands'],
34
+ ['hooks', 'View hook configurations for tool events'],
35
+ ['ide', 'Manage IDE integrations and show status'],
36
+ ['install-github-app', 'Set up Claude GitHub Actions for a repository'],
37
+ ['install-slack-app', 'Install the Claude Slack app'],
38
+ ['keybindings', 'Open your keyboard shortcuts file'],
39
+ ['login', 'Sign in with your Anthropic account'],
40
+ ['logout', 'Sign out from your Anthropic account'],
41
+ ['mcp', 'Manage MCP servers'],
42
+ ['memory', 'Open a memory file in your editor'],
43
+ ['mobile', 'Show QR code to download the Claude mobile app'],
44
+ ['model', 'Set the AI model for Claude Code'],
45
+ ['permissions', 'Manage allow and deny tool permission rules'],
46
+ ['plan', 'Enable plan mode or view the current session plan'],
47
+ ['plugin', 'Manage Claude Code plugins'],
48
+ ['powerup', 'Discover Claude Code features through quick interactive lessons'],
49
+ ['privacy-settings', 'View and update your privacy settings'],
50
+ ['radio', 'Listen to Claude FM lo-fi radio'],
51
+ ['recap', 'Generate a one-line session recap now'],
52
+ ['release-notes', 'View release notes'],
53
+ ['reload-plugins', 'Activate pending plugin changes in the current session'],
54
+ ['reload-skills', 'Pick up skills added or changed on disk during this session'],
55
+ ['remote-control', 'Control this session from your phone or claude.ai/code'],
56
+ ['remote-env', 'Choose the default environment for cloud agents'],
57
+ ['rename', 'Rename the current conversation'],
58
+ ['resume', 'Resume a previous conversation'],
59
+ ['rewind', 'Restore the code and/or conversation to a previous point'],
60
+ ['sandbox', 'Configure sandbox settings'],
61
+ ['skills', 'List available skills'],
62
+ ['status', 'Show Claude Code status including version, model, account, API connectivity, and tool statuses'],
63
+ ['stickers', 'Order Claude Code stickers'],
64
+ ['tasks', 'View and manage everything running in the background'],
65
+ ['teleport', 'Resume a Claude Code session from claude.ai'],
66
+ ['terminal-setup', 'Install Shift+Enter key binding for newlines'],
67
+ ['theme', 'Change the theme'],
68
+ ['tui', 'Set the terminal UI renderer (default | fullscreen)'],
69
+ ['ultraplan', 'Draft an editable plan in Claude Code on the web'],
70
+ ['ultrareview', 'Start a cloud agent that finds and verifies bugs in your branch'],
71
+ ['upgrade', 'Upgrade to Max for higher rate limits and more Opus'],
72
+ ['usage', 'Show session cost, plan usage, and activity stats'],
73
+ ['usage-credits', 'Configure usage credits to keep working when you hit a limit'],
74
+ ['voice', 'Toggle voice mode'],
75
+ ['web-setup', 'Set up Claude Code on the web with your GitHub account'],
76
+ ['workflows', 'Browse running and completed workflows'],
77
+ ];
78
+ // describe precedence (mirrors CC): a `description:` frontmatter line wins, else the first non-empty body
79
+ // line (leading `#` stripped). Frontmatter parsing is intentionally one `key: value` line.
80
+ function describe(src) {
81
+ const m = src.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
82
+ const fm = m ? m[1] : '';
83
+ const body = m ? m[2] : src;
84
+ for (const line of fm.split('\n')) {
85
+ const d = line.match(/^\s*description\s*:\s*(.+?)\s*$/);
86
+ if (d)
87
+ return d[1].replace(/^["']|["']$/g, '');
88
+ }
89
+ for (const line of body.split('\n')) {
90
+ const t = line.replace(/^#+\s*/, '').trim();
91
+ if (t)
92
+ return t;
93
+ }
94
+ return '';
95
+ }
96
+ // walk a commands/ dir; name = path under it minus `.md`, subdirs joined `a:b` (CC's namespace syntax).
97
+ function scanCommands(root, source, out) {
98
+ if (!existsSync(root))
99
+ return;
100
+ const walk = (dir) => {
101
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
102
+ const p = join(dir, e.name);
103
+ if (e.isDirectory())
104
+ walk(p);
105
+ else if (e.isFile() && e.name.endsWith('.md')) {
106
+ const name = relative(root, p).replace(/\.md$/, '').split('/').join(':');
107
+ out.push({ name, description: describe(readFileSync(p, 'utf8')), source });
108
+ }
109
+ }
110
+ };
111
+ walk(root);
112
+ }
113
+ // best-effort skills: each skill is a dir with a SKILL.md whose `name:` (or dir name) is the command.
114
+ function scanSkills(root, out) {
115
+ if (!existsSync(root))
116
+ return;
117
+ for (const e of readdirSync(root, { withFileTypes: true })) {
118
+ const skillFile = join(root, e.name, 'SKILL.md');
119
+ if (e.isDirectory() && existsSync(skillFile)) {
120
+ const src = readFileSync(skillFile, 'utf8');
121
+ const nm = src.match(/^---\n[\s\S]*?\nname\s*:\s*(.+?)\s*\n[\s\S]*?\n---/m);
122
+ out.push({ name: (nm ? nm[1] : e.name).trim(), description: describe(src), source: 'skill' });
123
+ }
124
+ }
125
+ }
126
+ // ordering mirrors CC: custom (user, then project), then built-in, then skills; alphabetical within each
127
+ // group. A same-named custom command shadows a built-in — dedupe keeps the higher-priority source.
128
+ const RANK = { user: 0, project: 1, 'built-in': 2, skill: 3 };
129
+ // dedupe by name keeping the higher-priority source, then sort by source rank then name.
130
+ function dedupeSort(all) {
131
+ const byName = new Map();
132
+ for (const c of all) {
133
+ const prev = byName.get(c.name);
134
+ if (!prev || RANK[c.source] < RANK[prev.source])
135
+ byName.set(c.name, c);
136
+ }
137
+ return [...byName.values()].sort((a, b) => RANK[a.source] - RANK[b.source] || a.name.localeCompare(b.name));
138
+ }
139
+ export function claudeSlashCommands() {
140
+ const home = homedir();
141
+ const repo = repoRoot();
142
+ const all = [];
143
+ scanCommands(join(home, '.claude', 'commands'), 'user', all);
144
+ scanCommands(join(repo, '.claude', 'commands'), 'project', all);
145
+ for (const [name, description] of BUILT_IN)
146
+ all.push({ name, description, source: 'built-in' });
147
+ scanSkills(join(home, '.claude', 'skills'), all);
148
+ scanSkills(join(repo, '.claude', 'skills'), all);
149
+ return dedupeSort(all);
150
+ }
151
+ // @@@ CODEX_BUILT_IN seed - Codex's `/` menu, taken from the codex-rs source of the pinned version
152
+ // (tui/src/slash_command.rs, codex-cli 0.142.3): the `SlashCommand` enum in PRESENTATION order with each
153
+ // `description()`. Discovered, not guessed — the same discipline as the Claude capture; to refresh for a new
154
+ // codex, re-read that enum. We drop the ones codex itself hides from a normal session: the debug-only
155
+ // (`rollout`, `test-approval`), the explicit DO-NOT-USE (`debug-m-drop`/`debug-m-update`), and the
156
+ // windows-only `sandbox-add-read-dir`. Feature-gated commands are kept (best-effort: the menu is informational).
157
+ const CODEX_BUILT_IN = [
158
+ ['model', 'choose what model and reasoning effort to use'],
159
+ ['ide', 'include current selection, open files, and other context from your IDE'],
160
+ ['permissions', 'choose what Codex is allowed to do'],
161
+ ['keymap', 'remap TUI shortcuts'],
162
+ ['vim', 'toggle Vim mode for the composer'],
163
+ ['setup-default-sandbox', 'set up elevated agent sandbox'],
164
+ ['experimental', 'toggle experimental features'],
165
+ ['approve', 'approve one retry of a recent auto-review denial'],
166
+ ['memories', 'configure memory use and generation'],
167
+ ['skills', 'use skills to improve how Codex performs specific tasks'],
168
+ ['import', 'import setup, this project, and recent chats from Claude Code'],
169
+ ['hooks', 'view and manage lifecycle hooks'],
170
+ ['review', 'review my current changes and find issues'],
171
+ ['rename', 'rename the current thread'],
172
+ ['new', 'start a new chat during a conversation'],
173
+ ['archive', 'archive this session and exit'],
174
+ ['delete', 'permanently delete this session and exit'],
175
+ ['resume', 'resume a saved chat'],
176
+ ['fork', 'fork the current chat'],
177
+ ['app', 'continue this session in Codex Desktop'],
178
+ ['init', 'create an AGENTS.md file with instructions for Codex'],
179
+ ['compact', 'summarize conversation to prevent hitting the context limit'],
180
+ ['plan', 'switch to Plan mode'],
181
+ ['goal', 'set or view the goal for a long-running task'],
182
+ ['agent', 'switch the active agent thread'],
183
+ ['side', 'start a side conversation in an ephemeral fork'],
184
+ ['btw', 'start a side conversation in an ephemeral fork'],
185
+ ['copy', 'copy last response as markdown'],
186
+ ['raw', 'toggle raw scrollback mode for copy-friendly terminal selection'],
187
+ ['diff', 'show git diff (including untracked files)'],
188
+ ['mention', 'mention a file'],
189
+ ['status', 'show current session configuration and token usage'],
190
+ ['usage', 'view account usage or use a usage limit reset'],
191
+ ['debug-config', 'show config layers and requirement sources for debugging'],
192
+ ['title', 'configure which items appear in the terminal title'],
193
+ ['statusline', 'configure which items appear in the status line'],
194
+ ['theme', 'choose a syntax highlighting theme'],
195
+ ['pets', 'choose or hide the terminal pet'],
196
+ ['mcp', 'list configured MCP tools; use /mcp verbose for details'],
197
+ ['apps', 'manage apps'],
198
+ ['plugins', 'browse plugins'],
199
+ ['logout', 'log out of Codex'],
200
+ ['quit', 'exit Codex'],
201
+ ['exit', 'exit Codex'],
202
+ ['feedback', 'send logs to maintainers'],
203
+ ['ps', 'list background terminals'],
204
+ ['stop', 'stop all background terminals'],
205
+ ['clear', 'clear the terminal and start a new chat'],
206
+ ['personality', 'choose a communication style for Codex'],
207
+ ['subagents', 'switch the active agent thread'],
208
+ ];
209
+ // @@@ codexSlashCommands - Codex's `/` menu, computed the way Codex computes its own: its built-ins (above) +
210
+ // the user's saved prompts in `$CODEX_HOME/prompts/*.md` (each filename becomes `/<name>`, codex's custom-
211
+ // prompt convention). Like the Claude builder it NEVER guesses — plugin commands that aren't readable as
212
+ // simple files contribute nothing. Presentation order: built-ins first (codex's enum order), then prompts.
213
+ // @@@ PI_BUILT_IN seed - pi's `/` menu, extracted from the INSTALLED pi's own command table
214
+ // (dist/core/slash-commands.js, @earendil-works/pi-coding-agent 0.80.10) — discovered, not guessed, same
215
+ // discipline as the claude/codex captures; to refresh for a new pi, re-read that module.
216
+ const PI_BUILT_IN = [
217
+ ['settings', 'Open settings menu'],
218
+ ['model', 'Select model (opens selector UI)'],
219
+ ['scoped-models', 'Enable/disable models for Ctrl+P cycling'],
220
+ ['export', 'Export session (HTML default, or specify path: .html/.jsonl)'],
221
+ ['import', 'Import and resume a session from a JSONL file'],
222
+ ['share', 'Share session as a secret GitHub gist'],
223
+ ['copy', 'Copy last agent message to clipboard'],
224
+ ['name', 'Set session display name'],
225
+ ['session', 'Show session info and stats'],
226
+ ['changelog', 'Show changelog entries'],
227
+ ['hotkeys', 'Show all keyboard shortcuts'],
228
+ ['fork', 'Create a new fork from a previous user message'],
229
+ ['clone', 'Duplicate the current session at the current position'],
230
+ ['tree', 'Navigate session tree (switch branches)'],
231
+ ['trust', 'Save project trust decision for future sessions'],
232
+ ['login', 'Configure provider authentication'],
233
+ ['logout', 'Remove provider authentication'],
234
+ ['new', 'Start a new session'],
235
+ ['compact', 'Manually compact the session context'],
236
+ ['resume', 'Resume a different session'],
237
+ ['reload', 'Reload keybindings, extensions, skills, prompts, themes, and context files'],
238
+ ];
239
+ // @@@ piSlashCommands - pi's `/` menu, computed the way pi computes its own: built-ins (above) + prompt
240
+ // templates (`~/.pi/agent/prompts/*.md` global, `.pi/prompts/*.md` project — each filename becomes `/<name>`)
241
+ // + skills (`/skill:<name>` is pi's spelling, but the bare name is what our dropdown wants). Best-effort like
242
+ // the codex builder: what isn't readable as simple files contributes nothing.
243
+ export function piSlashCommands() {
244
+ const repo = repoRoot();
245
+ const all = [];
246
+ for (const [name, description] of PI_BUILT_IN)
247
+ all.push({ name, description, source: 'built-in' });
248
+ scanCommands(join(homedir(), '.pi', 'agent', 'prompts'), 'user', all);
249
+ scanCommands(join(repo, '.pi', 'prompts'), 'project', all);
250
+ scanSkills(join(homedir(), '.pi', 'agent', 'skills'), all);
251
+ scanSkills(join(repo, '.pi', 'skills'), all);
252
+ return dedupeSort(all);
253
+ }
254
+ export function codexSlashCommands() {
255
+ const all = [];
256
+ for (const [name, description] of CODEX_BUILT_IN)
257
+ all.push({ name, description, source: 'built-in' });
258
+ const codexHome = process.env.CODEX_HOME || join(homedir(), '.codex');
259
+ scanCommands(join(codexHome, 'prompts'), 'user', all); // saved prompts → /<basename>
260
+ // codex built-ins keep their enum (presentation) order; user prompts sort after, alphabetical.
261
+ const seen = new Map();
262
+ const order = [];
263
+ for (const c of all) {
264
+ if (!seen.has(c.name))
265
+ order.push(c.name);
266
+ if (!seen.has(c.name) || RANK[c.source] < RANK[seen.get(c.name).source])
267
+ seen.set(c.name, c);
268
+ }
269
+ const builtins = order.filter((n) => seen.get(n).source === 'built-in').map((n) => seen.get(n));
270
+ const prompts = [...seen.values()].filter((c) => c.source !== 'built-in').sort((a, b) => a.name.localeCompare(b.name));
271
+ return [...builtins, ...prompts];
272
+ }
273
+ // opencode built-ins — a conservative pinned set (opencode 1.18.x TUI commands; its TUI registry is compiled,
274
+ // not file-discoverable, so like the other two capture blocks this is version-specific and re-pinned by hand).
275
+ const OPENCODE_BUILT_IN = [
276
+ ['compact', 'Summarize and compact the current session'],
277
+ ['editor', 'Open the external editor for the message'],
278
+ ['exit', 'Exit opencode'],
279
+ ['export', 'Export the session'],
280
+ ['help', 'Show help'],
281
+ ['init', 'Create or update AGENTS.md'],
282
+ ['models', 'List and switch models'],
283
+ ['new', 'Start a new session'],
284
+ ['redo', 'Redo a previously undone message'],
285
+ ['sessions', 'List and switch sessions'],
286
+ ['share', 'Share the current session'],
287
+ ['themes', 'List and switch themes'],
288
+ ['undo', 'Undo the last message'],
289
+ ['unshare', 'Unshare the current session'],
290
+ ];
291
+ // @@@ opencodeSlashCommands - opencode's `/` menu: the pinned built-ins + custom commands discovered the way
292
+ // opencode discovers its own — `.opencode/command(s)/**/*.md` in the project and `~/.config/opencode/command(s)`
293
+ // globally (both spellings are native). Like the other builders it never guesses: what isn't readable as a
294
+ // file contributes nothing.
295
+ export function opencodeSlashCommands() {
296
+ const all = [];
297
+ const cfgHome = process.env.OPENCODE_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode');
298
+ for (const d of ['command', 'commands'])
299
+ scanCommands(join(cfgHome, d), 'user', all);
300
+ const repo = repoRoot();
301
+ for (const d of ['command', 'commands'])
302
+ scanCommands(join(repo, '.opencode', d), 'project', all);
303
+ for (const [name, description] of OPENCODE_BUILT_IN)
304
+ all.push({ name, description, source: 'built-in' });
305
+ scanSkills(join(repo, '.opencode', 'skills'), all);
306
+ return dedupeSort(all);
307
+ }
@@ -0,0 +1,9 @@
1
+ export type SourcePolicy = {
2
+ sourceIncludeGlobs: string[] | null;
3
+ sourceExcludeGlobs: string[];
4
+ testGlobs: string[];
5
+ };
6
+ export declare const DEFAULT_TEST_GLOBS: string[];
7
+ export declare function isSourceFile(root: string, path: string, policy: SourcePolicy): boolean;
8
+ export declare function trackedSourceFiles(root: string, roots: string[], policy: SourcePolicy, tip?: string): string[];
9
+ export declare function sourcePolicyDescription(policy: SourcePolicy): string;
@@ -0,0 +1,113 @@
1
+ import { closeSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { git } from '@spexcode/spec-core';
4
+ export const DEFAULT_TEST_GLOBS = [
5
+ '**/*.test.*',
6
+ '**/*.spec.*',
7
+ '**/test_*.*',
8
+ '**/*_test.*',
9
+ '**/test/**',
10
+ '**/tests/**',
11
+ '**/__tests__/**',
12
+ ];
13
+ function globToRe(glob) {
14
+ const body = glob.split(/(\*\*\/|\*\*|\*|\?)/).map((seg) => {
15
+ if (seg === '**/')
16
+ return '(?:.*/)?';
17
+ if (seg === '**')
18
+ return '.*';
19
+ if (seg === '*')
20
+ return '[^/]*';
21
+ if (seg === '?')
22
+ return '[^/]';
23
+ return seg.replace(/[.+^${}()|[\]\\]/g, '\\$&');
24
+ }).join('');
25
+ return new RegExp(`^${body}$`);
26
+ }
27
+ function isSpexCodeData(path) {
28
+ return path === 'spexcode.json' || path === 'spexcode.local.json'
29
+ || path === '.spec' || path.startsWith('.spec/')
30
+ || path === '.plugins' || path.startsWith('.plugins/');
31
+ }
32
+ function isTextWorktreeFile(root, path) {
33
+ const full = join(root, path);
34
+ let fd = null;
35
+ try {
36
+ if (!lstatSync(full).isFile())
37
+ return false;
38
+ fd = openSync(full, 'r');
39
+ const sample = Buffer.allocUnsafe(8000);
40
+ const bytes = readSync(fd, sample, 0, sample.length, 0);
41
+ return !sample.subarray(0, bytes).includes(0);
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ finally {
47
+ if (fd !== null)
48
+ closeSync(fd);
49
+ }
50
+ }
51
+ // Source discovery classifies tracked paths and bytes only. Language structure belongs to anchors.ts's
52
+ // adapter registry; adding a language must never add a branch here.
53
+ export function isSourceFile(root, path, policy) {
54
+ if (!isSourcePath(path, policy))
55
+ return false;
56
+ return isTextWorktreeFile(root, path);
57
+ }
58
+ function isSourcePath(path, policy) {
59
+ if (isSpexCodeData(path))
60
+ return false;
61
+ if (policy.sourceIncludeGlobs !== null && !policy.sourceIncludeGlobs.some((glob) => globToRe(glob).test(path)))
62
+ return false;
63
+ if (policy.sourceExcludeGlobs.some((glob) => globToRe(glob).test(path)))
64
+ return false;
65
+ if (policy.testGlobs.some((glob) => globToRe(glob).test(path)))
66
+ return false;
67
+ return true;
68
+ }
69
+ export function trackedSourceFiles(root, roots, policy, tip = 'HEAD') {
70
+ if (tip !== 'HEAD') {
71
+ let listed = '', textOut = '';
72
+ try {
73
+ listed = git(['-C', root, '-c', 'core.quotePath=false', 'ls-tree', '-r', '-z', '-l', tip, '--', ...roots]);
74
+ textOut = git(['-C', root, '-c', 'core.quotePath=false', 'grep', '-I', '-l', '-z', '-e', '', tip, '--', ...roots]);
75
+ }
76
+ catch { /* git grep exits 1 when the tree slice has no non-empty text */ }
77
+ const text = new Set(textOut.split('\0').map((entry) => {
78
+ const prefix = `${tip}:`;
79
+ return entry.startsWith(prefix) ? entry.slice(prefix.length) : entry;
80
+ }).filter(Boolean));
81
+ const out = new Set();
82
+ for (const record of listed.split('\0')) {
83
+ if (!record)
84
+ continue;
85
+ const m = record.match(/^100\d+ blob [0-9a-f]+\s+(\d+)\t([\s\S]+)$/);
86
+ if (!m)
87
+ continue;
88
+ const path = m[2];
89
+ if (isSourcePath(path, policy) && (+m[1] === 0 || text.has(path)))
90
+ out.add(path);
91
+ }
92
+ return [...out];
93
+ }
94
+ const out = new Set();
95
+ for (const governedRoot of roots) {
96
+ let listed = '';
97
+ try {
98
+ listed = git(['-C', root, 'ls-files', '-z', '--', governedRoot]);
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ for (const path of listed.split('\0')) {
104
+ if (path && isSourceFile(root, path, policy))
105
+ out.add(path);
106
+ }
107
+ }
108
+ return [...out];
109
+ }
110
+ export function sourcePolicyDescription(policy) {
111
+ const includes = policy.sourceIncludeGlobs === null ? 'ALL tracked regular text' : `[${policy.sourceIncludeGlobs.join(', ')}]`;
112
+ return `includes ${includes}; sourceExcludeGlobs [${policy.sourceExcludeGlobs.join(', ')}]; testGlobs [${policy.testGlobs.join(', ')}] (SpexCode-owned data always excluded)`;
113
+ }
@@ -0,0 +1 @@
1
+ export {};