taskquoin 0.0.0-stage → 2026.12.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 (160) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/LICENSE +55 -0
  3. package/README.md +227 -2
  4. package/SECURITY.md +26 -0
  5. package/adapters/git/src/git.js +250 -0
  6. package/adapters/git/src/index.js +1 -0
  7. package/adapters/hooks-claude/src/canonical.js +45 -0
  8. package/adapters/hooks-claude/src/index.js +2 -0
  9. package/adapters/hooks-claude/src/main.js +58 -0
  10. package/adapters/hooks-claude/src/payload.js +40 -0
  11. package/adapters/host-probe/src/index.js +2 -0
  12. package/adapters/host-probe/src/ollama.js +18 -0
  13. package/adapters/host-probe/src/probe.js +107 -0
  14. package/adapters/local-tool/src/fingerprint.js +56 -0
  15. package/adapters/local-tool/src/index.js +4 -0
  16. package/adapters/local-tool/src/local-tool.js +22 -0
  17. package/adapters/local-tool/src/sandboxed.js +105 -0
  18. package/adapters/local-tool/src/scan.js +52 -0
  19. package/adapters/memory-claude-mem/src/claude-mem.js +115 -0
  20. package/adapters/memory-claude-mem/src/index.js +1 -0
  21. package/adapters/process-runner/src/index.js +1 -0
  22. package/adapters/process-runner/src/runner.js +123 -0
  23. package/adapters/runtime-api/src/capabilities.json +116 -0
  24. package/adapters/runtime-api/src/executor.js +131 -0
  25. package/adapters/runtime-api/src/index.js +1 -0
  26. package/adapters/runtime-claude/src/capabilities.json +375 -0
  27. package/adapters/runtime-claude/src/command.js +34 -0
  28. package/adapters/runtime-claude/src/executor.js +162 -0
  29. package/adapters/runtime-claude/src/index.js +4 -0
  30. package/adapters/runtime-claude/src/permissions.js +76 -0
  31. package/adapters/runtime-claude/src/stream.js +60 -0
  32. package/adapters/runtime-codex/src/capabilities.json +192 -0
  33. package/adapters/runtime-codex/src/command.js +36 -0
  34. package/adapters/runtime-codex/src/executor.js +83 -0
  35. package/adapters/runtime-codex/src/index.js +4 -0
  36. package/adapters/runtime-codex/src/scratch.js +32 -0
  37. package/adapters/runtime-codex/src/stream.js +39 -0
  38. package/adapters/runtime-opencode/src/capabilities.json +149 -0
  39. package/adapters/runtime-opencode/src/config.js +33 -0
  40. package/adapters/runtime-opencode/src/credentials.js +130 -0
  41. package/adapters/runtime-opencode/src/executor.js +127 -0
  42. package/adapters/runtime-opencode/src/facts.js +43 -0
  43. package/adapters/runtime-opencode/src/hosts.js +16 -0
  44. package/adapters/runtime-opencode/src/hosts.json +3 -0
  45. package/adapters/runtime-opencode/src/index.js +6 -0
  46. package/adapters/runtime-opencode/src/mounts.js +58 -0
  47. package/adapters/runtime-opencode/src/stream.js +63 -0
  48. package/adapters/skill-store/src/index.js +1 -0
  49. package/adapters/skill-store/src/skill-store.js +162 -0
  50. package/adapters/store-fs/src/index.js +2 -0
  51. package/adapters/store-fs/src/store.js +201 -0
  52. package/adapters/store-fs/src/trusted-dir.js +37 -0
  53. package/apps/cli/src/console.js +432 -0
  54. package/apps/cli/src/dashboard-approve.js +259 -0
  55. package/apps/cli/src/dashboard-data.js +424 -0
  56. package/apps/cli/src/dashboard.js +500 -0
  57. package/apps/cli/src/history.js +35 -0
  58. package/apps/cli/src/home.js +18 -0
  59. package/apps/cli/src/i18n/en.js +527 -0
  60. package/apps/cli/src/i18n/index.js +90 -0
  61. package/apps/cli/src/i18n/languages.js +25 -0
  62. package/apps/cli/src/i18n/locales/ar.json +526 -0
  63. package/apps/cli/src/i18n/locales/de.json +505 -0
  64. package/apps/cli/src/i18n/locales/es.json +505 -0
  65. package/apps/cli/src/i18n/locales/fa.json +505 -0
  66. package/apps/cli/src/i18n/locales/fr.json +505 -0
  67. package/apps/cli/src/i18n/locales/he.json +505 -0
  68. package/apps/cli/src/i18n/locales/hi.json +505 -0
  69. package/apps/cli/src/i18n/locales/id.json +491 -0
  70. package/apps/cli/src/i18n/locales/it.json +505 -0
  71. package/apps/cli/src/i18n/locales/ja.json +491 -0
  72. package/apps/cli/src/i18n/locales/ko.json +491 -0
  73. package/apps/cli/src/i18n/locales/nl.json +505 -0
  74. package/apps/cli/src/i18n/locales/pl.json +512 -0
  75. package/apps/cli/src/i18n/locales/pt-BR.json +505 -0
  76. package/apps/cli/src/i18n/locales/ru.json +512 -0
  77. package/apps/cli/src/i18n/locales/th.json +491 -0
  78. package/apps/cli/src/i18n/locales/tr.json +505 -0
  79. package/apps/cli/src/i18n/locales/uk.json +512 -0
  80. package/apps/cli/src/i18n/locales/vi.json +491 -0
  81. package/apps/cli/src/i18n/locales/zh-CN.json +491 -0
  82. package/apps/cli/src/i18n/locales/zh-TW.json +491 -0
  83. package/apps/cli/src/i18n/width.js +40 -0
  84. package/apps/cli/src/layout.js +18 -0
  85. package/apps/cli/src/main.js +830 -0
  86. package/apps/cli/src/preferences.js +46 -0
  87. package/apps/cli/src/runtime-notices.js +41 -0
  88. package/apps/cli/src/safe-text.js +3 -0
  89. package/apps/cli/src/shortcut.js +82 -0
  90. package/apps/cli/src/skills-cli.js +112 -0
  91. package/apps/cli/src/tui/caps.js +31 -0
  92. package/apps/cli/src/tui/components/agent-list.js +58 -0
  93. package/apps/cli/src/tui/components/approval-center.js +145 -0
  94. package/apps/cli/src/tui/components/approval.js +95 -0
  95. package/apps/cli/src/tui/components/dashboard-frame.js +293 -0
  96. package/apps/cli/src/tui/components/diff-viewer.js +549 -0
  97. package/apps/cli/src/tui/components/event-viewer.js +46 -0
  98. package/apps/cli/src/tui/components/help-panel.js +59 -0
  99. package/apps/cli/src/tui/components/home.js +185 -0
  100. package/apps/cli/src/tui/components/logo.js +67 -0
  101. package/apps/cli/src/tui/components/panel.js +70 -0
  102. package/apps/cli/src/tui/components/status-bar.js +96 -0
  103. package/apps/cli/src/tui/components/timeline.js +120 -0
  104. package/apps/cli/src/tui/keys.js +139 -0
  105. package/apps/cli/src/tui/neutral.js +68 -0
  106. package/apps/cli/src/tui/screen.js +111 -0
  107. package/apps/cli/src/tui/text.js +165 -0
  108. package/apps/cli/src/tui/tokens.js +89 -0
  109. package/apps/cli/src/tui/view.js +64 -0
  110. package/apps/cli/src/upgrade-check.js +86 -0
  111. package/apps/cli/src/upgrade-cli.js +168 -0
  112. package/apps/cli/src/workflow-cli.js +674 -0
  113. package/package.json +29 -4
  114. package/packages/application/src/index.js +8 -0
  115. package/packages/application/src/lib/digest.js +7 -0
  116. package/packages/application/src/ports/memory.js +1 -0
  117. package/packages/application/src/ports/runtime-executor.js +1 -0
  118. package/packages/application/src/projection/run-view.js +194 -0
  119. package/packages/application/src/projection/squad-view.js +33 -0
  120. package/packages/application/src/use-cases/prepare-run.js +68 -0
  121. package/packages/application/src/workflow/feature-governed.js +420 -0
  122. package/packages/application/src/workflow/gate-signals.js +40 -0
  123. package/packages/application/src/workflow/prompts.js +81 -0
  124. package/packages/config/src/config.js +372 -0
  125. package/packages/config/src/index.js +1 -0
  126. package/packages/domain/src/capabilities.js +13 -0
  127. package/packages/domain/src/capability-matrix.js +63 -0
  128. package/packages/domain/src/enforcement.js +95 -0
  129. package/packages/domain/src/index.js +4 -0
  130. package/packages/domain/src/policy.js +32 -0
  131. package/packages/rules/src/glob.js +47 -0
  132. package/packages/rules/src/index.js +5 -0
  133. package/packages/rules/src/inherit.js +19 -0
  134. package/packages/rules/src/lists.js +41 -0
  135. package/packages/rules/src/rules.js +79 -0
  136. package/packages/rules/src/shell.js +83 -0
  137. package/packages/skills/src/index.js +1 -0
  138. package/packages/skills/src/skills.js +108 -0
  139. package/skills/code-review/SKILL.md +51 -0
  140. package/skills/egm-design/LICENSE +202 -0
  141. package/skills/egm-design/SKILL.md +68 -0
  142. package/skills/egm-design/references/feature-spec-standard.md +39 -0
  143. package/skills/egm-implementation-readiness/LICENSE +202 -0
  144. package/skills/egm-implementation-readiness/SKILL.md +67 -0
  145. package/skills/egm-implementation-readiness/references/implementation-readiness-standard.md +37 -0
  146. package/skills/first-party.lock.json +10 -0
  147. package/skills/planning-contract/SKILL.md +51 -0
  148. package/skills/ponytail/LICENSE +21 -0
  149. package/skills/ponytail/SKILL.md +56 -0
  150. package/skills/security-review/SKILL.md +58 -0
  151. package/skills/tdd/SKILL.md +52 -0
  152. package/skills/unslop/LICENSE +396 -0
  153. package/skills/unslop/SKILL.md +239 -0
  154. package/skills/unslop/references/cjk.md +34 -0
  155. package/skills/unslop/references/effects.md +113 -0
  156. package/skills/unslop/references/refs.md +17 -0
  157. package/skills/unslop/references/rtl.md +111 -0
  158. package/skills/unslop/references/signs.md +122 -0
  159. package/skills/unslop/references/tokens.md +139 -0
  160. package/skills/unslop/references/visuals.md +84 -0
@@ -0,0 +1,674 @@
1
+ /**
2
+ * `taskquoin run | approve | resume | status | show` — composition of the feature-governed workflow with real adapters.
3
+ * Tree-based (ADR-0013): verify/review/approve/commit refer to one git tree id; git runs on the host with hooks and
4
+ * fsmonitor disabled and commits with `commit-tree` (no repository code runs on the host). Verify runs the project's
5
+ * tests in a clean room (ADR-0014): the tree materialized outside the workspace, mounted at the repository path in
6
+ * bubblewrap with no network, .git and the inherited dependency dirs read-only, HOME hidden, secrets masked.
7
+ * Approvals name the gate and the expected hash; a per-run lock serialises concurrent CLI calls (Codex R4 N4).
8
+ */
9
+ import { createHash, randomBytes } from 'node:crypto';
10
+ import { chmodSync, existsSync, linkSync, lstatSync, renameSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { basename, join, relative } from 'node:path';
12
+ import { homedir } from 'node:os';
13
+ import { advance, approve, interrupt, newRun, pendingApproval, projectRun, resume } from '../../../packages/application/src/index.js';
14
+ import { inheritGlobs, keyEnvName, testCommand, workflowOf } from '../../../packages/config/src/index.js';
15
+ import { ApiExecutor } from '../../../adapters/runtime-api/src/index.js';
16
+ import { appendEvent, ensureTrustedDir, getArtifact, listRuns, loadRunState, putArtifact, readEvents, saveRunState, stateBase } from '../../../adapters/store-fs/src/index.js';
17
+ import { ClaudeExecutor } from '../../../adapters/runtime-claude/src/index.js';
18
+ import { CodexExecutor } from '../../../adapters/runtime-codex/src/index.js';
19
+ import { OpenCodeExecutor, userOpenCodeDirs } from '../../../adapters/runtime-opencode/src/index.js';
20
+ import { ClaudeMemMemory } from '../../../adapters/memory-claude-mem/src/index.js';
21
+ import { defaultMaskDirs, dependencyDigests, fingerprintEntries, runSandboxedTool, scanWorkspace } from '../../../adapters/local-tool/src/index.js';
22
+ import { currentLanguage, english, t } from "./i18n/index.js";
23
+ import { displayWidth, padEndDisplay } from "./i18n/width.js";
24
+ import { LANGUAGES } from "./i18n/languages.js";
25
+ import { jsonOut, n, nBlock, nCut, nLog } from "./tui/neutral.js";
26
+ import { renderTimeline, timelineLine } from "./tui/components/timeline.js";
27
+ import { resolveAgentSkills, skillsBlock } from "./skills-cli.js";
28
+ import { matchGlob, SECRET_READ_GLOBS, selectInheritedRoots, TEST_HARNESS_GLOBS, TEST_PATH_GLOBS } from '../../../packages/rules/src/index.js';
29
+ /** Never sent to any judge (multi-LLM A3): the same names Taskquoin masks and denies elsewhere. */
30
+ const isSecretPath = (p) => SECRET_READ_GLOBS.some(g => matchGlob(g, p));
31
+ /** Always required; the judges are whoever `workflow` cites (the `challenger` agent by default — optional otherwise). */
32
+ const ROLES = ['planner', 'implementer'];
33
+ /** Planner and challenger must stay read-only: an "independent reviewer" that can write is not one (Codex R4 N8). */
34
+ const READ_ONLY_ROLES = ['planner'];
35
+ const FORBIDDEN_FOR_READ_ONLY = ['fs.write', 'shell.run', 'net.egress', 'vcs.commit', 'vcs.push', 'connector.write', 'config.modify'];
36
+ /** A Verify that could not even start (no test command, tree not materialized, refusal): never red tests, no rework can fix it. */
37
+ export const verifyNotRun = (log) => ({ passed: false, exitCode: null, conclusive: false, couldNotRun: true, treeChanged: false, log, firstLine: log.split('\n')[0].slice(0, 200) });
38
+ const PLAIN = { interactive: false, cursor: false, colorDepth: 0, charset: 'utf8', theme: 'dark', motion: false, plain: true, columns: 80, rows: 24 };
39
+ const capsOf = (c) => c.caps ?? PLAIN;
40
+ export const configDigest = (root) => 'sha256:' + createHash('sha256').update(readFileSync(join(root, 'taskquoin.yaml'))).digest('hex');
41
+ function preflight(c) {
42
+ const wf = workflowOf(c.cfg);
43
+ for (const r of [...new Set([...ROLES, ...wf.challengers, ...wf.reviewers])]) {
44
+ if (!Object.hasOwn(c.cfg.agents, r))
45
+ return { message: t('workflow.missingAgent', { agent: n(r) }) };
46
+ const sk = resolveAgentSkills(c.cfg, c.store, r);
47
+ if (sk.errors.length)
48
+ return { message: t('workflow.skillsUnusableStart', { agent: n(r), errors: sk.errors.map(n).join('; ') }) };
49
+ }
50
+ for (const r of [...new Set([...READ_ONLY_ROLES, ...wf.challengers, ...wf.reviewers])]) {
51
+ const bad = FORBIDDEN_FOR_READ_ONLY.filter(k => (c.cfg.agents[r].capabilities[k]?.length ?? 0) > 0);
52
+ if (bad.length)
53
+ return { message: t('workflow.mustBeReadOnly', { agent: n(r), granted: bad.join(', ') }) };
54
+ }
55
+ return gatesProblem(c);
56
+ }
57
+ /**
58
+ * The gate of EVERY agent the workflow will call (planner, implementer, challengers, reviewers, whatever the runtime),
59
+ * checked before anything runs or is paid for: a refusal known in advance must not come after the planner's call.
60
+ * The remedy is the documented one, never a waiver pushed on the agent that writes:
61
+ * - a runtime that is not installed is said as such (`upgrade` does not install it);
62
+ * - a runtime version the matrix was not measured on → `upgrade`;
63
+ * - an unmeasured restriction of a read-only agent (planner, challengers, reviewers) → `accept-risk`, one line per
64
+ * capability (ADR-0002: the owner decides knowingly);
65
+ * - an implementer without `shell.run` → the configuration (`shell.run`, `verify.command`): that is what makes its
66
+ * restrictions measured; accepting the risk would waive the protection of `.git` and `taskquoin.yaml` against it.
67
+ */
68
+ function gatesProblem(c) {
69
+ const wf = workflowOf(c.cfg);
70
+ // An api / OpenCode judge that cannot start keeps its own, more specific message (a missing key, an unconnected provider).
71
+ const judge = judgesProblem(c);
72
+ if (judge)
73
+ return { message: judge };
74
+ const readOnly = new Set([...READ_ONLY_ROLES, ...wf.challengers, ...wf.reviewers]);
75
+ for (const r of [...new Set([...ROLES, ...wf.challengers, ...wf.reviewers])]) {
76
+ const g = c.gate(r);
77
+ if (g.ok)
78
+ continue;
79
+ const a = c.cfg.agents[r];
80
+ if (a.runtime !== 'api' && !c.h.runtimes[a.runtime])
81
+ return { message: t('workflow.runtimeMissing', { runtime: a.runtime, agent: n(r) }) };
82
+ const message = t('workflow.judgeCannotStart', { agent: n(r), reasons: g.failures.map(f => n(f.message)).join('; ') });
83
+ if (g.failures.some(f => /capability matrix measured for/.test(f.message)))
84
+ return { message, hint: t('workflow.hint.upgrade') };
85
+ const unmeasured = [...new Set(g.failures.filter(f => /the mechanism is not measured/.test(f.message)).map(f => f.capability))];
86
+ if (!unmeasured.length)
87
+ return { message };
88
+ if (readOnly.has(r))
89
+ return { message, hint: unmeasured.map(cap => t('workflow.hint.acceptRisk', { agent: n(r), capability: n(cap) })).join('\n') };
90
+ if (a.runtime !== 'opencode' && !(a.capabilities['shell.run']?.length))
91
+ return { message, hint: t('workflow.hint.configure', { agent: n(r), config: 'taskquoin.yaml' }) };
92
+ return { message };
93
+ }
94
+ return undefined;
95
+ }
96
+ /**
97
+ * An api or OpenCode judge that cannot run (a missing key, an unconnected provider) stops `run`, `approve` and `resume`
98
+ * BEFORE anything changes — never after a paid implementation (multi-LLM A, project B). Claude/Codex keep their gate
99
+ * where they run.
100
+ */
101
+ function judgesProblem(c) {
102
+ const wf = workflowOf(c.cfg);
103
+ for (const r of [...new Set([...wf.challengers, ...wf.reviewers])].filter(id => c.cfg.agents[id].runtime === 'api' || c.cfg.agents[id].runtime === 'opencode')) {
104
+ const g = c.gate(r);
105
+ if (!g.ok)
106
+ return t('workflow.judgeCannotStart', { agent: n(r), reasons: g.failures.map(f => n(f.message)).join('; ') });
107
+ }
108
+ return undefined;
109
+ }
110
+ /**
111
+ * The run lock holds the owner's pid on the first line and, where the platform tells it (Linux), the owner's process
112
+ * start time on the second (additive: an older one-line lock still reads as a pid). The start time guards against a
113
+ * pid that was reused by an unrelated process after the owner died.
114
+ */
115
+ function processStart(pid) {
116
+ try {
117
+ const f = readFileSync(`/proc/${pid}/stat`, 'utf8');
118
+ return f.slice(f.lastIndexOf(')') + 2).split(' ')[19];
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ }
124
+ const lockContent = () => { const st = processStart(process.pid); return `${process.pid}\n${st ?? ''}\n`; };
125
+ /** Alive unless the pid does not exist (ESRCH) or now belongs to a process that started after the lock was taken. EPERM = alive, never taken over. */
126
+ function lockOwner(content) {
127
+ const [first, start] = content.split('\n');
128
+ const pid = Number(first);
129
+ // An empty or non-numeric lock names no holder: kill(0, 0) would signal the whole process group and "succeed". The
130
+ // holder cannot be shown dead, so it counts as alive (never taken over); the run stays `running` and `resume` refuses.
131
+ if (!Number.isSafeInteger(pid) || pid <= 0)
132
+ return { pid: 0, alive: true };
133
+ try {
134
+ process.kill(pid, 0);
135
+ }
136
+ catch (e) {
137
+ if (e.code !== 'EPERM')
138
+ return { pid, alive: false };
139
+ }
140
+ const now = start ? processStart(pid) : undefined;
141
+ return { pid, alive: !(start && now && now !== start) };
142
+ }
143
+ /**
144
+ * `running` with no live owner is a run whose process was killed. While a takeover is in progress (`lock.takeover`
145
+ * held, the lock briefly absent) the run is NOT reported as interrupted: its next owner is already being installed.
146
+ */
147
+ function ownerGone(c, s) {
148
+ if (s.status !== 'running')
149
+ return false;
150
+ const dir = join(c.store.runs, s.runId);
151
+ const read = () => { try {
152
+ return readFileSync(join(dir, 'lock'), 'utf8');
153
+ }
154
+ catch (e) {
155
+ if (e.code === 'ENOENT')
156
+ return undefined;
157
+ throw e;
158
+ } };
159
+ try {
160
+ let text = read();
161
+ if (text === undefined) { // absent: a takeover in flight, or no owner at all
162
+ let m;
163
+ try {
164
+ m = readFileSync(join(dir, 'lock.takeover'), 'utf8');
165
+ }
166
+ catch {
167
+ m = undefined;
168
+ }
169
+ if (m !== undefined && lockOwner(m).alive)
170
+ return false; // a live taker is installing the next owner
171
+ text = read(); // the takeover may have finished between the two looks
172
+ if (text === undefined)
173
+ return true;
174
+ }
175
+ return !lockOwner(text).alive;
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ }
181
+ /** What `status` shows: a killed run reads as interrupted, with the reason. */
182
+ const effective = (c, s) => (ownerGone(c, s) ? { ...s, status: 'interrupted', reason: s.reason ?? english('workflow.processGone') } : s);
183
+ /**
184
+ * Serialise every state-changing CLI call on a run. The lock is created with link() (atomic, never half-written). A
185
+ * lock of a dead process is replaced under a second mutex, `lock.takeover`, created the same way: only its holder may
186
+ * touch the lock, re-checks under it that the lock is still the dead one that was read, and unlinks and relinks it.
187
+ * A live lock is never renamed, moved or unlinked, so it is never displaced, even transiently.
188
+ * The mutex is removed only by its own holder, or — when its holder is dead — by the holder of the RUN lock (one
189
+ * process at a time; no live taker can exist then, since only one mutex exists and its holder is dead). A takeover
190
+ * never clears a dead mutex itself: a crash mid-takeover plus racing resumes could otherwise remove a live taker's
191
+ * mutex and give two holders. Such a run refuses with the file to delete (when no taskquoin process runs).
192
+ */
193
+ export async function withRunLock(c, runId, fn) {
194
+ const dir = ensureTrustedDir(join(c.store.runs, runId));
195
+ const lock = join(dir, 'lock'), mutex = join(dir, 'lock.takeover');
196
+ const tag = `${process.pid}.${randomBytes(4).toString('hex')}`;
197
+ const mine = join(dir, `.lock.${tag}`), mineMutex = join(dir, `.takeover.${tag}`);
198
+ const busy = (pid) => new Error(t('workflow.busy', { run: n(runId), pid }));
199
+ const stuck = (file) => new Error(t('workflow.lockStuck', { run: n(runId), file: n(file) }));
200
+ const exists = (e) => e.code === 'EEXIST';
201
+ const content = lockContent();
202
+ writeFileSync(mine, content, { mode: 0o600 });
203
+ const readOr = (f) => { try {
204
+ return readFileSync(f, 'utf8');
205
+ }
206
+ catch {
207
+ return undefined;
208
+ } };
209
+ let mutexHeld = false;
210
+ try {
211
+ for (let tries = 0;; tries++) {
212
+ try {
213
+ linkSync(mine, lock);
214
+ break;
215
+ }
216
+ catch (e) {
217
+ if (!exists(e))
218
+ throw e;
219
+ }
220
+ const seen = readOr(lock);
221
+ if (seen === undefined)
222
+ continue; // released meanwhile
223
+ const owner = lockOwner(seen);
224
+ if (owner.alive && owner.pid === 0)
225
+ throw stuck(lock); // names no process: no command can clear it
226
+ if (owner.alive || tries > 8)
227
+ throw busy(owner.pid);
228
+ // The holder is dead: take over, serialised on the mutex.
229
+ writeFileSync(mineMutex, content, { mode: 0o600 });
230
+ try {
231
+ linkSync(mineMutex, mutex);
232
+ mutexHeld = true;
233
+ }
234
+ catch (e) {
235
+ if (!exists(e))
236
+ throw e;
237
+ const m = readOr(mutex);
238
+ if (m === undefined)
239
+ continue; // released meanwhile
240
+ if (lockOwner(m).alive && lockOwner(m).pid !== 0)
241
+ throw busy(owner.pid); // another resume is taking over now
242
+ throw stuck(mutex); // a takeover whose holder died: never cleared here (see above)
243
+ }
244
+ finally {
245
+ rmSync(mineMutex, { force: true });
246
+ }
247
+ try {
248
+ if (readOr(lock) === seen) { // still the dead lock that was read: replace it (a creator racing us wins the link, we retry)
249
+ rmSync(lock, { force: true });
250
+ try {
251
+ linkSync(mine, lock);
252
+ break;
253
+ }
254
+ catch (e) {
255
+ if (!exists(e))
256
+ throw e;
257
+ }
258
+ }
259
+ }
260
+ finally {
261
+ if (readOr(mutex) === content)
262
+ rmSync(mutex, { force: true });
263
+ mutexHeld = false;
264
+ }
265
+ }
266
+ }
267
+ finally {
268
+ rmSync(mine, { force: true });
269
+ if (mutexHeld && readOr(mutex) === content)
270
+ rmSync(mutex, { force: true });
271
+ }
272
+ // Holding the run lock: a mutex left by a taker that died (e.g. between removing the dead lock and linking its own)
273
+ // can no longer be anyone's — clear it, so the next takeover is not refused.
274
+ const m = readOr(mutex);
275
+ if (m !== undefined && !lockOwner(m).alive)
276
+ rmSync(mutex, { force: true });
277
+ try {
278
+ return await fn();
279
+ }
280
+ finally {
281
+ rmSync(lock, { force: true });
282
+ }
283
+ }
284
+ function deps(c, state, git) {
285
+ const env = { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? homedir(), LANG: process.env.LANG ?? 'C.UTF-8' };
286
+ const claude = c.h.runtimes.claude, codex = c.h.runtimes.codex;
287
+ const executors = {
288
+ claude: claude?.version ? new ClaudeExecutor({ bin: claude.bin, version: claude.version }, { hook: { nodeBin: process.execPath, entry: c.hookEntry, policyDir: c.store.policies, controlStore: c.store.root } }) : undefined,
289
+ codex: codex?.version ? new CodexExecutor({ bin: codex.bin, version: codex.version }) : undefined,
290
+ opencode: c.h.runtimes.opencode?.version ? new OpenCodeExecutor({ bin: c.h.runtimes.opencode.bin, version: c.h.runtimes.opencode.version }, { userDirs: userOpenCodeDirs(), runBase: join(stateBase(), 'opencode', 'runs'), controlStore: c.store.root }) : undefined,
291
+ };
292
+ const agent = (id) => {
293
+ const a = c.cfg.agents[id];
294
+ const p = a.runtime === 'api' ? c.cfg.providers[a.provider] : undefined;
295
+ const ex = p ? new ApiExecutor({ id: a.provider, url: p.url, model: p.model, ...(keyEnvName(p) ? { keyEnv: keyEnvName(p) } : {}), maxOutputTokens: p.maxOutputTokens, timeoutSeconds: p.timeoutSeconds, tokenField: p.tokenField })
296
+ : executors[a.runtime];
297
+ if (!ex)
298
+ throw new Error(t('workflow.runtimeMissing', { runtime: a.runtime, agent: id }));
299
+ const sk = resolveAgentSkills(c.cfg, c.store, id);
300
+ if (sk.errors.length)
301
+ throw new Error(t('workflow.skillsUnusable', { agent: n(id), errors: sk.errors.map(n).join('; ') }));
302
+ const label = p ? `api: ${new URL(p.url).host}/${p.model}` : a.runtime === 'opencode' ? `opencode: ${a.model}` : a.runtime;
303
+ // An implementer without commands (OpenCode, or no shell.run): Taskquoin runs the tests and allows more reworks.
304
+ const noCommands = id === 'implementer' && !(a.capabilities['shell.run']?.length);
305
+ return { spec: { id, description: a.description, prompt: a.prompt + skillsBlock(sk.loaded), capabilities: a.capabilities, model: a.model, maxTurns: a.maxTurns }, executor: ex, label, textOnly: !!p, ...(noCommands ? { noCommands } : {}) };
306
+ };
307
+ const testCmd = testCommand(c.cfg);
308
+ const base = state.base, branch = state.branch;
309
+ return {
310
+ agents: Object.fromEntries([...new Set(['planner', 'implementer', ...workflowOf(c.cfg).challengers, ...workflowOf(c.cfg).reviewers])].map(id => [id, agent(id)])),
311
+ workflow: workflowOf(c.cfg),
312
+ judgeBudgetChars: (id) => { const a = c.cfg.agents[id]; return a.runtime === 'api' ? c.cfg.providers[a.provider].maxInputChars : undefined; },
313
+ gate: c.gate,
314
+ artifacts: { put: (name, text) => putArtifact(c.store, Buffer.from(text), { mediaType: 'text/plain', producer: name }).sha256, get: (h) => getArtifact(c.store, h).toString('utf8') },
315
+ save: (s) => saveRunState(c.store, s.runId, s),
316
+ event: (e) => {
317
+ appendEvent(c.store, state.runId, e);
318
+ const seen = { ts: new Date().toISOString(), ...e };
319
+ if (c.onEvent)
320
+ c.onEvent(seen);
321
+ else {
322
+ const line = timelineLine(seen, capsOf(c));
323
+ if (line !== undefined)
324
+ c.out(line);
325
+ }
326
+ },
327
+ verify: async (tree, roots) => {
328
+ const no = verifyNotRun;
329
+ const refuse = (why) => ({ ...no(`TASKQUOIN — Verify refused: ${why}`), refusal: why });
330
+ if (!testCmd)
331
+ return no('no test command configured (verify.command, or the implementer\'s shell.run) — cannot verify, failing closed');
332
+ // Clean room (ADR-0014): the tree is materialized OUTSIDE the workspace (control store: agents cannot write it)
333
+ // and mounted at the repository path; only `.git` and the inherited dependency dirs come from the working dir.
334
+ const rooms = ensureTrustedDir(join(c.store.root, 'verify'), c.root);
335
+ const room = mkdtempSync(join(rooms, `${state.runId}-`));
336
+ try {
337
+ try {
338
+ await git.materialize(tree, room);
339
+ }
340
+ catch (e) {
341
+ return no(`could not materialize tree ${tree.slice(0, 12)} in the clean room: ${e.message}`);
342
+ }
343
+ const unfreezable = symlinkedRoot(c.root, roots);
344
+ if (unfreezable)
345
+ return refuse(unfreezable);
346
+ const scan = scanWorkspace(room);
347
+ if (!scan.complete)
348
+ return refuse(`clean-room scan incomplete (${scan.problem}) — cannot mask every secret`);
349
+ const toVisible = (f) => (f === room || f.startsWith(room + '/') ? join(c.root, relative(room, f)) : f);
350
+ const hideFiles = scan.secretFiles.map(toVisible);
351
+ // Inherited dirs come from the working directory: scan them as content (their .git included) and mask their
352
+ // secrets, also behind secret-named links (Codex CR #3, CR2 #3).
353
+ for (const x of roots) {
354
+ const dep = scanWorkspace(join(c.root, x), 200_000, { includeRootGit: true });
355
+ if (!dep.complete)
356
+ return refuse(`scan of inherited ${x} incomplete (${dep.problem}) — cannot mask every secret`);
357
+ hideFiles.push(...dep.secretFiles);
358
+ }
359
+ const profile = { writableRoot: room, mountAt: c.root, home: env.HOME, hideHome: true, readOnly: [join(c.root, '.git'), ...roots.map(x => join(c.root, x))], hideFiles, maskDirs: [...defaultMaskDirs(), c.store.root] };
360
+ // Links are resolved INSIDE the very sandbox the tests will get (realpath -m: every component physically,
361
+ // dangling ones included) — no emulation can drift from what tests see (Codex CR #1, CR2 #1).
362
+ const probe = await runSandboxedTool({ bin: '/bin/sh', args: ['-c', LINK_PROBE, 'probe', c.root], cwd: c.root, env: { PATH: '/usr/bin:/bin', LANG: 'C' }, timeoutMs: 120_000, maxOutputBytes: 20_000_000 }, profile);
363
+ const parts = probe.stdout.split('\0');
364
+ const sep = parts.indexOf('TQ-SEP');
365
+ const links = parts.slice(0, Math.max(sep, 0)).map(l => join(c.root, l));
366
+ const reals = parts.slice(sep + 1, sep + 1 + links.length);
367
+ if (probe.status !== 'completed' || probe.truncated || sep < 0 || reals.length !== links.length || parts.length !== 2 * links.length + 2)
368
+ return refuse(`could not resolve every symlink in the clean room (status ${probe.status}${probe.stderr ? `: ${probe.stderr.slice(0, 200)}` : ''})`);
369
+ const inRepo = (t) => t === c.root || t.startsWith(c.root + '/');
370
+ const leaving = links.filter((_l, i) => !inRepo(reals[i])).map(l => relative(c.root, l));
371
+ const inDeps = leaving.filter(l => roots.some(x => l === x || l.startsWith(x + '/'))), inTree = leaving.filter(l => !inDeps.includes(l));
372
+ if (inTree.length)
373
+ return refuse(`the tree links outside the repository: ${inTree.slice(0, 5).join(', ')} — Verify would run code that is not in the tree`);
374
+ if (inDeps.length)
375
+ return refuse(`inherited dependencies link outside the repository: ${inDeps.slice(0, 5).join(', ')} — install them into the repository (not npm link) or remove them from verify.inherit`);
376
+ // What a secret-NAMED link points to is masked, as resolved INSIDE the sandbox (a host-side resolution in the
377
+ // room misses targets that only the inherited mounts provide, Codex CR3 #1).
378
+ links.forEach((l, i) => { if (SECRET_READ_GLOBS.some(g => matchGlob(g, relative(c.root, l))))
379
+ hideFiles.push(reals[i]); });
380
+ // The marker is printed INSIDE the sandbox before the test command: its presence proves the sandbox started.
381
+ const r = await runSandboxedTool({ bin: '/bin/sh', args: ['-c', `echo ${SANDBOX_STARTED}; exec /bin/sh -c "$0"`, testCmd], cwd: c.root, env: { PATH: env.PATH, HOME: '/tmp', LANG: env.LANG }, timeoutMs: 15 * 60_000, maxOutputBytes: 2_000_000 }, profile);
382
+ const treeChanged = (await git.dirTree(room, base)) !== tree;
383
+ // Conclusive = the command ran in the sandbox, exited by itself with a test result (126/127 = not runnable,
384
+ // 128+n = signal) and its WHOLE output was kept (a truncated log hides why it failed — Codex RED re-review #2).
385
+ const started = r.stdout.startsWith(`${SANDBOX_STARTED}\n`);
386
+ const conclusive = started && !r.truncated && (r.status === 'completed' || r.status === 'failed') && r.exitCode !== null && r.exitCode < 126;
387
+ const firstLine = `${started ? r.stdout.slice(SANDBOX_STARTED.length + 1) : r.stdout}\n${r.stderr}`.split('\n').find(l => l.trim() !== '') ?? '';
388
+ return { passed: started && r.status === 'completed' && r.exitCode === 0, exitCode: r.exitCode, conclusive, couldNotRun: !started || (r.exitCode !== null && r.exitCode >= 126) || (r.exitCode === null && r.status !== 'timeout'), treeChanged, firstLine: firstLine.slice(0, 200),
389
+ log: `$ ${testCmd} (clean room of tree ${tree.slice(0, 12)}: no network, .git read-only, HOME hidden, ${roots.length ? `inherited read-only: ${roots.join(', ')}` : 'no inherited dirs'}, ${hideFiles.length} secret file(s) masked)\nstatus=${r.status} exit=${r.exitCode}${r.truncated ? ' OUTPUT TRUNCATED' : ''}\n${r.stdout}\n${r.stderr}`.slice(-200_000) };
390
+ }
391
+ finally {
392
+ removeRoom(room);
393
+ }
394
+ },
395
+ workspace: {
396
+ snapshot: async (roots) => {
397
+ const entries = await git.ignoredEntries();
398
+ const r = roots ?? selectInheritedRoots(entries, inheritGlobs(c.cfg), (p) => existsSync(join(c.root, p)));
399
+ const unfreezable = symlinkedRoot(c.root, r);
400
+ if (unfreezable)
401
+ return { roots: r, deps: {}, ignored: {}, refusal: unfreezable };
402
+ const other = entries.filter(e => !r.some(x => e.path === x || e.path.startsWith(x + '/')));
403
+ return { roots: r, deps: dependencyDigests(c.root, r), ignored: fingerprintEntries(c.root, other, r) };
404
+ },
405
+ },
406
+ git: {
407
+ candidateTree: () => git.candidateTree(base),
408
+ diff: (t) => git.diff(base, t),
409
+ changes: (t) => git.changes(base, t),
410
+ gitlinks: (t) => git.gitlinks(t),
411
+ commit: (t, m) => git.commitTree(t, base, branch, m),
412
+ redTree: (t) => git.redTree(base, t, (p) => [...TEST_PATH_GLOBS, ...TEST_HARNESS_GLOBS].some(g => matchGlob(g, p))),
413
+ judgeDiff: (t) => git.judgeDiff(base, t, isSecretPath),
414
+ changedTexts: (t, budget) => git.changedTexts(base, t, isSecretPath, budget),
415
+ },
416
+ memory: c.cfg.memory.claudeMem.enabled ? new ClaudeMemMemory() : undefined,
417
+ project: basename(c.root),
418
+ run: { cwd: c.root, env, timeoutMs: 20 * 60_000, maxOutputBytes: 8_000_000 },
419
+ now: () => new Date(),
420
+ };
421
+ }
422
+ /**
423
+ * Inherited paths must be plain directories of the working dir: a symlink anywhere on the way would mount (and let
424
+ * the agent's sandbox resolve) what it points to, which neither the fingerprint nor the scans cover (Codex CR2 #2).
425
+ */
426
+ function symlinkedRoot(root, roots) {
427
+ for (const x of roots) {
428
+ let p = root;
429
+ for (const seg of x.split('/')) {
430
+ p = join(p, seg);
431
+ let link = false;
432
+ try {
433
+ link = lstatSync(p).isSymbolicLink();
434
+ }
435
+ catch {
436
+ break;
437
+ }
438
+ if (link)
439
+ return `inherited path ${x} goes through a symlink (${relative(root, p)}) — Verify would mount what it points to`;
440
+ }
441
+ }
442
+ return undefined;
443
+ }
444
+ /** Delete a clean room even if tests left read-only directories in it (never follows symlinks). */
445
+ function removeRoom(dir) {
446
+ try {
447
+ rmSync(dir, { recursive: true, force: true });
448
+ return;
449
+ }
450
+ catch { /* read-only dirs: make them writable, retry */ }
451
+ const fix = (p) => { const s = lstatSync(p); if (!s.isDirectory())
452
+ return; chmodSync(p, 0o700); for (const n of readdirSync(p))
453
+ fix(join(p, n)); };
454
+ try {
455
+ fix(dir);
456
+ rmSync(dir, { recursive: true, force: true });
457
+ }
458
+ catch { /* left in the control store; harmless, never reused */ }
459
+ }
460
+ const GATE = { plan: 'approve-plan', commit: 'approve-commit' };
461
+ const SANDBOX_STARTED = 'TASKQUOIN-SANDBOX-STARTED';
462
+ /** Every symlink of the clean room (and inherited dirs), then each one's physical resolution, NUL-separated, in order. */
463
+ const LINK_PROBE = 'cd "$1" && find . -path ./.git -prune -o -type l -print0 > /tmp/tq-links && xargs -0 -r realpath -m -z -- < /tmp/tq-links > /tmp/tq-real && cat /tmp/tq-links && printf "TQ-SEP\\0" && cat /tmp/tq-real';
464
+ // cd + a fixed `./.git` pattern: the repository path is never used as a find pattern (glob characters, Codex CR3 #2).
465
+ /** The CLI word for an approval node (`taskquoin approve <run> <plan|commit>`). */
466
+ const gateWord = (node) => (node === GATE.plan ? 'plan' : 'commit');
467
+ function report(c, s) {
468
+ c.out(t('workflow.report.head', { run: n(s.runId), status: n(s.status), node: n(s.current), attempt: s.attempts, branch: n(s.branch ?? '') }));
469
+ if (s.reason)
470
+ c.out(` ${n(s.reason)}`);
471
+ // The steps of the real state machine (never a progress bar), from the stored state and its event log.
472
+ let events = [];
473
+ try {
474
+ events = readEvents(c.store, s.runId).events;
475
+ }
476
+ catch { /* no log yet, or unreadable: the view shows what the state holds */ }
477
+ for (const l of renderTimeline(projectRun(s, events), capsOf(c), Date.now(), { slash: !!c.onEvent }))
478
+ c.out(l);
479
+ const p = pendingApproval(s);
480
+ // Labels share one column whatever the language (display width, so CJK aligns too).
481
+ const names = [t('workflow.report.reviewLabel'), t('workflow.report.approveLabel'), t('workflow.report.resumeLabel')];
482
+ const width = Math.max(...names.map(displayWidth)) + 2;
483
+ const labels = names.map(x => padEndDisplay(x, width));
484
+ if (p) {
485
+ const gate = gateWord(p.node);
486
+ const att = s.attempts;
487
+ const ignored = (s.artifacts[`ignored-${att}`] ? t('workflow.report.ignoredNote', { n: att }) : '') + (s.artifacts[`signals-${att}`] ? `, signals-${att}` : ''); // i18n-ok: artifact id
488
+ const what = gate === 'plan' ? t('workflow.report.planArtifacts') : t('workflow.report.diffArtifacts', { n: att, ignored });
489
+ c.out(` ${labels[0]}taskquoin show ${n(s.runId)} ${what}`); // i18n-ok: command line to type
490
+ c.out(` ${labels[1]}${t('workflow.report.approveCmd', { run: n(s.runId), gate, hash: p.binding.slice(0, 12) })}`);
491
+ c.out(` ${' '.repeat(width)}${gate === 'plan' ? t('workflow.report.bindingPlan', { hash: p.binding }) : t('workflow.report.bindingTree', { hash: p.binding })}`);
492
+ }
493
+ if (s.status === 'interrupted')
494
+ c.out(` ${labels[2]}taskquoin resume ${n(s.runId)}`); // i18n-ok: command line to type
495
+ if (s.status === 'completed')
496
+ c.out(t('workflow.report.committed', { commit: n(s.commit ?? ''), branch: n(s.branch ?? '') }));
497
+ }
498
+ const exitFor = (s) => (s.status === 'completed' || s.status === 'waiting-approval' ? 0 : 1);
499
+ async function checkRunContext(c, git, s) {
500
+ if ((await git.currentBranch()) !== s.branch)
501
+ return t('workflow.switchBranch', { branch: n(s.branch ?? '') });
502
+ if (s.configDigest && s.configDigest !== configDigest(c.root))
503
+ return t('workflow.configChanged');
504
+ return judgesProblem(c);
505
+ }
506
+ /** The language agents write their prose in for a run started in `lang`: the English name, or undefined for English. */
507
+ export const proseLanguageFor = (lang) => (lang === 'en' ? undefined : LANGUAGES.find(l => l.code === lang)?.englishName);
508
+ /** `onStart` receives the id of the run THIS call creates (the console selects exactly that run). */
509
+ /** The request of `run`: every positional after the command, joined by single spaces (flags are not positionals). */
510
+ export const requestFrom = (positionals) => (positionals.length > 1 ? positionals.slice(1).join(' ') : undefined);
511
+ export async function cmdRun(c, git, request, onStart) {
512
+ if (!request?.trim()) {
513
+ c.err(t('workflow.usage.run'));
514
+ return 2;
515
+ }
516
+ // The free local check first (no agent called, nothing created), then the gates of every agent.
517
+ if (!(await git.isClean())) {
518
+ c.err(t('workflow.cmdError', { command: 'run', message: t('workflow.dirtyTree') }));
519
+ return 1;
520
+ }
521
+ const pf = preflight(c);
522
+ if (pf) {
523
+ c.err(t('workflow.cmdError', { command: 'run', message: pf.message }));
524
+ if (pf.hint)
525
+ c.err(pf.hint);
526
+ return 1;
527
+ }
528
+ const runId = `run-${new Date().toISOString().replace(/[-:]/g, '').slice(0, 15)}-${randomBytes(3).toString('hex')}`;
529
+ const branch = `taskquoin/${runId}`;
530
+ const base = await git.startRunBranch(branch);
531
+ const proseLanguage = proseLanguageFor(currentLanguage());
532
+ const s0 = { ...newRun(runId, request), branch, base, configDigest: configDigest(c.root), ...(proseLanguage ? { proseLanguage } : {}) };
533
+ onStart?.(runId);
534
+ const s = await withRunLock(c, runId, () => advance(s0, deps(c, s0, git)));
535
+ report(c, s);
536
+ return exitFor(s);
537
+ }
538
+ export async function cmdApprove(c, git, runId, gate, expect, as) {
539
+ if (!runId || (gate !== 'plan' && gate !== 'commit') || !expect || !as?.trim()) {
540
+ c.err(t('workflow.usage.approve'));
541
+ return 2;
542
+ }
543
+ if (!loadRunState(c.store, runId)) {
544
+ c.err(t('workflow.unknownRun', { run: n(runId) }));
545
+ return 1;
546
+ }
547
+ try {
548
+ const s = await withRunLock(c, runId, async () => {
549
+ const s0 = loadRunState(c.store, runId);
550
+ const problem = await checkRunContext(c, git, s0);
551
+ if (problem)
552
+ throw new Error(problem);
553
+ const node = GATE[gate];
554
+ const s1 = approve(s0, node, as.trim(), new Date(), expect.trim().toLowerCase());
555
+ appendEvent(c.store, runId, { type: 'approval', node, approvedBy: as.trim(), binding: s1.approvals[node].binding });
556
+ return advance(s1, deps(c, s1, git));
557
+ });
558
+ report(c, s);
559
+ return exitFor(s);
560
+ }
561
+ catch (e) {
562
+ c.err(t('workflow.cmdError', { command: 'approve', message: nLog(e.message) }));
563
+ return 1;
564
+ }
565
+ }
566
+ /** A killed run: record `run.interrupted` and the history entry (once the lock proves nobody owns the run), and save it. */
567
+ function recordInterruption(c, s, reason) {
568
+ const s1 = interrupt(s, reason, new Date());
569
+ appendEvent(c.store, s.runId, { type: 'run.interrupted', runId: s.runId, node: s.current });
570
+ saveRunState(c.store, s.runId, s1);
571
+ return s1;
572
+ }
573
+ export async function cmdResume(c, git, runId) {
574
+ if (!runId) {
575
+ c.err(t('workflow.usage.resume'));
576
+ return 2;
577
+ }
578
+ if (!loadRunState(c.store, runId)) {
579
+ c.err(t('workflow.unknownRun', { run: n(runId) }));
580
+ return 1;
581
+ }
582
+ try {
583
+ const s = await withRunLock(c, runId, async () => {
584
+ const s0 = loadRunState(c.store, runId);
585
+ const problem = await checkRunContext(c, git, s0);
586
+ if (problem)
587
+ throw new Error(problem);
588
+ // Holding the lock, a `running` state has no owner: its process was killed. Record that, then re-enter at the same node.
589
+ const s1 = resume(s0.status === 'running' ? recordInterruption(c, s0, english('workflow.processGone')) : s0);
590
+ return advance(s1, deps(c, s1, git));
591
+ });
592
+ report(c, s);
593
+ return exitFor(s);
594
+ }
595
+ catch (e) {
596
+ c.err(t('workflow.cmdError', { command: 'resume', message: nLog(e.message) }));
597
+ return 1;
598
+ }
599
+ }
600
+ /** Fields shared by `status --json` and `status <run> --json`; every key is always present (null when unset). */
601
+ const runSummary = (s) => ({ runId: s.runId, status: s.status, current: s.current, attempts: s.attempts,
602
+ branch: s.branch ?? null, commit: s.commit ?? null, request: s.request.split('\n')[0] });
603
+ /**
604
+ * `--json` goes through jsonOut, not the neutraliser: JSON.stringify escapes only C0, so jsonOut also escapes DEL, C1,
605
+ * the bidi controls and U+2028/U+2029 as \u sequences. The parsed value is unchanged, and the bytes are identical for
606
+ * any output without those characters (the text output is neutralised below).
607
+ */
608
+ export function cmdStatus(c, runId, json = false) {
609
+ if (!runId && json) {
610
+ c.out(jsonOut(listRuns(c.store).map(id => runSummary(effective(c, loadRunState(c.store, id))))));
611
+ return 0;
612
+ }
613
+ if (!runId) {
614
+ for (const id of listRuns(c.store)) {
615
+ const s = effective(c, loadRunState(c.store, id));
616
+ c.out(`${n(id)} ${n(s.status).padEnd(16)} ${n(s.current).padEnd(15)} ${nCut(s.request.split('\n')[0], 60)}`);
617
+ }
618
+ return 0;
619
+ }
620
+ const s0 = loadRunState(c.store, runId);
621
+ if (!s0) {
622
+ c.err(t('workflow.unknownRun', { run: n(runId) }));
623
+ return 1;
624
+ }
625
+ const s = effective(c, s0);
626
+ if (json) {
627
+ const p = pendingApproval(s);
628
+ c.out(jsonOut({ ...runSummary(s), history: s.history, pendingApproval: p ? { gate: gateWord(p.node), expectedHash: p.binding } : null, reason: s.reason ?? null }));
629
+ return 0;
630
+ }
631
+ report(c, s);
632
+ // Where the code goes for this run's judges (spec §2 objective 6), from the current configuration.
633
+ const wf = workflowOf(c.cfg);
634
+ const judge = (id) => {
635
+ const a = c.cfg.agents[id];
636
+ if (!a)
637
+ return t('workflow.judgeAbsent', { id: n(id) });
638
+ if (a.runtime === 'opencode')
639
+ return `${n(id)} (opencode: ${n(a.model ?? '')})`;
640
+ if (a.runtime !== 'api')
641
+ return `${n(id)} (${a.runtime})`;
642
+ const p = c.cfg.providers[a.provider];
643
+ return `${n(id)} (api: ${n(new URL(p.url).host)}/${n(p.model)})`;
644
+ };
645
+ const judges = [...new Set([...wf.challengers, ...wf.reviewers])].map(judge).join(', ');
646
+ if (c.cfg.workflow)
647
+ c.out(` ${t('workflow.judges', { list: judges })}`); // default projects: no line
648
+ for (const h of s.history)
649
+ c.out(` ${n(h.at)} ${n(h.node).padEnd(15)} ${n(h.outcome)}`);
650
+ return 0;
651
+ }
652
+ export function cmdShow(c, runId, artifact) {
653
+ if (!runId) {
654
+ c.err(t('workflow.usage.show'));
655
+ return 2;
656
+ }
657
+ const s = loadRunState(c.store, runId);
658
+ if (!s) {
659
+ c.err(t('workflow.unknownRun', { run: n(runId) }));
660
+ return 1;
661
+ }
662
+ if (!artifact) {
663
+ for (const name of Object.keys(s.artifacts).sort())
664
+ c.out(`${n(name)} ${getArtifact(c.store, s.artifacts[name]).length}`);
665
+ return 0;
666
+ }
667
+ const h = s.artifacts[artifact];
668
+ if (!h) {
669
+ c.err(t('workflow.noArtifact', { artifact: n(artifact), available: Object.keys(s.artifacts).map(n).join(', ') }));
670
+ return 1;
671
+ }
672
+ c.out(nBlock(getArtifact(c.store, h).toString('utf8')));
673
+ return 0;
674
+ }