Skip to content

Commit 22ad2f0

Browse files
committed
fix: close harness lifecycle review findings
1 parent 13dfa1d commit 22ad2f0

11 files changed

Lines changed: 358 additions & 159 deletions

File tree

‎packages/core/src/config/compaction.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ export class Info extends Schema.Class<Info>("ConfigV2.Compaction")({
1919
// altimate_change start — V2 parity for the fork compaction keys (estimator
2020
// safety margin, state ledger/summary carry, task pin). Same names as V1 so
2121
// ConfigMigrateV1 can carry them through without renames.
22-
// Accept finite numeric configuration here and clamp at the one runtime
23-
// boundary (SessionCompaction.contextSafetyFraction). Rejecting the value at
24-
// document decode drops the entire config instead of safely clamping it.
22+
// Reject NaN and infinities at document decode; finite out-of-range values
23+
// are clamped at the one runtime boundary
24+
// (SessionCompaction.contextSafetyFraction).
2525
context_safety_fraction: Schema.Number.check(Schema.isFinite()).pipe(Schema.optional),
2626
state_ledger: Schema.Boolean.pipe(Schema.optional),
2727
ledger_max_tokens: NonNegativeInt.pipe(Schema.optional),

‎packages/opencode/src/cli/cmd/idle-done.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,16 @@ export namespace IdleDone {
270270
if (!sub || !GIT_READ_ONLY_SUBCOMMANDS.has(sub)) return true
271271
continue
272272
}
273+
// `find` is normally a read, but action predicates can delete paths,
274+
// execute arbitrary commands, or write listing output to a file. With
275+
// snapshots disabled there is no later patch event to recover this
276+
// mutation signal, so classify every write/exec action conservatively.
277+
if (
278+
head === "find" &&
279+
tokens.slice(1).some((token) => /^-(?:delete|exec(?:dir)?|ok(?:dir)?|fprint(?:0|f)?|fls)$/.test(token))
280+
) {
281+
return true
282+
}
273283
if (head && MUTATING_HEADS.has(head)) return true
274284
}
275285
// altimate_change end
@@ -391,8 +401,16 @@ export namespace IdleDone {
391401
let consecutiveIdleTurns = 0
392402
let challengeIssued = false
393403

394-
function observeBash(part: PartSlice) {
395-
const command = typeof part.state?.input?.["command"] === "string" ? (part.state.input["command"] as string) : ""
404+
function observeBash(part: PartSlice, completed = true) {
405+
const command = typeof part.state?.input?.["command"] === "string" ? part.state.input["command"] : ""
406+
// A shell can mutate successfully and only then fail (`rm file && false`).
407+
// Error-status tool parts therefore cannot be discarded before command
408+
// inspection. They are never verification evidence, but known mutating
409+
// forms still advance the watermark conservatively.
410+
if (!completed) {
411+
if (isMutatingCommand(command)) lastMutationSeq = seq
412+
return
413+
}
396414
const configuredPrefix = options.verifyCommand?.trim()
397415
let configuredTailMutates = false
398416
if (configuredPrefix && command.trimStart().startsWith(configuredPrefix)) {
@@ -446,9 +464,9 @@ export namespace IdleDone {
446464
if (status !== "completed" && status !== "error") return
447465
runningToolParts.delete(part.id)
448466
messageHadActivity.add(part.messageID)
449-
if (status !== "completed") return
450467
if (part.tool && MUTATING_TOOLS.has(part.tool)) lastMutationSeq = seq
451-
if (part.tool === "bash") observeBash(part)
468+
if (part.tool === "bash") observeBash(part, status === "completed")
469+
if (status !== "completed") return
452470
return
453471
}
454472
if (part.type === "step-finish") {

‎packages/opencode/src/cli/cmd/run.ts‎

Lines changed: 159 additions & 114 deletions
Large diffs are not rendered by default.

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,9 @@ export namespace SessionPrompt {
176176
string,
177177
{
178178
abort: AbortController
179+
// altimate_change start — prevent idle listeners attaching to a closing prompt generation
180+
closing?: boolean
181+
// altimate_change end
179182
callbacks: {
180183
resolve(input: MessageV2.WithParts): void
181184
reject(reason?: any): void
@@ -347,7 +350,9 @@ export namespace SessionPrompt {
347350

348351
function start(sessionID: SessionID) {
349352
const s = state()
350-
if (s[sessionID]) return
353+
// altimate_change start — replace closing prompt generations instead of reusing their callbacks
354+
if (s[sessionID] && !s[sessionID].closing) return
355+
// altimate_change end
351356
const controller = new AbortController()
352357
s[sessionID] = {
353358
abort: controller,
@@ -359,6 +364,9 @@ export namespace SessionPrompt {
359364
function resume(sessionID: SessionID) {
360365
const s = state()
361366
if (!s[sessionID]) return
367+
// altimate_change start — resume with a fresh generation once cleanup has begun
368+
if (s[sessionID].closing) return start(sessionID)
369+
// altimate_change end
362370

363371
return s[sessionID].abort.signal
364372
}
@@ -396,16 +404,29 @@ export namespace SessionPrompt {
396404
})
397405
}
398406

399-
// altimate_change start — cancel() became async (SessionStatus.set is async); use `await using` for async dispose.
400-
// Always finish at idle after cancellation cleanup. Processor errors already
401-
// publish error-before-idle themselves, but failures outside the processor
402-
// (notably the compaction circuit breaker) previously skipped the normal
403-
// idle transition and left every client waiting forever.
407+
// altimate_change start — generation-scoped cleanup owns the fallback idle.
408+
// Remove this exact loop generation from the registry before publishing
409+
// idle, so an event consumer can safely start the next prompt immediately.
410+
// Processor errors may already have published error -> idle; in that case
411+
// SessionStatus is already idle and cleanup must not publish a stale second
412+
// idle into the next generation. Failures outside the processor (notably
413+
// the compaction circuit breaker) still get the missing idle transition.
404414
await using _ = defer(async () => {
405-
await cancel(sessionID)
406-
await SessionStatus.set(sessionID, { type: "idle" }).catch((error) => {
407-
log.warn("failed to restore idle status during prompt-loop cleanup", { sessionID, error })
408-
})
415+
const s = state()
416+
const match = s[sessionID]
417+
if (!match || match.abort.signal !== abort) return
418+
// Keep a replaceable tombstone while publishing idle. start() may replace
419+
// it immediately when an idle listener begins the next generation, but
420+
// will not attach that new prompt to callbacks from this finished loop.
421+
match.closing = true
422+
match.abort.abort()
423+
const status = await SessionStatus.get(sessionID)
424+
if (s[sessionID] === match && status.type !== "idle") {
425+
await SessionStatus.set(sessionID, { type: "idle" }).catch((error) => {
426+
log.warn("failed to restore idle status during prompt-loop cleanup", { sessionID, error })
427+
})
428+
}
429+
if (s[sessionID] === match) delete s[sessionID]
409430
})
410431
// altimate_change end
411432
// A directive is valid only for this active generation. If the loop stops,
@@ -1621,10 +1642,9 @@ export namespace SessionPrompt {
16211642
}
16221643
continue
16231644
}
1624-
// altimate_change start — set idle on normal loop exit; abort path is handled by processor catch block
1625-
if (!abort.aborted) {
1626-
await SessionStatus.set(sessionID, { type: "idle" })
1627-
}
1645+
// altimate_change start — the generation-scoped disposer publishes the
1646+
// sole normal idle transition after removing this loop from state. Abort
1647+
// and processor-error paths may already be idle; the disposer detects that.
16281648
// altimate_change end
16291649
SessionCompaction.prune({ sessionID })
16301650
// altimate_change start — session end telemetry

‎packages/opencode/src/session/termination.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,17 @@ export namespace SessionTermination {
126126
"actions have been taken since. If the deliverable is complete and verified, confirm by replying " +
127127
`${DONE_TOKEN} alone on the final line. Otherwise, state specifically what remains and continue working on it.`
128128

129+
/**
130+
* Follow-up used only when the model declines the completion challenge but
131+
* ends that reply instead of actually continuing. A fresh synthetic turn is
132+
* required because a normal text-only `stop` has already returned from the
133+
* server-side prompt loop.
134+
*/
135+
export const CONTINUE_AFTER_DECLINED_CHALLENGE =
136+
"The completion check was not confirmed. Continue working now on the specific remaining steps you identified; " +
137+
`do not stop merely to describe them. When the deliverable is complete and verified, end with ${DONE_TOKEN} ` +
138+
"alone on the final line."
139+
129140
/**
130141
* Mechanism-accurate overflow notice. The previous text blamed "large
131142
* media attachments" — but the overflow flag is set whenever a request exceeded

‎packages/opencode/test/altimate/tracing-adversarial-snapshot.test.ts‎

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,32 @@ const ZERO_STEP = {
4141
// single fixed sleep. Snapshot writes are debounced/async, so a hardcoded delay
4242
// is too short under heavy parallel CI load (the snapshot hasn't flushed yet) →
4343
// flaky reads of a stale status. Polling is robust regardless of machine load.
44-
async function pollStatus(tracer: { getTracePath(): string | undefined }, expected: string, timeoutMs = 4000) {
44+
async function pollTrace(
45+
tracer: { getTracePath(): string | undefined },
46+
accept: (snapshot: TraceFile) => boolean,
47+
description: string,
48+
timeoutMs = 4000,
49+
) {
4550
const start = Date.now()
46-
let last = "<none>"
51+
let last: TraceFile | undefined
4752
while (Date.now() - start < timeoutMs) {
4853
try {
4954
const snap = JSON.parse(await fs.readFile(tracer.getTracePath()!, "utf-8")) as TraceFile
50-
last = snap.summary.status
51-
if (last === expected) return snap
55+
last = snap
56+
if (accept(snap)) return snap
5257
} catch {
5358
/* file mid-write or not yet created — keep polling */
5459
}
5560
await new Promise((r) => setTimeout(r, 25))
5661
}
57-
throw new Error(`timed out after ${timeoutMs}ms waiting for status '${expected}' (last seen '${last}')`)
62+
throw new Error(
63+
`timed out after ${timeoutMs}ms waiting for ${description} ` +
64+
`(last status '${last?.summary.status ?? "<none>"}', spans ${last?.spans.length ?? 0})`,
65+
)
66+
}
67+
68+
async function pollStatus(tracer: { getTracePath(): string | undefined }, expected: string, timeoutMs = 4000) {
69+
return pollTrace(tracer, (snapshot) => snapshot.summary.status === expected, `status '${expected}'`, timeoutMs)
5870
}
5971

6072
// ---------------------------------------------------------------------------
@@ -75,11 +87,13 @@ describe("buildTraceFile — snapshot isolation", () => {
7587
state: { status: "completed", input: {}, output: "ok", time: { start: 1, end: 2 } },
7688
})
7789

78-
// Wait for snapshot to write
79-
await new Promise((r) => setTimeout(r, 50))
80-
81-
// Read the snapshot
82-
const snap1 = JSON.parse(await fs.readFile(tracer.getTracePath()!, "utf-8")) as TraceFile
90+
// Snapshot writes are asynchronous/debounced; poll instead of racing a
91+
// fixed sleep on loaded CI hosts.
92+
const snap1 = await pollTrace(
93+
tracer,
94+
(snapshot) => snapshot.spans.some((span) => span.kind === "tool" && span.name === "bash"),
95+
"the first tool span",
96+
)
8397
const snap1Model = snap1.metadata.model
8498

8599
// Now mutate the metadata via enrichFromAssistant
@@ -103,9 +117,11 @@ describe("buildTraceFile — snapshot isolation", () => {
103117
state: { status: "completed", input: {}, output: "ok", time: { start: 1, end: 2 } },
104118
})
105119

106-
// Wait for snapshot
107-
await new Promise((r) => setTimeout(r, 50))
108-
const snap1 = JSON.parse(await fs.readFile(tracer.getTracePath()!, "utf-8")) as TraceFile
120+
const snap1 = await pollTrace(
121+
tracer,
122+
(snapshot) => snapshot.spans.some((span) => span.kind === "tool" && span.name === "bash"),
123+
"the first tool span",
124+
)
109125
const span1Count = snap1.spans.length
110126

111127
// Add more spans
@@ -115,9 +131,13 @@ describe("buildTraceFile — snapshot isolation", () => {
115131
state: { status: "completed", input: {}, output: "content", time: { start: 3, end: 4 } },
116132
})
117133

118-
// Wait for second snapshot
119-
await new Promise((r) => setTimeout(r, 50))
120-
const snap2 = JSON.parse(await fs.readFile(tracer.getTracePath()!, "utf-8")) as TraceFile
134+
const snap2 = await pollTrace(
135+
tracer,
136+
(snapshot) =>
137+
snapshot.spans.length > span1Count &&
138+
snapshot.spans.some((span) => span.kind === "tool" && span.name === "read"),
139+
`the second tool span after ${span1Count} spans`,
140+
)
121141

122142
// Second snapshot should have more spans
123143
expect(snap2.spans.length).toBeGreaterThan(span1Count)

‎packages/opencode/test/cli/idle-done.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ function bashPart(messageID: string, command: string, exit: number): IdleDone.Pa
2828
state: { status: "completed", input: { command }, metadata: { exit } },
2929
}
3030
}
31+
function failedBashPart(messageID: string, command: string): IdleDone.PartSlice {
32+
return {
33+
id: pid(),
34+
messageID,
35+
type: "tool",
36+
tool: "bash",
37+
state: { status: "error", input: { command } },
38+
}
39+
}
3140
function editPart(messageID: string): IdleDone.PartSlice {
3241
return { id: pid(), messageID, type: "tool", tool: "edit", state: { status: "completed", input: {} } }
3342
}
@@ -243,6 +252,22 @@ describe("IdleDone.isReadOnlyCommand (generic classifier, .ii)", () => {
243252
expect(IdleDone.isMutatingCommand("FOO=1 mv a b")).toBe(true)
244253
})
245254

255+
// altimate_change start — review regression: find's action predicates can
256+
// mutate even though its ordinary traversal forms are read-only.
257+
test("mutating find actions are classified conservatively", () => {
258+
for (const cmd of [
259+
"find . -delete",
260+
"find src -name '*.tmp' -exec rm {} \\;",
261+
"find src -execdir sh -c 'touch generated' \\;",
262+
"find . -ok rm {} \\;",
263+
"find . -fprintf files.txt '%p\\n'",
264+
]) {
265+
expect(IdleDone.isMutatingCommand(cmd)).toBe(true)
266+
}
267+
expect(IdleDone.isMutatingCommand("find src -type f -name '*.ts' -print")).toBe(false)
268+
})
269+
// altimate_change end
270+
246271
test("plain read-only commands are not mutating", () => {
247272
for (const cmd of ["ls -la", "cat file.txt", "grep -r pattern .", "git status", "sed s/a/b/ f.txt"]) {
248273
expect(IdleDone.isMutatingCommand(cmd)).toBe(false)
@@ -409,6 +434,24 @@ describe("IdleDone hard preconditions", () => {
409434
expect(snap.last_mutation_seq).toBeGreaterThan(snap.last_verify_seq)
410435
})
411436

437+
// altimate_change start — review regression: a command may change files and
438+
// then report tool status=error; its mutation still invalidates the verify.
439+
test("(i) a failed bash command that may have mutated invalidates the earlier verify", () => {
440+
const d = IdleDone.create(OPTS, deps(["cmp_1", "cmp_2"]))
441+
d.observePart(editPart("m_work"))
442+
d.observePart(stepFinish("m_work"))
443+
d.observePart(bashPart("m_verify", "make check", 0))
444+
d.observePart(stepFinish("m_verify"))
445+
d.observePart(failedBashPart("m_failed_delete", "rm generated.ts && false"))
446+
d.observePart(stepFinish("m_failed_delete"))
447+
d.observePart(stepFinish("cmp_1"))
448+
d.observePart(stepFinish("cmp_2"))
449+
for (const m of ["m_idle1", "m_idle2", "m_idle3"]) d.observePart(stepFinish(m))
450+
expect(d.shouldChallenge()).toBe(false)
451+
expect(d.snapshot().last_mutation_seq).toBeGreaterThan(d.snapshot().last_verify_seq)
452+
})
453+
// altimate_change end
454+
412455
test("(ii) a configured verify command that redirects its output is still the verification", () => {
413456
const opts: IdleDone.Options = { ...OPTS, verifyCommand: "make check" }
414457
const d = IdleDone.create(opts, deps(["cmp_1", "cmp_2"]))

‎packages/opencode/test/cli/run-accounting.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,3 +460,27 @@ describe("RunAccounting done_reason + idle-done bookkeeping", () => {
460460
})
461461
// altimate_change end
462462
})
463+
464+
// altimate_change start — source-level lifecycle contracts for the run command.
465+
// The generated SDK and embedded server make these races expensive to induce in
466+
// a unit test; pin the critical signal/phase wiring alongside behavioral
467+
// accounting tests so a refactor cannot silently detach it.
468+
describe("run command request/stream lifecycle contracts", () => {
469+
test("the initial synchronous request shares and is cancelled by the SSE lifetime", async () => {
470+
const source = await Bun.file(new URL("../../src/cli/cmd/run.ts", import.meta.url).pathname).text()
471+
expect(source).toMatch(
472+
/const loopPromise = loop\(events\.stream,[\s\S]*?\.catch\(\(e\) => \{[\s\S]*?eventAbort\.abort\(\)/,
473+
)
474+
expect(source).toMatch(/sdk\.session\.command\([\s\S]*?\{ signal: eventAbort\.signal \},\s*\)/)
475+
expect(source).toMatch(/sdk\.session\.prompt\([\s\S]*?\{ signal: eventAbort\.signal \},\s*\)/)
476+
})
477+
478+
test("abort suppression is initial-stream-only and a declined challenge enqueues continuation", async () => {
479+
const source = await Bun.file(new URL("../../src/cli/cmd/run.ts", import.meta.url).pathname).text()
480+
expect(source).toContain("options?.suppressInterruptedPromptAbort")
481+
expect(source).toContain('loop(events.stream, { suppressInterruptedPromptAbort: true })')
482+
expect(source).toContain("SessionTermination.CONTINUE_AFTER_DECLINED_CHALLENGE")
483+
expect(source).toContain('"IdleDoneContinuationUnconfirmed"')
484+
})
485+
})
486+
// altimate_change end

‎packages/opencode/test/session/termination.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,13 @@ describe("SessionTermination directive texts (/c/d wording contracts)", () => {
173173
expect(challenge).toContain("state specifically what remains")
174174
})
175175

176+
test("the declined-challenge continuation requires work now and an eventual DONE", () => {
177+
const continuation = SessionTermination.CONTINUE_AFTER_DECLINED_CHALLENGE
178+
expect(continuation).toContain("Continue working now")
179+
expect(continuation).toContain(SessionTermination.DONE_TOKEN)
180+
expect(continuation).toContain("do not stop merely to describe")
181+
})
182+
176183
test("the overflow notice is mechanism-accurate: no media-attachment blame", () => {
177184
expect(SessionTermination.OVERFLOW_NOTICE).not.toContain("media")
178185
expect(SessionTermination.OVERFLOW_NOTICE).toContain("context limit")
@@ -182,6 +189,7 @@ describe("SessionTermination directive texts (/c/d wording contracts)", () => {
182189
for (const text of [
183190
SessionTermination.COMPLETION_NUDGE,
184191
SessionTermination.CONFIRM_DONE_CHALLENGE,
192+
SessionTermination.CONTINUE_AFTER_DECLINED_CHALLENGE,
185193
SessionTermination.OVERFLOW_NOTICE,
186194
]) {
187195
expect(text.toLowerCase()).not.toContain("dbt")

‎packages/opencode/test/upstream/bridge-merge-e2e.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -687,11 +687,18 @@ describe("E2E: SessionStatus.set async drift fixed (cycle 4)", () => {
687687
expect(content).toMatch(/export\s+async\s+function\s+cancel\s*\(/)
688688
})
689689

690-
test("SessionPrompt.prompt awaits cancel before restoring idle in its async disposer", async () => {
690+
test("SessionPrompt.loop scopes fallback idle restoration to its own generation", async () => {
691691
const content = readFileSync(path.join(srcDir, "session", "prompt.ts"), "utf-8")
692-
expect(content).toMatch(
693-
/await\s+using\s+_\s*=\s*defer\(\s*async\s*\(\s*\)\s*=>\s*\{[\s\S]*?await\s+cancel\s*\(\s*sessionID\s*\)[\s\S]*?await\s+SessionStatus\.set\s*\(\s*sessionID\s*,\s*\{\s*type:\s*"idle"/,
692+
// Capture only the disposer body: the closing ` })` indentation anchors
693+
// the match before later bootstrap/normal-loop idle sites can satisfy it.
694+
const disposer = content.match(/^ await using _ = defer\(async \(\) => \{\n([\s\S]*?)^ \}\)$/m)?.[1]
695+
expect(disposer).toBeDefined()
696+
expect(disposer).toMatch(/match\.abort\.signal\s*!==\s*abort/)
697+
expect(disposer).toMatch(/match\.closing\s*=\s*true/)
698+
expect(disposer).toMatch(
699+
/await\s+SessionStatus\.get\(sessionID\)[\s\S]*?s\[sessionID\]\s*===\s*match[\s\S]*?status\.type\s*!==\s*"idle"[\s\S]*?await\s+SessionStatus\.set\(sessionID,\s*\{\s*type:\s*"idle"\s*\}\)/,
694700
)
701+
expect(disposer).toMatch(/s\[sessionID\]\s*===\s*match\)\s*delete\s+s\[sessionID\]/)
695702
})
696703
})
697704

0 commit comments

Comments
 (0)