@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
@@ -0,0 +1 @@
1
+ export declare function commitSurgery(proj?: string): void;
@@ -0,0 +1,90 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { relative } from 'node:path';
3
+ import { materialize, stripSpexcodeBlock, GENERATED_MARK } from './materialize.js';
4
+ import { HARNESSES } from './harness.js';
5
+ import { gitBinary } from '@spexcode/spec-core';
6
+ // GIT ENV, deliberately INVERTED from git.ts's git(): every call here PRESERVES the hook's environment —
7
+ // GIT_INDEX_FILE must be honored so the surgery reads/writes the EXACT index this commit is being built
8
+ // from (a `git commit <path>` pathspec commit and `git commit -a` both run hooks against a TEMPORARY index;
9
+ // operating on the real one would silently miss them). git.ts strips that env for repo DISCOVERY reasons;
10
+ // index surgery is the one place the env is the point.
11
+ const raw = (args, input) => execFileSync(gitBinary(process.env), args, { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
12
+ function inHead(p) {
13
+ try {
14
+ raw(['cat-file', '-e', `HEAD:${p}`]);
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ function stagedBlob(p) {
22
+ try {
23
+ return raw(['show', `:${p}`]);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ function evict(p, why) {
30
+ raw(['update-index', '--force-remove', '--', p]);
31
+ console.error(`spexcode: unstaged ${p} (${why} — generated artifacts are never tracked; the file stays on disk)`);
32
+ }
33
+ function replaceBlob(p, content) {
34
+ const stage = raw(['ls-files', '--stage', '--', p]).trim(); // "100644 <sha> 0\t<p>"
35
+ const mode = stage.split(/\s/)[0] || '100644';
36
+ const sha = raw(['hash-object', '-w', '--stdin'], content).trim();
37
+ raw(['update-index', '--cacheinfo', `${mode},${sha},${p}`]);
38
+ console.error(`spexcode: stripped the <!-- spexcode --> block from staged ${p} (the block is working-tree context, never history)`);
39
+ }
40
+ export function commitSurgery(proj = process.cwd()) {
41
+ // (1) unconditional materialize — machine-fixable state (exclude entries, filter binding, kind flips)
42
+ // is repaired BEFORE the index is inspected, so the inspection below judges against fresh masks.
43
+ try {
44
+ materialize(proj);
45
+ }
46
+ catch (e) {
47
+ console.error(`spexcode: pre-commit materialize failed (${e.message}) — footprint may be stale this commit`);
48
+ }
49
+ const staged = raw(['diff', '--cached', '--name-only', '-z']).split('\0').filter(Boolean);
50
+ if (!staged.length)
51
+ return;
52
+ const rel = (f) => relative(proj, f);
53
+ const contracts = new Set(HARNESSES.flatMap((h) => h.contractFiles(proj)).map(rel));
54
+ const machine = new Set(['spexcode.local.json', '.session']);
55
+ for (const h of HARNESSES) {
56
+ machine.add(rel(h.shimFile(proj)));
57
+ const a = h.worktreeHookAnchor(proj);
58
+ if (a)
59
+ machine.add(rel(a));
60
+ }
61
+ const generatedDirs = HARNESSES.flatMap((h) => [h.skillDir(proj), h.agentDir(proj)])
62
+ .filter((d) => !!d).map((d) => `${rel(d)}/`);
63
+ for (const p of staged) {
64
+ if (contracts.has(p)) {
65
+ const blob = stagedBlob(p);
66
+ if (blob === null)
67
+ continue;
68
+ const stripped = stripSpexcodeBlock(blob);
69
+ if (stripped === blob)
70
+ continue; // no block staged — clean already did its job
71
+ if (!stripped.trim() && !inHead(p))
72
+ evict(p, 'wholly a spexcode materialized artifact');
73
+ else
74
+ replaceBlob(p, stripped);
75
+ }
76
+ else if (machine.has(p) || p.startsWith('.worktrees/')) {
77
+ if (!inHead(p))
78
+ evict(p, 'a machine-local spexcode file');
79
+ else
80
+ console.error(`spexcode: ${p} is a machine-local spexcode file but HEAD already tracks it — not touching a tracked file; untrack it yourself (git rm --cached ${p})`);
81
+ }
82
+ else if (generatedDirs.some((d) => p.startsWith(d))) {
83
+ if (inHead(p))
84
+ continue; // historically tracked — the host's call
85
+ const blob = stagedBlob(p);
86
+ if (blob !== null && blob.includes(GENERATED_MARK))
87
+ evict(p, 'a generated skill/agent artifact');
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,14 @@
1
+ export type ContractFilterPayload = {
2
+ file: string;
3
+ content: string;
4
+ };
5
+ export type ContractFilterBinding = {
6
+ file: string;
7
+ start: string;
8
+ end: string;
9
+ };
10
+ export declare function plantContractFilter(proj: string, payloads: ContractFilterPayload[], bindings: ContractFilterBinding[], changedFiles?: readonly string[]): boolean;
11
+ export declare function settleIndexStat(proj: string, files: string[]): void;
12
+ export declare function clearContractFilterPayload(proj: string, files?: string[]): void;
13
+ export declare function removeContractFilter(proj: string, files?: string[], final?: boolean): void;
14
+ export declare function contractFilterPlanted(proj: string): boolean;
@@ -0,0 +1,219 @@
1
+ import { mkdirSync, readFileSync, rmSync, chmodSync, existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { git, gitBinary } from '@spexcode/spec-core';
5
+ import { writeManagedBlock, removeManagedBlock } from './harness.js';
6
+ import { encodeProject, runtimeRoot, treeSlotDir } from '@spexcode/spec-core';
7
+ import { writeFileIfChanged } from './file-write.js';
8
+ // the three field-sharpened edges this module owes ([[content-filter]]):
9
+ // ① the configured command points at a STABLE shim path and degrades to `cat` (identity) when the shim is
10
+ // missing — a bare missing filter command makes git spray "cannot fork" fatals on EVERY operation;
11
+ // ② a changed contract does NOT propagate by itself (git re-smudges only on checkout) — materialize's
12
+ // re-materialize writes the managed block straight into the working file (writeManagedBlock IS the re-smudge),
13
+ // and this module refreshes the block file the shim reads so future checkouts agree;
14
+ // ③ unplanting must strip the block from the WORKING FILES before the config goes away, or the block
15
+ // residue surfaces as an uncommitted modification — the caller (dematerialize) removes the managed
16
+ // blocks first and only then calls removeContractFilter.
17
+ function commonDirOf(proj) {
18
+ return git(['-C', proj, 'rev-parse', '--path-format=absolute', '--git-common-dir']).trim();
19
+ }
20
+ const filterDir = (common) => join(common, 'spexcode');
21
+ const shimPath = (common) => join(filterDir(common), 'contract-filter.sh');
22
+ const rootPath = (common) => join(filterDir(common), 'contract-filter-root');
23
+ const bindingsPath = (common) => join(filterDir(common), 'contract-filter-bindings');
24
+ const treeFilterDir = (proj) => join(treeSlotDir(proj), 'contract-filter');
25
+ const attributesPath = (common) => join(common, 'info', 'attributes');
26
+ // The common shim both filter directions run through. Pure shell/awk (no node boot on git's hot path), it
27
+ // resolves the invoking checkout to that tree's payload before mirroring managed-block normalization:
28
+ // clean : drop the sentinel block (+ the blank line smudge printed before it) → the pristine host prose.
29
+ // smudge: clean first (a block already in the index can never double-inject), then append the tree payload.
30
+ // Byte-exactness holds for text ending in exactly one newline (git's own well-formed-text shape); a pristine
31
+ // file ending in zero or 2+ newlines is normalized to one on the first round-trip and stable after.
32
+ const SHIM = `#!/usr/bin/env bash
33
+ # spexcode managed-text filter (generated by spex materialize; see [[content-filter]]).
34
+ # One common driver selects the payload belonging to the Git checkout that invoked it.
35
+ set -u
36
+ mode="\${1:?usage: contract-filter.sh smudge|clean <path>}"
37
+ path="\${2:?usage: contract-filter.sh smudge|clean <path>}"
38
+ here="$(cd "$(dirname "\${BASH_SOURCE[0]}")" && pwd)"
39
+ binding="$(awk -F '\t' -v p="$path" '$1 == p { print $2 "\t" $3; exit }' "$here/contract-filter-bindings" 2>/dev/null)"
40
+ [ -n "$binding" ] || { cat; exit 0; }
41
+ start="\${binding%%$'\t'*}"; rest="\${binding#*$'\t'}"
42
+ end="$rest"
43
+ top="$(git rev-parse --show-toplevel 2>/dev/null || true)"
44
+ root="$(cat "$here/contract-filter-root" 2>/dev/null || true)"
45
+ key="$(printf '%s' "$top" | sed 's#[/.]#-#g')"
46
+ manifest="$root/trees/$key/contract-filter/manifest"
47
+ payload="$(awk -F '\t' -v p="$path" '$1 == p { print $2; exit }' "$manifest" 2>/dev/null)"
48
+ strip() {
49
+ awk -v sline="$start" -v eline="$end" 'BEGIN { n = 0 }
50
+ { lines[n++] = $0 }
51
+ END {
52
+ s = -1; e = -1
53
+ for (i = 0; i < n; i++) {
54
+ if (lines[i] == sline && s < 0) s = i
55
+ if (lines[i] == eline && s >= 0 && e < 0) e = i
56
+ }
57
+ if (s >= 0 && e >= s) {
58
+ a = s; while (a > 0 && lines[a-1] == "") a--
59
+ b = e; while (b + 1 < n && lines[b+1] == "") b++
60
+ j = 0
61
+ for (i = 0; i < n; i++) if (i < a || i > b) lines[j++] = lines[i]
62
+ n = j
63
+ }
64
+ for (i = 0; i < n; i++) print lines[i]
65
+ }'
66
+ }
67
+ case "$mode" in
68
+ clean) strip ;;
69
+ smudge)
70
+ if [ ! -r "$payload" ]; then strip; exit 0; fi
71
+ strip | awk -v b="$payload" -v sline="$start" -v eline="$end" 'BEGIN { n = 0 }
72
+ { lines[n++] = $0 }
73
+ END {
74
+ while (n > 0 && lines[n-1] == "") n--
75
+ for (i = 0; i < n; i++) print lines[i]
76
+ if (n > 0) print ""
77
+ print sline
78
+ while ((getline l < b) > 0) print l
79
+ print eline
80
+ }' ;;
81
+ *) echo "contract-filter.sh: unknown mode $mode" >&2; exit 1 ;;
82
+ esac
83
+ `;
84
+ // edge ①: the command git runs is a tolerant wrapper — the shim path is an ARGUMENT ($0), and a missing/
85
+ // unreadable shim degrades to `cat` (identity) instead of a per-operation fatal.
86
+ const filterCmd = (shim, mode) => `sh -c 'test -r "$0" && exec bash "$0" ${mode} "$1" || exec cat' '${shim.replace(/'/g, `'\\''`)}' %f`;
87
+ // plant (or refresh) the filter for the given contract files (tracked, or untracked-with-host-content —
88
+ // pre-armed): the shim + the block content it smudges, the per-clone git config, and the attribute lines
89
+ // binding each file to the filter. `contract` is the assembled block body (guide + surface:system).
90
+ // settleIndexStat skips untracked entries (no index blob) by design and only runs after a real filter change.
91
+ export function plantContractFilter(proj, payloads, bindings, changedFiles = []) {
92
+ const common = commonDirOf(proj);
93
+ mkdirSync(filterDir(common), { recursive: true });
94
+ let changed = writeFileIfChanged(shimPath(common), SHIM);
95
+ if (changed || (statSync(shimPath(common)).mode & 0o777) !== 0o755)
96
+ chmodSync(shimPath(common), 0o755);
97
+ const commands = new Map([
98
+ ['filter.spexcode.smudge', filterCmd(shimPath(common), 'smudge')],
99
+ ['filter.spexcode.clean', filterCmd(shimPath(common), 'clean')],
100
+ ]);
101
+ const configured = new Map();
102
+ try {
103
+ for (const row of git(['-C', proj, 'config', '--get-regexp', '^filter\\.spexcode\\.(smudge|clean)$']).trimEnd().split('\n')) {
104
+ const at = row.indexOf(' ');
105
+ if (at > 0)
106
+ configured.set(row.slice(0, at), row.slice(at + 1));
107
+ }
108
+ }
109
+ catch { }
110
+ for (const [key, command] of commands) {
111
+ if (configured.get(key) === command)
112
+ continue;
113
+ git(['-C', proj, 'config', key, command]);
114
+ changed = true;
115
+ }
116
+ changed = writeFileIfChanged(bindingsPath(common), bindings.map((b) => `${b.file}\t${b.start}\t${b.end}`).join('\n') + '\n') || changed;
117
+ const dir = treeFilterDir(proj);
118
+ mkdirSync(dir, { recursive: true });
119
+ const manifest = [];
120
+ const wanted = new Set(['manifest']);
121
+ for (const [i, payload] of payloads.entries()) {
122
+ const target = join(dir, String(i));
123
+ wanted.add(String(i));
124
+ changed = writeFileIfChanged(target, payload.content.endsWith('\n') ? payload.content : `${payload.content}\n`) || changed;
125
+ manifest.push(`${payload.file}\t${target}`);
126
+ }
127
+ for (const entry of readdirSync(dir)) {
128
+ if (!wanted.has(entry)) {
129
+ rmSync(join(dir, entry), { recursive: true, force: true });
130
+ changed = true;
131
+ }
132
+ }
133
+ const manifestPath = join(dir, 'manifest');
134
+ changed = writeFileIfChanged(manifestPath, manifest.join('\n') + (manifest.length ? '\n' : '')) || changed;
135
+ changed = writeFileIfChanged(rootPath(common), `${runtimeRoot(proj)}\n`) || changed;
136
+ // Attribute patterns are checkout-relative; the stable binding set is safe in the common git dir because
137
+ // the driver selects a payload from the invoking checkout's tree slot.
138
+ const entries = bindings.map((b) => `/${b.file} filter=spexcode`).sort().join('\n');
139
+ mkdirSync(join(common, 'info'), { recursive: true });
140
+ changed = writeManagedBlock(attributesPath(common), entries, ['# ', '']) || changed;
141
+ const settle = changed ? payloads.map((p) => join(proj, p.file)) : changedFiles;
142
+ if (settle.length)
143
+ settleIndexStat(proj, [...new Set(settle)]);
144
+ return changed;
145
+ }
146
+ // settle the index STAT for each file — the famous filtered-path phantom-`M`: git cannot verify a
147
+ // clean-filtered path by stat alone (worktree size ≠ blob size by design), and `git status` reports such an
148
+ // entry modified FOREVER without ever content-checking it (field-verified on git 2.43; `git diff` meanwhile
149
+ // runs the filter and shows nothing; even `update-index --really-refresh` leaves it). The block-strip side of
150
+ // a mode switch/backout leaves the same stale stat on the then-unfiltered path. `git add --renormalize`
151
+ // re-cleans the file and refreshes the cached stat — run ONLY when the (possibly filtered) worktree already
152
+ // EQUALS the index blob, so it is a pure stat refresh that can never stage a user's real unstaged edit (a
153
+ // genuine edit keeps its honest `M`). Exported for dematerialize (the unplant side); plant calls it below.
154
+ // Best-effort: an unsettled stat is cosmetic noise, never corruption.
155
+ export function settleIndexStat(proj, files) {
156
+ const env = { ...process.env };
157
+ delete env.GIT_DIR;
158
+ delete env.GIT_WORK_TREE;
159
+ delete env.GIT_INDEX_FILE;
160
+ delete env.GIT_OBJECT_DIRECTORY;
161
+ for (const f of files) {
162
+ const rel = relative(proj, f);
163
+ try {
164
+ const indexBlob = git(['-C', proj, 'rev-parse', `:${rel}`]).trim();
165
+ const filtered = execFileSync(gitBinary(env), ['-C', proj, 'hash-object', '--path', rel, '--stdin'], { input: readFileSync(f), env, stdio: ['pipe', 'pipe', 'ignore'] }).toString().trim();
166
+ if (indexBlob === filtered)
167
+ git(['-C', proj, 'add', '--renormalize', '--', rel]);
168
+ }
169
+ catch { /* best-effort */ }
170
+ }
171
+ }
172
+ // the full inverse (edge ③ — call AFTER the managed blocks left the working files): attribute lines out,
173
+ // config keys unset, shim + block content removed. `<common>/spexcode/` may host other spexcode data
174
+ // (evidence blobs), so only OUR two files go, never the dir.
175
+ export function clearContractFilterPayload(proj, files = []) {
176
+ try {
177
+ rmSync(treeFilterDir(proj), { recursive: true, force: true });
178
+ }
179
+ catch { /* inaccessible tree */ }
180
+ settleIndexStat(proj, files);
181
+ }
182
+ export function removeContractFilter(proj, files = [], final = false) {
183
+ let common;
184
+ try {
185
+ common = commonDirOf(proj);
186
+ }
187
+ catch {
188
+ return;
189
+ } // not a git repo → nothing was ever planted
190
+ clearContractFilterPayload(proj, files);
191
+ const anotherPayload = final ? false : (() => {
192
+ const rows = git(['-C', proj, 'worktree', 'list', '--porcelain', '-z']).split('\0');
193
+ const root = runtimeRoot(proj);
194
+ return rows
195
+ .filter((row) => row.startsWith('worktree '))
196
+ .map((row) => row.slice('worktree '.length))
197
+ .some((tree) => existsSync(join(root, 'trees', encodeProject(tree), 'contract-filter', 'manifest')));
198
+ })();
199
+ if (!final && anotherPayload)
200
+ return;
201
+ removeManagedBlock(attributesPath(common), ['# ', ''], true);
202
+ for (const key of ['filter.spexcode.smudge', 'filter.spexcode.clean']) {
203
+ try {
204
+ git(['-C', proj, 'config', '--unset-all', key]);
205
+ }
206
+ catch { /* not set — already clean */ }
207
+ }
208
+ for (const path of [shimPath(common), rootPath(common), bindingsPath(common)])
209
+ rmSync(path, { force: true });
210
+ }
211
+ // is the filter currently planted? (the assert-side probe tests use; cheap: one config read)
212
+ export function contractFilterPlanted(proj) {
213
+ try {
214
+ return git(['-C', proj, 'config', 'filter.spexcode.clean']).trim().length > 0;
215
+ }
216
+ catch {
217
+ return false;
218
+ }
219
+ }
@@ -0,0 +1,6 @@
1
+ export type DashboardArtifact = 'dist' | 'dist-public';
2
+ export declare class DashboardAssetError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export declare function dashboardArtifactDir(artifact: DashboardArtifact): string;
6
+ export declare function ensureDashboardArtifact(artifact: DashboardArtifact): string;
@@ -0,0 +1,50 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join } from 'node:path';
5
+ export class DashboardAssetError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'DashboardAssetError';
9
+ }
10
+ }
11
+ const PACKAGE = '@spexcode/spec-dashboard';
12
+ const INSTALL = `npm install ${PACKAGE}`;
13
+ function dashboardRoot() {
14
+ try {
15
+ return dirname(createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`));
16
+ }
17
+ catch {
18
+ throw new DashboardAssetError(`dashboard UI is not installed (${PACKAGE}). Install it with: ${INSTALL}`);
19
+ }
20
+ }
21
+ // Dashboard assets belong to the dashboard package. Resolving its manifest handles both an npm dependency
22
+ // and a workspace link without teaching CLI code where either layout happens to live.
23
+ export function dashboardArtifactDir(artifact) {
24
+ const root = dashboardRoot();
25
+ const dir = join(root, artifact);
26
+ if (existsSync(join(dir, 'index.html')))
27
+ return dir;
28
+ const repair = existsSync(join(root, 'src'))
29
+ ? `build the dashboard package before running this command`
30
+ : `reinstall ${PACKAGE}`;
31
+ throw new DashboardAssetError(`dashboard UI package is incomplete: missing ${artifact}/index.html at ${root}. To repair, ${repair}.`);
32
+ }
33
+ export function ensureDashboardArtifact(artifact) {
34
+ try {
35
+ return dashboardArtifactDir(artifact);
36
+ }
37
+ catch (error) {
38
+ if (!(error instanceof DashboardAssetError))
39
+ throw error;
40
+ const root = dashboardRoot();
41
+ if (!existsSync(join(root, 'src')))
42
+ throw error;
43
+ const script = artifact === 'dist' ? 'build' : 'build:public';
44
+ console.log(`[dashboard] ${artifact} is not built — running npm run ${script} in ${PACKAGE}…`);
45
+ const result = spawnSync('npm', ['run', script], { cwd: root, stdio: 'inherit' });
46
+ if (result.status === 0)
47
+ return dashboardArtifactDir(artifact);
48
+ throw new DashboardAssetError(`dashboard UI build failed for ${PACKAGE}. Repair it with: (cd ${root} && npm run ${script})`);
49
+ }
50
+ }
@@ -0,0 +1,23 @@
1
+ export type PendingMessage = {
2
+ mid: string;
3
+ text: string;
4
+ from: string | null;
5
+ dispatch?: {
6
+ operation: 'merge';
7
+ requestDigest: string;
8
+ };
9
+ };
10
+ export declare function revokeSenderDelivery(id: string): void;
11
+ export declare const senderDeliveryRevoked: (id: string) => boolean;
12
+ export declare function pendingSnapshot(id: string): PendingMessage[];
13
+ export declare function replacePendingWhileLocked(id: string, msgs: PendingMessage[]): void;
14
+ export declare function revokePendingFromWhileLocked(id: string, sender: string): number;
15
+ export declare function enqueue(id: string, msg: PendingMessage): void;
16
+ export declare function ensurePendingWhileLocked(id: string, msg: PendingMessage): boolean;
17
+ export declare const pendingMessages: (id: string) => PendingMessage[];
18
+ export declare const owesDelivery: (id: string) => boolean;
19
+ export declare function withDeliveryLocks<T>(rawIds: string[], body: () => Promise<T>, index?: number, ids?: string[]): Promise<T>;
20
+ export declare function drain(id: string, insert: (msg: PendingMessage) => Promise<boolean>, timeoutMs?: number): Promise<{
21
+ delivered: number;
22
+ remaining: number;
23
+ }>;
@@ -0,0 +1,179 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { runtimeRoot, sessionArtifactPath, sessionStoreDir } from '@spexcode/spec-core';
4
+ const queuePath = (id) => sessionArtifactPath(id, 'pending.json');
5
+ const revokedSenderRoot = () => join(runtimeRoot(), '.revoked-senders');
6
+ const revokedSenderPath = (id) => join(revokedSenderRoot(), id);
7
+ // @@@ its own lock, deliberately NOT the record lock - the drain holds this across the adapter insert, which
8
+ // is what makes "claim" real: two processes draining the same session cannot both hand over one message. The
9
+ // record lock could never span that call — a native turn runs lifecycle hooks that re-enter the record writer,
10
+ // and holding it there deadlocks the adapter's own confirmation. Nothing in the delivery path takes this one,
11
+ // so spanning the insert costs no contention. PID liveness reclaims a lock whose holder died mid-insert.
12
+ const lockRoot = () => join(runtimeRoot(), '.delivery-locks');
13
+ const lockPath = (id) => join(lockRoot(), `${id}.lock`);
14
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
15
+ async function acquire(id, timeoutMs) {
16
+ mkdirSync(lockRoot(), { recursive: true });
17
+ const path = lockPath(id), deadline = Date.now() + timeoutMs;
18
+ for (;;) {
19
+ try {
20
+ const fd = openSync(path, 'wx');
21
+ writeSync(fd, String(process.pid));
22
+ closeSync(fd);
23
+ return () => { try {
24
+ unlinkSync(path);
25
+ }
26
+ catch { /* a liveness reclaim already removed it */ } };
27
+ }
28
+ catch (e) {
29
+ if (e.code !== 'EEXIST')
30
+ throw e;
31
+ let owner = 0;
32
+ try {
33
+ owner = Number(readFileSync(path, 'utf8').trim()) || 0;
34
+ }
35
+ catch { /* race with creator/releaser */ }
36
+ if (owner && owner !== process.pid) {
37
+ try {
38
+ process.kill(owner, 0);
39
+ }
40
+ catch {
41
+ try {
42
+ unlinkSync(path);
43
+ }
44
+ catch { /* race */ }
45
+ ;
46
+ continue;
47
+ }
48
+ }
49
+ // A drain is never urgent enough to fight for: whoever holds the lock is delivering these same messages,
50
+ // and the retry sweep will come back. Declining is not a lost message.
51
+ if (Date.now() >= deadline)
52
+ return null;
53
+ await pause(25);
54
+ }
55
+ }
56
+ }
57
+ function read(id) {
58
+ try {
59
+ const raw = JSON.parse(readFileSync(queuePath(id), 'utf8'));
60
+ if (!Array.isArray(raw))
61
+ return [];
62
+ return raw.filter((m) => !!m && typeof m === 'object'
63
+ && typeof m.mid === 'string'
64
+ && typeof m.text === 'string'
65
+ && (m.dispatch === undefined
66
+ || (m.dispatch?.operation === 'merge'
67
+ && typeof m.dispatch?.requestDigest === 'string')));
68
+ }
69
+ catch {
70
+ return [];
71
+ } // absent, empty, or unparseable all mean the honest thing: nothing owed
72
+ }
73
+ // Written whole and atomically; an empty queue is REMOVED rather than left as `[]`, so "is anything owed?" is
74
+ // one existsSync on the sweep's hot path.
75
+ function write(id, msgs) {
76
+ const path = queuePath(id);
77
+ if (!msgs.length) {
78
+ try {
79
+ unlinkSync(path);
80
+ }
81
+ catch { /* already gone */ }
82
+ ;
83
+ return;
84
+ }
85
+ mkdirSync(sessionStoreDir(id), { recursive: true });
86
+ const tmp = `${path}.${process.pid}.tmp`;
87
+ writeFileSync(tmp, JSON.stringify(msgs, null, 2) + '\n');
88
+ renameSync(tmp, path);
89
+ }
90
+ // A closed sender may have left debt in many other sessions' queues. The marker is deliberately outside its
91
+ // own store (which close removes) and is checked under the sender's record lock by dispatch: a close cannot
92
+ // return while an old process can still append, and a later sweep cannot hand over what it sees here.
93
+ export function revokeSenderDelivery(id) {
94
+ mkdirSync(revokedSenderRoot(), { recursive: true });
95
+ writeFileSync(revokedSenderPath(id), `${id}\n`);
96
+ }
97
+ export const senderDeliveryRevoked = (id) => existsSync(revokedSenderPath(id));
98
+ export function pendingSnapshot(id) { return read(id); }
99
+ // These two writes require the target's delivery lock. They are the queue half of a larger transaction
100
+ // (currently reparent), which must be able to restore the exact previous debt if a later record write fails.
101
+ export function replacePendingWhileLocked(id, msgs) { write(id, msgs); }
102
+ export function revokePendingFromWhileLocked(id, sender) {
103
+ const current = read(id);
104
+ const next = current.filter((msg) => msg.from !== sender);
105
+ write(id, next);
106
+ return current.length - next.length;
107
+ }
108
+ // The enqueue rides the timeline append ([[dispatch]]): the caller holds the session's RECORD lock across
109
+ // both, and the record is written first, so delivery is never unrecorded. A keyed dispatch also carries its
110
+ // exact delivery bytes in the timeline receipt, letting its retry restore a queue write lost to a crash.
111
+ export function enqueue(id, msg) {
112
+ write(id, [...read(id), msg]);
113
+ }
114
+ // Caller holds this target's delivery lock. A retry may reach this after either side of the receipt->queue
115
+ // crash boundary; exact mid identity makes reconstruction idempotent without inspecting message text.
116
+ export function ensurePendingWhileLocked(id, msg) {
117
+ const current = read(id);
118
+ if (current.some((pending) => pending.mid === msg.mid))
119
+ return false;
120
+ write(id, [...current, msg]);
121
+ return true;
122
+ }
123
+ export const pendingMessages = (id) => read(id);
124
+ export const owesDelivery = (id) => existsSync(queuePath(id));
125
+ // Record transitions and queue mutations take locks in the same direction: record locks first, then these
126
+ // target queue locks. A batch reparent needs all child queues held at once so its pointer/watch/debt change
127
+ // either commits together or restores together.
128
+ export async function withDeliveryLocks(rawIds, body, index = 0, ids = [...new Set(rawIds)].sort()) {
129
+ if (index >= ids.length)
130
+ return body();
131
+ const release = await acquire(ids[index], 30_000);
132
+ if (!release)
133
+ throw new Error(`delivery queue ${ids[index]}: timed out waiting for transaction lock`);
134
+ try {
135
+ return await withDeliveryLocks(ids, body, index + 1, ids);
136
+ }
137
+ finally {
138
+ release();
139
+ }
140
+ }
141
+ // Hand over what is owed, in order, exactly once. `insert` reports whether the adapter took the message: only
142
+ // then is the entry dropped. A refusal ENDS the pass with that entry still queued and everything behind it
143
+ // still behind it — order is a property of a conversation, so a message is never skipped to deliver a later
144
+ // one. Returns how many were handed over and how many are still owed.
145
+ export async function drain(id, insert, timeoutMs = 5_000) {
146
+ const release = await acquire(id, timeoutMs);
147
+ if (!release)
148
+ return { delivered: 0, remaining: read(id).length };
149
+ let delivered = 0;
150
+ try {
151
+ for (;;) {
152
+ const queued = read(id);
153
+ if (!queued.length)
154
+ return { delivered, remaining: 0 };
155
+ if (queued[0].from && senderDeliveryRevoked(queued[0].from)) {
156
+ // Closing a sender voids its undelivered output, not the recipient's immutable conversation history.
157
+ // Drop a revoked head and continue so it cannot permanently block the messages behind it.
158
+ write(id, read(id).filter((m) => m.mid !== queued[0].mid));
159
+ continue;
160
+ }
161
+ let ok = false;
162
+ try {
163
+ ok = await insert(queued[0]);
164
+ }
165
+ catch {
166
+ ok = false;
167
+ }
168
+ if (!ok)
169
+ return { delivered, remaining: queued.length };
170
+ // Re-read before removing: a send that landed while this pass ran appended to the tail, and rewriting a
171
+ // stale snapshot minus the head would silently drop it.
172
+ write(id, read(id).filter((m) => m.mid !== queued[0].mid));
173
+ delivered++;
174
+ }
175
+ }
176
+ finally {
177
+ release();
178
+ }
179
+ }
@@ -0,0 +1,9 @@
1
+ export type HealthFinding = {
2
+ check: string;
3
+ spec: string;
4
+ summary: string;
5
+ evidence: string[];
6
+ repair: string;
7
+ };
8
+ export declare function specHealthDiagnosis(root: string): Promise<HealthFinding[]>;
9
+ export declare function runDoctor(args: string[]): Promise<number>;