@ponythewhite/base-context 1.0.7 → 1.0.9
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/CHANGELOG.md +24 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/src/rlm/__init__.py +3 -0
- package/dist/base-context-runtime/src/rlm/harness.py +86 -48
- package/dist/base-context-runtime/test/test_harness.py +215 -140
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/amazon-bedrock.js +3 -3
- package/dist/bundle/{anthropic-UV5GZDGU.js → anthropic-5PSCZEER.js} +2 -7
- package/dist/bundle/{azure-openai-responses-WSNPXLYC.js → azure-openai-responses-AYTLJR33.js} +2 -2
- package/dist/bundle/{bundled-modules-PS66L3IT.js → bundled-modules-5JRM6P4T.js} +5 -5
- package/dist/bundle/{chunk-UPVDERMD.js → chunk-2IPDSTDR.js} +11 -9
- package/dist/bundle/chunk-D3KOF57W.js +22040 -0
- package/dist/bundle/{chunk-VSIYFWYI.js → chunk-KT2BNEPE.js} +21 -8
- package/dist/bundle/{chunk-VCW3YDFF.js → chunk-NEHLB7JV.js} +1548 -574
- package/dist/bundle/{chunk-KTNETTHI.js → chunk-Q3MBSBEB.js} +3 -101
- package/dist/bundle/{chunk-LFPWHI42.js → chunk-QKIFBA7N.js} +2 -2
- package/dist/bundle/{chunk-PFROC4EV.js → chunk-VVI3UKGR.js} +12 -9
- package/dist/bundle/{cli-main-MMHTK7EB.js → cli-main-YUDBEYE2.js} +4 -4
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{google-T32FMD4G.js → google-HTMCUJ7X.js} +2 -2
- package/dist/bundle/{google-vertex-56KP6I3B.js → google-vertex-ZQO65AXF.js} +2 -2
- package/dist/bundle/{main-XAIVH4Y7.js → main-ZLGGAAGU.js} +5 -5
- package/dist/bundle/{mistral-WGBMYIVU.js → mistral-SB7LU56G.js} +1 -1
- package/dist/bundle/{openai-codex-responses-PIV2RQ3G.js → openai-codex-responses-5CEW4VN3.js} +53 -27
- package/dist/bundle/{openai-completions-64C3JPR4.js → openai-completions-BAZJQSS2.js} +1 -1
- package/dist/bundle/{openai-responses-UI7RSTDV.js → openai-responses-VHOE427P.js} +48 -5
- package/dist/core/agent-session.d.ts +9 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +225 -29
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-context.d.ts +8 -0
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +37 -5
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +2 -2
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +31 -13
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/context-epoch.d.ts +1 -1
- package/dist/core/context-epoch.d.ts.map +1 -1
- package/dist/core/context-epoch.js +2 -1
- package/dist/core/context-epoch.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/history-index-worker.d.ts.map +1 -1
- package/dist/core/history-index-worker.js +29 -8
- package/dist/core/history-index-worker.js.map +1 -1
- package/dist/core/history-index.d.ts +11 -1
- package/dist/core/history-index.d.ts.map +1 -1
- package/dist/core/history-index.js +2 -1
- package/dist/core/history-index.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +110 -15
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/kernel/bootstrap.d.ts.map +1 -1
- package/dist/core/kernel/bootstrap.js +97 -107
- package/dist/core/kernel/bootstrap.js.map +1 -1
- package/dist/core/kernel/repl-manager.d.ts.map +1 -1
- package/dist/core/kernel/repl-manager.js +11 -0
- package/dist/core/kernel/repl-manager.js.map +1 -1
- package/dist/core/kernel/shared.d.ts +2 -0
- package/dist/core/kernel/shared.d.ts.map +1 -1
- package/dist/core/kernel/shared.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +4 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/prompts/rlm.d.ts.map +1 -1
- package/dist/core/prompts/rlm.js +4 -2
- package/dist/core/prompts/rlm.js.map +1 -1
- package/dist/core/public-context.d.ts.map +1 -1
- package/dist/core/public-context.js +16 -0
- package/dist/core/public-context.js.map +1 -1
- package/dist/core/refinement/refinement.d.ts +19 -5
- package/dist/core/refinement/refinement.d.ts.map +1 -1
- package/dist/core/refinement/refinement.js +90 -35
- package/dist/core/refinement/refinement.js.map +1 -1
- package/dist/core/request-view-selection.d.ts +13 -3
- package/dist/core/request-view-selection.d.ts.map +1 -1
- package/dist/core/request-view-selection.js +239 -101
- package/dist/core/request-view-selection.js.map +1 -1
- package/dist/core/retained-tool-output.d.ts +28 -0
- package/dist/core/retained-tool-output.d.ts.map +1 -0
- package/dist/core/retained-tool-output.js +102 -0
- package/dist/core/retained-tool-output.js.map +1 -0
- package/dist/core/selective-recovery.d.ts +47 -3
- package/dist/core/selective-recovery.d.ts.map +1 -1
- package/dist/core/selective-recovery.js +428 -109
- package/dist/core/selective-recovery.js.map +1 -1
- package/dist/core/session-history-index.d.ts +3 -1
- package/dist/core/session-history-index.d.ts.map +1 -1
- package/dist/core/session-history-index.js +1 -1
- package/dist/core/session-history-index.js.map +1 -1
- package/dist/core/session-manager.d.ts +2 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +38 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +5 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +3 -3
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/task-frame.d.ts +1 -1
- package/dist/core/task-frame.d.ts.map +1 -1
- package/dist/core/task-frame.js +21 -1
- package/dist/core/task-frame.js.map +1 -1
- package/dist/core/task-state-reader.d.ts +10 -2
- package/dist/core/task-state-reader.d.ts.map +1 -1
- package/dist/core/task-state-reader.js +75 -9
- package/dist/core/task-state-reader.js.map +1 -1
- package/dist/core/tools/ipython.d.ts +5 -0
- package/dist/core/tools/ipython.d.ts.map +1 -1
- package/dist/core/tools/ipython.js +59 -17
- package/dist/core/tools/ipython.js.map +1 -1
- package/dist/core/tools/prime-context.d.ts.map +1 -1
- package/dist/core/tools/prime-context.js +1 -1
- package/dist/core/tools/prime-context.js.map +1 -1
- package/dist/core/view-units.d.ts +4 -0
- package/dist/core/view-units.d.ts.map +1 -1
- package/dist/core/view-units.js +28 -19
- package/dist/core/view-units.js.map +1 -1
- package/dist/installer.mjs +98 -77
- package/dist/modes/interactive/components/refinement-outcome-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/refinement-outcome-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -5
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/skills/skill-creator/SKILL.md +18 -1
- package/docs/settings.md +45 -0
- package/docs/skills.md +77 -2
- package/package.json +4 -4
- package/skills/skill-creator/SKILL.md +18 -1
- package/dist/bundle/chunk-W46VZFI6.js +0 -21681
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refinement.js","sourceRoot":"","sources":["../../../src/core/refinement/refinement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,SAAS,EACT,UAAU,EACV,SAAS,EACT,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC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\"node:crypto\";\nimport {\n\tcloseSync,\n\texistsSync,\n\tfstatSync,\n\tmkdirSync,\n\topenSync,\n\treadSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { AgentMessage, ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport type { Model } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../../config.js\";\nimport { serializeConversation } from \"../compaction/utils.js\";\nimport { readSessionHistoryImage } from \"../export-html/history.js\";\nimport { completeInference, InferenceCoordinator } from \"../inference-coordinator.js\";\nimport { convertToLlm } from \"../messages.js\";\nimport type { NativePlannerRequestOutputWriter } from \"../request-events.js\";\nimport { MODEL_REQUEST_ID_HEADER } from \"../semantic-edges.js\";\nimport type { SessionHistoryReadLimits } from \"../session-history-index.js\";\nimport type { CustomEntry } from \"../session-manager.js\";\n\nexport const REFINEMENT_CUSTOM_TYPE = \"prime-agent.refinement\";\n\nexport const REFINE_SKILL_NAME = \"refine\";\nconst HARNESS_STATE_DIR_NAME = \"harness\";\nconst REFINEMENT_HISTORY_FILE_NAME = \"refinements.jsonl\";\nconst GLOBAL_REFINEMENT_HISTORY_LIMITS: SessionHistoryReadLimits = {\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n};\nconst MAX_GLOBAL_REFINEMENT_APPENDS = 32;\nconst MAX_GLOBAL_REFINEMENT_PENDING_BYTES = 64 * 1024 * 1024;\nlet globalRefinementAppendTail: Promise<void> = Promise.resolve();\nlet pendingGlobalRefinementAppends = 0;\nlet pendingGlobalRefinementBytes = 0;\n\nconst DEFAULT_OVERVIEW_ENTRY_LIMIT = 6;\nconst DEFAULT_OVERVIEW_REFINEMENT_LIMIT = 5;\nconst DEFAULT_OVERVIEW_CONTENT_LIMIT = 180;\n\nexport type RefinementKind = \"prompt\" | \"memory\" | \"skill\" | \"subagent\";\nexport type RefinementAction = \"create\" | \"update\" | \"delete\";\nexport type HarnessScope = \"local\" | \"global\";\n\nexport interface HarnessEntry {\n\tid: string;\n\tkind: RefinementKind;\n\ttitle: string;\n\tcontent: string;\n\tpath: string;\n\tscope?: HarnessScope;\n\treference: Record<string, unknown>;\n\targuments: Record<string, unknown>;\n\tmetadata: Record<string, unknown>;\n\tsource: string;\n\tcreated_at: string;\n\tupdated_at: string;\n\tversion: number;\n}\n\nexport interface HarnessRefinementEvent {\n\tid: string;\n\ttrigger: string;\n\tchanges: string[];\n\tevidence: string;\n\toutcome: string;\n\tcreated_at: string;\n}\n\nexport interface HarnessState {\n\tschema: number;\n\tentries: Record<RefinementKind, Record<string, HarnessEntry>>;\n\trefinements: HarnessRefinementEvent[];\n}\n\nexport interface RefinementEdit {\n\taction: RefinementAction;\n\tkind: RefinementKind;\n\tid?: string;\n\ttitle?: string;\n\tcontent?: string;\n\tpath?: string;\n\treference?: Record<string, unknown>;\n\targuments?: Record<string, unknown>;\n\tmetadata?: Record<string, unknown>;\n\treason?: string;\n}\n\nexport interface RefinementProposal {\n\tsummary: string;\n\trationale: string;\n\tedits: RefinementEdit[];\n\texpectedOutcome: string;\n}\n\nexport interface AppliedRefinementEdit extends RefinementEdit {\n\tid: string;\n\tbefore?: HarnessEntry;\n\tafter?: HarnessEntry;\n\tapplied: boolean;\n\terror?: string;\n}\n\nexport interface RefinementResult {\n\tid: string;\n\tsummary: string;\n\trationale: string;\n\texpectedOutcome: string;\n\tappliedEdits: AppliedRefinementEdit[];\n\tharnessStatePath: string;\n\trollbackOf?: string;\n\tscope?: HarnessScope;\n}\n\nexport interface RefineOptions {\n\tinstructions?: string;\n\trollbackId?: string;\n\tglobal?: boolean;\n}\n\nexport type AutoRefineReason = \"turn_interval\" | \"compact\";\n\nexport interface AutoRefineReviewContext {\n\treason: AutoRefineReason;\n\tturnsSinceLastReview: number;\n}\n\nexport interface AutoRefineReview {\n\tshouldRefine: boolean;\n\trationale: string;\n\tinstructions?: string;\n}\n\nconst REFINEMENT_SYSTEM_PROMPT = `You are Base Context's /refine continual harness subsystem.\n\nYour job is to improve the editable continual harness state from the current trajectory.\nThis is similar in spirit to context compaction, but instead of summarizing the\nconversation you emit precise Create, Update, or Delete edits to reusable state.\nThe continual harness is the persistent, editable set of prompt notes, memories,\nskills, and subagent specs that lets Base Context improve reusable behavior\noutside the token history.\nUse \"continual harness\" for that persistent artifact layer; keep \"RLM\" for the\nruntime, Python REPL kernel, and native call interface that executes those artifacts.\n\nContinual harness components:\n- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.\n- memory: durable facts, decisions, failures, preferences, and outcomes.\n- skill: installed Python REPL skill. Skill create/update edits MUST include a \\`reference\\` object with \\`{\"type\":\"python\"}\\`, a Python import, and a callable or call pattern; they also MUST include an \\`arguments\\` object describing accepted inputs, required fields, defaults, and constraints. Use \\`{}\\` for \\`arguments\\` only when the Python callable truly needs no external inputs. Include the RLM-native call form \\`await <skill_import>(...)\\`.\n- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: compose a concise task prompt and spawn with \\`handle = await rlm(\"sub-task\")\\`; admission returns immediately with \\`rlm_child_id\\`, \\`name\\`, \\`session_dir\\`, and \\`model\\`, never the child's answer. Results arrive only through explicit \\`agent_message\\` replies or files; children reply with \\`await agent_message.send(message, receiver_role=\"parent\")\\`. Use \\`await rlm.list_subagents()\\` to recover direct child handles and \\`await agent_message.send(..., receiver_role=\"child\", receiver_name=handle.name)\\` for follow-ups. Do not invent wrappers like \\`run_subagent(...)\\`.\n\nScope and persistence policy:\n- The default editable continual harness store is local to the current Base Context session. Use it for session-specific progress, active task state, current-run coordination notes, temporary blockers, and project facts that should not affect other sessions.\n- A caller may explicitly request global refinement. Global edits must be stable cross-session lessons, durable user preferences, reusable skills/subagents, or tool/environment facts that should affect future sessions.\n- Entry ids in the harness overview may carry a display-only \\`local:\\` or \\`global:\\` prefix. Always use the bare id (no prefix) in edits.\n- All edits in one refinement apply only to the requested scope's store. During a local refinement, global entries are read-only context: never propose update or delete edits for them; create a local entry instead when a session-specific override is genuinely needed.\n- Project/workspace-specific lessons may be persisted globally only when the title, path, or content explicitly names the project/workspace and the lesson is likely to be reused in future sessions for that project. Prefer local edits when the lesson only belongs in the current conversation.\n- Use memory for declarative facts and preferences, skill for repeatable procedures exposed as Python calls, prompt for narrow behavioral policy addendums, and subagent for reusable delegation roles.\n- Create or update the smallest relevant component: repeated delegation roles should become subagent specs, repeated procedures should become skills, durable facts/preferences should become memories, and narrow behavioral policies should become prompt addendums.\n- When an edit is persisted, include metadata such as \\`{\"scope\":\"local\"}\\` or \\`{\"scope\":\"global\"}\\` when that helps future review understand the intended blast radius.\n\nUse the trajectory, current continual harness state, and prior refinement history. Prefer\nsmall evidence-backed edits. If prior refinements caused issues, rollback or\nreplace the faulty editable entries. Never edit source files directly. Output\nJSON only with this exact shape:\n\n{\n \"summary\": \"one sentence\",\n \"rationale\": \"why these edits are justified by trajectory evidence\",\n \"expectedOutcome\": \"what should improve and how to validate it\",\n \"edits\": [\n {\n \"action\": \"create|update|delete\",\n \"kind\": \"prompt|memory|skill|subagent\",\n \"id\": \"stable id for update/delete, optional for create\",\n \"title\": \"required for create/update except delete\",\n \"content\": \"required for create/update except delete\",\n \"path\": \"optional grouping path\",\n \"reference\": {\"type\": \"python\", \"import\": \"package.module\", \"callable\": \"function_name\", \"call_pattern\": \"await function_name(...)\"},\n \"arguments\": {\"name\": {\"type\": \"string\", \"required\": true, \"description\": \"accepted input\"}},\n \"metadata\": {},\n \"reason\": \"why this edit is useful\"\n }\n ]\n}`;\n\nconst AUTOMATIC_REFINEMENT_UTILITY_POLICY = `Automatic refinement requires a concrete reusable improvement supported by the trajectory and not already supplied in the task or current harness context. Eligible improvements include stable facts/preferences, reusable failure lessons, and repeatable procedures; local reusable lessons are eligible. Do not refine solely to copy current progress, completion claims, output counts, next-step checklists, or temporary blockers; keep those in task context. If no supported reusable improvement remains, return shouldRefine=false when reviewing, or an empty edits array when planning.`;\n\nconst AUTO_REFINE_REVIEW_SYSTEM_PROMPT = `You are Base Context's automatic /refine review gate.\n\nDecide whether this checkpoint should run /refine. Auto /refine writes local continual harness state by default.\n${AUTOMATIC_REFINEMENT_UTILITY_POLICY}\nReject one-off noise, unsupported hypotheses, and transient tool outputs. Ask for global refinement only for durable cross-session lessons or explicitly project-qualified lessons likely to be reused in future sessions.\n\nReturn JSON only:\n{\n \"shouldRefine\": true|false,\n \"rationale\": \"short reason\",\n \"instructions\": \"optional concise instructions for /refine if shouldRefine is true\"\n}`;\n\n/**\n * Output budgets are derived from the selected model instead of fixed literals.\n * /refine input scales with harness size (entry overview, refinement history, and\n * the trajectory slice), so a constant output cap silently truncates exactly the\n * large multi-edit proposals that matter most. Math.min keeps small models honest.\n */\nconst REFINEMENT_MAX_OUTPUT_TOKENS = 32_000;\nconst AUTO_REFINE_REVIEW_MAX_OUTPUT_TOKENS = 4_096;\n\nconst TRUNCATED_JSON_ERROR =\n\t\"the model stopped before completing its JSON object. This usually means the output budget was exhausted; retry with a smaller request.\";\n\nfunction refinementMaxOutputTokens(model: Model<any>): number {\n\treturn Math.min(model.maxTokens, REFINEMENT_MAX_OUTPUT_TOKENS);\n}\n\nfunction autoRefineReviewMaxOutputTokens(model: Model<any>): number {\n\treturn Math.min(model.maxTokens, AUTO_REFINE_REVIEW_MAX_OUTPUT_TOKENS);\n}\n\nfunction now(): string {\n\treturn new Date().toISOString();\n}\n\nfunction emptyHarnessState(): HarnessState {\n\treturn {\n\t\tschema: 1,\n\t\tentries: {\n\t\t\tprompt: {},\n\t\t\tmemory: {},\n\t\t\tskill: {},\n\t\t\tsubagent: {},\n\t\t},\n\t\trefinements: [],\n\t};\n}\n\nfunction slug(raw: string, fallback: string): string {\n\tconst normalized = raw\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, \"_\")\n\t\t.replace(/^_+|_+$/g, \"\")\n\t\t.slice(0, 80);\n\treturn normalized || fallback;\n}\n\nfunction cloneEntry(entry: HarnessEntry | undefined): HarnessEntry | undefined {\n\treturn entry ? JSON.parse(JSON.stringify(entry)) : undefined;\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn undefined;\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction normalizeHarnessScope(value: unknown, fallback: HarnessScope): HarnessScope {\n\treturn value === \"global\" || value === \"local\" ? value : fallback;\n}\n\nexport function inferRefinementResultScope(result: RefinementResult): HarnessScope | undefined {\n\tif (result.scope) {\n\t\treturn result.scope;\n\t}\n\n\tconst scopes = new Set<HarnessScope>();\n\tfor (const edit of result.appliedEdits) {\n\t\tconst scope = edit.after?.scope ?? edit.before?.scope;\n\t\tif (scope) {\n\t\t\tscopes.add(scope);\n\t\t}\n\t}\n\treturn scopes.size === 1 ? [...scopes][0] : undefined;\n}\n\nfunction withDefaultRefinementScope(result: RefinementResult, scope: HarnessScope): RefinementResult {\n\tconst inferred = inferRefinementResultScope(result);\n\treturn { ...result, scope: inferred ?? scope };\n}\n\nexport function getGlobalHarnessStateDir(agentDir: string = getAgentDir()): string {\n\treturn join(agentDir, HARNESS_STATE_DIR_NAME);\n}\n\nexport function getLocalHarnessStateDir(sessionArtifactDir: string | undefined): string | undefined {\n\treturn sessionArtifactDir ? join(sessionArtifactDir, HARNESS_STATE_DIR_NAME) : undefined;\n}\n\nexport function getHarnessStatePath(harnessStateDir: string = getGlobalHarnessStateDir()): string {\n\treturn join(harnessStateDir, \"harness_state.json\");\n}\n\nconst HARNESS_STATE_LIMITS: SessionHistoryReadLimits = {\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n};\n\nclass HarnessStateLimitError extends Error {}\n\nfunction harnessStateLimits(limits: SessionHistoryReadLimits): SessionHistoryReadLimits {\n\tconst { maxEntries, maxSourceBytes } = limits;\n\tif (\n\t\t!Number.isSafeInteger(maxEntries) ||\n\t\tmaxEntries <= 0 ||\n\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\tmaxSourceBytes <= 0\n\t) {\n\t\tthrow new Error(\"Invalid harness state limits\");\n\t}\n\treturn { maxEntries, maxSourceBytes };\n}\n\n/** Count only owned kind records and refinement events, not arbitrary nested memory. */\nfunction assertHarnessStateItemLimit(state: Partial<HarnessState>, maxEntries: number): void {\n\tlet count = Array.isArray(state.refinements) ? state.refinements.length : 0;\n\tif (count > maxEntries) throw new HarnessStateLimitError(\"Harness state item limit exceeded\");\n\tfor (const kind of [\"prompt\", \"memory\", \"skill\", \"subagent\"] as const) {\n\t\tconst records = state.entries?.[kind];\n\t\tif (!records || typeof records !== \"object\") continue;\n\t\tfor (const id in records) {\n\t\t\tif (!Object.hasOwn(records, id) || !objectRecord(records[id])) continue;\n\t\t\tif (++count > maxEntries) throw new HarnessStateLimitError(\"Harness state item limit exceeded\");\n\t\t}\n\t}\n}\n\nfunction readHarnessStateImage(statePath: string, maxSourceBytes: number): Buffer {\n\tconst fd = openSync(statePath, \"r\");\n\tlet captured: Buffer;\n\ttry {\n\t\tconst size = fstatSync(fd, { bigint: true }).size;\n\t\tif (size > BigInt(maxSourceBytes)) throw new HarnessStateLimitError(\"Harness state source byte limit exceeded\");\n\t\tcaptured = Buffer.alloc(Number(size));\n\t\tlet offset = 0;\n\t\twhile (offset < captured.length) {\n\t\t\tconst count = readSync(fd, captured, offset, Math.min(64 * 1024, captured.length - offset), offset);\n\t\t\tif (count === 0) throw new Error(\"Harness state source changed during read\");\n\t\t\toffset += count;\n\t\t}\n\t\tconst after = fstatSync(fd, { bigint: true }).size;\n\t\tif (after > BigInt(maxSourceBytes)) throw new HarnessStateLimitError(\"Harness state source byte limit exceeded\");\n\t\tif (after !== size) throw new Error(\"Harness state source changed during read\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tcloseSync(fd);\n\t\t} catch (closeError) {\n\t\t\tthrow new AggregateError([error, closeError], \"Harness state read and close failed\", { cause: error });\n\t\t}\n\t\tthrow error;\n\t}\n\tcloseSync(fd);\n\treturn captured;\n}\n\nexport function loadHarnessState(\n\tharnessStateDir: string = getGlobalHarnessStateDir(),\n\tscope: HarnessScope = \"global\",\n\tlimits: SessionHistoryReadLimits = HARNESS_STATE_LIMITS,\n): HarnessState {\n\tconst { maxEntries, maxSourceBytes } = harnessStateLimits(limits);\n\tconst statePath = getHarnessStatePath(harnessStateDir);\n\tif (!existsSync(statePath)) {\n\t\treturn emptyHarnessState();\n\t}\n\tlet parsed: Partial<HarnessState>;\n\ttry {\n\t\tconst raw = JSON.parse(readHarnessStateImage(statePath, maxSourceBytes).toString(\"utf8\"));\n\t\t// loadHarnessState runs on every system-prompt build and before each /refine, so\n\t\t// a corrupt or unreadable (or non-object) state file must degrade to empty rather\n\t\t// than throw and break the session. The next saveHarnessState rewrites it cleanly.\n\t\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\t\treturn emptyHarnessState();\n\t\t}\n\t\tparsed = raw as Partial<HarnessState>;\n\t} catch (error) {\n\t\t// An oversized valid store must never become an empty snapshot that a later save can overwrite.\n\t\tif (\n\t\t\terror instanceof HarnessStateLimitError ||\n\t\t\t(error instanceof AggregateError && error.cause instanceof HarnessStateLimitError)\n\t\t)\n\t\t\tthrow error;\n\t\treturn emptyHarnessState();\n\t}\n\tassertHarnessStateItemLimit(parsed, maxEntries);\n\tconst state = emptyHarnessState();\n\tstate.schema = typeof parsed.schema === \"number\" ? parsed.schema : 1;\n\tfor (const kind of Object.keys(state.entries) as RefinementKind[]) {\n\t\tconst records = parsed.entries?.[kind];\n\t\tif (records && typeof records === \"object\") {\n\t\t\tfor (const id in records) {\n\t\t\t\tif (!Object.hasOwn(records, id)) continue;\n\t\t\t\tconst entry = objectRecord(records[id]);\n\t\t\t\tif (!entry) continue;\n\t\t\t\tstate.entries[kind][id] = {\n\t\t\t\t\t...(entry as unknown as HarnessEntry),\n\t\t\t\t\tscope: normalizeHarnessScope(entry.scope, scope),\n\t\t\t\t\treference: objectRecord(entry.reference) ?? {},\n\t\t\t\t\targuments: objectRecord(entry.arguments) ?? {},\n\t\t\t\t\tmetadata: objectRecord(entry.metadata) ?? {},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\tif (Array.isArray(parsed.refinements)) {\n\t\tstate.refinements = parsed.refinements;\n\t}\n\treturn state;\n}\n\nexport function mergeHarnessStates(globalState: HarnessState, localState?: HarnessState): HarnessState {\n\tconst merged = emptyHarnessState();\n\tmerged.schema = Math.max(globalState.schema, localState?.schema ?? 1);\n\tfor (const kind of Object.keys(merged.entries) as RefinementKind[]) {\n\t\tfor (const [id, entry] of Object.entries(globalState.entries[kind])) {\n\t\t\tconst cloned = cloneEntry(entry)!;\n\t\t\tmerged.entries[kind][id] = { ...cloned, scope: normalizeHarnessScope(cloned.scope, \"global\") };\n\t\t}\n\t\tfor (const [id, entry] of Object.entries(localState?.entries[kind] ?? {})) {\n\t\t\tconst cloned = cloneEntry(entry)!;\n\t\t\tconst scopedEntry = { ...cloned, scope: normalizeHarnessScope(cloned.scope, \"local\") };\n\t\t\tconst mergedId = merged.entries[kind][id] ? `${scopedEntry.scope}:${id}` : id;\n\t\t\tmerged.entries[kind][mergedId] = scopedEntry;\n\t\t}\n\t}\n\tmerged.refinements = [...globalState.refinements, ...(localState?.refinements ?? [])];\n\treturn merged;\n}\n\nexport function saveHarnessState(\n\tharnessStateDir: string,\n\tstate: HarnessState,\n\tlimits: SessionHistoryReadLimits = HARNESS_STATE_LIMITS,\n): string {\n\tconst { maxEntries, maxSourceBytes } = harnessStateLimits(limits);\n\tassertHarnessStateItemLimit(state, maxEntries);\n\tconst serialized = `${JSON.stringify(state, null, 2)}\\n`;\n\tif (Buffer.byteLength(serialized) > maxSourceBytes) {\n\t\tthrow new HarnessStateLimitError(\"Harness state source byte limit exceeded\");\n\t}\n\tconst statePath = getHarnessStatePath(harnessStateDir);\n\tconst tempPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`;\n\tmkdirSync(harnessStateDir, { recursive: true });\n\ttry {\n\t\tconst mode = existsSync(statePath) ? statSync(statePath).mode & 0o777 : 0o600;\n\t\twriteFileSync(tempPath, serialized, { encoding: \"utf8\", mode });\n\t\trenameSync(tempPath, statePath);\n\t} finally {\n\t\tif (existsSync(tempPath)) {\n\t\t\tunlinkSync(tempPath);\n\t\t}\n\t}\n\treturn statePath;\n}\n\nexport function getRefinementHistoryPath(harnessStateDir: string = getGlobalHarnessStateDir()): string {\n\treturn join(harnessStateDir, REFINEMENT_HISTORY_FILE_NAME);\n}\n\nfunction isRefinementResult(data: unknown): data is RefinementResult {\n\treturn typeof data === \"object\" && data !== null && \"id\" in data && \"appliedEdits\" in data;\n}\n\n/**\n * Append a global-scope refinement to the cross-session history log so it can be\n * rolled back from any session. Local-scope refinements are recorded only in the\n * session JSONL and roll back via their recorded harnessStatePath.\n */\nexport async function appendGlobalRefinement(\n\tharnessStateDir: string,\n\tresult: RefinementResult,\n\tmaxRecordBytes = GLOBAL_REFINEMENT_HISTORY_LIMITS.maxSourceBytes,\n): Promise<string> {\n\tif (!Number.isSafeInteger(maxRecordBytes) || maxRecordBytes <= 0) {\n\t\tthrow new Error(\"Invalid global refinement record byte limit\");\n\t}\n\tif (pendingGlobalRefinementAppends >= MAX_GLOBAL_REFINEMENT_APPENDS) {\n\t\tthrow new Error(\"Global refinement append queue limit exceeded\");\n\t}\n\tconst historyPath = getRefinementHistoryPath(harnessStateDir);\n\t// Preserve JSON.stringify semantics and freeze the caller's value before I/O yields.\n\tconst serialized = `${JSON.stringify(result)}\\n`;\n\tconst bytes = Buffer.byteLength(serialized);\n\tif (bytes > maxRecordBytes || pendingGlobalRefinementBytes + bytes > MAX_GLOBAL_REFINEMENT_PENDING_BYTES) {\n\t\tthrow new Error(\"Global refinement append byte limit exceeded\");\n\t}\n\tpendingGlobalRefinementAppends++;\n\tpendingGlobalRefinementBytes += bytes;\n\tconst write = globalRefinementAppendTail.then(async () => {\n\t\tawait mkdir(harnessStateDir, { recursive: true });\n\t\tawait appendFile(historyPath, serialized, \"utf8\");\n\t\treturn historyPath;\n\t});\n\t// Failed appends reject their caller, but do not poison later accepted work.\n\tglobalRefinementAppendTail = write.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\ttry {\n\t\treturn await write;\n\t} finally {\n\t\tpendingGlobalRefinementAppends--;\n\t\tpendingGlobalRefinementBytes -= bytes;\n\t}\n}\n\nexport async function loadGlobalRefinementHistory(\n\tharnessStateDir: string = getGlobalHarnessStateDir(),\n\tlimits: SessionHistoryReadLimits = GLOBAL_REFINEMENT_HISTORY_LIMITS,\n): Promise<RefinementResult[]> {\n\tconst { maxEntries, maxSourceBytes } = limits;\n\tif (\n\t\t!Number.isSafeInteger(maxEntries) ||\n\t\tmaxEntries <= 0 ||\n\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\tmaxSourceBytes <= 0\n\t) {\n\t\tthrow new Error(\"Invalid global refinement history limits\");\n\t}\n\tconst historyPath = getRefinementHistoryPath(harnessStateDir);\n\tconst priorAppends = globalRefinementAppendTail;\n\tawait priorAppends;\n\tif (!existsSync(historyPath)) return [];\n\tconst captured = await readSessionHistoryImage(historyPath, maxSourceBytes, \"Global refinement history\");\n\tconst text = captured.toString(\"utf8\");\n\tconst results: RefinementResult[] = [];\n\tlet start = 0;\n\tlet records = 0;\n\twhile (start < text.length) {\n\t\tconst newline = text.indexOf(\"\\n\", start);\n\t\tconst end = newline === -1 ? text.length : newline;\n\t\tconst trimmed = text.slice(start, end).trim();\n\t\tstart = end + 1;\n\t\tif (!trimmed) continue;\n\t\tif (++records > maxEntries) throw new Error(\"Global refinement history entry limit exceeded\");\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(trimmed);\n\t\t\tif (isRefinementResult(parsed)) results.push(withDefaultRefinementScope(parsed, \"global\"));\n\t\t} catch {\n\t\t\t// Preserve malformed-line skipping, including scope-inference failures.\n\t\t}\n\t}\n\treturn results;\n}\n\n/**\n * Merge global and session refinement history, de-duplicating by id. Session entries\n * win on conflict so a session that is mid-flight still resolves its own latest result.\n */\nexport function mergeRefinementHistory(\n\tglobal: readonly RefinementResult[],\n\tsession: readonly RefinementResult[],\n): RefinementResult[] {\n\tconst byId = new Map<string, RefinementResult>();\n\tfor (const result of global) {\n\t\tbyId.set(result.id, result);\n\t}\n\tfor (const result of session) {\n\t\tconst existing = byId.get(result.id);\n\t\tbyId.set(result.id, result.scope || !existing?.scope ? result : { ...result, scope: existing.scope });\n\t}\n\treturn [...byId.values()];\n}\n\nfunction compactText(text: string, maxLength: number): string {\n\tconst normalized = text.replace(/\\s+/g, \" \").trim();\n\tif (normalized.length <= maxLength) {\n\t\treturn normalized;\n\t}\n\treturn `${normalized.slice(0, Math.max(0, maxLength - 3))}...`;\n}\n\nexport function formatHarnessStateForPrompt(\n\tstate: HarnessState,\n\toptions: {\n\t\tmaxEntriesPerKind?: number;\n\t\tmaxRefinements?: number;\n\t\tmaxContentLength?: number;\n\t\tincludeIpythonExamples?: boolean;\n\t\tincludeShellExamples?: boolean;\n\t\tincludeRefineExamples?: boolean;\n\t} = {},\n): string {\n\tconst maxEntriesPerKind = options.maxEntriesPerKind ?? DEFAULT_OVERVIEW_ENTRY_LIMIT;\n\tconst maxRefinements = options.maxRefinements ?? DEFAULT_OVERVIEW_REFINEMENT_LIMIT;\n\tconst maxContentLength = options.maxContentLength ?? DEFAULT_OVERVIEW_CONTENT_LIMIT;\n\tconst includeIpythonExamples = options.includeIpythonExamples ?? true;\n\tconst includeRefineExamples = options.includeRefineExamples ?? includeIpythonExamples;\n\tconst lines = [\n\t\t\"# Continual Harness State\",\n\t\t\"\",\n\t\t\"Local continual harness entries belong to this Base Context session. Global continual harness entries persist across Base Context sessions.\",\n\t\t\"The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\",\n\t\t\"Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\",\n\t\t\"Use these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\",\n\t\t\"\",\n\t\tincludeRefineExamples\n\t\t\t? \"When to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\"\n\t\t\t: \"When to refine the continual harness: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep continual harness edits small and evidence-backed.\",\n\t\t\"\",\n\t\tincludeIpythonExamples\n\t\t\t? \"Call contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm('sub-task')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\"\n\t\t\t: options.includeShellExamples\n\t\t\t\t? \"Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without the Python REPL; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents a Python kernel.\"\n\t\t\t\t: \"Call contract: continual harness entries are routing/context hints only in sessions without the Python REPL or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.\",\n\t\t\"\",\n\t];\n\n\tlet totalEntries = 0;\n\tfor (const kind of Object.keys(state.entries) as RefinementKind[]) {\n\t\tconst entries = Object.values(state.entries[kind]).sort((a, b) =>\n\t\t\t[a.path, a.title, a.id].join(\"\\0\").localeCompare([b.path, b.title, b.id].join(\"\\0\")),\n\t\t);\n\t\ttotalEntries += entries.length;\n\t\t// Render subagent specs as a task-shaped roster the model can match against — the\n\t\t// analogue of Claude Code's agent-type menu — rather than a bare count. In\n\t\t// REPL sessions, include the native `rlm` invocation hint.\n\t\tif (kind === \"subagent\" && entries.length > 0 && includeIpythonExamples) {\n\t\t\tlines.push(\n\t\t\t\t`${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and spawning with \\`await rlm('<task>')\\`; admission returns a child handle, never the answer)`,\n\t\t\t);\n\t\t} else {\n\t\t\tlines.push(`${kind}: ${entries.length}`);\n\t\t}\n\t\tfor (const entry of entries.slice(0, maxEntriesPerKind)) {\n\t\t\tconst argumentsText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.arguments).length > 0\n\t\t\t\t\t? ` args=${compactText(JSON.stringify(entry.arguments), maxContentLength)}`\n\t\t\t\t\t: \"\";\n\t\t\tconst referenceText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.reference).length > 0\n\t\t\t\t\t? ` ref=${compactText(JSON.stringify(entry.reference), maxContentLength)}`\n\t\t\t\t\t: \"\";\n\t\t\tlines.push(\n\t\t\t\t`- [${entry.scope ?? \"global\"}:${entry.id}] ${entry.title} (${entry.path}, v${entry.version})${referenceText}${argumentsText}: ${compactText(\n\t\t\t\t\tentry.content,\n\t\t\t\t\tmaxContentLength,\n\t\t\t\t)}`,\n\t\t\t);\n\t\t}\n\t\tconst overflow = entries.length - Math.min(entries.length, maxEntriesPerKind);\n\t\tif (overflow > 0) {\n\t\t\tlines.push(`- +${overflow} more ${kind} entries`);\n\t\t}\n\t\tlines.push(\"\");\n\t}\n\n\tif (totalEntries === 0) {\n\t\tlines.push(\"No saved harness entries yet.\", \"\");\n\t}\n\n\tlines.push(`recent refinements: ${state.refinements.length}`);\n\tfor (const event of state.refinements.slice(-maxRefinements)) {\n\t\tconst changes = event.changes.length > 0 ? event.changes.join(\", \") : \"no applied edits\";\n\t\tconst outcome = event.outcome ? `; outcome: ${compactText(event.outcome, maxContentLength)}` : \"\";\n\t\tlines.push(`- [${event.id}] ${compactText(event.trigger, maxContentLength)}: ${changes}${outcome}`);\n\t}\n\tconst refinementOverflow = state.refinements.length - Math.min(state.refinements.length, maxRefinements);\n\tif (refinementOverflow > 0) {\n\t\tlines.push(`- +${refinementOverflow} older refinement events`);\n\t}\n\n\treturn lines.join(\"\\n\").trim();\n}\n\nfunction overviewForPrompt(state: HarnessState): string {\n\tconst lines: string[] = [];\n\tfor (const kind of Object.keys(state.entries) as RefinementKind[]) {\n\t\tconst entries = Object.values(state.entries[kind]);\n\t\tlines.push(`${kind}: ${entries.length}`);\n\t\tfor (const entry of entries.slice(0, 40)) {\n\t\t\tconst content = entry.content.replace(/\\s+/g, \" \").slice(0, 240);\n\t\t\tconst argumentsText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.arguments).length > 0\n\t\t\t\t\t? ` args=${JSON.stringify(entry.arguments).slice(0, 240)}`\n\t\t\t\t\t: \"\";\n\t\t\tconst referenceText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.reference).length > 0\n\t\t\t\t\t? ` ref=${JSON.stringify(entry.reference).slice(0, 240)}`\n\t\t\t\t\t: \"\";\n\t\t\tlines.push(\n\t\t\t\t`- [${entry.scope ?? \"global\"}:${entry.id}] ${entry.title} (${entry.path}, v${entry.version})${referenceText}${argumentsText}: ${content}`,\n\t\t\t);\n\t\t}\n\t\tif (entries.length > 40) {\n\t\t\tlines.push(`- +${entries.length - 40} more ${kind} entries`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction historyForPrompt(history: RefinementResult[]): string {\n\tif (history.length === 0) {\n\t\treturn \"No prior refinement history.\";\n\t}\n\treturn history\n\t\t.slice(-20)\n\t\t.map((item) => {\n\t\t\tconst edits = item.appliedEdits\n\t\t\t\t.map((edit) => `${edit.applied ? \"applied\" : \"failed\"} ${edit.action} ${edit.kind}:${edit.id}`)\n\t\t\t\t.join(\", \");\n\t\t\tconst rollback = item.rollbackOf ? ` rollbackOf=${item.rollbackOf}` : \"\";\n\t\t\treturn `[${item.id}]${rollback} ${item.summary}\\n${edits}\\nExpected outcome: ${item.expectedOutcome}`;\n\t\t})\n\t\t.join(\"\\n\\n\");\n}\n\n/**\n * Whether a JSON candidate ends mid-value: an unterminated string, or unclosed\n * objects/arrays. A reply cut off by an exhausted output budget is incomplete in\n * this sense, while a complete-but-malformed reply is balanced. Brace slicing can\n * also produce a balanced fragment, so callers treat \"balanced\" as malformed.\n */\nfunction isIncompleteJson(candidate: string): boolean {\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (const char of candidate) {\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (inString) {\n\t\t\tif (char === \"\\\\\") escaped = true;\n\t\t\telse if (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') inString = true;\n\t\telse if (char === \"{\" || char === \"[\") depth++;\n\t\telse if (char === \"}\" || char === \"]\") depth--;\n\t}\n\treturn inString || depth > 0;\n}\n\nfunction parseJsonCandidate(candidate: string): unknown {\n\ttry {\n\t\treturn JSON.parse(candidate);\n\t} catch (error) {\n\t\t// A truncated reply and a malformed one both fail here, and JSON.parse\n\t\t// describes the fragment rather than the cause. Name the cause instead.\n\t\tif (isIncompleteJson(candidate)) {\n\t\t\tthrow new Error(TRUNCATED_JSON_ERROR);\n\t\t}\n\t\tthrow new Error(`the model did not return valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n}\n\nfunction extractJsonObject(text: string): unknown {\n\tconst trimmed = text.trim();\n\tif (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n\t\t// A reply truncated after a nested closing brace still looks well-formed\n\t\t// here, so this path needs the same diagnosis as the slicing fallback.\n\t\treturn parseJsonCandidate(trimmed);\n\t}\n\tconst fenced = trimmed.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n\tif (fenced) {\n\t\treturn parseJsonCandidate(fenced[1].trim());\n\t}\n\t// Brace slicing recovers JSON wrapped in prose. On a reply truncated inside the\n\t// edits array it slices to an earlier edit's closing brace, so a failure here\n\t// is diagnosed against the original text rather than the balanced fragment.\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start !== -1 && end > start) {\n\t\ttry {\n\t\t\treturn JSON.parse(trimmed.slice(start, end + 1));\n\t\t} catch {\n\t\t\treturn parseJsonCandidate(trimmed.slice(start));\n\t\t}\n\t}\n\tif (isIncompleteJson(trimmed)) {\n\t\tthrow new Error(TRUNCATED_JSON_ERROR);\n\t}\n\tthrow new Error(\"Refiner did not return a JSON object\");\n}\n\n/**\n * Normalizes an untrusted refinement proposal while preserving invalid edit\n * fields for apply-time validation.\n */\nexport function normalizeRefinementProposal(value: unknown): RefinementProposal {\n\tconst record =\n\t\ttypeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n\tconst edits = Array.isArray(record.edits) ? record.edits : [];\n\treturn {\n\t\tsummary: typeof record.summary === \"string\" ? record.summary : \"Refined continual harness state\",\n\t\trationale: typeof record.rationale === \"string\" ? record.rationale : \"\",\n\t\texpectedOutcome: typeof record.expectedOutcome === \"string\" ? record.expectedOutcome : \"\",\n\t\tedits: edits\n\t\t\t.filter((edit): edit is Record<string, unknown> => typeof edit === \"object\" && edit !== null)\n\t\t\t.map((edit) => ({\n\t\t\t\taction: edit.action as RefinementAction,\n\t\t\t\tkind: edit.kind as RefinementKind,\n\t\t\t\tid: typeof edit.id === \"string\" ? edit.id : undefined,\n\t\t\t\ttitle: typeof edit.title === \"string\" ? edit.title : undefined,\n\t\t\t\tcontent: typeof edit.content === \"string\" ? edit.content : undefined,\n\t\t\t\tpath: typeof edit.path === \"string\" ? edit.path : undefined,\n\t\t\t\treference: objectRecord(edit.reference),\n\t\t\t\targuments: objectRecord(edit.arguments),\n\t\t\t\tmetadata:\n\t\t\t\t\ttypeof edit.metadata === \"object\" && edit.metadata !== null && !Array.isArray(edit.metadata)\n\t\t\t\t\t\t? (edit.metadata as Record<string, unknown>)\n\t\t\t\t\t\t: undefined,\n\t\t\t\treason: typeof edit.reason === \"string\" ? edit.reason : undefined,\n\t\t\t})),\n\t};\n}\n\nfunction parseProposal(text: string): RefinementProposal {\n\tconst value = extractJsonObject(text);\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new Error(\"Refiner JSON must be an object\");\n\t}\n\treturn normalizeRefinementProposal(value);\n}\n\nfunction validateEdit(edit: RefinementEdit, computedId?: string): string | undefined {\n\tif (![\"create\", \"update\", \"delete\"].includes(edit.action)) {\n\t\treturn `unsupported action ${String(edit.action)}`;\n\t}\n\tif (![\"prompt\", \"memory\", \"skill\", \"subagent\"].includes(edit.kind)) {\n\t\treturn `unsupported kind ${String(edit.kind)}`;\n\t}\n\tif (edit.kind === \"prompt\" && (edit.id === \"base_system_prompt\" || computedId === \"base_system_prompt\")) {\n\t\treturn \"base system prompt is not editable\";\n\t}\n\tif (edit.action !== \"create\" && !edit.id) {\n\t\treturn `${edit.action} requires id`;\n\t}\n\tif (edit.action !== \"delete\" && (!edit.title || !edit.content)) {\n\t\treturn `${edit.action} requires title and content`;\n\t}\n\tif (edit.action !== \"delete\" && edit.kind === \"skill\" && edit.arguments === undefined) {\n\t\treturn `${edit.action} skill requires arguments`;\n\t}\n\tif (edit.action !== \"delete\" && edit.kind === \"skill\") {\n\t\tconst reference = edit.reference;\n\t\tif (!reference) {\n\t\t\treturn `${edit.action} skill requires python reference`;\n\t\t}\n\t\tif (reference.type !== \"python\") {\n\t\t\treturn `${edit.action} skill reference.type must be python`;\n\t\t}\n\t\tconst hasImport =\n\t\t\t(typeof reference.import === \"string\" && reference.import.length > 0) ||\n\t\t\t(typeof reference.python_import === \"string\" && reference.python_import.length > 0);\n\t\tconst hasCallable =\n\t\t\t(typeof reference.callable === \"string\" && reference.callable.length > 0) ||\n\t\t\t(typeof reference.call_pattern === \"string\" && reference.call_pattern.length > 0);\n\t\tif (!hasImport) {\n\t\t\treturn `${edit.action} skill requires python import`;\n\t\t}\n\t\tif (!hasCallable) {\n\t\t\treturn `${edit.action} skill requires callable or call_pattern`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function applyRefinementProposal(\n\tstate: HarnessState,\n\tproposal: RefinementProposal,\n\toptions: { id: string; rollbackOf?: string; scope?: HarnessScope; baselineState?: HarnessState },\n): RefinementResult {\n\tconst application = nativePlannerApplications.get(proposal);\n\tnativePlannerApplications.delete(proposal);\n\tconst appliedEdits: AppliedRefinementEdit[] = [];\n\tconst proposalModifiedKeys = new Set<string>();\n\tfor (const edit of proposal.edits) {\n\t\tconst computedId = edit.id ?? (edit.action === \"create\" ? slug(edit.title ?? edit.kind, edit.kind) : undefined);\n\t\tconst id = computedId ?? \"\";\n\t\tconst validationError = validateEdit(edit, id);\n\t\tif (validationError) {\n\t\t\tappliedEdits.push({ ...edit, id, applied: false, error: validationError });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst records = state.entries[edit.kind];\n\t\tconst before = cloneEntry(records[id]);\n\t\tconst entryKey = `${edit.kind}:${id}`;\n\t\tconst baseline = cloneEntry(options.baselineState?.entries[edit.kind][id]);\n\t\tif (\n\t\t\toptions.baselineState &&\n\t\t\t!proposalModifiedKeys.has(entryKey) &&\n\t\t\tJSON.stringify(before) !== JSON.stringify(baseline)\n\t\t) {\n\t\t\tappliedEdits.push({\n\t\t\t\t...edit,\n\t\t\t\tid,\n\t\t\t\tbefore,\n\t\t\t\tapplied: false,\n\t\t\t\terror: \"entry changed during refinement planning\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (edit.action === \"delete\") {\n\t\t\tif (!before) {\n\t\t\t\tappliedEdits.push({ ...edit, id, applied: false, error: \"entry not found\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdelete records[id];\n\t\t\tproposalModifiedKeys.add(entryKey);\n\t\t\tappliedEdits.push({ ...edit, id, before, applied: true });\n\t\t\tcontinue;\n\t\t}\n\t\tif (edit.action === \"create\" && before) {\n\t\t\tappliedEdits.push({ ...edit, id, before, applied: false, error: \"entry already exists\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (edit.action === \"update\" && !before) {\n\t\t\tappliedEdits.push({ ...edit, id, applied: false, error: \"entry not found\" });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst createdAt = before?.created_at ?? now();\n\t\tconst version = before ? before.version + 1 : 1;\n\t\tconst after: HarnessEntry = {\n\t\t\tid,\n\t\t\tkind: edit.kind,\n\t\t\ttitle: edit.title ?? before?.title ?? id,\n\t\t\tcontent: edit.content ?? before?.content ?? \"\",\n\t\t\tpath: edit.path ?? before?.path ?? \"general\",\n\t\t\tscope: before?.scope ?? options.scope ?? \"local\",\n\t\t\treference: edit.reference ?? before?.reference ?? {},\n\t\t\targuments: edit.arguments ?? before?.arguments ?? {},\n\t\t\tmetadata: edit.metadata ?? before?.metadata ?? {},\n\t\t\tsource: \"refine\",\n\t\t\tcreated_at: createdAt,\n\t\t\tupdated_at: now(),\n\t\t\tversion,\n\t\t};\n\t\trecords[id] = after;\n\t\tproposalModifiedKeys.add(entryKey);\n\t\tappliedEdits.push({ ...edit, id, before, after: cloneEntry(after), applied: true });\n\t}\n\n\tconst changes = appliedEdits.filter((edit) => edit.applied).map((edit) => `${edit.action} ${edit.kind}:${edit.id}`);\n\tstate.refinements.push({\n\t\tid: options.id,\n\t\ttrigger: proposal.summary,\n\t\tchanges,\n\t\tevidence: proposal.rationale,\n\t\toutcome: proposal.expectedOutcome,\n\t\tcreated_at: now(),\n\t});\n\n\tconst result = {\n\t\tid: options.id,\n\t\tsummary: proposal.summary,\n\t\trationale: proposal.rationale,\n\t\texpectedOutcome: proposal.expectedOutcome,\n\t\tappliedEdits,\n\t\tharnessStatePath: \"\",\n\t\trollbackOf: options.rollbackOf,\n\t\tscope: options.scope,\n\t};\n\tif (\n\t\tapplication &&\n\t\tstate === application.state &&\n\t\toptions.id === application.native.id &&\n\t\toptions.scope === application.scope &&\n\t\toptions.rollbackOf === undefined &&\n\t\toptions.baselineState === application.native.baselineState &&\n\t\tmatchesNativePlannerPlan(application.plan, application.native) &&\n\t\tmatchesPlannerOptions(application.options, application.native.options) &&\n\t\tisDeepStrictEqual(proposal, application.projection)\n\t) {\n\t\t// Baseline/state references are the existing host inputs, not deep-immutability or conflict-correctness claims.\n\t\tnativePlannerResults.set(result, { native: application.native, scope: application.scope, edits: appliedEdits });\n\t}\n\treturn result;\n}\n\nfunction rollbackProposal(target: RefinementResult): RefinementProposal {\n\tconst edits: RefinementEdit[] = [];\n\tfor (const edit of [...target.appliedEdits].reverse()) {\n\t\tif (!edit.applied) continue;\n\t\tif (edit.before) {\n\t\t\tedits.push({\n\t\t\t\taction: edit.after ? \"update\" : \"create\",\n\t\t\t\tkind: edit.kind,\n\t\t\t\tid: edit.id,\n\t\t\t\ttitle: edit.before.title,\n\t\t\t\tcontent: edit.before.content,\n\t\t\t\tpath: edit.before.path,\n\t\t\t\treference: edit.before.reference,\n\t\t\t\targuments: edit.before.arguments,\n\t\t\t\tmetadata: edit.before.metadata,\n\t\t\t\treason: `Rollback ${target.id}`,\n\t\t\t});\n\t\t} else if (edit.after) {\n\t\t\tedits.push({\n\t\t\t\taction: \"delete\",\n\t\t\t\tkind: edit.kind,\n\t\t\t\tid: edit.id,\n\t\t\t\treason: `Rollback ${target.id}`,\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\tsummary: `Rollback refinement ${target.id}`,\n\t\trationale: `Restores continual harness state snapshots from refinement ${target.id}.`,\n\t\texpectedOutcome: \"Faulty refinement edits are reverted.\",\n\t\tedits,\n\t};\n}\n\nexport function getRefinementHistory(entries: readonly CustomEntry[]): RefinementResult[] {\n\treturn entries\n\t\t.filter((entry) => entry.customType === REFINEMENT_CUSTOM_TYPE)\n\t\t.map((entry) => entry.data)\n\t\t.filter((data): data is RefinementResult => {\n\t\t\treturn typeof data === \"object\" && data !== null && \"id\" in data && \"appliedEdits\" in data;\n\t\t});\n}\n\nexport interface RefinementPlan {\n\tproposal: RefinementProposal;\n\tid: string;\n\trollbackOf?: string;\n\trollbackScope?: HarnessScope;\n\t/** Target-scope state captured before planning, used to reject conflicting edits at apply time. */\n\tbaselineState?: HarnessState;\n}\n\ninterface NativePlannerPlan {\n\treadonly proposal: RefinementProposal;\n\treadonly projection: RefinementProposal;\n\treadonly id: string;\n\treadonly options: RefineOptions;\n\treadonly baselineState?: HarnessState;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\ninterface NativePlannerApplication {\n\treadonly plan: RefinementPlan;\n\treadonly native: NativePlannerPlan;\n\treadonly state: HarnessState;\n\treadonly options: RefineOptions;\n\treadonly scope: HarnessScope;\n\treadonly projection: RefinementProposal;\n}\nconst nativePlannerPlans = new WeakMap<RefinementPlan, NativePlannerPlan>();\nconst nativePlannerApplications = new WeakMap<RefinementProposal, NativePlannerApplication>();\nconst nativePlannerResults = new WeakMap<\n\tRefinementResult,\n\t{ native: NativePlannerPlan; scope: HarnessScope; edits: AppliedRefinementEdit[] }\n>();\n\nfunction matchesNativePlannerPlan(plan: RefinementPlan, native: NativePlannerPlan): boolean {\n\treturn (\n\t\tplan.proposal === native.proposal &&\n\t\tplan.id === native.id &&\n\t\tplan.rollbackOf === undefined &&\n\t\tplan.rollbackScope === undefined &&\n\t\tplan.baselineState === native.baselineState &&\n\t\tisDeepStrictEqual(plan.proposal, native.projection)\n\t);\n}\n\nfunction matchesPlannerOptions(options: RefineOptions, captured: RefineOptions): boolean {\n\treturn (\n\t\toptions.instructions === captured.instructions &&\n\t\toptions.global === captured.global &&\n\t\toptions.rollbackId === captured.rollbackId\n\t);\n}\n\n/** Preserve the actual AS baseline composition, not a copied or replacement plan's labels. */\nexport function withRefinementBaseline(plan: RefinementPlan, baselineState: HarnessState): RefinementPlan {\n\tconst composed = { ...plan, baselineState };\n\tconst native = nativePlannerPlans.get(plan);\n\tnativePlannerPlans.delete(plan);\n\tif (native && native.baselineState === undefined && matchesNativePlannerPlan(plan, native)) {\n\t\tnativePlannerPlans.set(composed, { ...native, baselineState });\n\t}\n\treturn composed;\n}\n\nfunction lowerRefinementProposal(proposal: RefinementProposal): RefinementProposal {\n\treturn {\n\t\t...proposal,\n\t\tedits: proposal.edits.map((edit) => {\n\t\t\tconst localPrefix = \"local:\";\n\t\t\tconst globalPrefix = \"global:\";\n\t\t\treturn {\n\t\t\t\t...edit,\n\t\t\t\tid: edit.id?.startsWith(localPrefix)\n\t\t\t\t\t? edit.id.slice(localPrefix.length)\n\t\t\t\t\t: edit.id?.startsWith(globalPrefix)\n\t\t\t\t\t\t? edit.id.slice(globalPrefix.length)\n\t\t\t\t\t\t: edit.id,\n\t\t\t};\n\t\t}),\n\t};\n}\n\n/** The existing application projection; metadata alone also retains its actual state/control identities. */\nexport function prepareRefinementApplication(\n\tplan: RefinementPlan,\n\tstate: HarnessState,\n\toptions: RefineOptions,\n\tscope: HarnessScope,\n): RefinementProposal {\n\tconst proposal = lowerRefinementProposal(plan.proposal);\n\tconst native = nativePlannerPlans.get(plan);\n\tnativePlannerPlans.delete(plan);\n\tif (\n\t\tnative?.baselineState &&\n\t\tmatchesNativePlannerPlan(plan, native) &&\n\t\tmatchesPlannerOptions(options, native.options) &&\n\t\tscope === (native.options.global ? \"global\" : \"local\")\n\t) {\n\t\tnativePlannerApplications.set(proposal, {\n\t\t\tplan,\n\t\t\tnative,\n\t\t\tstate,\n\t\t\toptions,\n\t\t\tscope,\n\t\t\tprojection: lowerRefinementProposal(native.projection),\n\t\t});\n\t}\n\treturn proposal;\n}\n\n/** Only the actual computed result can reach the existing session result append. */\nexport function takeNativePlannerRequestWrite(\n\tresult: RefinementResult,\n): ((manager: object) => Promise<string | undefined> | undefined) | undefined {\n\tconst captured = nativePlannerResults.get(result);\n\tnativePlannerResults.delete(result);\n\tif (\n\t\t!captured ||\n\t\tresult.id !== captured.native.id ||\n\t\tresult.scope !== captured.scope ||\n\t\tresult.rollbackOf !== undefined ||\n\t\tresult.summary !== captured.native.projection.summary ||\n\t\tresult.rationale !== captured.native.projection.rationale ||\n\t\tresult.expectedOutcome !== captured.native.projection.expectedOutcome ||\n\t\tresult.appliedEdits !== captured.edits\n\t)\n\t\treturn undefined;\n\treturn (manager) => captured.native.write(manager, result);\n}\n\n/**\n * Produce a refinement proposal (the LLM pass, or a rollback proposal) without\n * mutating any harness state. Separated from {@link applyRefinementProposal} so\n * callers can re-read the harness file immediately before applying — the LLM call\n * here can take many seconds, during which the kernel or another session may write\n * the shared `harness_state.json`.\n */\n/** Mint a refinement id in the canonical `refine_<timestamp>` format. */\nexport function generateRefinementId(): string {\n\treturn `refine_${new Date()\n\t\t.toISOString()\n\t\t.replace(/[^0-9]/g, \"\")\n\t\t.slice(0, 17)}`;\n}\n\nexport async function planRefinement(\n\tmessages: AgentMessage[],\n\tstate: HarnessState,\n\thistory: RefinementResult[],\n\tmodel: Model<any>,\n\tapiKey: string,\n\toptions: RefineOptions = {},\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\tuseConfiguredThinkingLevel = false,\n): Promise<RefinementPlan> {\n\tconst id = generateRefinementId();\n\tif (options.rollbackId) {\n\t\tconst target = history.find((item) => item.id === options.rollbackId);\n\t\tif (!target) {\n\t\t\tthrow new Error(`Refinement ${options.rollbackId} not found`);\n\t\t}\n\t\tconst fallbackScope: HarnessScope = options.global ? \"global\" : \"local\";\n\t\treturn {\n\t\t\tproposal: rollbackProposal(target),\n\t\t\tid,\n\t\t\trollbackOf: target.id,\n\t\t\trollbackScope: inferRefinementResultScope(target) ?? fallbackScope,\n\t\t};\n\t}\n\n\tconst conversationText = serializeConversation(convertToLlm(messages)).slice(-80_000);\n\tconst scopeInstruction = options.global\n\t\t? \"Requested refinement scope: global. Only propose stable cross-session continual harness edits, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts that should affect future Base Context sessions. Do not persist session-only progress, temporary blockers, or current-run coordination globally.\"\n\t\t: \"Requested refinement scope: local. Prefer local continual harness edits for current task progress, temporary blockers, current-run coordination, and project facts that are not clearly reusable across Base Context sessions. Global entries in the overview are read-only context: do not propose update or delete edits for them; create a local entry instead if an override is needed.\";\n\tconst userPrompt = [\n\t\t`<current_harness_state>\\n${overviewForPrompt(state)}\\n</current_harness_state>`,\n\t\t`<refinement_history>\\n${historyForPrompt(history)}\\n</refinement_history>`,\n\t\t`<conversation>\\n${conversationText}\\n</conversation>`,\n\t\t`<scope_policy>\\n${scopeInstruction}\\n</scope_policy>`,\n\t\toptions.instructions ? `<user_refine_instructions>\\n${options.instructions}\\n</user_refine_instructions>` : \"\",\n\t\t\"Return only JSON edits. If no useful edit is justified, return an empty edits array with a rationale.\",\n\t]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\n\t// Preserve legacy omitted effort for JSON requests. Only an explicit learning-model\n\t// contract opts into a captured effort; omission does not certify provider behavior.\n\tconst plannerOptions = {\n\t\tinstructions: options.instructions,\n\t\tglobal: options.global,\n\t\trollbackId: options.rollbackId,\n\t};\n\tconst completion = completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{\n\t\t\tsystemPrompt: REFINEMENT_SYSTEM_PROMPT,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t},\n\t\t{\n\t\t\tmaxTokens: refinementMaxOutputTokens(model),\n\t\t\tsignal,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\t...(useConfiguredThinkingLevel ? { reasoning: thinkingLevel } : {}),\n\t\t},\n\t\t{\n\t\t\tpurpose: \"refine\",\n\t\t\tpurposeDetail: \"plan\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\tconst response = await completion;\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Refinement failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tif (response.stopReason === \"length\") {\n\t\tthrow new Error(`Refinement failed: ${TRUNCATED_JSON_ERROR}`);\n\t}\n\n\tconst text = response.content\n\t\t.filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n\tconst plan = { proposal: parseProposal(text), id };\n\tconst write =\n\t\trequests instanceof InferenceCoordinator\n\t\t\t? InferenceCoordinator.prototype.takePlannerOutput.call(requests, completion)\n\t\t\t: undefined;\n\tif (write) {\n\t\tnativePlannerPlans.set(plan, {\n\t\t\tproposal: plan.proposal,\n\t\t\tprojection: structuredClone(plan.proposal),\n\t\t\tid,\n\t\t\toptions: plannerOptions,\n\t\t\twrite,\n\t\t});\n\t}\n\treturn plan;\n}\n\nfunction parseAutoRefineReview(text: string): AutoRefineReview {\n\tconst value = extractJsonObject(text);\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new Error(\"Auto-refine review JSON must be an object\");\n\t}\n\tconst record = value as Record<string, unknown>;\n\treturn {\n\t\tshouldRefine: record.shouldRefine === true,\n\t\trationale: typeof record.rationale === \"string\" ? record.rationale : \"No rationale provided.\",\n\t\tinstructions: typeof record.instructions === \"string\" ? record.instructions : undefined,\n\t};\n}\n\nexport async function reviewAutoRefine(\n\tmessages: AgentMessage[],\n\tstate: HarnessState,\n\thistory: RefinementResult[],\n\tmodel: Model<any>,\n\tapiKey: string,\n\tcontext: AutoRefineReviewContext,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\tuseConfiguredThinkingLevel = false,\n): Promise<AutoRefineReview> {\n\tconst conversationText = serializeConversation(convertToLlm(messages)).slice(-40_000);\n\tconst userPrompt = [\n\t\t`<trigger>\n${context.reason}; ${context.turnsSinceLastReview} assistant turns since last auto-refine review\n</trigger>`,\n\t\t`<current_harness_state>\n${overviewForPrompt(state)}\n</current_harness_state>`,\n\t\t`<refinement_history>\n${historyForPrompt(history)}\n</refinement_history>`,\n\t\t`<conversation>\n${conversationText}\n</conversation>`,\n\t\t\"Apply the automatic refinement utility policy. Ask for global refinement only for durable cross-session lessons or explicitly project-qualified facts likely to be reused in future sessions.\",\n\t].join(\"\\n\\n\");\n\t// Match planning: legacy requests omit effort; an explicit contract carries its exact level.\n\tconst response = await completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{\n\t\t\tsystemPrompt: AUTO_REFINE_REVIEW_SYSTEM_PROMPT,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t},\n\t\t{\n\t\t\tmaxTokens: autoRefineReviewMaxOutputTokens(model),\n\t\t\tsignal,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\t...(useConfiguredThinkingLevel ? { reasoning: thinkingLevel } : {}),\n\t\t},\n\t\t{\n\t\t\tpurpose: \"refine\",\n\t\t\tpurposeDetail: \"auto-refine-review\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Auto-refine review failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tif (response.stopReason === \"length\") {\n\t\tthrow new Error(`Auto-refine review failed: ${TRUNCATED_JSON_ERROR}`);\n\t}\n\tconst text = response.content\n\t\t.filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n\tconst review = parseAutoRefineReview(text);\n\tif (review.shouldRefine) {\n\t\treview.instructions = [review.instructions, AUTOMATIC_REFINEMENT_UTILITY_POLICY].filter(Boolean).join(\"\\n\\n\");\n\t}\n\treturn review;\n}\n\nexport async function refineHarness(\n\tmessages: AgentMessage[],\n\tstate: HarnessState,\n\thistory: RefinementResult[],\n\tmodel: Model<any>,\n\tapiKey: string,\n\toptions: RefineOptions = {},\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n): Promise<RefinementResult> {\n\tconst plan = await planRefinement(\n\t\tmessages,\n\t\tstate,\n\t\thistory,\n\t\tmodel,\n\t\tapiKey,\n\t\toptions,\n\t\theaders,\n\t\tsignal,\n\t\tthinkingLevel,\n\t\trequests,\n\t);\n\treturn applyRefinementProposal(state, plan.proposal, {\n\t\tid: plan.id,\n\t\trollbackOf: plan.rollbackOf,\n\t\tscope: plan.rollbackScope ?? (options.global ? \"global\" : \"local\"),\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"refinement.js","sourceRoot":"","sources":["../../../src/core/refinement/refinement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,SAAS,EACT,UAAU,EACV,SAAS,EACT,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAG9C,OAAO,EAAE,eAAe,EAAE,WA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AAM,cAAc,CAChC,QAAQ,EACR,KAAK,EACL,OAAO,EACP,KAAK,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,MAAM,EACN,aAAa,EACb,QAAQ,CACR,CAAC;IACF,OAAO,uBAAuB,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAE;QACpD,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,KAAK,EAAE,IAAI,CAAC,aAAa,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;KAClE,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\tcloseSync,\n\texistsSync,\n\tfstatSync,\n\tmkdirSync,\n\topenSync,\n\treadSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { AgentMessage, ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport type { Model } from \"@ponythewhite/base-context-ai\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.js\";\nimport { serializeConversation } from \"../compaction/utils.js\";\nimport { readSessionHistoryImage } from \"../export-html/history.js\";\nimport { completeInference, InferenceCoordinator } from \"../inference-coordinator.js\";\nimport { convertToLlm } from \"../messages.js\";\nimport type { NativePlannerRequestOutputWriter } from \"../request-events.js\";\nimport { MODEL_REQUEST_ID_HEADER } from \"../semantic-edges.js\";\nimport type { SessionHistoryReadLimits } from \"../session-history-index.js\";\nimport type { CustomEntry } from \"../session-manager.js\";\n\nexport const REFINEMENT_CUSTOM_TYPE = \"prime-agent.refinement\";\n\nexport const REFINE_SKILL_NAME = \"refine\";\nconst HARNESS_STATE_DIR_NAME = \"harness\";\nconst REFINEMENT_HISTORY_FILE_NAME = \"refinements.jsonl\";\nconst GLOBAL_REFINEMENT_HISTORY_LIMITS: SessionHistoryReadLimits = {\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n};\nconst MAX_GLOBAL_REFINEMENT_APPENDS = 32;\nconst MAX_GLOBAL_REFINEMENT_PENDING_BYTES = 64 * 1024 * 1024;\nlet globalRefinementAppendTail: Promise<void> = Promise.resolve();\nlet pendingGlobalRefinementAppends = 0;\nlet pendingGlobalRefinementBytes = 0;\n\nconst DEFAULT_OVERVIEW_ENTRY_LIMIT = 6;\nconst DEFAULT_OVERVIEW_CONTENT_LIMIT = 180;\n\nexport type RefinementKind = \"prompt\" | \"memory\" | \"skill\" | \"subagent\";\nexport type RefinementAction = \"create\" | \"update\" | \"delete\";\nexport type HarnessScope = \"local\" | \"global\" | \"workspace\";\n\nexport interface HarnessEntry {\n\tid: string;\n\tkind: RefinementKind;\n\ttitle: string;\n\tcontent: string;\n\tpath: string;\n\tscope?: HarnessScope;\n\treference: Record<string, unknown>;\n\targuments: Record<string, unknown>;\n\tmetadata: Record<string, unknown>;\n\tsource: string;\n\tcreated_at: string;\n\tupdated_at: string;\n\tversion: number;\n}\n\nexport interface HarnessRefinementEvent {\n\tid: string;\n\ttrigger: string;\n\tchanges: string[];\n\tevidence: string;\n\toutcome: string;\n\tcreated_at: string;\n}\n\nexport interface HarnessState {\n\tschema: number;\n\tentries: Record<RefinementKind, Record<string, HarnessEntry>>;\n\trefinements: HarnessRefinementEvent[];\n}\n\nexport interface RefinementEdit {\n\taction: RefinementAction;\n\tkind: RefinementKind;\n\tid?: string;\n\ttitle?: string;\n\tcontent?: string;\n\tpath?: string;\n\treference?: Record<string, unknown>;\n\targuments?: Record<string, unknown>;\n\tmetadata?: Record<string, unknown>;\n\treason?: string;\n}\n\nexport interface RefinementProposal {\n\tsummary: string;\n\trationale: string;\n\tedits: RefinementEdit[];\n\texpectedOutcome: string;\n}\n\nexport interface AppliedRefinementEdit extends RefinementEdit {\n\tid: string;\n\tbefore?: HarnessEntry;\n\tafter?: HarnessEntry;\n\tapplied: boolean;\n\terror?: string;\n}\n\nexport interface RefinementResult {\n\tid: string;\n\tsummary: string;\n\trationale: string;\n\texpectedOutcome: string;\n\tappliedEdits: AppliedRefinementEdit[];\n\tharnessStatePath: string;\n\trollbackOf?: string;\n\tscope?: HarnessScope;\n}\n\nexport interface RefineOptions {\n\tinstructions?: string;\n\trollbackId?: string;\n\tglobal?: boolean;\n}\n\nexport type AutoRefineReason = \"turn_interval\" | \"compact\";\n\nexport interface AutoRefineReviewContext {\n\treason: AutoRefineReason;\n\tturnsSinceLastReview: number;\n}\n\nexport interface AutoRefineReview {\n\tshouldRefine: boolean;\n\trationale: string;\n\tinstructions?: string;\n}\n\nconst REFINEMENT_SYSTEM_PROMPT = `You are Base Context's /refine continual harness subsystem.\n\nYour job is to improve the editable continual harness state from the current trajectory.\nThis is similar in spirit to context compaction, but instead of summarizing the\nconversation you emit precise Create, Update, or Delete edits to reusable state.\nThe continual harness is the persistent, editable set of prompt notes, memories,\nskills, and subagent specs that lets Base Context improve reusable behavior\noutside the token history.\nUse \"continual harness\" for that persistent artifact layer; keep \"RLM\" for the\nruntime, Python REPL kernel, and native call interface that executes those artifacts.\n\nContinual harness components:\n- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.\n- memory: durable facts, decisions, failures, preferences, and outcomes.\n- skill: installed Python REPL skill. Skill create/update edits MUST include a \\`reference\\` object with \\`{\"type\":\"python\"}\\`, a Python import, and a callable or call pattern; they also MUST include an \\`arguments\\` object describing accepted inputs, required fields, defaults, and constraints. Use \\`{}\\` for \\`arguments\\` only when the Python callable truly needs no external inputs. Include the RLM-native call form \\`await <skill_import>(...)\\`.\n- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: compose a concise task prompt and spawn with \\`handle = await rlm(\"sub-task\")\\`; admission returns immediately with \\`rlm_child_id\\`, \\`name\\`, \\`session_dir\\`, and \\`model\\`, never the child's answer. Results arrive only through explicit \\`agent_message\\` replies or files; children reply with \\`await agent_message.send(message, receiver_role=\"parent\")\\`. Use \\`await rlm.list_subagents()\\` to recover direct child handles and \\`await agent_message.send(..., receiver_role=\"child\", receiver_name=handle.name)\\` for follow-ups. Do not invent wrappers like \\`run_subagent(...)\\`.\n\nScope and persistence policy:\n- The default editable continual harness store is local to the current Base Context session. Use it for session-specific progress, active task state, current-run coordination notes, temporary blockers, and project facts that should not affect other sessions.\n- A caller may explicitly request global refinement. Global edits must be stable cross-session lessons, durable user preferences, reusable skills/subagents, or tool/environment facts that should affect future sessions.\n- Entry ids in the harness overview may carry a display-only \\`local:\\` or \\`global:\\` prefix. Always use the bare id (no prefix) in edits.\n- All edits in one refinement apply only to the requested scope's store. During a local refinement, global entries are read-only context: never propose update or delete edits for them; create a local entry instead when a session-specific override is genuinely needed.\n- Project/workspace-specific lessons may be persisted globally only when the title, path, or content explicitly names the project/workspace and the lesson is likely to be reused in future sessions for that project. Prefer local edits when the lesson only belongs in the current conversation.\n- Use memory for declarative facts and preferences, skill for repeatable procedures exposed as Python calls, prompt for narrow behavioral policy addendums, and subagent for reusable delegation roles.\n- Create or update the smallest relevant component: repeated delegation roles should become subagent specs, repeated procedures should become skills, durable facts/preferences should become memories, and narrow behavioral policies should become prompt addendums.\n- When an edit is persisted, include metadata such as \\`{\"scope\":\"local\"}\\` or \\`{\"scope\":\"global\"}\\` when that helps future review understand the intended blast radius.\n\nUse the trajectory, current continual harness state, and prior refinement history. Prefer\nsmall evidence-backed edits. If prior refinements caused issues, rollback or\nreplace the faulty editable entries. Never edit source files directly. Output\nJSON only with this exact shape:\n\n{\n \"summary\": \"one sentence\",\n \"rationale\": \"why these edits are justified by trajectory evidence\",\n \"expectedOutcome\": \"what should improve and how to validate it\",\n \"edits\": [\n {\n \"action\": \"create|update|delete\",\n \"kind\": \"prompt|memory|skill|subagent\",\n \"id\": \"stable id for update/delete, optional for create\",\n \"title\": \"required for create/update except delete\",\n \"content\": \"required for create/update except delete\",\n \"path\": \"optional grouping path\",\n \"reference\": {\"type\": \"python\", \"import\": \"package.module\", \"callable\": \"function_name\", \"call_pattern\": \"await function_name(...)\"},\n \"arguments\": {\"name\": {\"type\": \"string\", \"required\": true, \"description\": \"accepted input\"}},\n \"metadata\": {},\n \"reason\": \"why this edit is useful\"\n }\n ]\n}`;\n\nconst AUTOMATIC_REFINEMENT_UTILITY_POLICY = `Automatic refinement requires a concrete reusable improvement supported by the trajectory and not already supplied in the task or current harness context. Eligible improvements include stable facts/preferences, reusable failure lessons, and repeatable procedures; local reusable lessons are eligible. Do not refine solely to copy current progress, completion claims, output counts, next-step checklists, or temporary blockers; keep those in task context. If no supported reusable improvement remains, return shouldRefine=false when reviewing, or an empty edits array when planning.`;\n\nconst AUTO_REFINE_REVIEW_SYSTEM_PROMPT = `You are Base Context's automatic /refine review gate.\n\nDecide whether this checkpoint should run /refine. Auto /refine writes local continual harness state by default.\n${AUTOMATIC_REFINEMENT_UTILITY_POLICY}\nReject one-off noise, unsupported hypotheses, and transient tool outputs. Ask for global refinement only for durable cross-session lessons or explicitly project-qualified lessons likely to be reused in future sessions.\n\nReturn JSON only:\n{\n \"shouldRefine\": true|false,\n \"rationale\": \"short reason\",\n \"instructions\": \"optional concise instructions for /refine if shouldRefine is true\"\n}`;\n\n/**\n * Output budgets are derived from the selected model instead of fixed literals.\n * /refine input scales with harness size (entry overview, refinement history, and\n * the trajectory slice), so a constant output cap silently truncates exactly the\n * large multi-edit proposals that matter most. Math.min keeps small models honest.\n */\nconst REFINEMENT_MAX_OUTPUT_TOKENS = 32_000;\nconst AUTO_REFINE_REVIEW_MAX_OUTPUT_TOKENS = 4_096;\n\nconst TRUNCATED_JSON_ERROR =\n\t\"the model stopped before completing its JSON object. This usually means the output budget was exhausted; retry with a smaller request.\";\n\nfunction refinementMaxOutputTokens(model: Model<any>): number {\n\treturn Math.min(model.maxTokens, REFINEMENT_MAX_OUTPUT_TOKENS);\n}\n\nfunction autoRefineReviewMaxOutputTokens(model: Model<any>): number {\n\treturn Math.min(model.maxTokens, AUTO_REFINE_REVIEW_MAX_OUTPUT_TOKENS);\n}\n\nfunction now(): string {\n\treturn new Date().toISOString();\n}\n\nfunction emptyHarnessState(): HarnessState {\n\treturn {\n\t\tschema: 1,\n\t\tentries: {\n\t\t\tprompt: {},\n\t\t\tmemory: {},\n\t\t\tskill: {},\n\t\t\tsubagent: {},\n\t\t},\n\t\trefinements: [],\n\t};\n}\n\nfunction slug(raw: string, fallback: string): string {\n\tconst normalized = raw\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, \"_\")\n\t\t.replace(/^_+|_+$/g, \"\")\n\t\t.slice(0, 80);\n\treturn normalized || fallback;\n}\n\nfunction cloneEntry(entry: HarnessEntry | undefined): HarnessEntry | undefined {\n\treturn entry ? JSON.parse(JSON.stringify(entry)) : undefined;\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn undefined;\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction normalizeHarnessScope(value: unknown, fallback: HarnessScope): HarnessScope {\n\treturn value === \"global\" || value === \"local\" || value === \"workspace\" ? value : fallback;\n}\n\nexport function inferRefinementResultScope(result: RefinementResult): HarnessScope | undefined {\n\tif (result.scope) {\n\t\treturn result.scope;\n\t}\n\n\tconst scopes = new Set<HarnessScope>();\n\tfor (const edit of result.appliedEdits) {\n\t\tconst scope = edit.after?.scope ?? edit.before?.scope;\n\t\tif (scope) {\n\t\t\tscopes.add(scope);\n\t\t}\n\t}\n\treturn scopes.size === 1 ? [...scopes][0] : undefined;\n}\n\nfunction withDefaultRefinementScope(result: RefinementResult, scope: HarnessScope): RefinementResult {\n\tconst inferred = inferRefinementResultScope(result);\n\treturn { ...result, scope: inferred ?? scope };\n}\n\nexport function getGlobalHarnessStateDir(agentDir: string = getAgentDir()): string {\n\treturn join(agentDir, HARNESS_STATE_DIR_NAME);\n}\n\nexport function getLocalHarnessStateDir(sessionArtifactDir: string | undefined): string | undefined {\n\treturn sessionArtifactDir ? join(sessionArtifactDir, HARNESS_STATE_DIR_NAME) : undefined;\n}\n\nexport function getWorkspaceHarnessStateDir(projectRoot: string): string {\n\treturn join(projectRoot, CONFIG_DIR_NAME);\n}\n\nexport function getHarnessStatePath(\n\tharnessStateDir: string = getGlobalHarnessStateDir(),\n\tscope: HarnessScope = \"global\",\n): string {\n\treturn join(harnessStateDir, scope === \"workspace\" ? \"harness-state.json\" : \"harness_state.json\");\n}\n\nconst HARNESS_STATE_LIMITS: SessionHistoryReadLimits = {\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n};\n\nclass HarnessStateLimitError extends Error {}\n\nfunction harnessStateLimits(limits: SessionHistoryReadLimits): SessionHistoryReadLimits {\n\tconst { maxEntries, maxSourceBytes } = limits;\n\tif (\n\t\t!Number.isSafeInteger(maxEntries) ||\n\t\tmaxEntries <= 0 ||\n\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\tmaxSourceBytes <= 0\n\t) {\n\t\tthrow new Error(\"Invalid harness state limits\");\n\t}\n\treturn { maxEntries, maxSourceBytes };\n}\n\n/** Count only owned kind records and refinement events, not arbitrary nested memory. */\nfunction assertHarnessStateItemLimit(state: Partial<HarnessState>, maxEntries: number): void {\n\tlet count = Array.isArray(state.refinements) ? state.refinements.length : 0;\n\tif (count > maxEntries) throw new HarnessStateLimitError(\"Harness state item limit exceeded\");\n\tfor (const kind of [\"prompt\", \"memory\", \"skill\", \"subagent\"] as const) {\n\t\tconst records = state.entries?.[kind];\n\t\tif (!records || typeof records !== \"object\") continue;\n\t\tfor (const id in records) {\n\t\t\tif (!Object.hasOwn(records, id) || !objectRecord(records[id])) continue;\n\t\t\tif (++count > maxEntries) throw new HarnessStateLimitError(\"Harness state item limit exceeded\");\n\t\t}\n\t}\n}\n\nfunction readHarnessStateImage(statePath: string, maxSourceBytes: number): Buffer {\n\tconst fd = openSync(statePath, \"r\");\n\tlet captured: Buffer;\n\ttry {\n\t\tconst size = fstatSync(fd, { bigint: true }).size;\n\t\tif (size > BigInt(maxSourceBytes)) throw new HarnessStateLimitError(\"Harness state source byte limit exceeded\");\n\t\tcaptured = Buffer.alloc(Number(size));\n\t\tlet offset = 0;\n\t\twhile (offset < captured.length) {\n\t\t\tconst count = readSync(fd, captured, offset, Math.min(64 * 1024, captured.length - offset), offset);\n\t\t\tif (count === 0) throw new Error(\"Harness state source changed during read\");\n\t\t\toffset += count;\n\t\t}\n\t\tconst after = fstatSync(fd, { bigint: true }).size;\n\t\tif (after > BigInt(maxSourceBytes)) throw new HarnessStateLimitError(\"Harness state source byte limit exceeded\");\n\t\tif (after !== size) throw new Error(\"Harness state source changed during read\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tcloseSync(fd);\n\t\t} catch (closeError) {\n\t\t\tthrow new AggregateError([error, closeError], \"Harness state read and close failed\", { cause: error });\n\t\t}\n\t\tthrow error;\n\t}\n\tcloseSync(fd);\n\treturn captured;\n}\n\nexport function loadHarnessState(\n\tharnessStateDir: string = getGlobalHarnessStateDir(),\n\tscope: HarnessScope = \"global\",\n\tlimits: SessionHistoryReadLimits = HARNESS_STATE_LIMITS,\n): HarnessState {\n\tconst { maxEntries, maxSourceBytes } = harnessStateLimits(limits);\n\tconst statePath = getHarnessStatePath(harnessStateDir, scope);\n\tif (!existsSync(statePath)) {\n\t\treturn emptyHarnessState();\n\t}\n\tlet parsed: Partial<HarnessState>;\n\ttry {\n\t\tconst raw = JSON.parse(readHarnessStateImage(statePath, maxSourceBytes).toString(\"utf8\"));\n\t\t// loadHarnessState runs on every system-prompt build and before each /refine, so\n\t\t// a corrupt or unreadable (or non-object) state file must degrade to empty rather\n\t\t// than throw and break the session. The next saveHarnessState rewrites it cleanly.\n\t\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\t\treturn emptyHarnessState();\n\t\t}\n\t\tparsed = raw as Partial<HarnessState>;\n\t} catch (error) {\n\t\t// An oversized valid store must never become an empty snapshot that a later save can overwrite.\n\t\tif (\n\t\t\terror instanceof HarnessStateLimitError ||\n\t\t\t(error instanceof AggregateError && error.cause instanceof HarnessStateLimitError)\n\t\t)\n\t\t\tthrow error;\n\t\treturn emptyHarnessState();\n\t}\n\tassertHarnessStateItemLimit(parsed, maxEntries);\n\tconst state = emptyHarnessState();\n\tstate.schema = typeof parsed.schema === \"number\" ? parsed.schema : 1;\n\tfor (const kind of Object.keys(state.entries) as RefinementKind[]) {\n\t\tconst records = parsed.entries?.[kind];\n\t\tif (records && typeof records === \"object\") {\n\t\t\tfor (const id in records) {\n\t\t\t\tif (!Object.hasOwn(records, id)) continue;\n\t\t\t\tconst entry = objectRecord(records[id]);\n\t\t\t\tif (!entry) continue;\n\t\t\t\tstate.entries[kind][id] = {\n\t\t\t\t\t...(entry as unknown as HarnessEntry),\n\t\t\t\t\tscope: normalizeHarnessScope(entry.scope, scope),\n\t\t\t\t\treference: objectRecord(entry.reference) ?? {},\n\t\t\t\t\targuments: objectRecord(entry.arguments) ?? {},\n\t\t\t\t\tmetadata: objectRecord(entry.metadata) ?? {},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\tif (Array.isArray(parsed.refinements)) {\n\t\tstate.refinements = parsed.refinements;\n\t}\n\treturn state;\n}\n\nexport function mergeHarnessStates(\n\tglobalState: HarnessState,\n\tlocalState?: HarnessState,\n\tworkspaceState?: HarnessState,\n): HarnessState {\n\tconst merged = emptyHarnessState();\n\tconst sources: [HarnessScope, HarnessState | undefined][] = [\n\t\t[\"global\", globalState],\n\t\t[\"local\", localState],\n\t\t[\"workspace\", workspaceState],\n\t];\n\tfor (const [scope, state] of sources) {\n\t\tif (!state) continue;\n\t\tmerged.schema = Math.max(merged.schema, state.schema);\n\t\tfor (const kind of Object.keys(merged.entries) as RefinementKind[]) {\n\t\t\tfor (const [id, entry] of Object.entries(state.entries[kind])) {\n\t\t\t\tconst cloned = cloneEntry(entry)!;\n\t\t\t\tconst scopedEntry = { ...cloned, scope: normalizeHarnessScope(cloned.scope, scope) };\n\t\t\t\tconst mergedId = merged.entries[kind][id] ? `${scopedEntry.scope}:${id}` : id;\n\t\t\t\tmerged.entries[kind][mergedId] = scopedEntry;\n\t\t\t}\n\t\t}\n\t\tmerged.refinements.push(...state.refinements);\n\t}\n\treturn merged;\n}\n\nexport function saveHarnessState(\n\tharnessStateDir: string,\n\tstate: HarnessState,\n\tlimits: SessionHistoryReadLimits = HARNESS_STATE_LIMITS,\n\tscope: HarnessScope = \"global\",\n): string {\n\tconst { maxEntries, maxSourceBytes } = harnessStateLimits(limits);\n\tassertHarnessStateItemLimit(state, maxEntries);\n\tconst serialized = `${JSON.stringify(state, null, 2)}\\n`;\n\tif (Buffer.byteLength(serialized) > maxSourceBytes) {\n\t\tthrow new HarnessStateLimitError(\"Harness state source byte limit exceeded\");\n\t}\n\tconst statePath = getHarnessStatePath(harnessStateDir, scope);\n\tconst tempPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`;\n\tmkdirSync(harnessStateDir, { recursive: true });\n\ttry {\n\t\tconst mode = existsSync(statePath) ? statSync(statePath).mode & 0o777 : 0o600;\n\t\twriteFileSync(tempPath, serialized, { encoding: \"utf8\", mode });\n\t\trenameSync(tempPath, statePath);\n\t} finally {\n\t\tif (existsSync(tempPath)) {\n\t\t\tunlinkSync(tempPath);\n\t\t}\n\t}\n\treturn statePath;\n}\n\nexport function getRefinementHistoryPath(harnessStateDir: string = getGlobalHarnessStateDir()): string {\n\treturn join(harnessStateDir, REFINEMENT_HISTORY_FILE_NAME);\n}\n\nfunction isRefinementResult(data: unknown): data is RefinementResult {\n\treturn typeof data === \"object\" && data !== null && \"id\" in data && \"appliedEdits\" in data;\n}\n\n/**\n * Append a global-scope refinement to the cross-session history log so it can be\n * rolled back from any session. Local-scope refinements are recorded only in the\n * session JSONL and roll back via their recorded harnessStatePath.\n */\nexport async function appendGlobalRefinement(\n\tharnessStateDir: string,\n\tresult: RefinementResult,\n\tmaxRecordBytes = GLOBAL_REFINEMENT_HISTORY_LIMITS.maxSourceBytes,\n): Promise<string> {\n\tif (!Number.isSafeInteger(maxRecordBytes) || maxRecordBytes <= 0) {\n\t\tthrow new Error(\"Invalid global refinement record byte limit\");\n\t}\n\tif (pendingGlobalRefinementAppends >= MAX_GLOBAL_REFINEMENT_APPENDS) {\n\t\tthrow new Error(\"Global refinement append queue limit exceeded\");\n\t}\n\tconst historyPath = getRefinementHistoryPath(harnessStateDir);\n\t// Preserve JSON.stringify semantics and freeze the caller's value before I/O yields.\n\tconst serialized = `${JSON.stringify(result)}\\n`;\n\tconst bytes = Buffer.byteLength(serialized);\n\tif (bytes > maxRecordBytes || pendingGlobalRefinementBytes + bytes > MAX_GLOBAL_REFINEMENT_PENDING_BYTES) {\n\t\tthrow new Error(\"Global refinement append byte limit exceeded\");\n\t}\n\tpendingGlobalRefinementAppends++;\n\tpendingGlobalRefinementBytes += bytes;\n\tconst write = globalRefinementAppendTail.then(async () => {\n\t\tawait mkdir(harnessStateDir, { recursive: true });\n\t\tawait appendFile(historyPath, serialized, \"utf8\");\n\t\treturn historyPath;\n\t});\n\t// Failed appends reject their caller, but do not poison later accepted work.\n\tglobalRefinementAppendTail = write.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\ttry {\n\t\treturn await write;\n\t} finally {\n\t\tpendingGlobalRefinementAppends--;\n\t\tpendingGlobalRefinementBytes -= bytes;\n\t}\n}\n\nexport async function loadGlobalRefinementHistory(\n\tharnessStateDir: string = getGlobalHarnessStateDir(),\n\tlimits: SessionHistoryReadLimits = GLOBAL_REFINEMENT_HISTORY_LIMITS,\n): Promise<RefinementResult[]> {\n\tconst { maxEntries, maxSourceBytes } = limits;\n\tif (\n\t\t!Number.isSafeInteger(maxEntries) ||\n\t\tmaxEntries <= 0 ||\n\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\tmaxSourceBytes <= 0\n\t) {\n\t\tthrow new Error(\"Invalid global refinement history limits\");\n\t}\n\tconst historyPath = getRefinementHistoryPath(harnessStateDir);\n\tconst priorAppends = globalRefinementAppendTail;\n\tawait priorAppends;\n\tif (!existsSync(historyPath)) return [];\n\tconst captured = await readSessionHistoryImage(historyPath, maxSourceBytes, \"Global refinement history\");\n\tconst text = captured.toString(\"utf8\");\n\tconst results: RefinementResult[] = [];\n\tlet start = 0;\n\tlet records = 0;\n\twhile (start < text.length) {\n\t\tconst newline = text.indexOf(\"\\n\", start);\n\t\tconst end = newline === -1 ? text.length : newline;\n\t\tconst trimmed = text.slice(start, end).trim();\n\t\tstart = end + 1;\n\t\tif (!trimmed) continue;\n\t\tif (++records > maxEntries) throw new Error(\"Global refinement history entry limit exceeded\");\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(trimmed);\n\t\t\tif (isRefinementResult(parsed)) results.push(withDefaultRefinementScope(parsed, \"global\"));\n\t\t} catch {\n\t\t\t// Preserve malformed-line skipping, including scope-inference failures.\n\t\t}\n\t}\n\treturn results;\n}\n\n/**\n * Merge global and session refinement history, de-duplicating by id. Session entries\n * win on conflict so a session that is mid-flight still resolves its own latest result.\n */\nexport function mergeRefinementHistory(\n\tglobal: readonly RefinementResult[],\n\tsession: readonly RefinementResult[],\n): RefinementResult[] {\n\tconst byId = new Map<string, RefinementResult>();\n\tfor (const result of global) {\n\t\tbyId.set(result.id, result);\n\t}\n\tfor (const result of session) {\n\t\tconst existing = byId.get(result.id);\n\t\tbyId.set(result.id, result.scope || !existing?.scope ? result : { ...result, scope: existing.scope });\n\t}\n\treturn [...byId.values()];\n}\n\nfunction compactText(text: string, maxLength: number): string {\n\tconst normalized = text.replace(/\\s+/g, \" \").trim();\n\tif (normalized.length <= maxLength) {\n\t\treturn normalized;\n\t}\n\treturn `${normalized.slice(0, Math.max(0, maxLength - 3))}...`;\n}\n\nexport interface ErrorFixSelectionOptions {\n\tenabled: boolean;\n\t/** Captured available tool names; this does not predict the next tool call. */\n\ttools: readonly string[];\n\toperation?: string;\n\tgoal?: string;\n\t/** Only values already known to the owner; retrieval never probes the environment. */\n\tenvironment?: Readonly<Record<string, string>>;\n\t/** Local request-meter text cost, including the complete rendered advice wrapper. */\n\tcountTokens: (text: string) => number;\n}\n\nfunction isErrorFixMemory(entry: HarnessEntry): boolean {\n\treturn entry.kind === \"memory\" && entry.id.startsWith(\"error-fix:\");\n}\n\nfunction lessonWords(text: string): Set<string> {\n\treturn new Set(text.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []);\n}\n\n/** Optional contextual advice, never a replacement for current task evidence or policy. */\nexport function selectErrorFixAdvice(state: HarnessState, options: ErrorFixSelectionOptions): string {\n\tif (!options.enabled) return \"\";\n\tconst query = lessonWords(`${options.operation ?? \"\"} ${options.goal ?? \"\"}`);\n\tif (query.size === 0) return \"\";\n\tconst ranked = Object.entries(state.entries.memory)\n\t\t.filter(([, entry]) => isErrorFixMemory(entry))\n\t\t.map(([key, entry]) => {\n\t\t\tconst metadata = entry.metadata;\n\t\t\tif (typeof metadata.tool === \"string\" && !options.tools.includes(metadata.tool)) return undefined;\n\t\t\tconst environment = objectRecord(metadata.environment);\n\t\t\tif (\n\t\t\t\tenvironment &&\n\t\t\t\tObject.entries(environment).some(\n\t\t\t\t\t([name, value]) =>\n\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\toptions.environment?.[name] !== undefined &&\n\t\t\t\t\t\toptions.environment[name] !== value,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\tconst words = lessonWords(\n\t\t\t\t[metadata.operation, metadata.condition].filter((value) => typeof value === \"string\").join(\" \"),\n\t\t\t);\n\t\t\tconst score = [...words].filter((word) => query.has(word)).length;\n\t\t\treturn score > 0 ? { key, entry, score } : undefined;\n\t\t})\n\t\t.filter((candidate) => candidate !== undefined)\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.score - a.score ||\n\t\t\t\t(a.entry.id < b.entry.id ? -1 : a.entry.id > b.entry.id ? 1 : a.key < b.key ? -1 : a.key > b.key ? 1 : 0),\n\t\t);\n\tconst header = \"## Error-fix advice\\nPast advice only; the active task and current observations take precedence.\";\n\tlet advice = \"\";\n\tlet selected = 0;\n\tfor (const { entry } of ranked) {\n\t\tconst condition = typeof entry.metadata.condition === \"string\" ? `\\nCondition: ${entry.metadata.condition}` : \"\";\n\t\tconst note = `- [${entry.scope ?? \"global\"}:${entry.id}] ${entry.title}${condition}\\n${entry.content}`;\n\t\tconst candidate = `${advice || header}\\n${note}`;\n\t\t// Include the formatter's separating blank line in the local allowance.\n\t\tconst tokens = options.countTokens(`\\n\\n${candidate}`);\n\t\tif (!Number.isFinite(tokens) || tokens < 0 || tokens > 512) continue;\n\t\tadvice = candidate;\n\t\tif (++selected === 3) break;\n\t}\n\treturn advice;\n}\n\nconst ERROR_FIX_CREATION_GUIDANCE = `When learning is enabled, after repairing a useful recurring mistake and reaching the task's normal success condition, or after an explicit user correction, save a short problem/fix note with \\`rlm.get_harness_state(scope=\"workspace\").upsert(\"memory\", title, \"Problem: ...\\\\nFix: ...\", id=\"error-fix:readable-key\", metadata={\"tool\": \"ipython\", \"operation\": \"...\", \"condition\": \"...\"})\\`. Update the matching key, not copies. Use local scope for session-only notes; global scope requires an explicit global action. Metadata may also contain an environment mapping of already-known versions. Do not copy secrets, tracebacks, source files, or history. Do not record cancellation, intentionally failing tests, or transient rate limits, and never ban a command permanently. Correct obsolete notes with ordinary edit/delete. Do not add a model call or test just to record a note. Missing optional memory support must not block the task.`;\n\nexport function formatHarnessStateForPrompt(\n\tstate: HarnessState,\n\toptions: {\n\t\tmaxEntriesPerKind?: number;\n\t\tmaxContentLength?: number;\n\t\tincludeIpythonExamples?: boolean;\n\t\tincludeShellExamples?: boolean;\n\t\tincludeRefineExamples?: boolean;\n\t\terrorFixSelection?: ErrorFixSelectionOptions;\n\t} = {},\n): string {\n\tconst maxEntriesPerKind = options.maxEntriesPerKind ?? DEFAULT_OVERVIEW_ENTRY_LIMIT;\n\tconst maxContentLength = options.maxContentLength ?? DEFAULT_OVERVIEW_CONTENT_LIMIT;\n\tconst includeIpythonExamples = options.includeIpythonExamples ?? true;\n\tconst includeRefineExamples = options.includeRefineExamples ?? includeIpythonExamples;\n\tconst lines = [\n\t\t\"# Continual Harness State\",\n\t\t\"\",\n\t\t\"Local continual harness entries belong to this Base Context session. Global continual harness entries persist across Base Context sessions. Workspace entries belong only to the selected project.\",\n\t\t\"The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\",\n\t\t\"Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\",\n\t\t\"Use these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\",\n\t\t\"\",\n\t\tincludeRefineExamples\n\t\t\t? \"When to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\"\n\t\t\t: \"When to refine the continual harness: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep continual harness edits small and evidence-backed.\",\n\t\t\"\",\n\t\tincludeIpythonExamples\n\t\t\t? \"Call contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm('sub-task')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\"\n\t\t\t: options.includeShellExamples\n\t\t\t\t? \"Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without the Python REPL; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents a Python kernel.\"\n\t\t\t\t: \"Call contract: continual harness entries are routing/context hints only in sessions without the Python REPL or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.\",\n\t\t\"\",\n\t];\n\n\tlet totalEntries = 0;\n\tfor (const kind of Object.keys(state.entries) as RefinementKind[]) {\n\t\tconst entries = Object.values(state.entries[kind])\n\t\t\t.filter((entry) => !isErrorFixMemory(entry))\n\t\t\t.sort((a, b) => [a.path, a.title, a.id].join(\"\\0\").localeCompare([b.path, b.title, b.id].join(\"\\0\")));\n\t\ttotalEntries += entries.length;\n\t\t// Render subagent specs as a task-shaped roster the model can match against — the\n\t\t// analogue of Claude Code's agent-type menu — rather than a bare count. In\n\t\t// REPL sessions, include the native `rlm` invocation hint.\n\t\tif (kind === \"subagent\" && entries.length > 0 && includeIpythonExamples) {\n\t\t\tlines.push(\n\t\t\t\t`${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and spawning with \\`await rlm('<task>')\\`; admission returns a child handle, never the answer)`,\n\t\t\t);\n\t\t} else {\n\t\t\tlines.push(`${kind}: ${entries.length}`);\n\t\t}\n\t\tfor (const entry of entries.slice(0, maxEntriesPerKind)) {\n\t\t\tconst argumentsText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.arguments).length > 0\n\t\t\t\t\t? ` args=${compactText(JSON.stringify(entry.arguments), maxContentLength)}`\n\t\t\t\t\t: \"\";\n\t\t\tconst referenceText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.reference).length > 0\n\t\t\t\t\t? ` ref=${compactText(JSON.stringify(entry.reference), maxContentLength)}`\n\t\t\t\t\t: \"\";\n\t\t\tlines.push(\n\t\t\t\t`- [${entry.scope ?? \"global\"}:${entry.id}] ${entry.title} (${entry.path})${referenceText}${argumentsText}: ${compactText(\n\t\t\t\t\tentry.content,\n\t\t\t\t\tmaxContentLength,\n\t\t\t\t)}`,\n\t\t\t);\n\t\t}\n\t\tconst overflow = entries.length - Math.min(entries.length, maxEntriesPerKind);\n\t\tif (overflow > 0) {\n\t\t\tlines.push(`- +${overflow} more ${kind} entries`);\n\t\t}\n\t\tlines.push(\"\");\n\t}\n\n\tif (totalEntries === 0) {\n\t\tlines.push(\"No saved harness entries yet.\", \"\");\n\t}\n\n\tif (options.errorFixSelection?.enabled) {\n\t\tif (includeIpythonExamples) lines.push(\"\", ERROR_FIX_CREATION_GUIDANCE);\n\t\tconst advice = selectErrorFixAdvice(state, options.errorFixSelection);\n\t\tif (advice) lines.push(\"\", advice);\n\t}\n\treturn lines.join(\"\\n\").trim();\n}\n\nfunction overviewForPrompt(state: HarnessState): string {\n\tconst lines: string[] = [];\n\tfor (const kind of Object.keys(state.entries) as RefinementKind[]) {\n\t\tconst entries = Object.values(state.entries[kind]).filter((entry) => !isErrorFixMemory(entry));\n\t\tlines.push(`${kind}: ${entries.length}`);\n\t\tfor (const entry of entries.slice(0, 40)) {\n\t\t\tconst content = entry.content.replace(/\\s+/g, \" \").slice(0, 240);\n\t\t\tconst argumentsText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.arguments).length > 0\n\t\t\t\t\t? ` args=${JSON.stringify(entry.arguments).slice(0, 240)}`\n\t\t\t\t\t: \"\";\n\t\t\tconst referenceText =\n\t\t\t\tentry.kind === \"skill\" && Object.keys(entry.reference).length > 0\n\t\t\t\t\t? ` ref=${JSON.stringify(entry.reference).slice(0, 240)}`\n\t\t\t\t\t: \"\";\n\t\t\tlines.push(\n\t\t\t\t`- [${entry.scope ?? \"global\"}:${entry.id}] ${entry.title} (${entry.path}, v${entry.version})${referenceText}${argumentsText}: ${content}`,\n\t\t\t);\n\t\t}\n\t\tif (entries.length > 40) {\n\t\t\tlines.push(`- +${entries.length - 40} more ${kind} entries`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction historyForPrompt(history: RefinementResult[]): string {\n\tif (history.length === 0) {\n\t\treturn \"No prior refinement history.\";\n\t}\n\treturn history\n\t\t.slice(-20)\n\t\t.map((item) => {\n\t\t\tconst edits = item.appliedEdits\n\t\t\t\t.map((edit) => `${edit.applied ? \"applied\" : \"failed\"} ${edit.action} ${edit.kind}:${edit.id}`)\n\t\t\t\t.join(\", \");\n\t\t\tconst rollback = item.rollbackOf ? ` rollbackOf=${item.rollbackOf}` : \"\";\n\t\t\treturn `[${item.id}]${rollback} ${item.summary}\\n${edits}\\nExpected outcome: ${item.expectedOutcome}`;\n\t\t})\n\t\t.join(\"\\n\\n\");\n}\n\n/**\n * Whether a JSON candidate ends mid-value: an unterminated string, or unclosed\n * objects/arrays. A reply cut off by an exhausted output budget is incomplete in\n * this sense, while a complete-but-malformed reply is balanced. Brace slicing can\n * also produce a balanced fragment, so callers treat \"balanced\" as malformed.\n */\nfunction isIncompleteJson(candidate: string): boolean {\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (const char of candidate) {\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (inString) {\n\t\t\tif (char === \"\\\\\") escaped = true;\n\t\t\telse if (char === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"') inString = true;\n\t\telse if (char === \"{\" || char === \"[\") depth++;\n\t\telse if (char === \"}\" || char === \"]\") depth--;\n\t}\n\treturn inString || depth > 0;\n}\n\nfunction parseJsonCandidate(candidate: string): unknown {\n\ttry {\n\t\treturn JSON.parse(candidate);\n\t} catch (error) {\n\t\t// A truncated reply and a malformed one both fail here, and JSON.parse\n\t\t// describes the fragment rather than the cause. Name the cause instead.\n\t\tif (isIncompleteJson(candidate)) {\n\t\t\tthrow new Error(TRUNCATED_JSON_ERROR);\n\t\t}\n\t\tthrow new Error(`the model did not return valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n}\n\nfunction extractJsonObject(text: string): unknown {\n\tconst trimmed = text.trim();\n\tif (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n\t\t// A reply truncated after a nested closing brace still looks well-formed\n\t\t// here, so this path needs the same diagnosis as the slicing fallback.\n\t\treturn parseJsonCandidate(trimmed);\n\t}\n\tconst fenced = trimmed.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n\tif (fenced) {\n\t\treturn parseJsonCandidate(fenced[1].trim());\n\t}\n\t// Brace slicing recovers JSON wrapped in prose. On a reply truncated inside the\n\t// edits array it slices to an earlier edit's closing brace, so a failure here\n\t// is diagnosed against the original text rather than the balanced fragment.\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start !== -1 && end > start) {\n\t\ttry {\n\t\t\treturn JSON.parse(trimmed.slice(start, end + 1));\n\t\t} catch {\n\t\t\treturn parseJsonCandidate(trimmed.slice(start));\n\t\t}\n\t}\n\tif (isIncompleteJson(trimmed)) {\n\t\tthrow new Error(TRUNCATED_JSON_ERROR);\n\t}\n\tthrow new Error(\"Refiner did not return a JSON object\");\n}\n\n/**\n * Normalizes an untrusted refinement proposal while preserving invalid edit\n * fields for apply-time validation.\n */\nexport function normalizeRefinementProposal(value: unknown): RefinementProposal {\n\tconst record =\n\t\ttypeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n\tconst edits = Array.isArray(record.edits) ? record.edits : [];\n\treturn {\n\t\tsummary: typeof record.summary === \"string\" ? record.summary : \"Refined continual harness state\",\n\t\trationale: typeof record.rationale === \"string\" ? record.rationale : \"\",\n\t\texpectedOutcome: typeof record.expectedOutcome === \"string\" ? record.expectedOutcome : \"\",\n\t\tedits: edits\n\t\t\t.filter((edit): edit is Record<string, unknown> => typeof edit === \"object\" && edit !== null)\n\t\t\t.map((edit) => ({\n\t\t\t\taction: edit.action as RefinementAction,\n\t\t\t\tkind: edit.kind as RefinementKind,\n\t\t\t\tid: typeof edit.id === \"string\" ? edit.id : undefined,\n\t\t\t\ttitle: typeof edit.title === \"string\" ? edit.title : undefined,\n\t\t\t\tcontent: typeof edit.content === \"string\" ? edit.content : undefined,\n\t\t\t\tpath: typeof edit.path === \"string\" ? edit.path : undefined,\n\t\t\t\treference: objectRecord(edit.reference),\n\t\t\t\targuments: objectRecord(edit.arguments),\n\t\t\t\tmetadata:\n\t\t\t\t\ttypeof edit.metadata === \"object\" && edit.metadata !== null && !Array.isArray(edit.metadata)\n\t\t\t\t\t\t? (edit.metadata as Record<string, unknown>)\n\t\t\t\t\t\t: undefined,\n\t\t\t\treason: typeof edit.reason === \"string\" ? edit.reason : undefined,\n\t\t\t})),\n\t};\n}\n\nfunction parseProposal(text: string): RefinementProposal {\n\tconst value = extractJsonObject(text);\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new Error(\"Refiner JSON must be an object\");\n\t}\n\treturn normalizeRefinementProposal(value);\n}\n\nfunction validateEdit(edit: RefinementEdit, computedId?: string): string | undefined {\n\tif (![\"create\", \"update\", \"delete\"].includes(edit.action)) {\n\t\treturn `unsupported action ${String(edit.action)}`;\n\t}\n\tif (![\"prompt\", \"memory\", \"skill\", \"subagent\"].includes(edit.kind)) {\n\t\treturn `unsupported kind ${String(edit.kind)}`;\n\t}\n\tif (edit.kind === \"prompt\" && (edit.id === \"base_system_prompt\" || computedId === \"base_system_prompt\")) {\n\t\treturn \"base system prompt is not editable\";\n\t}\n\tif (edit.action !== \"create\" && !edit.id) {\n\t\treturn `${edit.action} requires id`;\n\t}\n\tif (edit.action !== \"delete\" && (!edit.title || !edit.content)) {\n\t\treturn `${edit.action} requires title and content`;\n\t}\n\tif (edit.action !== \"delete\" && edit.kind === \"skill\" && edit.arguments === undefined) {\n\t\treturn `${edit.action} skill requires arguments`;\n\t}\n\tif (edit.action !== \"delete\" && edit.kind === \"skill\") {\n\t\tconst reference = edit.reference;\n\t\tif (!reference) {\n\t\t\treturn `${edit.action} skill requires python reference`;\n\t\t}\n\t\tif (reference.type !== \"python\") {\n\t\t\treturn `${edit.action} skill reference.type must be python`;\n\t\t}\n\t\tconst hasImport =\n\t\t\t(typeof reference.import === \"string\" && reference.import.length > 0) ||\n\t\t\t(typeof reference.python_import === \"string\" && reference.python_import.length > 0);\n\t\tconst hasCallable =\n\t\t\t(typeof reference.callable === \"string\" && reference.callable.length > 0) ||\n\t\t\t(typeof reference.call_pattern === \"string\" && reference.call_pattern.length > 0);\n\t\tif (!hasImport) {\n\t\t\treturn `${edit.action} skill requires python import`;\n\t\t}\n\t\tif (!hasCallable) {\n\t\t\treturn `${edit.action} skill requires callable or call_pattern`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function applyRefinementProposal(\n\tstate: HarnessState,\n\tproposal: RefinementProposal,\n\toptions: { id: string; rollbackOf?: string; scope?: HarnessScope; baselineState?: HarnessState },\n): RefinementResult {\n\tconst application = nativePlannerApplications.get(proposal);\n\tnativePlannerApplications.delete(proposal);\n\tconst appliedEdits: AppliedRefinementEdit[] = [];\n\tconst proposalModifiedKeys = new Set<string>();\n\tfor (const edit of proposal.edits) {\n\t\tconst computedId = edit.id ?? (edit.action === \"create\" ? slug(edit.title ?? edit.kind, edit.kind) : undefined);\n\t\tconst id = computedId ?? \"\";\n\t\tconst validationError = validateEdit(edit, id);\n\t\tif (validationError) {\n\t\t\tappliedEdits.push({ ...edit, id, applied: false, error: validationError });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst records = state.entries[edit.kind];\n\t\tconst before = cloneEntry(records[id]);\n\t\tconst entryKey = `${edit.kind}:${id}`;\n\t\tconst baseline = cloneEntry(options.baselineState?.entries[edit.kind][id]);\n\t\tif (\n\t\t\toptions.baselineState &&\n\t\t\t!proposalModifiedKeys.has(entryKey) &&\n\t\t\tJSON.stringify(before) !== JSON.stringify(baseline)\n\t\t) {\n\t\t\tappliedEdits.push({\n\t\t\t\t...edit,\n\t\t\t\tid,\n\t\t\t\tbefore,\n\t\t\t\tapplied: false,\n\t\t\t\terror: \"entry changed during refinement planning\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (edit.action === \"delete\") {\n\t\t\tif (!before) {\n\t\t\t\tappliedEdits.push({ ...edit, id, applied: false, error: \"entry not found\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdelete records[id];\n\t\t\tproposalModifiedKeys.add(entryKey);\n\t\t\tappliedEdits.push({ ...edit, id, before, applied: true });\n\t\t\tcontinue;\n\t\t}\n\t\tif (edit.action === \"create\" && before) {\n\t\t\tappliedEdits.push({ ...edit, id, before, applied: false, error: \"entry already exists\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (edit.action === \"update\" && !before) {\n\t\t\tappliedEdits.push({ ...edit, id, applied: false, error: \"entry not found\" });\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst createdAt = before?.created_at ?? now();\n\t\tconst version = before ? before.version + 1 : 1;\n\t\tconst after: HarnessEntry = {\n\t\t\tid,\n\t\t\tkind: edit.kind,\n\t\t\ttitle: edit.title ?? before?.title ?? id,\n\t\t\tcontent: edit.content ?? before?.content ?? \"\",\n\t\t\tpath: edit.path ?? before?.path ?? \"general\",\n\t\t\tscope: before?.scope ?? options.scope ?? \"local\",\n\t\t\treference: edit.reference ?? before?.reference ?? {},\n\t\t\targuments: edit.arguments ?? before?.arguments ?? {},\n\t\t\tmetadata: edit.metadata ?? before?.metadata ?? {},\n\t\t\tsource: \"refine\",\n\t\t\tcreated_at: createdAt,\n\t\t\tupdated_at: now(),\n\t\t\tversion,\n\t\t};\n\t\trecords[id] = after;\n\t\tproposalModifiedKeys.add(entryKey);\n\t\tappliedEdits.push({ ...edit, id, before, after: cloneEntry(after), applied: true });\n\t}\n\n\tconst changes = appliedEdits.filter((edit) => edit.applied).map((edit) => `${edit.action} ${edit.kind}:${edit.id}`);\n\tstate.refinements.push({\n\t\tid: options.id,\n\t\ttrigger: proposal.summary,\n\t\tchanges,\n\t\tevidence: proposal.rationale,\n\t\toutcome: proposal.expectedOutcome,\n\t\tcreated_at: now(),\n\t});\n\n\tconst result = {\n\t\tid: options.id,\n\t\tsummary: proposal.summary,\n\t\trationale: proposal.rationale,\n\t\texpectedOutcome: proposal.expectedOutcome,\n\t\tappliedEdits,\n\t\tharnessStatePath: \"\",\n\t\trollbackOf: options.rollbackOf,\n\t\tscope: options.scope,\n\t};\n\tif (\n\t\tapplication &&\n\t\tstate === application.state &&\n\t\toptions.id === application.native.id &&\n\t\toptions.scope === application.scope &&\n\t\toptions.rollbackOf === undefined &&\n\t\toptions.baselineState === application.native.baselineState &&\n\t\tmatchesNativePlannerPlan(application.plan, application.native) &&\n\t\tmatchesPlannerOptions(application.options, application.native.options) &&\n\t\tisDeepStrictEqual(proposal, application.projection)\n\t) {\n\t\t// Baseline/state references are the existing host inputs, not deep-immutability or conflict-correctness claims.\n\t\tnativePlannerResults.set(result, { native: application.native, scope: application.scope, edits: appliedEdits });\n\t}\n\treturn result;\n}\n\nfunction rollbackProposal(target: RefinementResult): RefinementProposal {\n\tconst edits: RefinementEdit[] = [];\n\tfor (const edit of [...target.appliedEdits].reverse()) {\n\t\tif (!edit.applied) continue;\n\t\tif (edit.before) {\n\t\t\tedits.push({\n\t\t\t\taction: edit.after ? \"update\" : \"create\",\n\t\t\t\tkind: edit.kind,\n\t\t\t\tid: edit.id,\n\t\t\t\ttitle: edit.before.title,\n\t\t\t\tcontent: edit.before.content,\n\t\t\t\tpath: edit.before.path,\n\t\t\t\treference: edit.before.reference,\n\t\t\t\targuments: edit.before.arguments,\n\t\t\t\tmetadata: edit.before.metadata,\n\t\t\t\treason: `Rollback ${target.id}`,\n\t\t\t});\n\t\t} else if (edit.after) {\n\t\t\tedits.push({\n\t\t\t\taction: \"delete\",\n\t\t\t\tkind: edit.kind,\n\t\t\t\tid: edit.id,\n\t\t\t\treason: `Rollback ${target.id}`,\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\tsummary: `Rollback refinement ${target.id}`,\n\t\trationale: `Restores continual harness state snapshots from refinement ${target.id}.`,\n\t\texpectedOutcome: \"Faulty refinement edits are reverted.\",\n\t\tedits,\n\t};\n}\n\nexport function getRefinementHistory(entries: readonly CustomEntry[]): RefinementResult[] {\n\treturn entries\n\t\t.filter((entry) => entry.customType === REFINEMENT_CUSTOM_TYPE)\n\t\t.map((entry) => entry.data)\n\t\t.filter((data): data is RefinementResult => {\n\t\t\treturn typeof data === \"object\" && data !== null && \"id\" in data && \"appliedEdits\" in data;\n\t\t});\n}\n\nexport interface RefinementPlan {\n\tproposal: RefinementProposal;\n\tid: string;\n\trollbackOf?: string;\n\trollbackScope?: HarnessScope;\n\t/** Target-scope state captured before planning, used to reject conflicting edits at apply time. */\n\tbaselineState?: HarnessState;\n}\n\ninterface NativePlannerPlan {\n\treadonly proposal: RefinementProposal;\n\treadonly projection: RefinementProposal;\n\treadonly id: string;\n\treadonly options: RefineOptions;\n\treadonly baselineState?: HarnessState;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\ninterface NativePlannerApplication {\n\treadonly plan: RefinementPlan;\n\treadonly native: NativePlannerPlan;\n\treadonly state: HarnessState;\n\treadonly options: RefineOptions;\n\treadonly scope: HarnessScope;\n\treadonly projection: RefinementProposal;\n}\nconst nativePlannerPlans = new WeakMap<RefinementPlan, NativePlannerPlan>();\nconst nativePlannerApplications = new WeakMap<RefinementProposal, NativePlannerApplication>();\nconst nativePlannerResults = new WeakMap<\n\tRefinementResult,\n\t{ native: NativePlannerPlan; scope: HarnessScope; edits: AppliedRefinementEdit[] }\n>();\n\nfunction matchesNativePlannerPlan(plan: RefinementPlan, native: NativePlannerPlan): boolean {\n\treturn (\n\t\tplan.proposal === native.proposal &&\n\t\tplan.id === native.id &&\n\t\tplan.rollbackOf === undefined &&\n\t\tplan.rollbackScope === undefined &&\n\t\tplan.baselineState === native.baselineState &&\n\t\tisDeepStrictEqual(plan.proposal, native.projection)\n\t);\n}\n\nfunction matchesPlannerOptions(options: RefineOptions, captured: RefineOptions): boolean {\n\treturn (\n\t\toptions.instructions === captured.instructions &&\n\t\toptions.global === captured.global &&\n\t\toptions.rollbackId === captured.rollbackId\n\t);\n}\n\n/** Preserve the actual AS baseline composition, not a copied or replacement plan's labels. */\nexport function withRefinementBaseline(plan: RefinementPlan, baselineState: HarnessState): RefinementPlan {\n\tconst composed = { ...plan, baselineState };\n\tconst native = nativePlannerPlans.get(plan);\n\tnativePlannerPlans.delete(plan);\n\tif (native && native.baselineState === undefined && matchesNativePlannerPlan(plan, native)) {\n\t\tnativePlannerPlans.set(composed, { ...native, baselineState });\n\t}\n\treturn composed;\n}\n\nfunction lowerRefinementProposal(proposal: RefinementProposal): RefinementProposal {\n\treturn {\n\t\t...proposal,\n\t\tedits: proposal.edits.map((edit) => {\n\t\t\tconst localPrefix = \"local:\";\n\t\t\tconst globalPrefix = \"global:\";\n\t\t\treturn {\n\t\t\t\t...edit,\n\t\t\t\tid: edit.id?.startsWith(localPrefix)\n\t\t\t\t\t? edit.id.slice(localPrefix.length)\n\t\t\t\t\t: edit.id?.startsWith(globalPrefix)\n\t\t\t\t\t\t? edit.id.slice(globalPrefix.length)\n\t\t\t\t\t\t: edit.id,\n\t\t\t};\n\t\t}),\n\t};\n}\n\n/** The existing application projection; metadata alone also retains its actual state/control identities. */\nexport function prepareRefinementApplication(\n\tplan: RefinementPlan,\n\tstate: HarnessState,\n\toptions: RefineOptions,\n\tscope: HarnessScope,\n): RefinementProposal {\n\tconst proposal = lowerRefinementProposal(plan.proposal);\n\tconst native = nativePlannerPlans.get(plan);\n\tnativePlannerPlans.delete(plan);\n\tif (\n\t\tnative?.baselineState &&\n\t\tmatchesNativePlannerPlan(plan, native) &&\n\t\tmatchesPlannerOptions(options, native.options) &&\n\t\tscope === (native.options.global ? \"global\" : \"local\")\n\t) {\n\t\tnativePlannerApplications.set(proposal, {\n\t\t\tplan,\n\t\t\tnative,\n\t\t\tstate,\n\t\t\toptions,\n\t\t\tscope,\n\t\t\tprojection: lowerRefinementProposal(native.projection),\n\t\t});\n\t}\n\treturn proposal;\n}\n\n/** Only the actual computed result can reach the existing session result append. */\nexport function takeNativePlannerRequestWrite(\n\tresult: RefinementResult,\n): ((manager: object) => Promise<string | undefined> | undefined) | undefined {\n\tconst captured = nativePlannerResults.get(result);\n\tnativePlannerResults.delete(result);\n\tif (\n\t\t!captured ||\n\t\tresult.id !== captured.native.id ||\n\t\tresult.scope !== captured.scope ||\n\t\tresult.rollbackOf !== undefined ||\n\t\tresult.summary !== captured.native.projection.summary ||\n\t\tresult.rationale !== captured.native.projection.rationale ||\n\t\tresult.expectedOutcome !== captured.native.projection.expectedOutcome ||\n\t\tresult.appliedEdits !== captured.edits\n\t)\n\t\treturn undefined;\n\treturn (manager) => captured.native.write(manager, result);\n}\n\n/**\n * Produce a refinement proposal (the LLM pass, or a rollback proposal) without\n * mutating any harness state. Separated from {@link applyRefinementProposal} so\n * callers can re-read the harness file immediately before applying — the LLM call\n * here can take many seconds, during which the kernel or another session may write\n * the shared `harness_state.json`.\n */\n/** Mint a refinement id in the canonical `refine_<timestamp>` format. */\nexport function generateRefinementId(): string {\n\treturn `refine_${new Date()\n\t\t.toISOString()\n\t\t.replace(/[^0-9]/g, \"\")\n\t\t.slice(0, 17)}`;\n}\n\nexport async function planRefinement(\n\tmessages: AgentMessage[],\n\tstate: HarnessState,\n\thistory: RefinementResult[],\n\tmodel: Model<any>,\n\tapiKey: string,\n\toptions: RefineOptions = {},\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\tuseConfiguredThinkingLevel = false,\n): Promise<RefinementPlan> {\n\tconst id = generateRefinementId();\n\tif (options.rollbackId) {\n\t\tconst target = history.find((item) => item.id === options.rollbackId);\n\t\tif (!target) {\n\t\t\tthrow new Error(`Refinement ${options.rollbackId} not found`);\n\t\t}\n\t\tconst fallbackScope: HarnessScope = options.global ? \"global\" : \"local\";\n\t\treturn {\n\t\t\tproposal: rollbackProposal(target),\n\t\t\tid,\n\t\t\trollbackOf: target.id,\n\t\t\trollbackScope: inferRefinementResultScope(target) ?? fallbackScope,\n\t\t};\n\t}\n\n\tconst conversationText = serializeConversation(convertToLlm(messages)).slice(-80_000);\n\tconst scopeInstruction = options.global\n\t\t? \"Requested refinement scope: global. Only propose stable cross-session continual harness edits, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts that should affect future Base Context sessions. Do not persist session-only progress, temporary blockers, or current-run coordination globally.\"\n\t\t: \"Requested refinement scope: local. Prefer local continual harness edits for current task progress, temporary blockers, current-run coordination, and project facts that are not clearly reusable across Base Context sessions. Global entries in the overview are read-only context: do not propose update or delete edits for them; create a local entry instead if an override is needed.\";\n\tconst userPrompt = [\n\t\t`<current_harness_state>\\n${overviewForPrompt(state)}\\n</current_harness_state>`,\n\t\t`<refinement_history>\\n${historyForPrompt(history)}\\n</refinement_history>`,\n\t\t`<conversation>\\n${conversationText}\\n</conversation>`,\n\t\t`<scope_policy>\\n${scopeInstruction}\\n</scope_policy>`,\n\t\toptions.instructions ? `<user_refine_instructions>\\n${options.instructions}\\n</user_refine_instructions>` : \"\",\n\t\t\"Return only JSON edits. If no useful edit is justified, return an empty edits array with a rationale.\",\n\t]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\n\t// Preserve legacy omitted effort for JSON requests. Only an explicit learning-model\n\t// contract opts into a captured effort; omission does not certify provider behavior.\n\tconst plannerOptions = {\n\t\tinstructions: options.instructions,\n\t\tglobal: options.global,\n\t\trollbackId: options.rollbackId,\n\t};\n\tconst completion = completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{\n\t\t\tsystemPrompt: REFINEMENT_SYSTEM_PROMPT,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t},\n\t\t{\n\t\t\tmaxTokens: refinementMaxOutputTokens(model),\n\t\t\tsignal,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\t...(useConfiguredThinkingLevel ? { reasoning: thinkingLevel } : {}),\n\t\t},\n\t\t{\n\t\t\tpurpose: \"refine\",\n\t\t\tpurposeDetail: \"plan\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\tconst response = await completion;\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Refinement failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tif (response.stopReason === \"length\") {\n\t\tthrow new Error(`Refinement failed: ${TRUNCATED_JSON_ERROR}`);\n\t}\n\n\tconst text = response.content\n\t\t.filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n\tconst plan = { proposal: parseProposal(text), id };\n\tconst write =\n\t\trequests instanceof InferenceCoordinator\n\t\t\t? InferenceCoordinator.prototype.takePlannerOutput.call(requests, completion)\n\t\t\t: undefined;\n\tif (write) {\n\t\tnativePlannerPlans.set(plan, {\n\t\t\tproposal: plan.proposal,\n\t\t\tprojection: structuredClone(plan.proposal),\n\t\t\tid,\n\t\t\toptions: plannerOptions,\n\t\t\twrite,\n\t\t});\n\t}\n\treturn plan;\n}\n\nfunction parseAutoRefineReview(text: string): AutoRefineReview {\n\tconst value = extractJsonObject(text);\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new Error(\"Auto-refine review JSON must be an object\");\n\t}\n\tconst record = value as Record<string, unknown>;\n\treturn {\n\t\tshouldRefine: record.shouldRefine === true,\n\t\trationale: typeof record.rationale === \"string\" ? record.rationale : \"No rationale provided.\",\n\t\tinstructions: typeof record.instructions === \"string\" ? record.instructions : undefined,\n\t};\n}\n\nexport async function reviewAutoRefine(\n\tmessages: AgentMessage[],\n\tstate: HarnessState,\n\thistory: RefinementResult[],\n\tmodel: Model<any>,\n\tapiKey: string,\n\tcontext: AutoRefineReviewContext,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\tuseConfiguredThinkingLevel = false,\n): Promise<AutoRefineReview> {\n\tconst conversationText = serializeConversation(convertToLlm(messages)).slice(-40_000);\n\tconst userPrompt = [\n\t\t`<trigger>\n${context.reason}; ${context.turnsSinceLastReview} assistant turns since last auto-refine review\n</trigger>`,\n\t\t`<current_harness_state>\n${overviewForPrompt(state)}\n</current_harness_state>`,\n\t\t`<refinement_history>\n${historyForPrompt(history)}\n</refinement_history>`,\n\t\t`<conversation>\n${conversationText}\n</conversation>`,\n\t\t\"Apply the automatic refinement utility policy. Ask for global refinement only for durable cross-session lessons or explicitly project-qualified facts likely to be reused in future sessions.\",\n\t].join(\"\\n\\n\");\n\t// Match planning: legacy requests omit effort; an explicit contract carries its exact level.\n\tconst response = await completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{\n\t\t\tsystemPrompt: AUTO_REFINE_REVIEW_SYSTEM_PROMPT,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t},\n\t\t{\n\t\t\tmaxTokens: autoRefineReviewMaxOutputTokens(model),\n\t\t\tsignal,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\t...(useConfiguredThinkingLevel ? { reasoning: thinkingLevel } : {}),\n\t\t},\n\t\t{\n\t\t\tpurpose: \"refine\",\n\t\t\tpurposeDetail: \"auto-refine-review\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Auto-refine review failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tif (response.stopReason === \"length\") {\n\t\tthrow new Error(`Auto-refine review failed: ${TRUNCATED_JSON_ERROR}`);\n\t}\n\tconst text = response.content\n\t\t.filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n\tconst review = parseAutoRefineReview(text);\n\tif (review.shouldRefine) {\n\t\treview.instructions = [review.instructions, AUTOMATIC_REFINEMENT_UTILITY_POLICY].filter(Boolean).join(\"\\n\\n\");\n\t}\n\treturn review;\n}\n\nexport async function refineHarness(\n\tmessages: AgentMessage[],\n\tstate: HarnessState,\n\thistory: RefinementResult[],\n\tmodel: Model<any>,\n\tapiKey: string,\n\toptions: RefineOptions = {},\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n): Promise<RefinementResult> {\n\tconst plan = await planRefinement(\n\t\tmessages,\n\t\tstate,\n\t\thistory,\n\t\tmodel,\n\t\tapiKey,\n\t\toptions,\n\t\theaders,\n\t\tsignal,\n\t\tthinkingLevel,\n\t\trequests,\n\t);\n\treturn applyRefinementProposal(state, plan.proposal, {\n\t\tid: plan.id,\n\t\trollbackOf: plan.rollbackOf,\n\t\tscope: plan.rollbackScope ?? (options.global ? \"global\" : \"local\"),\n\t});\n}\n"]}
|
|
@@ -4,11 +4,19 @@ import { type CanonicalViewSelectionSource } from "./canonical-context.js";
|
|
|
4
4
|
import type { ContextEpochEntryRef, SourceSnapshotRef } from "./request-events.js";
|
|
5
5
|
/** Actual adapter-public measurement, not a verdict about the opaque native request. */
|
|
6
6
|
export declare class PublicContextBudgetError extends RequestTokenBudgetError {
|
|
7
|
+
#private;
|
|
7
8
|
readonly originalAssessment: RequestTokenAssessment;
|
|
9
|
+
readonly mandatoryAssessment?: RequestTokenAssessment | undefined;
|
|
10
|
+
readonly taskFrameRebaseAvailable: boolean;
|
|
11
|
+
readonly isSourceCurrent?: (() => boolean) | undefined;
|
|
8
12
|
readonly source: SourceSnapshotRef;
|
|
9
|
-
|
|
13
|
+
remainingSummaryTokens(retained: ReadonlySet<string>, wrapper: string): number | undefined;
|
|
14
|
+
getCompactionKey(): string | undefined;
|
|
15
|
+
constructor(source: SourceSnapshotRef, assessment: RequestTokenAssessment, originalAssessment: RequestTokenAssessment, mandatoryAssessment?: RequestTokenAssessment | undefined, taskFrameRebaseAvailable?: boolean, compactionKey?: string, summaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined, isSourceCurrent?: (() => boolean) | undefined);
|
|
10
16
|
}
|
|
11
17
|
export interface RequestViewCandidate {
|
|
18
|
+
/** Session-local Responses ID namespace; a new owner requires a fresh representation. */
|
|
19
|
+
readonly responseItemIdentity?: string;
|
|
12
20
|
readonly source: SourceSnapshotRef;
|
|
13
21
|
readonly selectedUnitIds: readonly string[];
|
|
14
22
|
readonly request: ProviderRequestRepresentation;
|
|
@@ -23,6 +31,7 @@ export type RequestViewCommit = (candidate: RequestViewCandidate) => Promise<Con
|
|
|
23
31
|
export type RequestViewValidate = (request: ProviderRequestRepresentation, assessment: RequestTokenAssessment | undefined) => void;
|
|
24
32
|
export type RequestViewFixedPrepare = (request: ProviderRequestRepresentation, projection: ProviderRequestProjection, assessment: RequestTokenAssessment | undefined) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;
|
|
25
33
|
export interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {
|
|
34
|
+
readonly responseItemIdentity?: string;
|
|
26
35
|
readonly messages: readonly AgentMessage[];
|
|
27
36
|
/** Provider logical positions mapped to the unchanged canonical messages/units. */
|
|
28
37
|
readonly providerMessageIndices: readonly number[];
|
|
@@ -30,11 +39,12 @@ export interface CapturedRequestViewBoundary extends CanonicalViewSelectionSourc
|
|
|
30
39
|
readonly commit: RequestViewCommit;
|
|
31
40
|
readonly validate?: RequestViewValidate;
|
|
32
41
|
readonly fixedPrepare?: RequestViewFixedPrepare;
|
|
42
|
+
readonly isSourceCurrent?: () => boolean;
|
|
33
43
|
}
|
|
34
|
-
export declare function captureRequestViewBoundary(messages: readonly AgentMessage[], commit: RequestViewCommit, validate?: RequestViewValidate, fixedPrepare?: RequestViewFixedPrepare): CapturedRequestViewBoundary;
|
|
44
|
+
export declare function captureRequestViewBoundary(messages: readonly AgentMessage[], commit: RequestViewCommit, validate?: RequestViewValidate, fixedPrepare?: RequestViewFixedPrepare, isSourceCurrent?: () => boolean): CapturedRequestViewBoundary;
|
|
35
45
|
export declare function matchesRequestView(boundary: CapturedRequestViewBoundary, source: SourceSnapshotRef, context: Context): boolean;
|
|
36
46
|
/** Check the actual final mapping without selecting, converting, or committing another view. */
|
|
37
47
|
export declare function prepareFixedRequestView(boundary: CapturedRequestViewBoundary, request: ProviderRequestRepresentation, projection: ProviderRequestProjection, assessment: RequestTokenAssessment | undefined): Promise<void | ContextEpochEntryRef | undefined>;
|
|
38
48
|
/** Only the actual serializer's established replay contract authorizes historical-literal omission. */
|
|
39
|
-
export declare function selectRequestView(boundary: CapturedRequestViewBoundary, request: ProviderRequestRepresentation, projection: ProviderRequestProjection, budget: RequestTokenBudgetEvaluator | undefined, allowShrink: boolean): Promise<string | undefined>;
|
|
49
|
+
export declare function selectRequestView(boundary: CapturedRequestViewBoundary, request: ProviderRequestRepresentation, projection: ProviderRequestProjection, budget: RequestTokenBudgetEvaluator | undefined, allowShrink: boolean, finalizeMeasurement?: (request: ProviderRequestRepresentation, assessment: RequestTokenAssessment | undefined) => Promise<RequestTokenAssessment | undefined>): Promise<string | undefined>;
|
|
40
50
|
//# sourceMappingURL=request-view-selection.d.ts.map
|