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,424 @@
1
+ /**
2
+ * The dashboard's data layer: a READ-ONLY watcher over the control store (spec §6, AC-10/13/14).
3
+ *
4
+ * It never writes, never locks, never creates a directory, never calls `repoStore()`, never opens `runs/<id>/lock`
5
+ * for writing. `poll()` only stats (the `runs` directory, the `state.json` of the newest runs, the selected run's
6
+ * directory, its `events.jsonl` and, for a running run, whether its process is alive); it reads a file only when its
7
+ * stamp changed, and an unchanged stamp returns `false` with the same model object. Every string that comes from the
8
+ * store goes through `n()` here, once, and the characters made visible are counted in `marked` (untrusted-text rules
9
+ * 1 and 2); renderers receive neutral text only.
10
+ */
11
+ import { lstatSync, statSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { pendingApproval, projectRun, runIdTime } from '../../../packages/application/src/index.js';
14
+ import { getArtifact, listRuns, readEvents, readRegularFile } from '../../../adapters/store-fs/src/index.js';
15
+ import { t } from "./i18n/index.js";
16
+ import { parseDiff, textDocs } from "./tui/components/diff-viewer.js";
17
+ import { n, neutralize } from "./tui/neutral.js";
18
+ import { shownRun } from "./tui/view.js";
19
+ export const MAX_RUNS = 50;
20
+ export const MAX_EVENTS = 1000;
21
+ const TAIL_BYTES = 512 * 1024;
22
+ const STATE_MAX_BYTES = 4 * 1024 * 1024;
23
+ const RUN_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
24
+ const STATUSES = ['running', 'waiting-approval', 'completed', 'failed', 'needs-human', 'interrupted'];
25
+ const validId = (id) => RUN_ID_RE.test(id) && !id.includes('..');
26
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? String(v) : '?');
27
+ // ---- event lines -------------------------------------------------------------------------------------------------
28
+ /** One stored event as a line: every string through `n()`, the number of characters made visible in `marked`. */
29
+ export function eventLine(e) {
30
+ let marked = 0;
31
+ const s = (v, fallback = '?') => {
32
+ if (typeof v !== 'string' || v === '')
33
+ return fallback;
34
+ const r = neutralize(v, { singleLine: true });
35
+ marked += r.marked;
36
+ return r.text;
37
+ };
38
+ const at = typeof e.ts === 'string' ? s(e.ts, '') : '';
39
+ const type = typeof e.type === 'string' ? e.type : undefined;
40
+ const done = (subject, text, tone) => ({ at, subject, text, ...(tone ? { tone } : {}), marked });
41
+ const who = () => s(e.label ?? e.runtime);
42
+ switch (type) {
43
+ case 'node.transition': return done(s(e.node), t('dashboard.event.transition', { outcome: s(e.outcome), next: s(e.next) }));
44
+ case 'agent.started': return done(s(e.agent), t('dashboard.event.agentStarted', { who: who() }));
45
+ case 'agent.finished': return done(s(e.agent), t('dashboard.event.agentFinished', { who: who(), status: s(e.status) }));
46
+ case 'verify.result': return e.passed === true
47
+ ? done(s(type), t('dashboard.event.verifyPassed', { attempt: num(e.attempt) }), 'green')
48
+ : done(s(type), t('dashboard.event.verifyFailed', { attempt: num(e.attempt), exit: e.exitCode === null || e.exitCode === undefined ? '?' : num(e.exitCode) }), 'red');
49
+ case 'red.result': return e.inconclusive === true
50
+ ? done(s(type), t('dashboard.event.redInconclusive', { attempt: num(e.attempt) }), 'amber')
51
+ : e.redFailed === true ? done(s(type), t('dashboard.event.redProven', { attempt: num(e.attempt) }), 'green')
52
+ : done(s(type), t('dashboard.event.redNotProven', { attempt: num(e.attempt) }), 'red');
53
+ case 'approval': return done(s(e.node), t('dashboard.event.approval', { by: s(e.approvedBy) }), 'green');
54
+ case 'risk.accepted': return done(s(e.agent), t('dashboard.event.risk', { capability: s(e.capability), by: s(e.approvedBy) }), 'amber');
55
+ default:
56
+ if (type !== undefined && type.startsWith('run.')) {
57
+ const status = type.slice(4);
58
+ const tone = status === 'completed' ? 'green' : status === 'waiting-approval' ? 'amber' : ['failed', 'needs-human', 'interrupted'].includes(status) ? 'red' : undefined;
59
+ return done(s('run'), t('dashboard.event.run', { status: s(status), node: s(e.node) }), tone);
60
+ }
61
+ return done('', s(type));
62
+ }
63
+ }
64
+ // ---- agent rows --------------------------------------------------------------------------------------------------
65
+ /** The Agents panel's rows: the squad with each agent's runtime version, last model and, when live, its running step. */
66
+ export function agentRows(fixed, sel) {
67
+ return fixed.squad.map((m) => {
68
+ const runtime = m.runtime ?? '?';
69
+ const base = { role: m.role, runtime: `${n(runtime)} ${n(fixed.runtimeVersions[runtime] ?? '?')}`, state: m.state, ...(m.note ? { note: m.note } : {}) };
70
+ if (m.agent === undefined)
71
+ return { ...base, model: null };
72
+ let model;
73
+ let workingSince;
74
+ const steps = sel?.view.steps ?? [];
75
+ for (let i = steps.length - 1; i >= 0 && model === undefined; i--) {
76
+ const st = steps[i];
77
+ model = (st.runs ?? []).findLast(r => r.agent === m.agent && r.model)?.model ?? (st.agent === m.agent ? st.model : undefined);
78
+ }
79
+ const running = steps.find(st => st.state === 'running' && (st.agent === m.agent || (st.runs ?? []).some(r => r.agent === m.agent)));
80
+ if (running && sel?.liveness === 'live' && running.startedAt)
81
+ workingSince = running.startedAt;
82
+ return { ...base, id: m.agent, ...(model !== undefined ? { model } : {}), ...(workingSince ? { workingSince } : {}) };
83
+ });
84
+ }
85
+ // ---- liveness ----------------------------------------------------------------------------------------------------
86
+ const defaultIsAlive = (pid) => {
87
+ try {
88
+ process.kill(pid, 0);
89
+ return true;
90
+ }
91
+ catch (e) {
92
+ const c = e.code;
93
+ return c === 'ESRCH' ? false : c === 'EPERM' ? true : undefined;
94
+ }
95
+ };
96
+ /**
97
+ * The pid written in runs/<id>/lock, read only (one descriptor: never a link, never a FIFO, at most 32 bytes): an
98
+ * integer above 0 or nothing (kill(0) would signal our own group).
99
+ */
100
+ function lockPid(store, id) {
101
+ try {
102
+ const text = readRegularFile(join(store.runs, id, 'lock'), { maxBytes: 32 }).bytes.toString('utf8').trim();
103
+ if (!/^\d{1,10}$/.test(text))
104
+ return undefined;
105
+ const pid = Number(text);
106
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ // ---- stamps ------------------------------------------------------------------------------------------------------
113
+ const BINDING_RE = /^[0-9a-f]{40,64}$/;
114
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
115
+ const OPTIONAL_STRINGS = ['request', 'reason', 'branch', 'commit', 'reviewedTree'];
116
+ /**
117
+ * state.json of run `id` (its directory), read now, and its shape: the one check between the store and every reader
118
+ * here. A regular file of at most 4 MiB (opened once, never through a link, never blocking on a FIFO) holding an object whose `runId` is that directory (a state naming another run
119
+ * would send an approval there), `status` and `current` strings, `attempts` a finite number, `artifacts` an object of
120
+ * strings, `approvals` an object, `history` an array of `{node, outcome, at}` strings, `request`, `reason`, `branch`,
121
+ * `commit` and `reviewedTree` strings when present, and a pending binding that is a hash (40 to 64 lowercase hex).
122
+ * Throws otherwise: the row reads `unreadable` and the selection keeps its last view.
123
+ */
124
+ function readStateFile(store, id) {
125
+ if (!validId(id))
126
+ throw new Error('invalid run id');
127
+ const v = JSON.parse(readRegularFile(join(store.runs, id, 'state.json'), { maxBytes: STATE_MAX_BYTES }).bytes.toString('utf8'));
128
+ if (!isObject(v) || typeof v.status !== 'string')
129
+ throw new Error('invalid state');
130
+ if (v.runId !== id)
131
+ throw new Error('the state of another run');
132
+ if (typeof v.current !== 'string' || typeof v.attempts !== 'number' || !Number.isFinite(v.attempts))
133
+ throw new Error('invalid state');
134
+ if (!isObject(v.artifacts) || !Object.values(v.artifacts).every((x) => typeof x === 'string') || !isObject(v.approvals))
135
+ throw new Error('invalid state');
136
+ if (!Array.isArray(v.history) || !v.history.every((h) => isObject(h) && typeof h.node === 'string' && typeof h.outcome === 'string' && typeof h.at === 'string'))
137
+ throw new Error('invalid state');
138
+ if (OPTIONAL_STRINGS.some((k) => v[k] !== undefined && typeof v[k] !== 'string'))
139
+ throw new Error('invalid state');
140
+ const p = pendingApproval(v);
141
+ if (p && !BINDING_RE.test(p.binding))
142
+ throw new Error('the pending binding is not a hash');
143
+ return v;
144
+ }
145
+ // ---- the viewer's data -------------------------------------------------------------------------------------------
146
+ /**
147
+ * The gate a run waits for and its binding, read from state.json NOW (never the cached model); undefined when none or
148
+ * unreadable. `at`: when it started waiting (the run's last history entry), for the stale screen's re-verify time.
149
+ */
150
+ export function freshPending(store, runId) {
151
+ try {
152
+ if (!validId(runId))
153
+ return undefined;
154
+ const state = readStateFile(store, runId);
155
+ const p = pendingApproval(state);
156
+ if (!p || !BINDING_RE.test(p.binding))
157
+ return undefined; // a binding is a hash, or there is none
158
+ const at = Array.isArray(state.history) ? state.history.at(-1)?.at : undefined;
159
+ return { gate: p.node === 'approve-plan' ? 'plan' : 'commit', binding: p.binding, ...(typeof at === 'string' ? { at } : {}) };
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ }
165
+ /**
166
+ * The run's state and its last events, read NOW, for one check only: did `taskquoin approve` record the approval
167
+ * (dashboard-approve.ts approvalRecorded). Never rendered; nothing here is shown or neutralised.
168
+ */
169
+ export function freshApproval(store, runId) {
170
+ if (!validId(runId))
171
+ return { events: [] };
172
+ let state;
173
+ try {
174
+ state = readStateFile(store, runId);
175
+ }
176
+ catch {
177
+ state = undefined;
178
+ }
179
+ let events = [];
180
+ try {
181
+ events = readEvents(store, runId, { max: MAX_EVENTS, tailBytes: TAIL_BYTES }).events;
182
+ }
183
+ catch {
184
+ events = [];
185
+ }
186
+ return { ...(state ? { state } : {}), events };
187
+ }
188
+ /** The sha of a named artifact in state.json now. */
189
+ export function artifactSha(store, runId, name) {
190
+ try {
191
+ if (!validId(runId))
192
+ return undefined;
193
+ const v = readStateFile(store, runId).artifacts?.[name];
194
+ return typeof v === 'string' ? v : undefined;
195
+ }
196
+ catch {
197
+ return undefined;
198
+ }
199
+ }
200
+ export const MAX_ARTIFACT_BYTES = 4 * 1024 * 1024;
201
+ const SHA_RE = /^[0-9a-f]{64}$/;
202
+ const highest = (names, prefix) => {
203
+ let best;
204
+ for (const k of names) {
205
+ const m = new RegExp(`^${prefix}-(\\d+)$`).exec(k);
206
+ if (m && (best === undefined || Number(m[1]) > best))
207
+ best = Number(m[1]);
208
+ }
209
+ return best;
210
+ };
211
+ /**
212
+ * What the viewer shows, read on demand: `review` is plan + challenge at the plan gate (or before any diff), else the
213
+ * highest `diff-N`; `verify` is the highest `verify-N` and its `red-N`. Each artifact is opened once through
214
+ * `getArtifact` (never through a link, never blocking on a FIFO or a device; over 4 MiB is refused, unread, with the
215
+ * `taskquoin show` route) and re-hashed. `binding` is
216
+ * the commit gate's tree hash when the run waits at commit and the artifact is its `diff-<attempts>`.
217
+ */
218
+ export function loadDocs(store, runId, which) {
219
+ if (!validId(runId))
220
+ return { error: t('dashboard.viewer.noRun') };
221
+ let state;
222
+ try {
223
+ state = readStateFile(store, runId);
224
+ }
225
+ catch {
226
+ return { error: t('dashboard.data.stateInvalid') };
227
+ }
228
+ const arts = state.artifacts ?? {};
229
+ const names = Object.keys(arts);
230
+ const short = n(runId.split('-').at(-1) ?? runId);
231
+ let picked = [], titleKey = 'dashboard.viewer.titleDiff', asDiff = false;
232
+ if (which === 'verify') {
233
+ const v = highest(names, 'verify');
234
+ if (v !== undefined)
235
+ picked = [`verify-${v}`, ...(`red-${v}` in arts ? [`red-${v}`] : [])];
236
+ titleKey = 'dashboard.viewer.titleVerify';
237
+ }
238
+ else {
239
+ const d = highest(names, 'diff');
240
+ if (d !== undefined && state.current !== 'approve-plan') {
241
+ picked = [`diff-${d}`];
242
+ asDiff = true;
243
+ }
244
+ else {
245
+ picked = ['plan', 'challenge'].filter((k) => k in arts);
246
+ titleKey = 'dashboard.viewer.titlePlan';
247
+ }
248
+ }
249
+ if (picked.length === 0)
250
+ return { error: t('dashboard.viewer.none') };
251
+ const shaOf = (name) => (typeof arts[name] === 'string' && SHA_RE.test(arts[name]) ? arts[name] : undefined);
252
+ for (const name of picked)
253
+ if (shaOf(name) === undefined)
254
+ return { error: t('dashboard.viewer.unreadable', { artifact: n(name), run: n(runId) }) };
255
+ const texts = [];
256
+ for (const name of picked) {
257
+ try {
258
+ texts.push({ name, text: getArtifact(store, shaOf(name), { maxBytes: MAX_ARTIFACT_BYTES }).toString('utf8') });
259
+ }
260
+ catch (e) {
261
+ const { code, size, message } = (e ?? {});
262
+ if (code === 'EFBIG' && typeof size === 'number')
263
+ return { error: t('dashboard.viewer.tooBig', { artifact: n(name), size: (size / 1048576).toFixed(1), run: n(runId) }) };
264
+ const mismatch = /hash mismatch/.test(String(message));
265
+ return { error: t(mismatch ? 'dashboard.viewer.mismatch' : 'dashboard.viewer.unreadable', { artifact: n(name), run: n(runId) }) };
266
+ }
267
+ }
268
+ let docs = asDiff ? parseDiff(texts[0].text) : textDocs(texts);
269
+ if (docs.length === 0)
270
+ docs = textDocs(texts);
271
+ const pending = pendingApproval(state);
272
+ const binding = asDiff && pending?.node === 'approve-commit' && picked[0] === `diff-${state.attempts}` && BINDING_RE.test(pending.binding) ? pending.binding : undefined;
273
+ return { title: t(titleKey, { run: short }), artifact: picked[0], sha: shaOf(picked[0]), docs, ...(binding !== undefined ? { binding } : {}) };
274
+ }
275
+ const stampOf = (path, link = false) => {
276
+ try {
277
+ const s = (link ? lstatSync : statSync)(path);
278
+ return `${s.mtimeMs}:${s.size}`;
279
+ }
280
+ catch {
281
+ return '-';
282
+ }
283
+ };
284
+ export function createWatcher(store, fixed, o) {
285
+ const isAlive = o.isAlive ?? defaultIsAlive;
286
+ let runsStamp = '';
287
+ let ids = [];
288
+ const rows = new Map();
289
+ let want = o.runId;
290
+ let sel;
291
+ let key = '';
292
+ let current;
293
+ const listIds = () => {
294
+ try {
295
+ return listRuns(store).filter(validId).sort().reverse().slice(0, MAX_RUNS);
296
+ }
297
+ catch {
298
+ return [];
299
+ }
300
+ };
301
+ const readState = (id) => readStateFile(store, id);
302
+ const liveness = (id, status) => {
303
+ if (status !== 'running')
304
+ return 'none';
305
+ const pid = lockPid(store, id);
306
+ if (pid === undefined)
307
+ return 'none';
308
+ const a = isAlive(pid);
309
+ return a === undefined ? 'unknown' : a ? 'live' : 'none';
310
+ };
311
+ const shortOf = (id) => { const last = id.split('-').at(-1) ?? ''; return n(last === '' ? id : last); };
312
+ const rowOf = (id) => {
313
+ const base = { runId: n(id), short: shortOf(id), startedAt: runIdTime(id) ?? '' };
314
+ try {
315
+ const s = readState(id);
316
+ const status = (STATUSES.includes(s.status) ? s.status : 'unreadable');
317
+ const pending = status === 'waiting-approval' ? pendingApproval(s) : undefined;
318
+ const request = typeof s.request === 'string' ? n(s.request.split('\n')[0].slice(0, 300)) : n('');
319
+ return { ...base, status, request, ...(pending ? { waiting: pending.node === 'approve-plan' ? 'plan' : 'commit' } : {}), ...(status === 'running' ? { liveness: liveness(id, status) } : {}) };
320
+ }
321
+ catch {
322
+ return { ...base, status: 'unreadable', request: n('') };
323
+ }
324
+ };
325
+ /** The selected run: state, events and projection, neutralised. Throws when state.json cannot be used. */
326
+ const loadSelected = (id, lv) => {
327
+ const state = readState(id);
328
+ const { events: raw, skipped, cut } = readEvents(store, id, { max: MAX_EVENTS, tailBytes: TAIL_BYTES });
329
+ const shown = shownRun(projectRun(state, raw));
330
+ let marked = shown.marked;
331
+ const reqText = typeof state.request === 'string' ? state.request.split('\n')[0].slice(0, 300) : '';
332
+ const req = neutralize(reqText, { singleLine: true });
333
+ marked += req.marked;
334
+ const events = raw.map(eventLine).reverse();
335
+ for (const e of events)
336
+ marked += e.marked;
337
+ return { runId: id, view: shown.view, request: req.text, ...(shown.view.reason !== undefined ? { reason: shown.view.reason } : {}), marked, events, skipped, cut, liveness: lv(state.status) };
338
+ };
339
+ /** Rebuild what the stamps say changed; returns the new composite key. */
340
+ const refresh = (first) => {
341
+ const rs = stampOf(store.runs);
342
+ if (first || rs !== runsStamp) {
343
+ runsStamp = rs;
344
+ ids = listIds();
345
+ }
346
+ const live = new Set(ids);
347
+ for (const k of [...rows.keys()])
348
+ if (!live.has(k))
349
+ rows.delete(k);
350
+ const parts = [rs];
351
+ for (const id of ids) {
352
+ const stamp = stampOf(join(store.runs, id, 'state.json'), true);
353
+ const prev = rows.get(id);
354
+ if (!prev || prev.stamp !== stamp)
355
+ rows.set(id, { stamp, entry: stamp === '-' ? undefined : rowOf(id) });
356
+ parts.push(`${id}=${stamp}`);
357
+ }
358
+ if (want !== undefined && validId(want)) {
359
+ const id = want;
360
+ const dir = stampOf(join(store.runs, id)), state = stampOf(join(store.runs, id, 'state.json'), true), ev = stampOf(join(store.runs, id, 'events.jsonl'), true);
361
+ const same = sel?.id === id;
362
+ if (!same || sel.stateStamp !== state || sel.evStamp !== ev) {
363
+ const next = { id, stateStamp: state, evStamp: ev };
364
+ if (state === '-' && dir === '-') {
365
+ if (same && sel.selected)
366
+ next.selected = { ...sel.selected, gone: true };
367
+ }
368
+ else {
369
+ try {
370
+ next.selected = loadSelected(id, st => liveness(id, st));
371
+ }
372
+ catch {
373
+ next.readError = t('dashboard.data.stateInvalid');
374
+ if (same)
375
+ next.selected = sel.selected;
376
+ }
377
+ }
378
+ sel = next;
379
+ }
380
+ else if (sel.selected && sel.selected.view.status === 'running') {
381
+ const lv = liveness(id, 'running'); // the process dying changes no file: it is probed on every poll
382
+ if (sel.selected.liveness !== lv)
383
+ sel = { ...sel, selected: { ...sel.selected, liveness: lv } };
384
+ }
385
+ parts.push(`sel=${id}:${dir}:${state}:${ev}:${sel.selected?.liveness ?? ''}`);
386
+ }
387
+ else {
388
+ sel = undefined;
389
+ parts.push('sel=none');
390
+ }
391
+ return parts.join('|');
392
+ };
393
+ const build = () => ({
394
+ fixed,
395
+ runs: ids.map(id => rows.get(id)?.entry).filter((e) => e !== undefined),
396
+ ...(sel?.selected ? { selected: sel.selected } : {}),
397
+ lastChange: o.now().toISOString(),
398
+ ...(sel?.readError ? { readError: sel.readError } : {}),
399
+ });
400
+ if (want === undefined) {
401
+ ids = listIds();
402
+ runsStamp = stampOf(store.runs);
403
+ want = ids[0];
404
+ }
405
+ key = refresh(true);
406
+ current = build();
407
+ return {
408
+ model: () => current,
409
+ poll() {
410
+ const before = key;
411
+ key = refresh(false);
412
+ if (key === before)
413
+ return false;
414
+ current = build();
415
+ return true;
416
+ },
417
+ select(runId) {
418
+ want = runId;
419
+ sel = undefined;
420
+ key = refresh(false);
421
+ current = build();
422
+ },
423
+ };
424
+ }