@caupulican/pi-agent-core 0.90.7 → 0.90.12
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/dist/agent-loop.d.ts +1 -1
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +18 -2
- package/dist/agent-loop.js.map +1 -1
- package/dist/agent.d.ts +2 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +4 -0
- package/dist/agent.js.map +1 -1
- package/dist/compaction/compaction.d.ts.map +1 -1
- package/dist/compaction/compaction.js +1 -34
- package/dist/compaction/compaction.js.map +1 -1
- package/dist/compaction/extraction.d.ts +1 -0
- package/dist/compaction/extraction.d.ts.map +1 -1
- package/dist/compaction/extraction.js +1 -1
- package/dist/compaction/extraction.js.map +1 -1
- package/dist/compaction/utils.d.ts +13 -1
- package/dist/compaction/utils.d.ts.map +1 -1
- package/dist/compaction/utils.js +49 -1
- package/dist/compaction/utils.js.map +1 -1
- package/dist/compaction/verification.d.ts.map +1 -1
- package/dist/compaction/verification.js +154 -6
- package/dist/compaction/verification.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/provider-request-planner.d.ts +8 -0
- package/dist/provider-request-planner.d.ts.map +1 -1
- package/dist/provider-request-planner.js +8 -1
- package/dist/provider-request-planner.js.map +1 -1
- package/dist/provider-tool-projection.d.ts.map +1 -1
- package/dist/provider-tool-projection.js +4 -11
- package/dist/provider-tool-projection.js.map +1 -1
- package/dist/tool-failure-memory.d.ts +12 -0
- package/dist/tool-failure-memory.d.ts.map +1 -1
- package/dist/tool-failure-memory.js +102 -3
- package/dist/tool-failure-memory.js.map +1 -1
- package/dist/tool-failure-recovery-gate.d.ts +9 -2
- package/dist/tool-failure-recovery-gate.d.ts.map +1 -1
- package/dist/tool-failure-recovery-gate.js +59 -2
- package/dist/tool-failure-recovery-gate.js.map +1 -1
- package/dist/tool-protocol-residue.d.ts.map +1 -1
- package/dist/tool-protocol-residue.js +58 -18
- package/dist/tool-protocol-residue.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extraction.js","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AA4C3C,MAAM,mBAAmB,GAAG,iEAAiE,CAAC;AAC9F,+FAA+F;AAC/F,qFAAqF;AACrF,oEAAoE;AACpE,MAAM,gBAAgB,GACrB,mHAAmH,CAAC;AAErH,oFAAoF;AACpF,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAC3C,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,mGAAmG;AACnG,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,2GAA2G;AAC3G,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAElD,MAAM,kBAAkB,GAA2D;IAClF,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;CACX,CAAC;AAEF,MAAM,iBAAiB,GAA2D;IACjF,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,UAAU;IACjB,IAAI,EAAE,UAAU;IAChB,IAAI,EAAE,IAAI;CACV,CAAC;AAEF,MAAM,iBAAiB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ACpF,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\nimport { isPlainRecord } from \"./utils.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n\tdiscardedFailure: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\nconst PROHIBITION_MAX_CHARS = 160;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn (parts.length === 1 ? parts[0] : parts.join(\" \")).trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\tlet normalized = \"\";\n\tfor (const match of text.matchAll(/\\S+/g)) {\n\t\tconst separator = normalized.length > 0 ? \" \" : \"\";\n\t\tconst remaining = maxLen - normalized.length - separator.length;\n\t\tif (remaining <= 0) break;\n\t\tnormalized += `${separator}${match[0].slice(0, remaining)}`;\n\t\tif (match[0].length >= remaining) break;\n\t}\n\treturn normalized;\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nfunction hasOneTurnFailureDirective(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tconst details = (message as { details?: unknown }).details;\n\tif (!isPlainRecord(details) || !isPlainRecord(details.piToolFailureDirective)) return false;\n\tconst directive = details.piToolFailureDirective;\n\treturn (\n\t\tdirective.version === 1 &&\n\t\t(directive.state === \"failed\" || directive.state === \"rejected\") &&\n\t\ttypeof directive.failureCode === \"string\" &&\n\t\ttypeof directive.nextAction === \"string\"\n\t);\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, PROHIBITION_MAX_CHARS);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t\tdiscardedFailure: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tconst discardedFailure = failed && hasOneTurnFailureDirective(message);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tfact.discardedFailure = discardedFailure;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && !discardedFailure && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.discardedFailure) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\n/**\n * Carry user-owned checkpoint facts across an iterative compaction without rescanning the discarded\n * session prefix. Facts from the current span win; only the most recent bounded rules survive.\n */\nexport function mergePersistentCompactionUserFacts(\n\tcurrent: CompactionFacts,\n\tprevious: Pick<CompactionFacts, \"activeTaskSource\" | \"prohibitions\">,\n): CompactionFacts {\n\tconst seen = new Set<string>();\n\tconst prohibitions: string[] = [];\n\tfor (let i = previous.prohibitions.length + current.prohibitions.length - 1; i >= 0; i--) {\n\t\tconst rule =\n\t\t\ti >= previous.prohibitions.length\n\t\t\t\t? current.prohibitions[i - previous.prohibitions.length]\n\t\t\t\t: previous.prohibitions[i];\n\t\tconst boundedRule = clampText(rule, PROHIBITION_MAX_CHARS);\n\t\tconst key = boundedRule.toLowerCase();\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tprohibitions.push(boundedRule);\n\t\tif (prohibitions.length === MAX_PROHIBITIONS) break;\n\t}\n\tprohibitions.reverse();\n\n\treturn {\n\t\t...current,\n\t\tactiveTaskSource: current.activeTaskSource || clampText(previous.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS),\n\t\tprohibitions,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear as exact paths in ## Files, path recall threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"extraction.js","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AA4C3C,MAAM,mBAAmB,GAAG,iEAAiE,CAAC;AAC9F,+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IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACxD,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,uDAAuD,CAAC,CAAC;IACpE,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;QACtC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;IAClD,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAC;IACvD,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QACpC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,8DAA8D,CAAC,CAAC;IAC3E,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzB,CAAC;IACD,2FAA2F;IAC3F,wFAAwF;IACxF,+EAA+E;IAC/E,KAAK,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;QAC5B,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,gBAAgB,EAAE,4BAA4B,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,uEAAuE,CAAC,CAAC;IACpF,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\nimport { isPlainRecord } from \"./utils.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n\tdiscardedFailure: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\nconst PROHIBITION_MAX_CHARS = 160;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn (parts.length === 1 ? parts[0] : parts.join(\" \")).trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\tlet normalized = \"\";\n\tfor (const match of text.matchAll(/\\S+/g)) {\n\t\tconst separator = normalized.length > 0 ? \" \" : \"\";\n\t\tconst remaining = maxLen - normalized.length - separator.length;\n\t\tif (remaining <= 0) break;\n\t\tnormalized += `${separator}${match[0].slice(0, remaining)}`;\n\t\tif (match[0].length >= remaining) break;\n\t}\n\treturn normalized;\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nexport function splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nfunction hasOneTurnFailureDirective(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tconst details = (message as { details?: unknown }).details;\n\tif (!isPlainRecord(details) || !isPlainRecord(details.piToolFailureDirective)) return false;\n\tconst directive = details.piToolFailureDirective;\n\treturn (\n\t\tdirective.version === 1 &&\n\t\t(directive.state === \"failed\" || directive.state === \"rejected\") &&\n\t\ttypeof directive.failureCode === \"string\" &&\n\t\ttypeof directive.nextAction === \"string\"\n\t);\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, PROHIBITION_MAX_CHARS);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t\tdiscardedFailure: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tconst discardedFailure = failed && hasOneTurnFailureDirective(message);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tfact.discardedFailure = discardedFailure;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && !discardedFailure && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.discardedFailure) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\n/**\n * Carry user-owned checkpoint facts across an iterative compaction without rescanning the discarded\n * session prefix. Facts from the current span win; only the most recent bounded rules survive.\n */\nexport function mergePersistentCompactionUserFacts(\n\tcurrent: CompactionFacts,\n\tprevious: Pick<CompactionFacts, \"activeTaskSource\" | \"prohibitions\">,\n): CompactionFacts {\n\tconst seen = new Set<string>();\n\tconst prohibitions: string[] = [];\n\tfor (let i = previous.prohibitions.length + current.prohibitions.length - 1; i >= 0; i--) {\n\t\tconst rule =\n\t\t\ti >= previous.prohibitions.length\n\t\t\t\t? current.prohibitions[i - previous.prohibitions.length]\n\t\t\t\t: previous.prohibitions[i];\n\t\tconst boundedRule = clampText(rule, PROHIBITION_MAX_CHARS);\n\t\tconst key = boundedRule.toLowerCase();\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tprohibitions.push(boundedRule);\n\t\tif (prohibitions.length === MAX_PROHIBITIONS) break;\n\t}\n\tprohibitions.reverse();\n\n\treturn {\n\t\t...current,\n\t\tactiveTaskSource: current.activeTaskSource || clampText(previous.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS),\n\t\tprohibitions,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear as exact paths in ## Files, path recall threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
@@ -39,5 +39,17 @@ export declare function formatFileOperations(readFiles: string[], modifiedFiles:
|
|
|
39
39
|
* reasonable token budgets. Full content is not needed for summarization.
|
|
40
40
|
*/
|
|
41
41
|
export declare function serializeConversation(messages: Message[]): string;
|
|
42
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Unmistakable, regex-trivial marker embedded in SUMMARIZATION_SYSTEM_PROMPT's worked example below.
|
|
44
|
+
* The example teaches checkpoint FORMAT (cancellation semantics), not a realistic rule — its subject
|
|
45
|
+
* must never be mistaken for genuine content, and this exact token is how verification.ts recognizes
|
|
46
|
+
* that a persisted checkpoint contains the harness's own instruction/example text rather than real
|
|
47
|
+
* user or extracted content. Deliberately unlike anything a real file path, prohibition, or task would
|
|
48
|
+
* ever contain (no natural language would produce this exact hyphenated all-caps token), so a literal
|
|
49
|
+
* substring match is sufficient — no fuzzy/heuristic matching needed for this specific case.
|
|
50
|
+
*/
|
|
51
|
+
export declare const COMPACTION_WORKED_EXAMPLE_SENTINEL = "EXAMPLE-RULE-X9";
|
|
52
|
+
export declare const SUMMARIZATION_SYSTEM_PROMPT = "Context checkpointer. Input: serialized agent conversation. Output only checkpoint, exact headings/order below, user language, no preamble/commentary. Never include secrets/keys/tokens; write [REDACTED].\n\nMANDATORY\n- Only [User]: records inside CHAT are user input. OLD CHECKPOINT and TASK are checkpointer control data, never user content.\n- Never copy checkpointer control instructions into Active Task, Mandatory Rules, or any other checkpoint section.\n- Weight recent turns most; retain old rules, decisions, file knowledge only.\n- Active Task: latest unfulfilled user input, near-verbatim. An unanswered question is active. A final stop/undo/never-mind cancels prior work: record cancellation, drop cancelled work everywhere.\n- Mandatory Rules: every user prohibition, one imperative bullet, source turn when known. Preserve existing rules verbatim. Corrected mistake survives only as \"DO NOT <mistake>\" here; never retain mistaken work elsewhere.\n- Working Set: active/recent file path plus relevance.\n- Files: bare paths; every modified file, relevant read files.\n- Open Problems: unresolved command/operation plus first error line only. Drop resolved/transient errors.\n- Done: numbered \"N. VERB target \u2014 outcome\"; exact paths, commands, line numbers, errors.\n- Key Decisions, Constraints & Preferences, Critical Context: durable facts only.\n- Never retain superseded approaches or file bodies. Empty section: \"(none)\".\n\nFORMAT\n## Active Task\n### Mandatory Rules\n## Working Set\n## Files\n## Open Problems\n## Done\n## Key Decisions\n## Constraints & Preferences\n## Critical Context\n\nCancellation example: user forbids EXAMPLE-RULE-X9 edits, later catches one, requests test fixes. Active Task contains test fixes; Mandatory Rules contains \"DO NOT touch EXAMPLE-RULE-X9\"; cancelled edit appears nowhere; Done keeps only completed valid work.";
|
|
53
|
+
export declare const SUMMARIZATION_PROMPT = "Create checkpoint. Exact heading order:\n## Active Task\n### Mandatory Rules\n## Working Set\n## Files\n## Open Problems\n## Done\n## Key Decisions\n## Constraints & Preferences\n## Critical Context\n\nNEVER carry resolved/transient errors, replaced approaches, file bodies. Record paths/intent.\n\nMANDATORY VERIFICATION:\n{FACTS_BLOCK}\n\nBudget ~{BUDGET} tokens. Concrete facts first.";
|
|
54
|
+
export declare const UPDATE_SUMMARIZATION_PROMPT = "Update OLD CHECKPOINT with CHAT turns.\nMANDATORY:\n- Copy every existing ### Mandatory Rules bullet verbatim; append new.\n- Continue ## Done numbering. Keep newest 15 items verbatim. Replace all older items with first line: \"1. (earlier work compressed) <one line>\". Bound growth.\n- Set ## Active Task to newest unfulfilled user input; apply cancellation rule.\n- Keep ## Files current: add new, retain relevant, drop obsolete.\n- Drop resolved ## Open Problems.\n- Drop ## Working Set files untouched since OLD CHECKPOINT unless active task names them.\n- Keep exact paths/commands/errors.\n- NEVER carry resolved/transient errors, replaced approaches, file bodies. Record paths/intent.\n\nKeep required heading order.\nMANDATORY VERIFICATION:\n{FACTS_BLOCK}\n\nBudget ~{BUDGET} tokens.";
|
|
43
55
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAMhD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAI9E;AAED,wBAAgB,aAAa,IAAI,cAAc,CAM9C;AAED,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,cAAc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,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,GACvD,IAAI,CAWN;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CA2B9F;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAK1G;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAUzF;AAuBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAuDjE;AAMD;;;;;;;;GAQG;AACH,eAAO,MAAM,kCAAkC,oBAAoB,CAAC;AAEpE,eAAO,MAAM,2BAA2B,+1DA0BsQ,CAAC;AAO/S,eAAO,MAAM,oBAAoB,wYAgBc,CAAC;AAEhD,eAAO,MAAM,2BAA2B,6xBAef,CAAC"}
|
package/dist/compaction/utils.js
CHANGED
|
@@ -171,6 +171,16 @@ export function serializeConversation(messages) {
|
|
|
171
171
|
// ============================================================================
|
|
172
172
|
// Summarization System Prompt
|
|
173
173
|
// ============================================================================
|
|
174
|
+
/**
|
|
175
|
+
* Unmistakable, regex-trivial marker embedded in SUMMARIZATION_SYSTEM_PROMPT's worked example below.
|
|
176
|
+
* The example teaches checkpoint FORMAT (cancellation semantics), not a realistic rule — its subject
|
|
177
|
+
* must never be mistaken for genuine content, and this exact token is how verification.ts recognizes
|
|
178
|
+
* that a persisted checkpoint contains the harness's own instruction/example text rather than real
|
|
179
|
+
* user or extracted content. Deliberately unlike anything a real file path, prohibition, or task would
|
|
180
|
+
* ever contain (no natural language would produce this exact hyphenated all-caps token), so a literal
|
|
181
|
+
* substring match is sufficient — no fuzzy/heuristic matching needed for this specific case.
|
|
182
|
+
*/
|
|
183
|
+
export const COMPACTION_WORKED_EXAMPLE_SENTINEL = "EXAMPLE-RULE-X9";
|
|
174
184
|
export const SUMMARIZATION_SYSTEM_PROMPT = `Context checkpointer. Input: serialized agent conversation. Output only checkpoint, exact headings/order below, user language, no preamble/commentary. Never include secrets/keys/tokens; write [REDACTED].
|
|
175
185
|
|
|
176
186
|
MANDATORY
|
|
@@ -197,5 +207,43 @@ FORMAT
|
|
|
197
207
|
## Constraints & Preferences
|
|
198
208
|
## Critical Context
|
|
199
209
|
|
|
200
|
-
Cancellation example: user forbids
|
|
210
|
+
Cancellation example: user forbids ${COMPACTION_WORKED_EXAMPLE_SENTINEL} edits, later catches one, requests test fixes. Active Task contains test fixes; Mandatory Rules contains "DO NOT touch ${COMPACTION_WORKED_EXAMPLE_SENTINEL}"; cancelled edit appears nowhere; Done keeps only completed valid work.`;
|
|
211
|
+
// Task-level prompts (as opposed to the system prompt above). Kept here, not in compaction.ts, so
|
|
212
|
+
// verification.ts can single-source the literal text the harness injects — it needs the exact
|
|
213
|
+
// sentences to recognize when a model echoes them back into a checkpoint section instead of
|
|
214
|
+
// following the system prompt's "never copy checkpointer control instructions" rule. compaction.ts
|
|
215
|
+
// imports these rather than defining its own copies, so there is exactly one source of truth.
|
|
216
|
+
export const SUMMARIZATION_PROMPT = `Create checkpoint. Exact heading order:
|
|
217
|
+
## Active Task
|
|
218
|
+
### Mandatory Rules
|
|
219
|
+
## Working Set
|
|
220
|
+
## Files
|
|
221
|
+
## Open Problems
|
|
222
|
+
## Done
|
|
223
|
+
## Key Decisions
|
|
224
|
+
## Constraints & Preferences
|
|
225
|
+
## Critical Context
|
|
226
|
+
|
|
227
|
+
NEVER carry resolved/transient errors, replaced approaches, file bodies. Record paths/intent.
|
|
228
|
+
|
|
229
|
+
MANDATORY VERIFICATION:
|
|
230
|
+
{FACTS_BLOCK}
|
|
231
|
+
|
|
232
|
+
Budget ~{BUDGET} tokens. Concrete facts first.`;
|
|
233
|
+
export const UPDATE_SUMMARIZATION_PROMPT = `Update OLD CHECKPOINT with CHAT turns.
|
|
234
|
+
MANDATORY:
|
|
235
|
+
- Copy every existing ### Mandatory Rules bullet verbatim; append new.
|
|
236
|
+
- Continue ## Done numbering. Keep newest 15 items verbatim. Replace all older items with first line: "1. (earlier work compressed) <one line>". Bound growth.
|
|
237
|
+
- Set ## Active Task to newest unfulfilled user input; apply cancellation rule.
|
|
238
|
+
- Keep ## Files current: add new, retain relevant, drop obsolete.
|
|
239
|
+
- Drop resolved ## Open Problems.
|
|
240
|
+
- Drop ## Working Set files untouched since OLD CHECKPOINT unless active task names them.
|
|
241
|
+
- Keep exact paths/commands/errors.
|
|
242
|
+
- NEVER carry resolved/transient errors, replaced approaches, file bodies. Record paths/intent.
|
|
243
|
+
|
|
244
|
+
Keep required heading order.
|
|
245
|
+
MANDATORY VERIFICATION:
|
|
246
|
+
{FACTS_BLOCK}
|
|
247
|
+
|
|
248
|
+
Budget ~{BUDGET} tokens.`;
|
|
201
249
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAeH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC3C,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAC7D,CAAC;AAED,MAAM,UAAU,aAAa;IAC5B,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AAC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{ Message } from \"@caupulican/pi-ai\";\nimport type { AgentMessage } from \"../types.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\nexport function addPersistedFileOperations(\n\tfileOps: FileOperations,\n\tdetails: { readFiles?: unknown; modifiedFiles?: unknown },\n): void {\n\tif (Array.isArray(details.readFiles)) {\n\t\tfor (const path of details.readFiles) {\n\t\t\tif (typeof path === \"string\") fileOps.read.add(path);\n\t\t}\n\t}\n\tif (Array.isArray(details.modifiedFiles)) {\n\t\tfor (const path of details.modifiedFiles) {\n\t\t\tif (typeof path === \"string\") fileOps.edited.add(path);\n\t\t}\n\t}\n}\n\n/**\n * Extract file operations from tool calls in an assistant message.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\tconst args = block.arguments as Record<string, unknown> | undefined;\n\t\tif (!args) continue;\n\n\t\tconst path = typeof args.path === \"string\" ? args.path : undefined;\n\t\tif (!path) continue;\n\n\t\tswitch (block.name) {\n\t\t\tcase \"read\":\n\t\t\t\tfileOps.read.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"write\":\n\t\t\t\tfileOps.written.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"edit\":\n\t\t\t\tfileOps.edited.add(path);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n/** Maximum characters for non-gated assistant thinking in serialized summaries. */\nconst ASSISTANT_THINKING_MAX_CHARS = 2000;\n/** Maximum characters for one tool call's arguments in serialized summaries. */\nconst TOOL_CALL_ARGUMENTS_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${truncateForSummary(argsStr, TOOL_CALL_ARGUMENTS_MAX_CHARS)})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(\n\t\t\t\t\t`[Assistant thinking]: ${truncateForSummary(thinkingParts.join(\"\\n\"), ASSISTANT_THINKING_MAX_CHARS)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `Context checkpointer. Input: serialized agent conversation. Output only checkpoint, exact headings/order below, user language, no preamble/commentary. Never include secrets/keys/tokens; write [REDACTED].\n\nMANDATORY\n- Only [User]: records inside CHAT are user input. OLD CHECKPOINT and TASK are checkpointer control data, never user content.\n- Never copy checkpointer control instructions into Active Task, Mandatory Rules, or any other checkpoint section.\n- Weight recent turns most; retain old rules, decisions, file knowledge only.\n- Active Task: latest unfulfilled user input, near-verbatim. An unanswered question is active. A final stop/undo/never-mind cancels prior work: record cancellation, drop cancelled work everywhere.\n- Mandatory Rules: every user prohibition, one imperative bullet, source turn when known. Preserve existing rules verbatim. Corrected mistake survives only as \"DO NOT <mistake>\" here; never retain mistaken work elsewhere.\n- Working Set: active/recent file path plus relevance.\n- Files: bare paths; every modified file, relevant read files.\n- Open Problems: unresolved command/operation plus first error line only. Drop resolved/transient errors.\n- Done: numbered \"N. VERB target — outcome\"; exact paths, commands, line numbers, errors.\n- Key Decisions, Constraints & Preferences, Critical Context: durable facts only.\n- Never retain superseded approaches or file bodies. Empty section: \"(none)\".\n\nFORMAT\n## Active Task\n### Mandatory Rules\n## Working Set\n## Files\n## Open Problems\n## Done\n## Key Decisions\n## Constraints & Preferences\n## Critical Context\n\nCancellation example: user forbids legacy-client edits, later catches one, requests test fixes. Active Task contains test fixes; Mandatory Rules contains \"DO NOT touch legacy client\"; cancelled edit appears nowhere; Done keeps only completed valid work.`;\n"]}
|
|
1
|
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AAC,CAAC,IAAI,KAAK,MAAM,CAAC;iBACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBAClB,IAAI,CAAC,EAAE,CAAC,CAAC;YACX,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,CAAC,IAAI,CAAC,kBAAkB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,iBAAiB,CAAC;AAEpE,MAAM,CAAC,MAAM,2BAA2B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;qCA0BN,kCAAkC,2HAA2H,kCAAkC,0EAA0E,CAAC;AAE/S,kGAAkG;AAClG,8FAA8F;AAC9F,4FAA4F;AAC5F,mGAAmG;AACnG,8FAA8F;AAC9F,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;+CAgBW,CAAC;AAEhD,MAAM,CAAC,MAAM,2BAA2B,GAAG;;;;;;;;;;;;;;;yBAelB,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { Message } from \"@caupulican/pi-ai\";\nimport type { AgentMessage } from \"../types.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\nexport function addPersistedFileOperations(\n\tfileOps: FileOperations,\n\tdetails: { readFiles?: unknown; modifiedFiles?: unknown },\n): void {\n\tif (Array.isArray(details.readFiles)) {\n\t\tfor (const path of details.readFiles) {\n\t\t\tif (typeof path === \"string\") fileOps.read.add(path);\n\t\t}\n\t}\n\tif (Array.isArray(details.modifiedFiles)) {\n\t\tfor (const path of details.modifiedFiles) {\n\t\t\tif (typeof path === \"string\") fileOps.edited.add(path);\n\t\t}\n\t}\n}\n\n/**\n * Extract file operations from tool calls in an assistant message.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\tconst args = block.arguments as Record<string, unknown> | undefined;\n\t\tif (!args) continue;\n\n\t\tconst path = typeof args.path === \"string\" ? args.path : undefined;\n\t\tif (!path) continue;\n\n\t\tswitch (block.name) {\n\t\t\tcase \"read\":\n\t\t\t\tfileOps.read.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"write\":\n\t\t\t\tfileOps.written.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"edit\":\n\t\t\t\tfileOps.edited.add(path);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n/** Maximum characters for non-gated assistant thinking in serialized summaries. */\nconst ASSISTANT_THINKING_MAX_CHARS = 2000;\n/** Maximum characters for one tool call's arguments in serialized summaries. */\nconst TOOL_CALL_ARGUMENTS_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${truncateForSummary(argsStr, TOOL_CALL_ARGUMENTS_MAX_CHARS)})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(\n\t\t\t\t\t`[Assistant thinking]: ${truncateForSummary(thinkingParts.join(\"\\n\"), ASSISTANT_THINKING_MAX_CHARS)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\n/**\n * Unmistakable, regex-trivial marker embedded in SUMMARIZATION_SYSTEM_PROMPT's worked example below.\n * The example teaches checkpoint FORMAT (cancellation semantics), not a realistic rule — its subject\n * must never be mistaken for genuine content, and this exact token is how verification.ts recognizes\n * that a persisted checkpoint contains the harness's own instruction/example text rather than real\n * user or extracted content. Deliberately unlike anything a real file path, prohibition, or task would\n * ever contain (no natural language would produce this exact hyphenated all-caps token), so a literal\n * substring match is sufficient — no fuzzy/heuristic matching needed for this specific case.\n */\nexport const COMPACTION_WORKED_EXAMPLE_SENTINEL = \"EXAMPLE-RULE-X9\";\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `Context checkpointer. Input: serialized agent conversation. Output only checkpoint, exact headings/order below, user language, no preamble/commentary. Never include secrets/keys/tokens; write [REDACTED].\n\nMANDATORY\n- Only [User]: records inside CHAT are user input. OLD CHECKPOINT and TASK are checkpointer control data, never user content.\n- Never copy checkpointer control instructions into Active Task, Mandatory Rules, or any other checkpoint section.\n- Weight recent turns most; retain old rules, decisions, file knowledge only.\n- Active Task: latest unfulfilled user input, near-verbatim. An unanswered question is active. A final stop/undo/never-mind cancels prior work: record cancellation, drop cancelled work everywhere.\n- Mandatory Rules: every user prohibition, one imperative bullet, source turn when known. Preserve existing rules verbatim. Corrected mistake survives only as \"DO NOT <mistake>\" here; never retain mistaken work elsewhere.\n- Working Set: active/recent file path plus relevance.\n- Files: bare paths; every modified file, relevant read files.\n- Open Problems: unresolved command/operation plus first error line only. Drop resolved/transient errors.\n- Done: numbered \"N. VERB target — outcome\"; exact paths, commands, line numbers, errors.\n- Key Decisions, Constraints & Preferences, Critical Context: durable facts only.\n- Never retain superseded approaches or file bodies. Empty section: \"(none)\".\n\nFORMAT\n## Active Task\n### Mandatory Rules\n## Working Set\n## Files\n## Open Problems\n## Done\n## Key Decisions\n## Constraints & Preferences\n## Critical Context\n\nCancellation example: user forbids ${COMPACTION_WORKED_EXAMPLE_SENTINEL} edits, later catches one, requests test fixes. Active Task contains test fixes; Mandatory Rules contains \"DO NOT touch ${COMPACTION_WORKED_EXAMPLE_SENTINEL}\"; cancelled edit appears nowhere; Done keeps only completed valid work.`;\n\n// Task-level prompts (as opposed to the system prompt above). Kept here, not in compaction.ts, so\n// verification.ts can single-source the literal text the harness injects — it needs the exact\n// sentences to recognize when a model echoes them back into a checkpoint section instead of\n// following the system prompt's \"never copy checkpointer control instructions\" rule. compaction.ts\n// imports these rather than defining its own copies, so there is exactly one source of truth.\nexport const SUMMARIZATION_PROMPT = `Create checkpoint. Exact heading order:\n## Active Task\n### Mandatory Rules\n## Working Set\n## Files\n## Open Problems\n## Done\n## Key Decisions\n## Constraints & Preferences\n## Critical Context\n\nNEVER carry resolved/transient errors, replaced approaches, file bodies. Record paths/intent.\n\nMANDATORY VERIFICATION:\n{FACTS_BLOCK}\n\nBudget ~{BUDGET} tokens. Concrete facts first.`;\n\nexport const UPDATE_SUMMARIZATION_PROMPT = `Update OLD CHECKPOINT with CHAT turns.\nMANDATORY:\n- Copy every existing ### Mandatory Rules bullet verbatim; append new.\n- Continue ## Done numbering. Keep newest 15 items verbatim. Replace all older items with first line: \"1. (earlier work compressed) <one line>\". Bound growth.\n- Set ## Active Task to newest unfulfilled user input; apply cancellation rule.\n- Keep ## Files current: add new, retain relevant, drop obsolete.\n- Drop resolved ## Open Problems.\n- Drop ## Working Set files untouched since OLD CHECKPOINT unless active task names them.\n- Keep exact paths/commands/errors.\n- NEVER carry resolved/transient errors, replaced approaches, file bodies. Record paths/intent.\n\nKeep required heading order.\nMANDATORY VERIFICATION:\n{FACTS_BLOCK}\n\nBudget ~{BUDGET} tokens.`;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verification.d.ts","sourceRoot":"","sources":["../../src/compaction/verification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,eAAe,
|
|
1
|
+
{"version":3,"file":"verification.d.ts","sourceRoot":"","sources":["../../src/compaction/verification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,eAAe,EAAsB,MAAM,iBA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E,MAAM,GAAG,MAAM,CAI7F;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,kBAAkB,EAAE,GAAG,MAAM,CAKxF;AAgQD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAQlD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,CAWzE;AAED,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,CAY9D"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { ACTIVE_TASK_SOURCE_MAX_CHARS } from "./extraction.js";
|
|
1
|
+
import { ACTIVE_TASK_SOURCE_MAX_CHARS, splitSentenceLines } from "./extraction.js";
|
|
2
|
+
import { COMPACTION_WORKED_EXAMPLE_SENTINEL, SUMMARIZATION_PROMPT, SUMMARIZATION_SYSTEM_PROMPT, UPDATE_SUMMARIZATION_PROMPT, } from "./utils.js";
|
|
2
3
|
/** A failed verification attempt with its structured reports preserved for the retry ladder. */
|
|
3
4
|
export class CompactionVerificationError extends Error {
|
|
4
5
|
constructor(reports) {
|
|
@@ -47,6 +48,19 @@ export function verifySummary(summary, facts) {
|
|
|
47
48
|
comparator: "minimum",
|
|
48
49
|
});
|
|
49
50
|
}
|
|
51
|
+
// Mandatory Rules is the one section the deterministic fill unconditionally scrubs of the
|
|
52
|
+
// sentinel (reconcileMandatoryRules), so its presence there is self-healing, not a failure. Any
|
|
53
|
+
// OTHER section is contamination the fill never touches and cannot safely repair — fail loudly
|
|
54
|
+
// rather than silently persist harness instruction/example text as if it were real content.
|
|
55
|
+
if (textContainsCompactionSentinel(removeSection(summary, SECTION_MANDATORY_RULES))) {
|
|
56
|
+
failures.push({
|
|
57
|
+
check: "compaction-control-sentinel",
|
|
58
|
+
detail: `Checkpoint must never carry the harness's own worked-example sentinel "${COMPACTION_WORKED_EXAMPLE_SENTINEL}" outside ### Mandatory Rules — the model echoed instruction/example text into a persisted section`,
|
|
59
|
+
score: 0,
|
|
60
|
+
threshold: 1,
|
|
61
|
+
comparator: "minimum",
|
|
62
|
+
});
|
|
63
|
+
}
|
|
50
64
|
if (factsAreEmpty(facts)) {
|
|
51
65
|
return { ok: failures.length === 0, failures };
|
|
52
66
|
}
|
|
@@ -226,9 +240,9 @@ export function deterministicallyFillSummaryGaps(summary, facts) {
|
|
|
226
240
|
}
|
|
227
241
|
removeCancelledWorkLines(sectionByName, facts);
|
|
228
242
|
const activeTask = sectionByName.get(SECTION_ACTIVE_TASK);
|
|
229
|
-
activeTask.lines = facts.activeTaskSource ?
|
|
243
|
+
activeTask.lines = facts.activeTaskSource ? buildActiveTaskLines(facts.activeTaskSource) : ["(none)"];
|
|
230
244
|
const mandatoryRules = sectionByName.get(SECTION_MANDATORY_RULES);
|
|
231
|
-
mandatoryRules.lines =
|
|
245
|
+
mandatoryRules.lines = reconcileMandatoryRules(mandatoryRules.lines, facts.prohibitions);
|
|
232
246
|
const workingSet = sectionByName.get(SECTION_WORKING_SET);
|
|
233
247
|
for (const file of facts.workingSet) {
|
|
234
248
|
if (!sectionContainsExactPath(workingSet.lines.join("\n"), file.path)) {
|
|
@@ -359,6 +373,127 @@ function appendContentLine(lines, line) {
|
|
|
359
373
|
lines.length = 0;
|
|
360
374
|
lines.push(...normalized);
|
|
361
375
|
}
|
|
376
|
+
/**
|
|
377
|
+
* The exact instruction sentences the harness itself injects into the summarization prompts —
|
|
378
|
+
* SUMMARIZATION_SYSTEM_PROMPT, SUMMARIZATION_PROMPT, and UPDATE_SUMMARIZATION_PROMPT. All three
|
|
379
|
+
* sources single-sourced from utils.ts so this never drifts from what was actually sent; not a
|
|
380
|
+
* heuristic guess at what "looks like" an instruction. Sentences below a minimum length are
|
|
381
|
+
* dropped — a lone heading fragment like "## Files" would otherwise sit in the set as a
|
|
382
|
+
* near-universal 1-2 token match.
|
|
383
|
+
*
|
|
384
|
+
* SUMMARIZATION_SYSTEM_PROMPT was previously excluded here: its worked example used to read
|
|
385
|
+
* `Mandatory Rules contains "DO NOT touch legacy client"`, generic enough to false-positive-match a
|
|
386
|
+
* real extractor-owned prohibition about a "legacy client". The example's subject is now the
|
|
387
|
+
* synthetic COMPACTION_WORKED_EXAMPLE_SENTINEL token instead (see utils.ts), so that specific
|
|
388
|
+
* collision is gone; the isCompactionControlEcho regression tests below (including the canonical "do
|
|
389
|
+
* not touch the legacy client" fixture used throughout this file) are the evidence that re-including
|
|
390
|
+
* it is safe.
|
|
391
|
+
*/
|
|
392
|
+
const COMPACTION_CONTROL_ECHO_MIN_SENTENCE_TOKENS = 4;
|
|
393
|
+
/** A line must share at least this many tokens with a single control sentence, not spread thinly
|
|
394
|
+
* across several, before it is treated as an echo — mirrors lineShouldBeDroppedAsCancelledWork's
|
|
395
|
+
* "overlap >= N and overlap ratio >= threshold" dual guard below. */
|
|
396
|
+
const COMPACTION_CONTROL_ECHO_MIN_OVERLAP = 3;
|
|
397
|
+
/** Stricter than MANDATORY_RULES_RECALL_THRESHOLD on purpose: dropping model content is destructive,
|
|
398
|
+
* so the bar for "this line basically IS the harness's own sentence" is set high. */
|
|
399
|
+
const COMPACTION_CONTROL_ECHO_THRESHOLD = 0.8;
|
|
400
|
+
const COMPACTION_CONTROL_SENTENCE_TOKEN_SETS = [
|
|
401
|
+
SUMMARIZATION_SYSTEM_PROMPT,
|
|
402
|
+
SUMMARIZATION_PROMPT,
|
|
403
|
+
UPDATE_SUMMARIZATION_PROMPT,
|
|
404
|
+
]
|
|
405
|
+
.flatMap((prompt) => splitSentenceLines(prompt))
|
|
406
|
+
.map((sentence) => tokenSet(sentence))
|
|
407
|
+
.filter((tokens) => tokens.size >= COMPACTION_CONTROL_ECHO_MIN_SENTENCE_TOKENS);
|
|
408
|
+
/** True when `line` is substantially reconstructed from a single harness-injected instruction
|
|
409
|
+
* sentence — i.e. the model echoed the prompt back instead of writing a checkpoint fact. Direction
|
|
410
|
+
* matters: containment is measured with the LINE as the needle and one sentence as the haystack, so
|
|
411
|
+
* a short prompt fragment can never "explain away" a longer, mostly-unrelated user rule that merely
|
|
412
|
+
* shares a couple of words with it. This is the fuzzy backstop for paraphrased echoes; a line
|
|
413
|
+
* carrying COMPACTION_WORKED_EXAMPLE_SENTINEL is a separate, unconditional (non-heuristic) drop —
|
|
414
|
+
* see textContainsCompactionSentinel below. */
|
|
415
|
+
function isCompactionControlEcho(line) {
|
|
416
|
+
const lineTokens = tokenSet(line);
|
|
417
|
+
if (lineTokens.size === 0)
|
|
418
|
+
return false;
|
|
419
|
+
for (const sentenceTokens of COMPACTION_CONTROL_SENTENCE_TOKEN_SETS) {
|
|
420
|
+
let hits = 0;
|
|
421
|
+
for (const token of lineTokens) {
|
|
422
|
+
if (sentenceTokens.has(token))
|
|
423
|
+
hits++;
|
|
424
|
+
}
|
|
425
|
+
if (hits >= COMPACTION_CONTROL_ECHO_MIN_OVERLAP && hits / lineTokens.size >= COMPACTION_CONTROL_ECHO_THRESHOLD) {
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return false;
|
|
430
|
+
}
|
|
431
|
+
/** True when `text` carries the harness's worked-example sentinel — deterministic, not
|
|
432
|
+
* model-dependent: no containment threshold, no token overlap, just a literal substring check
|
|
433
|
+
* against a token no real content could plausibly contain. */
|
|
434
|
+
function textContainsCompactionSentinel(text) {
|
|
435
|
+
return text.includes(COMPACTION_WORKED_EXAMPLE_SENTINEL);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Force each extractor-owned prohibition to appear verbatim (anti-paraphrase), while preserving every
|
|
439
|
+
* model-carried line the extractor does not own. A rule replaces the first existing line that already
|
|
440
|
+
* paraphrases it (by the same recall threshold the gate uses); otherwise it is appended. The harness owns
|
|
441
|
+
* only the facts it extracted — it must never delete model content it never extracted, and it must never
|
|
442
|
+
* stamp "(none)" over a non-empty section (2026-08 incident: unconditional overwrite silently dropped
|
|
443
|
+
* user rules that don't match PROHIBITION_PATTERN, e.g. positive instructions like "always run tests from
|
|
444
|
+
* packages/coding-agent", permanently across every later checkpoint). Two things it MUST still drop:
|
|
445
|
+
* a line that echoes the harness's own injected instructions (isCompactionControlEcho), and a line
|
|
446
|
+
* carrying the worked-example sentinel by definition (textContainsCompactionSentinel) — the latter is
|
|
447
|
+
* exact and unconditional, since that token can only ever have come from the harness's own prompt.
|
|
448
|
+
*/
|
|
449
|
+
function reconcileMandatoryRules(lines, prohibitions) {
|
|
450
|
+
const result = lines.filter((line) => line.trim() !== "(none)" &&
|
|
451
|
+
line.trim() !== "" &&
|
|
452
|
+
!isCompactionControlEcho(line) &&
|
|
453
|
+
!textContainsCompactionSentinel(line));
|
|
454
|
+
for (const rule of prohibitions) {
|
|
455
|
+
const canonical = `- ${rule}`;
|
|
456
|
+
const ruleTokens = tokenSet(rule);
|
|
457
|
+
let bestIndex = -1;
|
|
458
|
+
let bestScore = 0;
|
|
459
|
+
for (let i = 0; i < result.length; i++) {
|
|
460
|
+
const score = containment(ruleTokens, tokenSet(result[i]));
|
|
461
|
+
if (score > bestScore) {
|
|
462
|
+
bestScore = score;
|
|
463
|
+
bestIndex = i;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (bestIndex >= 0 && bestScore >= MANDATORY_RULES_RECALL_THRESHOLD) {
|
|
467
|
+
result[bestIndex] = canonical;
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
result.push(canonical);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return result.length > 0 ? result : ["(none)"];
|
|
474
|
+
}
|
|
475
|
+
/** Markdown-style escape: a line starting with `##`/`###` gains one leading backslash so the harness's
|
|
476
|
+
* own heading parser (`^(?:##|###)\s`) can never re-split the Active Task section on it. Lines that
|
|
477
|
+
* already start with a backslash before the heading marker gain one more, so decode (below) always
|
|
478
|
+
* strips exactly one and the transform is a bijection — no other line is touched. */
|
|
479
|
+
const ACTIVE_TASK_HEADING_LIKE = /^\\*(?:##|###)\s/;
|
|
480
|
+
const ACTIVE_TASK_ESCAPED_HEADING = /^\\(?:\\*(?:##|###)\s)/;
|
|
481
|
+
function escapeActiveTaskHeadingLine(line) {
|
|
482
|
+
return ACTIVE_TASK_HEADING_LIKE.test(line) ? `\\${line}` : line;
|
|
483
|
+
}
|
|
484
|
+
function unescapeActiveTaskHeadingLine(line) {
|
|
485
|
+
return ACTIVE_TASK_ESCAPED_HEADING.test(line) ? line.slice(1) : line;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Render the Active Task body so it survives being re-parsed by extractSections/parseSummarySections:
|
|
489
|
+
* a user request that itself contains a `##`/`###` line (e.g. a pasted "## Steps" list) must not be
|
|
490
|
+
* mistaken for a checkpoint heading, or the section gets truncated and verbatim verification can never
|
|
491
|
+
* pass (2026-08 incident: permanently broken compaction for any conversation whose request had a
|
|
492
|
+
* markdown heading). Only offending lines are touched, so plain requests render exactly as before.
|
|
493
|
+
*/
|
|
494
|
+
function buildActiveTaskLines(source) {
|
|
495
|
+
return `User: ${source}`.replaceAll("\r\n", "\n").split("\n").map(escapeActiveTaskHeadingLine);
|
|
496
|
+
}
|
|
362
497
|
function findNextDoneNumber(lines) {
|
|
363
498
|
let max = 0;
|
|
364
499
|
for (const line of lines) {
|
|
@@ -482,10 +617,23 @@ function removeSection(summary, heading) {
|
|
|
482
617
|
function normalizeHeading(heading) {
|
|
483
618
|
return heading.trim().toLowerCase();
|
|
484
619
|
}
|
|
620
|
+
/** Trailing whitespace per line and leading/trailing blank lines are lost in the render pipeline
|
|
621
|
+
* (normalizeSectionLines trims both); normalize both sides identically so the comparison is a fixed
|
|
622
|
+
* point regardless of that lossy step, while leading whitespace on interior lines is preserved. */
|
|
623
|
+
function normalizeActiveTaskText(text) {
|
|
624
|
+
return text
|
|
625
|
+
.replaceAll("\r\n", "\n")
|
|
626
|
+
.split("\n")
|
|
627
|
+
.map((line) => line.trimEnd())
|
|
628
|
+
.join("\n")
|
|
629
|
+
.trim();
|
|
630
|
+
}
|
|
485
631
|
function activeTaskMatchesVerbatim(section, source) {
|
|
486
|
-
const
|
|
487
|
-
const
|
|
488
|
-
|
|
632
|
+
const decodedSection = section.replaceAll("\r\n", "\n").split("\n").map(unescapeActiveTaskHeadingLine).join("\n");
|
|
633
|
+
const normalizedSection = normalizeActiveTaskText(decodedSection);
|
|
634
|
+
const normalizedSource = normalizeActiveTaskText(source);
|
|
635
|
+
const normalizedWithPrefix = normalizeActiveTaskText(`User: ${source}`);
|
|
636
|
+
return normalizedSection === normalizedSource || normalizedSection === normalizedWithPrefix;
|
|
489
637
|
}
|
|
490
638
|
function formatScore(score) {
|
|
491
639
|
return score.toFixed(2);
|