Skip to content

Commit 0011ec3

Browse files
committed
fix: close final harness release findings
1 parent a95f5e5 commit 0011ec3

15 files changed

Lines changed: 499 additions & 211 deletions

‎packages/opencode/src/altimate/prompts/builder.txt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,6 @@ declare a task complete, ALWAYS:
228228
3. **If you are running low on turns or context**, stop exploring and commit:
229229
write the change, build, verify. A completed adequate solution beats an
230230
unfinished perfect one.
231+
4. **Signal completion explicitly**: only after every requirement above is
232+
satisfied, end your final response with the literal token `DONE` on its own
233+
final line. Do not emit `DONE` while work or verification remains.

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,11 @@ export namespace IdleDone {
243243

244244
/** True when the command writes to the filesystem through a head, flag, or redirection. */
245245
export function isMutatingCommand(command: string): boolean {
246+
// Command/process substitutions can execute arbitrary writes before the
247+
// visible command reports its status (`make check$(rm generated.ts)`). We
248+
// cannot safely parse their nested shell here, so invalidate earlier
249+
// verification evidence conservatively whenever one is present.
250+
if (/\$\(|`|[<>]\(/.test(command)) return true
246251
// altimate_change start — Output redirection to a file. Only fd DUPLICATION
247252
// (`2>&1`, `>&2`) is excluded, and duplication is identified by the `&`
248253
// that FOLLOWS the operator. The previous lookbehind also rejected a `>`

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,22 @@ export namespace RunAccounting {
3434
// Timeout classification for why_harness_stopped="timeout" and retry decisions.
3535
const TIMEOUT_PATTERN = /\btimed?\s*out\b|\bETIMEDOUT\b|TimeoutError/i
3636

37+
/** Holds only overflow errors whose trace status depends on later recovery. */
38+
export function createRecoverableOverflowTraceErrors() {
39+
let pending: string[] = []
40+
return {
41+
add(error: string) {
42+
pending.push(error)
43+
},
44+
recover() {
45+
pending = []
46+
},
47+
values() {
48+
return [...pending]
49+
},
50+
}
51+
}
52+
3753
// the explicit model DONE assertion is the primary termination path.
3854
// Detection delegates to the SessionTermination completion-token contract —
3955
// the single detector shared with the processor stop-path and the idle-done

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,7 @@ You are speaking to a non-technical business executive. Follow these rules stric
636636
const events = await sdk.event.subscribe(undefined, { signal: eventAbort.signal })
637637
// altimate_change end
638638
let error: string | undefined
639+
const recoverableOverflowTraceErrors = RunAccounting.createRecoverableOverflowTraceErrors()
639640
// altimate_change start — turn accounting + dual-attribution
640641
// termination state for this run (see run-accounting.ts).
641642
const accounting = RunAccounting.create()
@@ -887,7 +888,8 @@ You are speaking to a non-technical business executive. Follow these rules stric
887888
: undefined,
888889
)
889890
// altimate_change end
890-
error = error ? error + EOL + err : err
891+
if (props.error.name === "ContextOverflowError") recoverableOverflowTraceErrors.add(err)
892+
else error = error ? error + EOL + err : err
891893
if (emit("error", { error: props.error })) continue
892894
UI.error(err)
893895
}
@@ -898,6 +900,7 @@ You are speaking to a non-technical business executive. Follow these rules stric
898900
// without it (disabled/failed compaction) the run exits nonzero.
899901
if (event.type === "session.compacted" && event.properties.sessionID === sessionID) {
900902
accounting.onCompactionRecovered()
903+
recoverableOverflowTraceErrors.recover()
901904
}
902905
// altimate_change end
903906

@@ -1419,7 +1422,8 @@ You are speaking to a non-technical business executive. Follow these rules stric
14191422
// Finalize trace and save to disk
14201423
if (tracer) {
14211424
Tracer.setActive(null)
1422-
const tracePath = await tracer.endTrace(error)
1425+
const traceError = [error, ...recoverableOverflowTraceErrors.values()].filter(Boolean).join(EOL) || undefined
1426+
const tracePath = await tracer.endTrace(traceError)
14231427
if (tracePath) {
14241428
emit("trace_saved", { path: tracePath })
14251429
if (args.format !== "json" && process.stdout.isTTY) {

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

Lines changed: 71 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,33 @@ export namespace SessionCompaction {
550550
})
551551
}
552552

553+
function shellSegmentBefore(value: string, end: number): string {
554+
let start = 0
555+
let quote: "'" | '"' | undefined
556+
let escaped = false
557+
for (let i = 0; i < end; i++) {
558+
const char = value[i]
559+
if (escaped) {
560+
escaped = false
561+
continue
562+
}
563+
if (char === "\\" && quote !== "'") {
564+
escaped = true
565+
continue
566+
}
567+
if (quote) {
568+
if (char === quote) quote = undefined
569+
continue
570+
}
571+
if (char === "'" || char === '"') {
572+
quote = char
573+
continue
574+
}
575+
if (char === ";" || char === "|" || char === "&" || char === "\n") start = i + 1
576+
}
577+
return value.slice(start, end)
578+
}
579+
553580
/**
554581
* Ledger text is persisted into a later model prompt, so treat every tool
555582
* argument as sensitive. This intentionally over-redacts opaque credentials
@@ -561,19 +588,32 @@ export namespace SessionCompaction {
561588
/(?:api[_-]?key|access[_-]?key|access[_-]?token|session[_-]?token|client[_-]?secret|private[_-]?key|(?:^|[_-])(?:key|token|secret|password|passwd|credential|signature|authorization|cookie)(?:$|[_-]))/i
562589
let masked = Telemetry.maskString(value)
563590

564-
// curl-style authentication flags are credentials even though the generic
565-
// long-flag classifier cannot safely treat every `user` argument as secret.
566-
// Cover spaced, equals, and attached short-flag forms.
567-
masked = masked
568-
.replace(
569-
/(^|\s)(--user)(=|\s+)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
570-
(_match, lead: string, flag: string, separator: string) => `${lead}${flag}${separator}<redacted>`,
571-
)
572-
.replace(
573-
/(^|\s)(-u)(?:(=|\s+)(?:"[^"]*"|'[^']*'|[^\s,;]+)|([^\s,;]+))/gi,
574-
(_match, lead: string, flag: string, separator: string | undefined) =>
575-
`${lead}${flag}${separator ?? ""}<redacted>`,
576-
)
591+
// `-u` is also a benign flag for commands such as `git push -u` and
592+
// `python -u`. Redact it as authentication only in the current curl shell
593+
// segment, or when the value itself has a user:password shape. Long
594+
// `--user` follows the same rule so task literals are not discarded merely
595+
// because an unrelated CLI chose that option name.
596+
masked = masked.replace(
597+
/(^|\s)(--user|-u)(?:(=|\s+)("[^"]*"|'[^']*'|[^\s,;]+)|([^\s,;]+))/gi,
598+
(
599+
match,
600+
lead: string,
601+
flag: string,
602+
separator: string | undefined,
603+
separatedValue: string | undefined,
604+
attachedValue: string | undefined,
605+
offset: number,
606+
whole: string,
607+
) => {
608+
// Attached values are valid only for short `-u` (`-ualice:pass`).
609+
if (flag.toLowerCase() === "--user" && separator === undefined) return match
610+
const rawValue = (separatedValue ?? attachedValue ?? "").replace(/^["']|["']$/g, "")
611+
const curlContext = /(?:^|[\s/])curl(?=\s|$)/i.test(shellSegmentBefore(whole, offset + lead.length))
612+
const credentialShaped = /^[^:/\s]+:[^/\s]+$/.test(rawValue)
613+
if (!curlContext && !credentialShaped) return match
614+
return `${lead}${flag}${separator ?? ""}<redacted>`
615+
},
616+
)
577617

578618
// Strip URL userinfo and signed/query material before applying structural
579619
// command redaction. This works for HTTP-compatible and custom schemes.
@@ -913,6 +953,22 @@ export namespace SessionCompaction {
913953
export const PIN_WORKING_SLACK = 2_000
914954
export const PIN_CARD_MAX_TOKENS = 500
915955

956+
const TASK_PIN_FRAME = {
957+
open: "<system-reminder>",
958+
description:
959+
"Original task — authoritative over any summary. The conversation above was compacted into a summary; the task below is the user's own instruction, reproduced verbatim. If the summary and this task conflict, this task wins.",
960+
close: "</system-reminder>",
961+
} as const
962+
963+
export function renderTaskPin(body: string): string {
964+
return [TASK_PIN_FRAME.open, TASK_PIN_FRAME.description, "", body, TASK_PIN_FRAME.close].join("\n")
965+
}
966+
967+
/** Tokens available for the verbatim body after the fixed reminder frame. */
968+
export function taskPinBodyBudget(capTokens: number): number {
969+
return Math.max(0, capTokens - Token.estimate(renderTaskPin("")))
970+
}
971+
916972
export function pinEnabled(cfg: ConfigInfo) {
917973
return cfg.compaction?.pin_task !== false
918974
}
@@ -1267,9 +1323,10 @@ When constructing the summary, try to stick to this template:
12671323
// small-window session, which would otherwise tell the summarizer to omit
12681324
// the task while no pin exists to compensate. Layered as an ADDITION to
12691325
// whichever summary prompt is active — never a replacement.
1326+
const taskPinBudget = pinBudget({ cfg, model: sessionModel, sessionID: input.sessionID })
12701327
if (
12711328
pinEnabled(cfg) &&
1272-
pinBudget({ cfg, model: sessionModel, sessionID: input.sessionID }) > 0 &&
1329+
taskPinBodyBudget(taskPinBudget) > 0 &&
12731330
hasPinnableTask(input.unfilteredMessages ?? input.messages)
12741331
)
12751332
promptText += "\n\n" + PIN_SUMMARY_ADDITION

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

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ export namespace SessionProcessor {
105105
// the one unambiguous running part. Returning undefined is deliberate:
106106
// silently attaching an output to the wrong call corrupts the transcript.
107107
export type ToolCallIdentity = { toolName?: string; input?: unknown }
108+
export type ToolExecution = { raw: unknown; occurrence: number }
108109

109110
/** @internal Exported for focused pairing tests. */
110111
export function matchToolCallID(
@@ -127,8 +128,11 @@ export namespace SessionProcessor {
127128
const owners = new Map<string, string>()
128129
const used = new Set<string>()
129130
const occurrences = new Map<string, number>()
131+
const allocated = new Map<string, string[]>()
130132
const started = new Map<string, string[]>()
131133
const awaitingResult = new Map<string, string[]>()
134+
const executionOccurrences = new Map<string, number>()
135+
const settledExecutions = new Map<string, number[]>()
132136
const keyOf = (raw: unknown) => (typeof raw === "string" ? raw : (JSON.stringify(raw) ?? String(raw)))
133137
const stable = (raw: unknown): string => {
134138
const key = keyOf(raw)
@@ -156,6 +160,9 @@ export namespace SessionProcessor {
156160
while (used.has(candidate)) candidate = `${base}_${++occurrence}`
157161
occurrences.set(key, occurrence + 1)
158162
used.add(candidate)
163+
const ids = allocated.get(key) ?? []
164+
ids.push(candidate)
165+
allocated.set(key, ids)
159166
return candidate
160167
}
161168
const enqueue = (table: Map<string, string[]>, raw: unknown, value: string) => {
@@ -192,14 +199,37 @@ export namespace SessionProcessor {
192199
return id
193200
},
194201
result(raw: unknown, expected?: string) {
195-
return dequeue(awaitingResult, raw, expected) ?? stable(raw)
202+
return dequeue(awaitingResult, raw, expected) ?? expected ?? stable(raw)
196203
},
197204
peek(raw: unknown) {
198205
return awaitingResult.get(keyOf(raw))?.[0] ?? stable(raw)
199206
},
200207
pending(raw: unknown) {
201208
return [...(awaitingResult.get(keyOf(raw)) ?? [])]
202209
},
210+
beginExecution(raw: unknown): ToolExecution {
211+
const key = keyOf(raw)
212+
const occurrence = executionOccurrences.get(key) ?? 0
213+
executionOccurrences.set(key, occurrence + 1)
214+
return { raw, occurrence }
215+
},
216+
finishExecution(execution: ToolExecution) {
217+
const key = keyOf(execution.raw)
218+
const queue = settledExecutions.get(key) ?? []
219+
queue.push(execution.occurrence)
220+
settledExecutions.set(key, queue)
221+
},
222+
settled(raw: unknown) {
223+
const key = keyOf(raw)
224+
const queue = settledExecutions.get(key)
225+
const occurrence = queue?.shift()
226+
if (queue?.length === 0) settledExecutions.delete(key)
227+
if (occurrence === undefined) return undefined
228+
return allocated.get(key)?.[occurrence]
229+
},
230+
executionID(execution: ToolExecution) {
231+
return allocated.get(keyOf(execution.raw))?.[execution.occurrence]
232+
},
203233
})
204234
}
205235
// altimate_change end
@@ -221,6 +251,12 @@ export namespace SessionProcessor {
221251
// regenerated ids for empty/duplicate raw values cannot collide across steps.
222252
const coerceToolCallID = createToolCallIDCoercer(input.assistantMessage.id)
223253
const consumeToolCallID = (raw: unknown, identity: ToolCallIdentity) => {
254+
// Local tool wrappers preserve the exact execution occurrence through
255+
// settlement, even when the provider repeats one malformed raw ID and
256+
// omits input from tool-result/tool-error. Prefer that association over
257+
// heuristic identity matching; provider-executed tools fall back below.
258+
const executed = coerceToolCallID.settled(raw)
259+
if (executed !== undefined) return coerceToolCallID.result(raw, executed)
224260
const candidates = coerceToolCallID.pending(raw)
225261
const matched = matchToolCallID(candidates, identity, toolcalls)
226262
if (candidates.length > 1 && matched === undefined) {
@@ -260,6 +296,16 @@ export namespace SessionProcessor {
260296
if (candidates.length > 1 && matched === undefined) return undefined
261297
return toolcalls.get(matched ?? coerceToolCallID.peek(toolCallID))
262298
},
299+
beginToolExecution(toolCallID: string) {
300+
return coerceToolCallID.beginExecution(toolCallID)
301+
},
302+
finishToolExecution(execution: ToolExecution) {
303+
coerceToolCallID.finishExecution(execution)
304+
},
305+
partFromToolExecution(execution: ToolExecution) {
306+
const id = coerceToolCallID.executionID(execution)
307+
return id === undefined ? undefined : toolcalls.get(id)
308+
},
263309
// altimate_change end
264310
async process(streamInput: LLM.StreamInput) {
265311
log.info("process")

0 commit comments

Comments
 (0)