@heretek-ai/opencode-teamwork-v2 0.0.0-stage → 0.5.10
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.
- package/LICENSE +22 -0
- package/README.md +387 -2
- package/agents/team/crafter.md +146 -0
- package/agents/team/falsifier.md +98 -0
- package/agents/team/orchestrator.md +136 -0
- package/agents/team/proof-worker.md +66 -0
- package/agents/team/proposer.md +76 -0
- package/agents/team/scout.md +93 -0
- package/agents/team/security-auditor.md +64 -0
- package/agents/team/sentinel.md +175 -0
- package/agents/team/synthesizer.md +108 -0
- package/agents/team/verifier.md +106 -0
- package/agents/team/worker.md +74 -0
- package/bin/opencode-teamwork.mjs +517 -0
- package/docs/ARTIFACTS.md +806 -0
- package/docs/GUARDRAILS.md +48 -0
- package/lib/doctor.mjs +280 -0
- package/lib/export.mjs +1119 -0
- package/lib/picker.mjs +132 -0
- package/lib/runs.mjs +165 -0
- package/lib/team.mjs +394 -0
- package/lib/timeline.mjs +713 -0
- package/package.json +68 -4
- package/plugins/opencode-teamwork/index.ts +232 -0
- package/plugins/opencode-teamwork/package.json +11 -0
- package/plugins/opencode-teamwork/tools.ts +2912 -0
- package/postinstall.mjs +71 -0
- package/scripts/lint-prompts.mjs +168 -0
- package/scripts/test-cost.mjs +242 -0
- package/scripts/test-doctor.mjs +287 -0
- package/scripts/test-engine.mjs +2041 -0
- package/scripts/test-export.mjs +540 -0
- package/scripts/test-timeline.mjs +1041 -0
|
@@ -0,0 +1,1041 @@
|
|
|
1
|
+
// @heretek-ai/opencode-teamwork-v2 — lifecycle timeline test suite
|
|
2
|
+
//
|
|
3
|
+
// Hermetic, zero-dependency coverage for `lib/timeline.mjs` and the
|
|
4
|
+
// `opencode-teamwork timeline` CLI. Every fixture is a synthetic run directory
|
|
5
|
+
// inside its own mkdtemp dir. The CLI is spawned with cwd set to the fixture
|
|
6
|
+
// root and HOME pointed at an empty temp dir, so neither the developer's real
|
|
7
|
+
// ~/.config/opencode nor the live .opencode/teamwork/ tree is ever read.
|
|
8
|
+
//
|
|
9
|
+
// Run with plain Node (no test framework): failures are counted, printed, and
|
|
10
|
+
// make the process exit non-zero.
|
|
11
|
+
|
|
12
|
+
import { buildTimeline, renderTimeline, timelineWarnings } from "../lib/timeline.mjs"
|
|
13
|
+
import { registerTeamworkTools } from "../plugins/opencode-teamwork/tools.ts"
|
|
14
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync, symlinkSync, truncateSync, existsSync, lstatSync } from "node:fs"
|
|
15
|
+
import { tmpdir } from "node:os"
|
|
16
|
+
import { join, dirname } from "node:path"
|
|
17
|
+
import { fileURLToPath } from "node:url"
|
|
18
|
+
import { spawnSync, execFileSync } from "node:child_process"
|
|
19
|
+
import assert from "node:assert"
|
|
20
|
+
|
|
21
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
22
|
+
const cliPath = join(here, "..", "bin", "opencode-teamwork.mjs")
|
|
23
|
+
const ESC = "\u001b["
|
|
24
|
+
|
|
25
|
+
// Root temp dir for this run; every fixture lives under it and it is removed in the end.
|
|
26
|
+
const testDir = mkdtempSync(join(tmpdir(), "teamwork-timeline-test-"))
|
|
27
|
+
|
|
28
|
+
// An empty HOME: any accidental read of ~/.config/opencode finds nothing.
|
|
29
|
+
const emptyHome = mkdtempSync(join(testDir, "home-"))
|
|
30
|
+
|
|
31
|
+
// Keep the in-process environment hermetic too.
|
|
32
|
+
process.env.HOME = emptyHome
|
|
33
|
+
process.env.USERPROFILE = emptyHome
|
|
34
|
+
process.env.XDG_CONFIG_HOME = join(emptyHome, ".config")
|
|
35
|
+
|
|
36
|
+
const SESSION = "20261018-100000-tl01"
|
|
37
|
+
const SESSION_TWO = "20261018-110000-tl02"
|
|
38
|
+
|
|
39
|
+
let passed = 0
|
|
40
|
+
let failed = 0
|
|
41
|
+
|
|
42
|
+
/** Run one named check; a thrown assertion is recorded and the suite continues. */
|
|
43
|
+
async function check(name, fn) {
|
|
44
|
+
try {
|
|
45
|
+
await fn()
|
|
46
|
+
passed++
|
|
47
|
+
console.log(`✓ ${name}`)
|
|
48
|
+
} catch (err) {
|
|
49
|
+
failed++
|
|
50
|
+
console.error(`✗ ${name}\n ${err && err.message ? err.message : err}`)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function makeRoot() {
|
|
55
|
+
return mkdtempSync(join(testDir, "root-"))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A unique path under testDir for a sibling/outside fixture (never collides).
|
|
59
|
+
let fixtureSeq = 0
|
|
60
|
+
const uniq = (label) => join(testDir, `${label}-${++fixtureSeq}`)
|
|
61
|
+
|
|
62
|
+
function runDirOf(root, id) {
|
|
63
|
+
return join(root, ".opencode", "teamwork", id)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function writeJson(file, value) {
|
|
67
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
68
|
+
writeFileSync(file, JSON.stringify(value, null, 2) + "\n")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ---------------------------------------------------------------- fixtures
|
|
72
|
+
|
|
73
|
+
// Known timestamps. Every expected value below is derived by hand from these.
|
|
74
|
+
// run: run_created 09:59:50 → last event 10:04:00 ⇒ durationMs 250000 (4m 10s)
|
|
75
|
+
// alpha: worker_active 10:00:00 → verifier 10:01:00 → verified_fail r1 10:01:30
|
|
76
|
+
// → worker_active r2 10:02:00 → verifier 10:03:00 → verified_pass r2 10:04:00
|
|
77
|
+
// ⇒ startedAt 10:00:00, endedAt 10:04:00, durationMs 240000 (4m 00s),
|
|
78
|
+
// rounds 2, passedAtRound 2, agent team/worker
|
|
79
|
+
// beta: worker_active 10:00:10 → blocked r1 10:02:10 ⇒ durationMs 120000 (2m 00s), rounds 1
|
|
80
|
+
const EVENTS = [
|
|
81
|
+
{ ts: "2026-10-18T09:59:50.000Z", event: "run_created", sessionId: SESSION, taskId: null, from: null, to: "pending", round: 0, agent: null, branch: null, worktree: null, phase: "DAG_BUILD" },
|
|
82
|
+
{ ts: "2026-10-18T10:00:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "pending", to: "worker_active", round: 1, agent: "team/worker", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "DISPATCH" },
|
|
83
|
+
{ ts: "2026-10-18T10:00:10.000Z", event: "task_transition", sessionId: SESSION, taskId: "beta", from: "pending", to: "worker_active", round: 1, agent: "team/worker", branch: "teamwork/tl-beta", worktree: "/wt/beta", phase: "DISPATCH" },
|
|
84
|
+
{ ts: "2026-10-18T10:01:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "worker_active", to: "verifier_active", round: 1, agent: "team/verifier", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "VERIFY" },
|
|
85
|
+
{ ts: "2026-10-18T10:01:30.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "verifier_active", to: "verified_fail", round: 1, agent: "team/verifier", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "VERIFY" },
|
|
86
|
+
{ ts: "2026-10-18T10:02:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "verified_fail", to: "worker_active", round: 2, agent: "team/worker", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "DISPATCH" },
|
|
87
|
+
{ ts: "2026-10-18T10:02:10.000Z", event: "task_transition", sessionId: SESSION, taskId: "beta", from: "worker_active", to: "blocked", round: 1, agent: "team/verifier", branch: "teamwork/tl-beta", worktree: "/wt/beta", phase: "VERIFY" },
|
|
88
|
+
{ ts: "2026-10-18T10:03:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "worker_active", to: "verifier_active", round: 2, agent: "team/verifier", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "VERIFY" },
|
|
89
|
+
{ ts: "2026-10-18T10:04:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "verifier_active", to: "verified_pass", round: 2, agent: "team/verifier", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "VERIFY" },
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
const STATE = {
|
|
93
|
+
version: 1,
|
|
94
|
+
sessionId: SESSION,
|
|
95
|
+
phase: "DONE",
|
|
96
|
+
tasks: {
|
|
97
|
+
alpha: { status: "verified_pass", round: 2, updatedAt: "2026-10-18T10:04:00.000Z", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", summary: "alpha done", feedback: null, verification: null },
|
|
98
|
+
beta: { status: "blocked", round: 1, updatedAt: "2026-10-18T10:02:10.000Z", branch: "teamwork/tl-beta", worktree: "/wt/beta", summary: "beta blocked", feedback: null, verification: null },
|
|
99
|
+
},
|
|
100
|
+
updatedAt: "2026-10-18T10:04:00.000Z",
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const PLAN = {
|
|
104
|
+
sessionId: SESSION,
|
|
105
|
+
topology: "iterative-coding",
|
|
106
|
+
tasks: [
|
|
107
|
+
{ id: "alpha", dependsOn: [], requirements: [], agent: "team/worker", maxRounds: 4, status: "verified_pass", round: 2 },
|
|
108
|
+
{ id: "beta", dependsOn: [], requirements: [], agent: "team/worker", maxRounds: 4, status: "blocked", round: 1 },
|
|
109
|
+
],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const COSTS = {
|
|
113
|
+
sessionId: SESSION,
|
|
114
|
+
rootSessionIds: ["ses_root"],
|
|
115
|
+
budgetUsd: 5,
|
|
116
|
+
budgetSource: "manual",
|
|
117
|
+
spentUsd: 0.21,
|
|
118
|
+
byTask: { alpha: 0.12, beta: 0.05, _sentinel: 0.01, _unattributed: 0.02, "team/worker": 0.01 },
|
|
119
|
+
updatedAt: "2026-10-18T10:04:00.000Z",
|
|
120
|
+
tokens: { input: 1000, output: 200, reasoning: 0, cache: { read: 5, write: 6 } },
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Write a run directory under a fresh root and return the root.
|
|
125
|
+
* Pass `null` for any file to omit it (an explicit `undefined` would take the default).
|
|
126
|
+
*/
|
|
127
|
+
function makeRun({ id = SESSION, events = null, state = STATE, plan = PLAN, costs = COSTS, reports = {} } = {}) {
|
|
128
|
+
const root = makeRoot()
|
|
129
|
+
const dir = runDirOf(root, id)
|
|
130
|
+
mkdirSync(dir, { recursive: true })
|
|
131
|
+
if (events !== null) {
|
|
132
|
+
writeFileSync(join(dir, "events.jsonl"), events.map((e) => JSON.stringify(e)).join("\n") + "\n")
|
|
133
|
+
}
|
|
134
|
+
if (state !== null) writeJson(join(dir, "state.json"), state)
|
|
135
|
+
if (plan !== null) writeJson(join(dir, "plan.dag.json"), plan)
|
|
136
|
+
if (costs !== null) writeJson(join(dir, "costs.json"), costs)
|
|
137
|
+
for (const [taskId, report] of Object.entries(reports)) {
|
|
138
|
+
writeJson(join(dir, "verify", `report-${taskId}.json`), report)
|
|
139
|
+
}
|
|
140
|
+
return root
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function taskOf(timeline, taskId) {
|
|
144
|
+
const t = timeline.tasks.find((x) => x.taskId === taskId)
|
|
145
|
+
assert(t, `task ${taskId} must be present in timeline.tasks`)
|
|
146
|
+
return t
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const TASK_KEYS = [
|
|
150
|
+
"taskId", "status", "rounds", "passedAtRound", "agent", "agentSource", "branch", "seq", "startedAt", "endedAt",
|
|
151
|
+
"durationMs", "approx", "costUsd", "tokens", "note",
|
|
152
|
+
]
|
|
153
|
+
const TIMELINE_KEYS = [
|
|
154
|
+
"sessionId", "topology", "phase", "mode", "budgetUsd", "budgetSource", "spentUsd",
|
|
155
|
+
"startedAt", "endedAt", "durationMs", "tasks", "unattributed", "totals",
|
|
156
|
+
]
|
|
157
|
+
const TOTALS_KEYS = ["tasks", "passed", "failed", "blocked", "totalRounds", "spentUsd", "tokens"]
|
|
158
|
+
|
|
159
|
+
function assertShape(t) {
|
|
160
|
+
assert.deepStrictEqual(Object.keys(t).sort(), [...TIMELINE_KEYS].sort(), "top-level R2 keys")
|
|
161
|
+
assert.deepStrictEqual(Object.keys(t.totals).sort(), [...TOTALS_KEYS].sort(), "totals keys")
|
|
162
|
+
assert(Array.isArray(t.tasks), "tasks must be an array")
|
|
163
|
+
for (const task of t.tasks) {
|
|
164
|
+
assert.deepStrictEqual(Object.keys(task).sort(), [...TASK_KEYS].sort(), `task keys for ${task.taskId}`)
|
|
165
|
+
}
|
|
166
|
+
assert(Array.isArray(t.unattributed), "unattributed must be an array")
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Shared fixtures (built once; every one lives under testDir).
|
|
170
|
+
const eventsRoot = makeRun({ events: EVENTS, reports: { alpha: { taskId: "alpha", round: 2, status: "PASS" } } })
|
|
171
|
+
const derivedRoot = makeRun({ events: null, reports: { alpha: { taskId: "alpha", round: 2, status: "PASS" } } })
|
|
172
|
+
const eventsTimeline = buildTimeline(eventsRoot, SESSION)
|
|
173
|
+
const derivedTimeline = buildTimeline(derivedRoot, SESSION)
|
|
174
|
+
|
|
175
|
+
// ==========================================
|
|
176
|
+
// 1. events mode
|
|
177
|
+
// ==========================================
|
|
178
|
+
|
|
179
|
+
await check("events mode: mode and run-level startedAt/endedAt/durationMs are exact", () => {
|
|
180
|
+
const t = eventsTimeline
|
|
181
|
+
assert.strictEqual(t.mode, "events")
|
|
182
|
+
assert.strictEqual(t.startedAt, "2026-10-18T09:59:50.000Z")
|
|
183
|
+
assert.strictEqual(t.endedAt, "2026-10-18T10:04:00.000Z")
|
|
184
|
+
assert.strictEqual(t.durationMs, 250000)
|
|
185
|
+
assert.strictEqual(t.sessionId, SESSION)
|
|
186
|
+
assert.strictEqual(t.topology, "iterative-coding")
|
|
187
|
+
assert.strictEqual(t.phase, "DONE")
|
|
188
|
+
assert.strictEqual(t.budgetUsd, 5)
|
|
189
|
+
assert.strictEqual(t.budgetSource, "manual")
|
|
190
|
+
assert.strictEqual(t.spentUsd, 0.21)
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
await check("events mode: alpha startedAt/endedAt/durationMs/rounds/passedAtRound/agent are exact", () => {
|
|
194
|
+
const a = taskOf(eventsTimeline, "alpha")
|
|
195
|
+
assert.strictEqual(a.startedAt, "2026-10-18T10:00:00.000Z")
|
|
196
|
+
assert.strictEqual(a.endedAt, "2026-10-18T10:04:00.000Z")
|
|
197
|
+
assert.strictEqual(a.durationMs, 240000)
|
|
198
|
+
assert.strictEqual(a.rounds, 2)
|
|
199
|
+
assert.strictEqual(a.passedAtRound, 2)
|
|
200
|
+
assert.strictEqual(a.agent, "team/worker")
|
|
201
|
+
assert.strictEqual(a.status, "verified_pass")
|
|
202
|
+
assert.strictEqual(a.branch, "teamwork/tl-alpha")
|
|
203
|
+
assert.strictEqual(a.approx, false)
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
await check("events mode: beta (blocked) has exact duration, no pass round, approx false", () => {
|
|
207
|
+
const b = taskOf(eventsTimeline, "beta")
|
|
208
|
+
assert.strictEqual(b.startedAt, "2026-10-18T10:00:10.000Z")
|
|
209
|
+
assert.strictEqual(b.endedAt, "2026-10-18T10:02:10.000Z")
|
|
210
|
+
assert.strictEqual(b.durationMs, 120000)
|
|
211
|
+
assert.strictEqual(b.rounds, 1)
|
|
212
|
+
assert.strictEqual(b.passedAtRound, null)
|
|
213
|
+
assert.strictEqual(b.agent, "team/worker")
|
|
214
|
+
assert.strictEqual(b.approx, false)
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
await check("events mode: mixed legacy (no seq) and new (seq + agentSource) lines render together", () => {
|
|
218
|
+
// alpha's first transition carries seq 2 and agentSource; beta's lines are legacy.
|
|
219
|
+
const mixed = [
|
|
220
|
+
{ ...EVENTS[0] },
|
|
221
|
+
{ ...EVENTS[1], seq: 2, agentSource: "session" },
|
|
222
|
+
{ ...EVENTS[2] },
|
|
223
|
+
{ ...EVENTS[3], seq: 4, agentSource: "explicit" },
|
|
224
|
+
{ ...EVENTS[4], seq: 5, agentSource: "explicit" },
|
|
225
|
+
{ ...EVENTS[5], seq: 6, agentSource: "session" },
|
|
226
|
+
{ ...EVENTS[6] },
|
|
227
|
+
{ ...EVENTS[7], seq: 8, agentSource: "explicit" },
|
|
228
|
+
{ ...EVENTS[8], seq: 9, agentSource: "explicit" },
|
|
229
|
+
]
|
|
230
|
+
const t = buildTimeline(makeRun({ events: mixed }), SESSION)
|
|
231
|
+
assert.strictEqual(t.mode, "events")
|
|
232
|
+
const alpha = taskOf(t, "alpha")
|
|
233
|
+
assert.strictEqual(alpha.seq, 2, "the new line must expose its sequence")
|
|
234
|
+
assert.strictEqual(alpha.agentSource, "session", "agentSource must sit alongside the actor")
|
|
235
|
+
const beta = taskOf(t, "beta")
|
|
236
|
+
assert.strictEqual(beta.seq, null, "legacy lines have no sequence")
|
|
237
|
+
assert.strictEqual(beta.agentSource, null, "legacy lines have no agentSource")
|
|
238
|
+
const text = renderTimeline(t, { color: false }).join("\n")
|
|
239
|
+
assert(text.includes("seq: 2"), "the rendered timeline must show the new sequence")
|
|
240
|
+
assert(text.includes("worker: team/worker (session)"), "the rendered actor must show its source")
|
|
241
|
+
assert(
|
|
242
|
+
text.includes(" worker: team/worker branch: teamwork/tl-beta"),
|
|
243
|
+
"a legacy task line must render exactly as before",
|
|
244
|
+
)
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
await check("events mode: totals are exact", () => {
|
|
248
|
+
const { totals } = eventsTimeline
|
|
249
|
+
assert.strictEqual(totals.tasks, 2)
|
|
250
|
+
assert.strictEqual(totals.passed, 1)
|
|
251
|
+
assert.strictEqual(totals.failed, 0)
|
|
252
|
+
assert.strictEqual(totals.blocked, 1)
|
|
253
|
+
assert.strictEqual(totals.totalRounds, 3)
|
|
254
|
+
})
|
|
255
|
+
|
|
256
|
+
// ==========================================
|
|
257
|
+
// 2. derived mode
|
|
258
|
+
// ==========================================
|
|
259
|
+
|
|
260
|
+
await check("derived mode: mode, durationMs 0 together with approx true, startedAt null", () => {
|
|
261
|
+
const t = derivedTimeline
|
|
262
|
+
assert.strictEqual(t.mode, "derived")
|
|
263
|
+
assert.strictEqual(t.startedAt, null)
|
|
264
|
+
assert.strictEqual(t.durationMs, 0)
|
|
265
|
+
for (const task of [taskOf(t, "alpha"), taskOf(t, "beta")]) {
|
|
266
|
+
assert.strictEqual(task.durationMs, 0, `${task.taskId} durationMs must be 0`)
|
|
267
|
+
assert.strictEqual(task.approx, true, `${task.taskId} must be approx`)
|
|
268
|
+
assert.strictEqual(task.startedAt, null, `${task.taskId} startedAt must be null`)
|
|
269
|
+
}
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
await check("derived mode: passedAtRound comes from verify/report-<taskId>.json", () => {
|
|
273
|
+
assert.strictEqual(taskOf(derivedTimeline, "alpha").passedAtRound, 2)
|
|
274
|
+
assert.strictEqual(taskOf(derivedTimeline, "beta").passedAtRound, null)
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
await check("derived mode: passedAtRound follows the report round, not the state round", () => {
|
|
278
|
+
// state says alpha passed at round 2; the report says round 3. Must follow the report.
|
|
279
|
+
const root = makeRun({ events: null, reports: { alpha: { taskId: "alpha", round: 3, status: "PASS" } } })
|
|
280
|
+
assert.strictEqual(taskOf(buildTimeline(root, SESSION), "alpha").passedAtRound, 3)
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
await check("derived mode: a FAIL report does not produce a passedAtRound", () => {
|
|
284
|
+
const root = makeRun({ events: null, reports: { alpha: { taskId: "alpha", round: 2, status: "FAIL" } } })
|
|
285
|
+
assert.strictEqual(taskOf(buildTimeline(root, SESSION), "alpha").passedAtRound, null)
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
await check("derived mode: totals still come from state.json", () => {
|
|
289
|
+
const { totals } = derivedTimeline
|
|
290
|
+
assert.strictEqual(totals.tasks, 2)
|
|
291
|
+
assert.strictEqual(totals.passed, 1)
|
|
292
|
+
assert.strictEqual(totals.blocked, 1)
|
|
293
|
+
assert.strictEqual(totals.totalRounds, 3)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
// ==========================================
|
|
297
|
+
// 3. no fabrication
|
|
298
|
+
// ==========================================
|
|
299
|
+
|
|
300
|
+
await check("no fabrication: hand-carried startedAt/durationMs in state.json are ignored", () => {
|
|
301
|
+
const forged = JSON.parse(JSON.stringify(STATE))
|
|
302
|
+
forged.startedAt = "2020-01-01T00:00:00.000Z"
|
|
303
|
+
forged.durationMs = 987654321
|
|
304
|
+
forged.tasks.alpha.startedAt = "2020-01-01T00:00:00.000Z"
|
|
305
|
+
forged.tasks.alpha.durationMs = 987654321
|
|
306
|
+
forged.tasks.beta.startedAt = "2020-01-01T00:00:00.000Z"
|
|
307
|
+
forged.tasks.beta.durationMs = 111
|
|
308
|
+
const t = buildTimeline(makeRun({ events: null, state: forged }), SESSION)
|
|
309
|
+
assert.strictEqual(t.mode, "derived")
|
|
310
|
+
assert.strictEqual(t.startedAt, null, "run startedAt must not be taken from state.json")
|
|
311
|
+
assert.strictEqual(t.durationMs, 0, "run durationMs must not be taken from state.json")
|
|
312
|
+
for (const task of t.tasks) {
|
|
313
|
+
assert.strictEqual(task.startedAt, null, `${task.taskId} startedAt must not be forged`)
|
|
314
|
+
assert.strictEqual(task.durationMs, 0, `${task.taskId} durationMs must not be forged`)
|
|
315
|
+
assert.strictEqual(task.approx, true, `${task.taskId} must stay approx`)
|
|
316
|
+
}
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
await check("no fabrication: derived endedAt is the state updatedAt, not an invented start", () => {
|
|
320
|
+
assert.strictEqual(taskOf(derivedTimeline, "alpha").endedAt, "2026-10-18T10:04:00.000Z")
|
|
321
|
+
assert.strictEqual(taskOf(derivedTimeline, "beta").endedAt, "2026-10-18T10:02:10.000Z")
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
// ==========================================
|
|
325
|
+
// 4. corrupt tolerance and missing files
|
|
326
|
+
// ==========================================
|
|
327
|
+
|
|
328
|
+
await check("corrupt tolerance: unparseable/truncated lines are skipped, valid events still used", () => {
|
|
329
|
+
// Garbage between valid lines, non-object JSON, a blank line, and a truncated
|
|
330
|
+
// tail with no newline (a partial write at process kill).
|
|
331
|
+
const lines = EVENTS.map((e) => JSON.stringify(e))
|
|
332
|
+
const corrupt = [
|
|
333
|
+
lines[0], "{not json at all", lines[1], "42", "[]", "", lines[2], lines[3],
|
|
334
|
+
'{"ts":"2026-10-18T10:0', lines[4], lines[5], lines[6], lines[7], lines[8],
|
|
335
|
+
].join("\n") + "\n" + '{"ts":"2026-10-18T10:05'
|
|
336
|
+
const root = makeRun({ events: null })
|
|
337
|
+
writeFileSync(join(runDirOf(root, SESSION), "events.jsonl"), corrupt)
|
|
338
|
+
const t = buildTimeline(root, SESSION)
|
|
339
|
+
assert.strictEqual(t.mode, "events", "corrupt events must still yield events mode")
|
|
340
|
+
assert.strictEqual(t.startedAt, eventsTimeline.startedAt)
|
|
341
|
+
assert.strictEqual(t.endedAt, eventsTimeline.endedAt)
|
|
342
|
+
assert.strictEqual(t.durationMs, 250000)
|
|
343
|
+
assert.deepStrictEqual(t.tasks, eventsTimeline.tasks, "tasks must equal the clean-events result")
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
await check("corrupt tolerance: a file of pure garbage falls back to derived mode without throwing", () => {
|
|
347
|
+
const root = makeRun({ events: null })
|
|
348
|
+
writeFileSync(join(runDirOf(root, SESSION), "events.jsonl"), "garbage\n{\n\n")
|
|
349
|
+
const t = buildTimeline(root, SESSION)
|
|
350
|
+
assert.strictEqual(t.mode, "derived")
|
|
351
|
+
assert.strictEqual(t.durationMs, 0)
|
|
352
|
+
assert.strictEqual(taskOf(t, "alpha").approx, true)
|
|
353
|
+
})
|
|
354
|
+
|
|
355
|
+
await check("missing run dir yields a well-formed empty timeline (no throw)", () => {
|
|
356
|
+
const t = buildTimeline(makeRoot(), "20261018-999999-none")
|
|
357
|
+
assertShape(t)
|
|
358
|
+
assert.deepStrictEqual(t.tasks, [])
|
|
359
|
+
assert.strictEqual(t.durationMs, 0)
|
|
360
|
+
})
|
|
361
|
+
|
|
362
|
+
await check("missing state.json yields a well-formed timeline with no tasks (no throw)", () => {
|
|
363
|
+
const root = makeRun({ events: null, state: null, plan: null, costs: null })
|
|
364
|
+
const t = buildTimeline(root, SESSION)
|
|
365
|
+
assertShape(t)
|
|
366
|
+
assert.deepStrictEqual(t.tasks, [])
|
|
367
|
+
assert.strictEqual(t.mode, "derived")
|
|
368
|
+
})
|
|
369
|
+
|
|
370
|
+
await check("no runs at all yields a well-formed empty timeline (no throw)", () => {
|
|
371
|
+
const t = buildTimeline(makeRoot())
|
|
372
|
+
assertShape(t)
|
|
373
|
+
assert.deepStrictEqual(t.tasks, [])
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
await check("default sessionId picks the most recently modified run", () => {
|
|
377
|
+
const root = makeRun({ events: EVENTS })
|
|
378
|
+
const older = runDirOf(root, SESSION_TWO)
|
|
379
|
+
mkdirSync(older, { recursive: true })
|
|
380
|
+
writeJson(join(older, "state.json"), { ...STATE, sessionId: SESSION_TWO })
|
|
381
|
+
const past = new Date("2020-01-01T00:00:00Z")
|
|
382
|
+
utimesSync(older, past, past)
|
|
383
|
+
assert.strictEqual(buildTimeline(root).sessionId, SESSION)
|
|
384
|
+
})
|
|
385
|
+
|
|
386
|
+
// ==========================================
|
|
387
|
+
// 5. cost attribution
|
|
388
|
+
// ==========================================
|
|
389
|
+
|
|
390
|
+
await check("cost attribution: task buckets land on the right tasks", () => {
|
|
391
|
+
assert.strictEqual(taskOf(eventsTimeline, "alpha").costUsd, 0.12)
|
|
392
|
+
assert.strictEqual(taskOf(eventsTimeline, "beta").costUsd, 0.05)
|
|
393
|
+
assert.strictEqual(taskOf(derivedTimeline, "alpha").costUsd, 0.12)
|
|
394
|
+
})
|
|
395
|
+
|
|
396
|
+
await check("cost attribution: _sentinel/_unattributed/agent buckets are unattributed and NOT tasks", () => {
|
|
397
|
+
const byBucket = Object.fromEntries(eventsTimeline.unattributed.map((u) => [u.bucket, u.costUsd]))
|
|
398
|
+
assert.deepStrictEqual(byBucket, { _sentinel: 0.01, _unattributed: 0.02, "team/worker": 0.01 })
|
|
399
|
+
assert.strictEqual(eventsTimeline.tasks.length, 2, "non-task buckets must not add task rows")
|
|
400
|
+
assert(
|
|
401
|
+
!eventsTimeline.tasks.some((x) => x.taskId.startsWith("_") || x.taskId.includes("/")),
|
|
402
|
+
"no internal bucket may be a task",
|
|
403
|
+
)
|
|
404
|
+
})
|
|
405
|
+
|
|
406
|
+
await check("cost attribution: non-task buckets never leak into per-task costUsd", () => {
|
|
407
|
+
// If _sentinel/_unattributed/team/worker leaked into a task, these values would change.
|
|
408
|
+
assert.strictEqual(taskOf(eventsTimeline, "alpha").costUsd, 0.12)
|
|
409
|
+
assert.strictEqual(taskOf(eventsTimeline, "beta").costUsd, 0.05)
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
await check("cost attribution: a plan task with no cost bucket gets costUsd null", () => {
|
|
413
|
+
const costs = { ...COSTS, byTask: { _sentinel: 0.5 } }
|
|
414
|
+
const t = buildTimeline(makeRun({ events: EVENTS, costs }), SESSION)
|
|
415
|
+
assert.strictEqual(taskOf(t, "alpha").costUsd, null)
|
|
416
|
+
assert.strictEqual(taskOf(t, "beta").costUsd, null)
|
|
417
|
+
assert.deepStrictEqual(t.unattributed, [{ bucket: "_sentinel", costUsd: 0.5 }])
|
|
418
|
+
})
|
|
419
|
+
|
|
420
|
+
await check("cost attribution: per-task tokens are null; totals carry the run tokens", () => {
|
|
421
|
+
assert.strictEqual(taskOf(eventsTimeline, "alpha").tokens, null)
|
|
422
|
+
assert.strictEqual(taskOf(eventsTimeline, "beta").tokens, null)
|
|
423
|
+
assert.deepStrictEqual(eventsTimeline.totals.tokens, COSTS.tokens)
|
|
424
|
+
assert.strictEqual(eventsTimeline.totals.spentUsd, 0.21)
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
// Populated per-task token buckets (costs.byTaskTokens). The legacy check above
|
|
428
|
+
// keeps covering the path with no bucket; these cover the path that surfaces one.
|
|
429
|
+
const BT_ALPHA = { input: 1234, output: 567, reasoning: 8, cache: { read: 90, write: 11 } }
|
|
430
|
+
|
|
431
|
+
await check("cost attribution: per-task tokens are surfaced from byTaskTokens with the exact numbers", () => {
|
|
432
|
+
const costs = { ...COSTS, byTaskTokens: { alpha: BT_ALPHA } }
|
|
433
|
+
for (const root of [makeRun({ events: EVENTS, costs }), makeRun({ events: null, costs })]) {
|
|
434
|
+
const t = buildTimeline(root, SESSION)
|
|
435
|
+
const alpha = taskOf(t, "alpha").tokens
|
|
436
|
+
assert.deepStrictEqual(alpha, BT_ALPHA, `alpha tokens must equal the bucket (mode ${t.mode})`)
|
|
437
|
+
assert.strictEqual(alpha.input, 1234)
|
|
438
|
+
assert.strictEqual(alpha.output, 567)
|
|
439
|
+
assert.strictEqual(alpha.reasoning, 8)
|
|
440
|
+
assert.strictEqual(alpha.cache.read, 90)
|
|
441
|
+
assert.strictEqual(alpha.cache.write, 11)
|
|
442
|
+
assert.strictEqual(taskOf(t, "beta").tokens, null, "beta has no bucket, so its tokens stay null")
|
|
443
|
+
assert.deepStrictEqual(t.totals.tokens, COSTS.tokens, "run totals must be unaffected by per-task buckets")
|
|
444
|
+
}
|
|
445
|
+
})
|
|
446
|
+
|
|
447
|
+
await check("cost attribution: a zero-valued bucket is a real measurement, not null", () => {
|
|
448
|
+
const zero = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
|
|
449
|
+
const t = buildTimeline(makeRun({ events: EVENTS, costs: { ...COSTS, byTaskTokens: { alpha: zero } } }), SESSION)
|
|
450
|
+
assert.deepStrictEqual(taskOf(t, "alpha").tokens, zero)
|
|
451
|
+
})
|
|
452
|
+
|
|
453
|
+
await check("cost attribution: per-task tokens are null when only other tasks have a bucket", () => {
|
|
454
|
+
const costs = { ...COSTS, byTaskTokens: { beta: { input: 5, output: 6, reasoning: 7, cache: { read: 8, write: 9 } } } }
|
|
455
|
+
const t = buildTimeline(makeRun({ events: EVENTS, costs }), SESSION)
|
|
456
|
+
assert.strictEqual(taskOf(t, "alpha").tokens, null, "alpha has no bucket")
|
|
457
|
+
assert.deepStrictEqual(taskOf(t, "beta").tokens, { input: 5, output: 6, reasoning: 7, cache: { read: 8, write: 9 } })
|
|
458
|
+
})
|
|
459
|
+
|
|
460
|
+
await check("cost attribution: a malformed token bucket yields null, never a throw or NaN", () => {
|
|
461
|
+
const BAD = [
|
|
462
|
+
"nope",
|
|
463
|
+
null,
|
|
464
|
+
42,
|
|
465
|
+
[1, 2, 3, 4],
|
|
466
|
+
{ input: -1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
467
|
+
{ input: 1, output: 1, reasoning: 0, cache: { read: 0 } },
|
|
468
|
+
{ input: 1, output: 1, reasoning: 0 },
|
|
469
|
+
{ input: 1, output: 1, reasoning: 0, cache: 5 },
|
|
470
|
+
{ input: "NaN", output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
471
|
+
{ output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
472
|
+
]
|
|
473
|
+
for (const bad of BAD) {
|
|
474
|
+
for (const events of [EVENTS, null]) {
|
|
475
|
+
const label = `${JSON.stringify(bad)} (mode ${events ? "events" : "derived"})`
|
|
476
|
+
const t = buildTimeline(makeRun({ events, costs: { ...COSTS, byTaskTokens: { alpha: bad } } }), SESSION)
|
|
477
|
+
assert.strictEqual(taskOf(t, "alpha").tokens, null, `malformed bucket ${label} must yield null`)
|
|
478
|
+
const text = renderTimeline(t, { color: false }).join("\n")
|
|
479
|
+
assert(!text.includes("NaN"), `render must never print NaN for ${label}`)
|
|
480
|
+
assert(!JSON.stringify(t).includes("NaN"), `output must never contain NaN for ${label}`)
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
})
|
|
484
|
+
|
|
485
|
+
await check("frozen shape: buildTimeline key sets are exactly the R2 contract, literal and unchanged", () => {
|
|
486
|
+
const costs = { ...COSTS, byTaskTokens: { alpha: BT_ALPHA } }
|
|
487
|
+
for (const t of [buildTimeline(makeRun({ events: EVENTS, costs }), SESSION), buildTimeline(makeRun({ events: null, costs }), SESSION)]) {
|
|
488
|
+
assert.deepStrictEqual(
|
|
489
|
+
Object.keys(t).sort(),
|
|
490
|
+
["budgetSource", "budgetUsd", "durationMs", "endedAt", "mode", "phase", "sessionId", "spentUsd", "startedAt", "tasks", "topology", "totals", "unattributed"],
|
|
491
|
+
)
|
|
492
|
+
assert.deepStrictEqual(
|
|
493
|
+
Object.keys(t.totals).sort(),
|
|
494
|
+
["blocked", "failed", "passed", "spentUsd", "tasks", "tokens", "totalRounds"],
|
|
495
|
+
)
|
|
496
|
+
for (const task of t.tasks) {
|
|
497
|
+
assert.deepStrictEqual(
|
|
498
|
+
Object.keys(task).sort(),
|
|
499
|
+
["agent", "agentSource", "approx", "branch", "costUsd", "durationMs", "endedAt", "note", "passedAtRound", "rounds", "seq", "startedAt", "status", "taskId", "tokens"],
|
|
500
|
+
`task keys for ${task.taskId}`,
|
|
501
|
+
)
|
|
502
|
+
}
|
|
503
|
+
assert.deepStrictEqual(Object.keys(taskOf(t, "alpha").tokens).sort(), ["cache", "input", "output", "reasoning"])
|
|
504
|
+
assert.deepStrictEqual(Object.keys(taskOf(t, "alpha").tokens.cache).sort(), ["read", "write"])
|
|
505
|
+
for (const u of t.unattributed) assert.deepStrictEqual(Object.keys(u).sort(), ["bucket", "costUsd"])
|
|
506
|
+
}
|
|
507
|
+
})
|
|
508
|
+
|
|
509
|
+
// ==========================================
|
|
510
|
+
// 6. render purity / colour
|
|
511
|
+
// ==========================================
|
|
512
|
+
|
|
513
|
+
await check("render: color false emits no ANSI escape", () => {
|
|
514
|
+
const lines = renderTimeline(eventsTimeline, { color: false })
|
|
515
|
+
assert(Array.isArray(lines) && lines.length > 0, "renderTimeline must return a non-empty string array")
|
|
516
|
+
for (const line of lines) assert.strictEqual(typeof line, "string")
|
|
517
|
+
assert(!lines.some((l) => l.includes(ESC)), "no line may contain an ANSI escape when color is false")
|
|
518
|
+
})
|
|
519
|
+
|
|
520
|
+
await check("render: color false emits no ANSI escape for a derived timeline", () => {
|
|
521
|
+
const lines = renderTimeline(derivedTimeline, { color: false })
|
|
522
|
+
assert(!lines.some((l) => l.includes(ESC)), "derived render must be plain with color false")
|
|
523
|
+
})
|
|
524
|
+
|
|
525
|
+
await check("render: color true emits ANSI escapes", () => {
|
|
526
|
+
const lines = renderTimeline(eventsTimeline, { color: true })
|
|
527
|
+
assert(lines.some((l) => l.includes(ESC)), "color true must emit at least one ANSI escape")
|
|
528
|
+
})
|
|
529
|
+
|
|
530
|
+
await check("render: events output shows the exact wall-clock, per-task duration and pass round", () => {
|
|
531
|
+
const text = renderTimeline(eventsTimeline, { color: false }).join("\n")
|
|
532
|
+
assert(text.includes("wall-clock: 4m 10s"), `header must show 4m 10s, got:\n${text}`)
|
|
533
|
+
assert(text.includes("duration: 4m 00s"), `alpha must show 4m 00s, got:\n${text}`)
|
|
534
|
+
assert(text.includes("pass@round 2"), "alpha must show its pass round")
|
|
535
|
+
})
|
|
536
|
+
|
|
537
|
+
await check("render: derived output marks approximate rows and never prints a 0ms duration", () => {
|
|
538
|
+
const text = renderTimeline(derivedTimeline, { color: false }).join("\n")
|
|
539
|
+
assert(text.includes("[APPROX]"), "derived header must be marked approximate")
|
|
540
|
+
assert(text.includes("~ approx"), "derived rows must be marked approximate")
|
|
541
|
+
assert(text.includes("duration: unknown"), "derived rows must say duration unknown, not 0ms")
|
|
542
|
+
assert(!/duration: 0ms/.test(text), "a derived row must never print duration: 0ms")
|
|
543
|
+
})
|
|
544
|
+
|
|
545
|
+
// ==========================================
|
|
546
|
+
// 7. timezone invariance
|
|
547
|
+
// ==========================================
|
|
548
|
+
|
|
549
|
+
await check("timezone: durations come from ISO strings, identical under different TZ", () => {
|
|
550
|
+
const runChild = (tz) => {
|
|
551
|
+
const res = spawnSync(process.execPath, [cliPath, "timeline", SESSION, "--json"], {
|
|
552
|
+
cwd: eventsRoot,
|
|
553
|
+
encoding: "utf8",
|
|
554
|
+
env: { ...process.env, TZ: tz, HOME: emptyHome, NO_COLOR: "1" },
|
|
555
|
+
})
|
|
556
|
+
assert.strictEqual(res.status, 0, `timeline under TZ=${tz} must exit 0, got ${res.status}: ${res.stderr}`)
|
|
557
|
+
return JSON.parse(res.stdout)
|
|
558
|
+
}
|
|
559
|
+
const tokyo = runChild("Asia/Tokyo")
|
|
560
|
+
const la = runChild("America/Los_Angeles")
|
|
561
|
+
assert.deepStrictEqual(tokyo, la, "output must not depend on TZ")
|
|
562
|
+
assert.deepStrictEqual(tokyo, JSON.parse(JSON.stringify(eventsTimeline)), "CLI output must match the library")
|
|
563
|
+
assert.strictEqual(tokyo.durationMs, 250000)
|
|
564
|
+
assert.strictEqual(taskOf(tokyo, "alpha").durationMs, 240000)
|
|
565
|
+
})
|
|
566
|
+
|
|
567
|
+
await check("timezone: human render is identical under different TZ", () => {
|
|
568
|
+
const under = (tz) => {
|
|
569
|
+
const res = spawnSync(process.execPath, [cliPath, "timeline", SESSION, "--no-color"], {
|
|
570
|
+
cwd: eventsRoot,
|
|
571
|
+
encoding: "utf8",
|
|
572
|
+
env: { ...process.env, TZ: tz, HOME: emptyHome },
|
|
573
|
+
})
|
|
574
|
+
assert.strictEqual(res.status, 0, `human render under TZ=${tz} must exit 0`)
|
|
575
|
+
return res.stdout
|
|
576
|
+
}
|
|
577
|
+
const tokyo = under("Asia/Tokyo")
|
|
578
|
+
assert(tokyo.includes("wall-clock: 4m 10s"), "human output must show 4m 10s under Tokyo")
|
|
579
|
+
assert.strictEqual(tokyo, under("Pacific/Kiritimati"), "human output must not depend on TZ")
|
|
580
|
+
})
|
|
581
|
+
|
|
582
|
+
// ==========================================
|
|
583
|
+
// 8. CLI contract (real bin, cwd = fixture root)
|
|
584
|
+
// ==========================================
|
|
585
|
+
|
|
586
|
+
function runCli(args, cwd) {
|
|
587
|
+
return spawnSync(process.execPath, [cliPath, ...args], {
|
|
588
|
+
cwd,
|
|
589
|
+
encoding: "utf8",
|
|
590
|
+
env: { ...process.env, HOME: emptyHome, NO_COLOR: "" },
|
|
591
|
+
})
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
await check("CLI: `timeline <id> --json` exits 0, stderr empty, parses, matches R2 shape", () => {
|
|
595
|
+
const res = runCli(["timeline", SESSION, "--json"], eventsRoot)
|
|
596
|
+
assert.strictEqual(res.status, 0, `exit must be 0, got ${res.status}: ${res.stderr}`)
|
|
597
|
+
assert.strictEqual(res.stderr, "", "--json stderr must be empty")
|
|
598
|
+
assert(!res.stdout.includes(ESC), "--json stdout must have no ANSI escapes")
|
|
599
|
+
const parsed = JSON.parse(res.stdout)
|
|
600
|
+
assertShape(parsed)
|
|
601
|
+
assert.strictEqual(parsed.mode, "events")
|
|
602
|
+
assert.strictEqual(parsed.durationMs, 250000)
|
|
603
|
+
assert.strictEqual(taskOf(parsed, "alpha").passedAtRound, 2)
|
|
604
|
+
})
|
|
605
|
+
|
|
606
|
+
await check("CLI: `--session <id> --json` is equivalent to the positional form", () => {
|
|
607
|
+
const res = runCli(["timeline", "--session", SESSION, "--json"], eventsRoot)
|
|
608
|
+
assert.strictEqual(res.status, 0, `exit must be 0, got ${res.status}: ${res.stderr}`)
|
|
609
|
+
assert.strictEqual(res.stderr, "")
|
|
610
|
+
assertShape(JSON.parse(res.stdout))
|
|
611
|
+
})
|
|
612
|
+
|
|
613
|
+
await check("CLI: derived run `--json` has mode derived and approx rows with durationMs 0", () => {
|
|
614
|
+
const res = runCli(["timeline", SESSION, "--json"], derivedRoot)
|
|
615
|
+
assert.strictEqual(res.status, 0, `exit must be 0, got ${res.status}: ${res.stderr}`)
|
|
616
|
+
assert.strictEqual(res.stderr, "", "derived --json stderr must be empty")
|
|
617
|
+
const parsed = JSON.parse(res.stdout)
|
|
618
|
+
assertShape(parsed)
|
|
619
|
+
assert.strictEqual(parsed.mode, "derived")
|
|
620
|
+
assert(parsed.tasks.length > 0, "derived run must list tasks")
|
|
621
|
+
for (const task of parsed.tasks) {
|
|
622
|
+
assert.strictEqual(task.approx, true)
|
|
623
|
+
assert.strictEqual(task.durationMs, 0)
|
|
624
|
+
}
|
|
625
|
+
})
|
|
626
|
+
|
|
627
|
+
await check("CLI: a missing session exits 1 and explains on stderr", () => {
|
|
628
|
+
const res = runCli(["timeline", "20261018-999999-none", "--json"], eventsRoot)
|
|
629
|
+
assert.strictEqual(res.status, 1, `missing session must exit 1, got ${res.status}`)
|
|
630
|
+
assert(res.stderr.length > 0, "missing session must explain itself on stderr")
|
|
631
|
+
})
|
|
632
|
+
|
|
633
|
+
await check("CLI: no runs at all exits 1", () => {
|
|
634
|
+
const res = runCli(["timeline"], makeRoot())
|
|
635
|
+
assert.strictEqual(res.status, 1, `no runs must exit 1, got ${res.status}`)
|
|
636
|
+
})
|
|
637
|
+
|
|
638
|
+
await check("CLI: a valid session exits 0 in human mode, no ANSI under --no-color", () => {
|
|
639
|
+
const res = runCli(["timeline", SESSION, "--no-color"], eventsRoot)
|
|
640
|
+
assert.strictEqual(res.status, 0, `valid session must exit 0, got ${res.status}: ${res.stderr}`)
|
|
641
|
+
assert(!res.stdout.includes(ESC), "--no-color stdout must have no ANSI escapes")
|
|
642
|
+
assert(res.stdout.includes("Teamwork timeline"), "human output must have a header")
|
|
643
|
+
})
|
|
644
|
+
|
|
645
|
+
await check("CLI: no `unknown argument` warning for timeline's positional id", () => {
|
|
646
|
+
const res = runCli(["timeline", SESSION, "--json"], eventsRoot)
|
|
647
|
+
assert(!res.stderr.includes("Ignoring unknown argument"), `unexpected warning: ${res.stderr}`)
|
|
648
|
+
})
|
|
649
|
+
|
|
650
|
+
// ==========================================
|
|
651
|
+
// 9. R6.5 — CLI error echo is sanitised and capped
|
|
652
|
+
// ==========================================
|
|
653
|
+
|
|
654
|
+
const CONTROL_RE = /[\x00-\x1f\x7f-\x9f]/
|
|
655
|
+
const MiB = 1024 * 1024
|
|
656
|
+
|
|
657
|
+
await check("R6.5: a hostile --session / positional value is echoed without control bytes", () => {
|
|
658
|
+
const hostile = "A".repeat(20) + "\u001b]52;c;ZZ\u0007\r\nFAKE"
|
|
659
|
+
for (const args of [["timeline", "--session", hostile], ["timeline", hostile]]) {
|
|
660
|
+
const res = runCli(args, eventsRoot)
|
|
661
|
+
assert.strictEqual(res.status, 1, `hostile id must exit 1, got ${res.status}`)
|
|
662
|
+
const msg = res.stderr.replace(/\n$/, "")
|
|
663
|
+
assert(!CONTROL_RE.test(msg), `stderr must carry no control bytes, got ${JSON.stringify(res.stderr)}`)
|
|
664
|
+
assert(msg.startsWith('Run "AAAA'), `stderr must still name the run, got ${JSON.stringify(res.stderr)}`)
|
|
665
|
+
}
|
|
666
|
+
})
|
|
667
|
+
|
|
668
|
+
await check("R6.5: a 200-char --session value is truncated in the error message", () => {
|
|
669
|
+
const res = runCli(["timeline", "--session", "B".repeat(200)], eventsRoot)
|
|
670
|
+
assert.strictEqual(res.status, 1)
|
|
671
|
+
assert(res.stderr.length < 120, `stderr must be short, got ${res.stderr.length} bytes`)
|
|
672
|
+
assert(!res.stderr.includes("B".repeat(65)), "at most 64 chars of the value may be echoed")
|
|
673
|
+
})
|
|
674
|
+
|
|
675
|
+
// ==========================================
|
|
676
|
+
// 10. R6.7b — --json escapes DEL and C1 bytes
|
|
677
|
+
// ==========================================
|
|
678
|
+
|
|
679
|
+
await check("R6.7b: --json and human output carry no raw DEL/C1 byte for a hostile branch", () => {
|
|
680
|
+
const hostileBranch = "hx\u009b31mZ\u007fQ\u0085"
|
|
681
|
+
const root = makeRun({
|
|
682
|
+
events: EVENTS,
|
|
683
|
+
state: { ...STATE, tasks: { ...STATE.tasks, alpha: { ...STATE.tasks.alpha, branch: hostileBranch } } },
|
|
684
|
+
})
|
|
685
|
+
const json = runCli(["timeline", SESSION, "--json"], root)
|
|
686
|
+
assert.strictEqual(json.status, 0, `exit must be 0, got ${json.status}: ${json.stderr}`)
|
|
687
|
+
assert(!/[\x7f-\x9f]/.test(json.stdout), `--json stdout must have no raw DEL/C1 byte, got ${JSON.stringify(json.stdout.slice(0, 200))}`)
|
|
688
|
+
assert.strictEqual(JSON.parse(json.stdout).tasks.find((x) => x.taskId === "alpha").branch, hostileBranch, "value must round-trip")
|
|
689
|
+
const human = runCli(["timeline", SESSION, "--no-color"], root)
|
|
690
|
+
assert(!/[\x7f-\x9f]/.test(human.stdout), "human output must have no raw DEL/C1 byte")
|
|
691
|
+
})
|
|
692
|
+
|
|
693
|
+
// ==========================================
|
|
694
|
+
// 11. R6.7 — an oversized file is reported, never silently absent or UNKNOWN
|
|
695
|
+
// ==========================================
|
|
696
|
+
|
|
697
|
+
await check("R6.7: a 9.4 MiB events.jsonl is reported as oversize, never as absent", () => {
|
|
698
|
+
const line = JSON.stringify(EVENTS[1]) + "\n"
|
|
699
|
+
const root = makeRun({ events: null })
|
|
700
|
+
writeFileSync(join(runDirOf(root, SESSION), "events.jsonl"), line.repeat(Math.ceil((9.4 * MiB) / line.length)))
|
|
701
|
+
const t = buildTimeline(root, SESSION)
|
|
702
|
+
assertShape(t)
|
|
703
|
+
assert.strictEqual(t.mode, "derived")
|
|
704
|
+
assert.strictEqual(t.durationMs, 0)
|
|
705
|
+
assert.strictEqual(taskOf(t, "alpha").approx, true)
|
|
706
|
+
const warnings = timelineWarnings(t)
|
|
707
|
+
assert(warnings.some((w) => /^events\.jsonl exceeds the 8 MiB read cap \(9\.\d MiB\)$/.test(w)), `warning missing: ${warnings}`)
|
|
708
|
+
const text = renderTimeline(t, { color: false }).join("\n")
|
|
709
|
+
assert(/derived mode: events\.jsonl exceeds the 8 MiB read cap \(9\.\d MiB\); timing unavailable/.test(text), `header must give the oversize reason:\n${text}`)
|
|
710
|
+
assert(!text.includes("no events.jsonl"), "an oversize events.jsonl must never be described as absent")
|
|
711
|
+
assert(taskOf(t, "alpha").note.includes("exceeds the 8 MiB read cap"), "task note must carry the reason (reaches --json)")
|
|
712
|
+
})
|
|
713
|
+
|
|
714
|
+
await check("R6.7: absent events.jsonl is still described as absent, with no warning", () => {
|
|
715
|
+
assert.deepStrictEqual(timelineWarnings(derivedTimeline), [])
|
|
716
|
+
assert(renderTimeline(derivedTimeline, { color: false }).join("\n").includes("derived mode: no events.jsonl"))
|
|
717
|
+
})
|
|
718
|
+
|
|
719
|
+
await check("R6.7: CLI --json warns on stderr when events.jsonl is oversize", () => {
|
|
720
|
+
const line = JSON.stringify(EVENTS[1]) + "\n"
|
|
721
|
+
const root = makeRun({ events: null })
|
|
722
|
+
writeFileSync(join(runDirOf(root, SESSION), "events.jsonl"), line.repeat(Math.ceil((9.4 * MiB) / line.length)))
|
|
723
|
+
const res = runCli(["timeline", SESSION, "--json"], root)
|
|
724
|
+
assert.strictEqual(res.status, 0)
|
|
725
|
+
assert(/warning: events\.jsonl exceeds the 8 MiB read cap/.test(res.stderr), `stderr must warn, got ${res.stderr}`)
|
|
726
|
+
assert.strictEqual(JSON.parse(res.stdout).mode, "derived")
|
|
727
|
+
})
|
|
728
|
+
|
|
729
|
+
await check("R6.7: a 9.4 MiB state.json still yields its real phase, status and rounds", () => {
|
|
730
|
+
const root = makeRun({ events: null, state: null })
|
|
731
|
+
const padded = JSON.stringify({ ...STATE, phase: "SECURITY_AUDIT" }, null, 2) + " ".repeat(9.4 * MiB)
|
|
732
|
+
writeFileSync(join(runDirOf(root, SESSION), "state.json"), padded)
|
|
733
|
+
const t = buildTimeline(root, SESSION)
|
|
734
|
+
assert.strictEqual(t.phase, "SECURITY_AUDIT", `phase must not be UNKNOWN, got ${t.phase}`)
|
|
735
|
+
const alpha = taskOf(t, "alpha")
|
|
736
|
+
assert.strictEqual(alpha.status, "verified_pass")
|
|
737
|
+
assert.strictEqual(alpha.rounds, 2)
|
|
738
|
+
assert.deepStrictEqual(timelineWarnings(t), [], "a readable 9.4 MiB state.json needs no warning")
|
|
739
|
+
})
|
|
740
|
+
|
|
741
|
+
await check("R6.7: a state.json beyond the 64 MiB cap is reported explicitly, not silently", () => {
|
|
742
|
+
const root = makeRun({ events: null, state: null })
|
|
743
|
+
const file = join(runDirOf(root, SESSION), "state.json")
|
|
744
|
+
writeFileSync(file, JSON.stringify(STATE))
|
|
745
|
+
truncateSync(file, 65 * MiB) // sparse: no real disk use, and never read
|
|
746
|
+
const t = buildTimeline(root, SESSION)
|
|
747
|
+
assertShape(t)
|
|
748
|
+
assert(timelineWarnings(t).some((w) => w === "state.json exceeds the 64 MiB read cap (65 MiB)"), `warning missing: ${timelineWarnings(t)}`)
|
|
749
|
+
const text = renderTimeline(t, { color: false }).join("\n")
|
|
750
|
+
assert(text.includes("! state.json exceeds the 64 MiB read cap (65 MiB)"), "the reason must be rendered")
|
|
751
|
+
assert(text.includes("some run files were not read"), "the header must not claim a plain absence")
|
|
752
|
+
})
|
|
753
|
+
|
|
754
|
+
await check("R6.7: an oversize verify report is reported, not treated as no pass", () => {
|
|
755
|
+
const root = makeRun({ events: null, reports: {} })
|
|
756
|
+
const dir = runDirOf(root, SESSION)
|
|
757
|
+
mkdirSync(join(dir, "verify"), { recursive: true })
|
|
758
|
+
const report = join(dir, "verify", "report-alpha.json")
|
|
759
|
+
writeFileSync(report, JSON.stringify({ status: "PASS", round: 2 }))
|
|
760
|
+
truncateSync(report, 65 * MiB)
|
|
761
|
+
const t = buildTimeline(root, SESSION)
|
|
762
|
+
assert(timelineWarnings(t).some((w) => w.startsWith("verify/report-alpha.json exceeds")), `warning missing: ${timelineWarnings(t)}`)
|
|
763
|
+
})
|
|
764
|
+
|
|
765
|
+
// ==========================================
|
|
766
|
+
// 12. R6.6 — guardrail coverage for the library read path
|
|
767
|
+
// ==========================================
|
|
768
|
+
|
|
769
|
+
await check("R6.6 (1r): a symlinked events.jsonl is not read by buildTimeline", () => {
|
|
770
|
+
const root = makeRun({ events: null })
|
|
771
|
+
const outside = uniq("outside-events") + ".jsonl"
|
|
772
|
+
writeFileSync(outside, EVENTS.map((e) => JSON.stringify(e)).join("\n") + "\n")
|
|
773
|
+
symlinkSync(outside, join(runDirOf(root, SESSION), "events.jsonl"))
|
|
774
|
+
const t = buildTimeline(root, SESSION)
|
|
775
|
+
assert.strictEqual(t.mode, "derived", "a symlinked events.jsonl must not yield events mode")
|
|
776
|
+
assert.strictEqual(t.durationMs, 0)
|
|
777
|
+
assert(timelineWarnings(t).some((w) => w.startsWith("events.jsonl is not a regular file")), `warning missing: ${timelineWarnings(t)}`)
|
|
778
|
+
})
|
|
779
|
+
|
|
780
|
+
await check("R6.6 (2r): a dangling symlinked events.jsonl is not read by buildTimeline", () => {
|
|
781
|
+
const root = makeRun({ events: null })
|
|
782
|
+
symlinkSync(join(testDir, "no-such-target.jsonl"), join(runDirOf(root, SESSION), "events.jsonl"))
|
|
783
|
+
const t = buildTimeline(root, SESSION)
|
|
784
|
+
assert.strictEqual(t.mode, "derived")
|
|
785
|
+
assert(timelineWarnings(t).some((w) => w.startsWith("events.jsonl is not a regular file")), `warning missing: ${timelineWarnings(t)}`)
|
|
786
|
+
})
|
|
787
|
+
|
|
788
|
+
for (const where of ["outside", "inside"]) {
|
|
789
|
+
await check(`R6.6 (3r): a symlinked .opencode/teamwork run root (target ${where} the project) is refused by buildTimeline`, () => {
|
|
790
|
+
const root = makeRoot()
|
|
791
|
+
// "outside" points at a sibling tree; "inside" points at a directory within the project.
|
|
792
|
+
const target = where === "outside" ? uniq("outside-runs") : join(root, "elsewhere")
|
|
793
|
+
const outDir = join(target, SESSION)
|
|
794
|
+
mkdirSync(outDir, { recursive: true })
|
|
795
|
+
writeJson(join(outDir, "state.json"), STATE)
|
|
796
|
+
writeJson(join(outDir, "plan.dag.json"), PLAN)
|
|
797
|
+
writeFileSync(join(outDir, "events.jsonl"), EVENTS.map((e) => JSON.stringify(e)).join("\n") + "\n")
|
|
798
|
+
mkdirSync(join(root, ".opencode"), { recursive: true })
|
|
799
|
+
symlinkSync(target, join(root, ".opencode", "teamwork"))
|
|
800
|
+
const t = buildTimeline(root, SESSION)
|
|
801
|
+
assertShape(t)
|
|
802
|
+
assert.deepStrictEqual(t.tasks, [], "nothing may be read through a symlinked run root")
|
|
803
|
+
assert.strictEqual(t.mode, "derived")
|
|
804
|
+
assert.strictEqual(t.phase, "UNKNOWN")
|
|
805
|
+
assert(timelineWarnings(t).some((w) => w.includes("symlink")), `warning missing: ${timelineWarnings(t)}`)
|
|
806
|
+
const byDefault = buildTimeline(root)
|
|
807
|
+
assert.strictEqual(byDefault.sessionId, null, "the default run lookup must not list runs through the symlink")
|
|
808
|
+
assert.deepStrictEqual(byDefault.tasks, [])
|
|
809
|
+
})
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
await check("R6.6 (5): hostile task ids cannot read a report outside their own slot", () => {
|
|
813
|
+
const hostile = ["..", "../../x", "a/b", "/abs/x", "a\u0000b", "x".repeat(65)]
|
|
814
|
+
const root = makeRun({
|
|
815
|
+
events: null,
|
|
816
|
+
state: { ...STATE, tasks: Object.fromEntries(hostile.map((id) => [id, { status: "verified_pass", round: 2 }])) },
|
|
817
|
+
plan: { ...PLAN, tasks: hostile.map((id) => ({ id, dependsOn: [], maxRounds: 4 })) },
|
|
818
|
+
})
|
|
819
|
+
const dir = runDirOf(root, SESSION)
|
|
820
|
+
// Plant a PASS report exactly where a naive join(verify, `report-${id}.json`) would read it.
|
|
821
|
+
for (const id of hostile) {
|
|
822
|
+
if (id.includes("\u0000")) continue
|
|
823
|
+
const file = join(dir, "verify", `report-${id}.json`)
|
|
824
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
825
|
+
writeFileSync(file, JSON.stringify({ status: "PASS", round: 9 }))
|
|
826
|
+
}
|
|
827
|
+
const t = buildTimeline(root, SESSION)
|
|
828
|
+
assertShape(t)
|
|
829
|
+
for (const id of hostile) {
|
|
830
|
+
const task = taskOf(t, id)
|
|
831
|
+
assert.strictEqual(task.passedAtRound, null, `task ${JSON.stringify(id)} must not read a report`)
|
|
832
|
+
assert(task.note && task.note.includes("failed validation"), `task ${JSON.stringify(id)} must say why it was not read`)
|
|
833
|
+
}
|
|
834
|
+
})
|
|
835
|
+
|
|
836
|
+
await check("R6.6 (containment): a symlinked verify/ directory is not followed for reports", () => {
|
|
837
|
+
const root = makeRun({ events: null })
|
|
838
|
+
const dir = runDirOf(root, SESSION)
|
|
839
|
+
const outside = uniq("outside-verify")
|
|
840
|
+
mkdirSync(outside, { recursive: true })
|
|
841
|
+
writeFileSync(join(outside, "report-alpha.json"), JSON.stringify({ status: "PASS", round: 7 }))
|
|
842
|
+
symlinkSync(outside, join(dir, "verify"))
|
|
843
|
+
const t = buildTimeline(root, SESSION)
|
|
844
|
+
assert.strictEqual(taskOf(t, "alpha").passedAtRound, null, "a report reached through a symlinked verify/ must be ignored")
|
|
845
|
+
})
|
|
846
|
+
|
|
847
|
+
await check("R6.6 (6): a task whose last event is non-terminal pins endedAt to its terminal event", () => {
|
|
848
|
+
const extra = {
|
|
849
|
+
ts: "2026-10-18T10:05:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha",
|
|
850
|
+
from: "verified_pass", to: "worker_active", round: 3, agent: "team/worker", branch: "teamwork/tl-alpha", worktree: "/wt/alpha", phase: "DISPATCH",
|
|
851
|
+
}
|
|
852
|
+
const t = buildTimeline(makeRun({ events: [...EVENTS, extra] }), SESSION)
|
|
853
|
+
const a = taskOf(t, "alpha")
|
|
854
|
+
assert.strictEqual(a.endedAt, "2026-10-18T10:04:00.000Z", "endedAt must be the verified_pass event, not the trailing worker_active")
|
|
855
|
+
assert.strictEqual(a.durationMs, 240000)
|
|
856
|
+
assert.strictEqual(a.passedAtRound, 2)
|
|
857
|
+
assert.strictEqual(t.endedAt, "2026-10-18T10:05:00.000Z", "the run-level end is still the final line")
|
|
858
|
+
})
|
|
859
|
+
|
|
860
|
+
// ==========================================
|
|
861
|
+
// 13. R6.6 — guardrails in the engine write path (real tools.ts)
|
|
862
|
+
// ==========================================
|
|
863
|
+
|
|
864
|
+
const GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0" }
|
|
865
|
+
function gitInit(root) {
|
|
866
|
+
execFileSync("git", ["init", "-q"], { cwd: root, env: GIT_ENV, stdio: "ignore" })
|
|
867
|
+
execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false", "commit", "-q", "--allow-empty", "-m", "init"], {
|
|
868
|
+
cwd: root,
|
|
869
|
+
env: GIT_ENV,
|
|
870
|
+
stdio: "ignore",
|
|
871
|
+
})
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** Register the real engine tools against `root` and return them by name. */
|
|
875
|
+
async function engineTools(root) {
|
|
876
|
+
const tools = {}
|
|
877
|
+
await registerTeamworkTools(
|
|
878
|
+
{
|
|
879
|
+
tool: {
|
|
880
|
+
transform: async (cb) => {
|
|
881
|
+
await cb({
|
|
882
|
+
namespace: () => {},
|
|
883
|
+
add: (tool) => {
|
|
884
|
+
tools[tool.name] = tool
|
|
885
|
+
},
|
|
886
|
+
})
|
|
887
|
+
},
|
|
888
|
+
},
|
|
889
|
+
session: { get: async () => undefined },
|
|
890
|
+
},
|
|
891
|
+
root,
|
|
892
|
+
)
|
|
893
|
+
return tools
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/** A project root holding one engine-writable run (state with alpha pending, plan with alpha). */
|
|
897
|
+
function engineRun() {
|
|
898
|
+
const root = makeRoot()
|
|
899
|
+
const dir = runDirOf(root, SESSION)
|
|
900
|
+
mkdirSync(dir, { recursive: true })
|
|
901
|
+
writeJson(join(dir, "state.json"), { sessionId: SESSION, phase: "DISPATCH", tasks: { alpha: { status: "pending", round: 0 } } })
|
|
902
|
+
writeJson(join(dir, "plan.dag.json"), { sessionId: SESSION, topology: "iterative-coding", tasks: [{ id: "alpha", dependsOn: [], maxRounds: 4, agent: "team/worker" }] })
|
|
903
|
+
return { root, dir }
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
const readLines = (file) => readFileSync(file, "utf8").split("\n").filter((l) => l !== "")
|
|
907
|
+
|
|
908
|
+
await check("R6.6 control: task_update appends exactly one event to a plain events.jsonl", async () => {
|
|
909
|
+
const { root, dir } = engineRun()
|
|
910
|
+
const tools = await engineTools(root)
|
|
911
|
+
const res = await tools.task_update.execute({ sessionId: SESSION, taskId: "alpha", status: "worker_active" })
|
|
912
|
+
assert(res.content.includes("updated"), res.content)
|
|
913
|
+
const lines = readLines(join(dir, "events.jsonl"))
|
|
914
|
+
assert.strictEqual(lines.length, 1, "one event expected")
|
|
915
|
+
assert.strictEqual(JSON.parse(lines[0]).to, "worker_active")
|
|
916
|
+
})
|
|
917
|
+
|
|
918
|
+
await check("R6.6 (1): a symlinked events.jsonl is refused; its target is not appended to", async () => {
|
|
919
|
+
const { root, dir } = engineRun()
|
|
920
|
+
const outside = uniq("outside-events") + ".jsonl"
|
|
921
|
+
writeFileSync(outside, "CANARY\n")
|
|
922
|
+
symlinkSync(outside, join(dir, "events.jsonl"))
|
|
923
|
+
const tools = await engineTools(root)
|
|
924
|
+
await tools.task_update.execute({ sessionId: SESSION, taskId: "alpha", status: "worker_active" })
|
|
925
|
+
// Proof the call ran: state.json was written, so the append path was reached.
|
|
926
|
+
assert.strictEqual(JSON.parse(readFileSync(join(dir, "state.json"), "utf8")).tasks.alpha.status, "worker_active")
|
|
927
|
+
assert.strictEqual(readFileSync(outside, "utf8"), "CANARY\n", "the symlink target must not receive the event")
|
|
928
|
+
assert(lstatSync(join(dir, "events.jsonl")).isSymbolicLink(), "the symlink is left in place")
|
|
929
|
+
})
|
|
930
|
+
|
|
931
|
+
await check("R6.6 (2): a DANGLING symlinked events.jsonl is refused; no target is created", async () => {
|
|
932
|
+
const { root, dir } = engineRun()
|
|
933
|
+
const target = uniq("dangling") + ".jsonl" // does not exist
|
|
934
|
+
symlinkSync(target, join(dir, "events.jsonl"))
|
|
935
|
+
const tools = await engineTools(root)
|
|
936
|
+
await tools.task_update.execute({ sessionId: SESSION, taskId: "alpha", status: "worker_active" })
|
|
937
|
+
assert.strictEqual(JSON.parse(readFileSync(join(dir, "state.json"), "utf8")).tasks.alpha.status, "worker_active")
|
|
938
|
+
assert(!existsSync(target), "appending through a dangling symlink would create the target; it must not")
|
|
939
|
+
})
|
|
940
|
+
|
|
941
|
+
for (const where of ["outside", "inside"]) {
|
|
942
|
+
await check(`R6.6 (3e): a symlinked .opencode/teamwork run root (target ${where} the project) is refused by the engine`, async () => {
|
|
943
|
+
const root = makeRoot()
|
|
944
|
+
const target = where === "outside" ? uniq("outside-engine-runs") : join(root, "elsewhere")
|
|
945
|
+
const outDir = join(target, SESSION)
|
|
946
|
+
mkdirSync(outDir, { recursive: true })
|
|
947
|
+
writeJson(join(outDir, "state.json"), { sessionId: SESSION, phase: "DISPATCH", tasks: { alpha: { status: "pending", round: 0 } } })
|
|
948
|
+
writeJson(join(outDir, "plan.dag.json"), { sessionId: SESSION, tasks: [{ id: "alpha", dependsOn: [], maxRounds: 4 }] })
|
|
949
|
+
mkdirSync(join(root, ".opencode"), { recursive: true })
|
|
950
|
+
symlinkSync(target, join(root, ".opencode", "teamwork"))
|
|
951
|
+
const tools = await engineTools(root)
|
|
952
|
+
const res = await tools.task_update.execute({ sessionId: SESSION, taskId: "alpha", status: "worker_active" })
|
|
953
|
+
assert(/refused/.test(res.content), `must be refused, got: ${res.content}`)
|
|
954
|
+
assert.strictEqual(JSON.parse(readFileSync(join(outDir, "state.json"), "utf8")).tasks.alpha.status, "pending", "nothing may be written through the link")
|
|
955
|
+
assert(!existsSync(join(outDir, "events.jsonl")), "no event may be written through the link")
|
|
956
|
+
})
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
await check("R6.6 (4): control chars and newlines in every appended field cannot inject a second JSONL line", async () => {
|
|
960
|
+
const { root, dir } = engineRun()
|
|
961
|
+
// Hostile values reach appendEvent raw from: input.branch, input.worktree (task_update),
|
|
962
|
+
// state.phase and state.tasks.alpha.status (existing state), plan agent (plan.dag.json).
|
|
963
|
+
const state = JSON.parse(readFileSync(join(dir, "state.json"), "utf8"))
|
|
964
|
+
state.phase = "DISPATCH\nFAKE\rX"
|
|
965
|
+
state.tasks.alpha.status = "pending\u2028FAKE"
|
|
966
|
+
writeJson(join(dir, "state.json"), state)
|
|
967
|
+
const plan = JSON.parse(readFileSync(join(dir, "plan.dag.json"), "utf8"))
|
|
968
|
+
plan.tasks[0].agent = 'team/worker\n{"event":"injected"}'
|
|
969
|
+
writeJson(join(dir, "plan.dag.json"), plan)
|
|
970
|
+
|
|
971
|
+
const tools = await engineTools(root)
|
|
972
|
+
const res = await tools.task_update.execute({
|
|
973
|
+
sessionId: SESSION,
|
|
974
|
+
taskId: "alpha",
|
|
975
|
+
status: "worker_active",
|
|
976
|
+
branch: "teamwork/x\nINJECT",
|
|
977
|
+
worktree: "/wt\r\nINJECT",
|
|
978
|
+
})
|
|
979
|
+
assert(res.content.includes("updated"), res.content)
|
|
980
|
+
const raw = readFileSync(join(dir, "events.jsonl"), "utf8")
|
|
981
|
+
assert.strictEqual(raw.split("\n").length, 2, `exactly one physical line expected, got ${JSON.stringify(raw)}`)
|
|
982
|
+
assert(!/[\r\u2028\u2029]/.test(raw), "no CR or line separator may reach events.jsonl")
|
|
983
|
+
const ev = JSON.parse(raw.trimEnd())
|
|
984
|
+
assert.strictEqual(ev.event, "task_transition")
|
|
985
|
+
assert.strictEqual(ev.branch, "teamwork/x INJECT")
|
|
986
|
+
assert.strictEqual(ev.worktree, "/wt INJECT")
|
|
987
|
+
assert.strictEqual(ev.phase, "DISPATCH FAKE X")
|
|
988
|
+
assert.strictEqual(ev.from, "pending FAKE")
|
|
989
|
+
assert.strictEqual(ev.agent, 'team/worker {"event":"injected"}')
|
|
990
|
+
})
|
|
991
|
+
|
|
992
|
+
await check("R6.6 (4b): a hostile taskId writes no event and is not found", async () => {
|
|
993
|
+
const { root, dir } = engineRun()
|
|
994
|
+
const tools = await engineTools(root)
|
|
995
|
+
const res = await tools.task_update.execute({ sessionId: SESSION, taskId: "alpha\nFAKE", status: "worker_active" })
|
|
996
|
+
assert(/not found/.test(res.content), `hostile id must not match a task, got: ${res.content}`)
|
|
997
|
+
assert(!existsSync(join(dir, "events.jsonl")), "no event may be written for it")
|
|
998
|
+
})
|
|
999
|
+
|
|
1000
|
+
await check("R6.6 (7): a '..' task id is REFUSED by worktree setup and deletes nothing outside worktreesBase", async () => {
|
|
1001
|
+
const { root } = engineRun()
|
|
1002
|
+
gitInit(root)
|
|
1003
|
+
const wtBase = uniq("wt-base")
|
|
1004
|
+
mkdirSync(join(wtBase, SESSION), { recursive: true })
|
|
1005
|
+
writeFileSync(join(wtBase, "keep.txt"), "keep")
|
|
1006
|
+
writeFileSync(join(wtBase, SESSION, "keep.txt"), "keep")
|
|
1007
|
+
const sibling = uniq("sibling")
|
|
1008
|
+
mkdirSync(sibling, { recursive: true })
|
|
1009
|
+
writeFileSync(join(sibling, "keep.txt"), "keep")
|
|
1010
|
+
|
|
1011
|
+
const saved = process.env.TEAMWORK_WORKTREES_DIR
|
|
1012
|
+
process.env.TEAMWORK_WORKTREES_DIR = wtBase
|
|
1013
|
+
try {
|
|
1014
|
+
const tools = await engineTools(root)
|
|
1015
|
+
// Control: a valid id really does create a worktree, so the harness is live.
|
|
1016
|
+
const ok = await tools.worktree.execute({ sessionId: SESSION, action: "setup", role: "worker", taskId: "alpha" })
|
|
1017
|
+
assert(ok.content.includes("worker worktree ready"), `control setup must succeed, got: ${ok.content}`)
|
|
1018
|
+
|
|
1019
|
+
for (const bad of ["..", "../../" + basenameOf(sibling), "a/b", "/abs/x", "x".repeat(65)]) {
|
|
1020
|
+
const res = await tools.worktree.execute({ sessionId: SESSION, action: "setup", role: "worker", taskId: bad })
|
|
1021
|
+
assert(/refused/.test(res.content), `task id ${JSON.stringify(bad)} must be refused, got: ${res.content}`)
|
|
1022
|
+
}
|
|
1023
|
+
for (const kept of [join(wtBase, "keep.txt"), join(wtBase, SESSION, "keep.txt"), join(sibling, "keep.txt")]) {
|
|
1024
|
+
assert(existsSync(kept), `nothing outside the worktree may be deleted: ${kept} is gone`)
|
|
1025
|
+
}
|
|
1026
|
+
} finally {
|
|
1027
|
+
if (saved === undefined) delete process.env.TEAMWORK_WORKTREES_DIR
|
|
1028
|
+
else process.env.TEAMWORK_WORKTREES_DIR = saved
|
|
1029
|
+
}
|
|
1030
|
+
})
|
|
1031
|
+
|
|
1032
|
+
function basenameOf(p) {
|
|
1033
|
+
return p.slice(p.lastIndexOf("/") + 1)
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// ---------------------------------------------------------------- cleanup
|
|
1037
|
+
|
|
1038
|
+
rmSync(testDir, { recursive: true, force: true })
|
|
1039
|
+
|
|
1040
|
+
console.log(`\n${passed} passed, ${failed} failed`)
|
|
1041
|
+
process.exitCode = failed ? 1 : 0
|