dsh-context-compression-improved 0.10.5 → 0.11.0

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/CHANGELOG.zh.md +9 -0
  3. package/docs/shallow-teaching-preset-template.md +46 -0
  4. package/package.json +5 -5
  5. package/packages/selector/dsh.plugin.json +1 -1
  6. package/packages/selector/lib/client.d.ts +8 -0
  7. package/packages/selector/lib/client.js +212 -3
  8. package/packages/selector/lib/index.js +1 -1
  9. package/packages/selector/lib/profiles.d.ts +34 -0
  10. package/packages/selector/lib/pruner.d.ts +55 -0
  11. package/packages/selector/lib/pruner.js +1925 -303
  12. package/packages/selector/lib/savings-integral.js +126 -3
  13. package/packages/selector/lib/tool-result.js +9 -1
  14. package/packages/selector/package.json +1 -1
  15. package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
  16. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  17. package/packages/selector/src/client/decode.ts +5 -1
  18. package/packages/selector/src/client/index.ts +4 -0
  19. package/packages/selector/src/client/locales/de.ts +7 -0
  20. package/packages/selector/src/client/locales/es.ts +7 -0
  21. package/packages/selector/src/client/locales/fr.ts +7 -0
  22. package/packages/selector/src/client/locales/it.ts +7 -0
  23. package/packages/selector/src/client/locales/ja.ts +7 -0
  24. package/packages/selector/src/client/locales/ko.ts +7 -0
  25. package/packages/selector/src/client/locales/ru.ts +7 -0
  26. package/packages/selector/src/client/locales.ts +14 -0
  27. package/packages/selector/src/client/monitor-fab.ts +14 -0
  28. package/packages/selector/src/client/settings-section.tsx +9 -2
  29. package/packages/selector/src/profiles.ts +103 -0
  30. package/packages/selector/src/pruner.ts +310 -4
  31. package/packages/selector/src/runtime/audit.ts +1 -0
  32. package/packages/selector/src/runtime/config.ts +88 -1
  33. package/packages/selector/src/runtime/fold-router.ts +143 -0
  34. package/packages/selector/src/runtime/monitor.ts +31 -0
  35. package/packages/selector/src/runtime/reducers.ts +1 -1
  36. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  37. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  38. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  39. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  40. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  41. package/packages/selector/src/runtime/sediment.ts +209 -0
  42. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  43. package/packages/selector/src/runtime/tool-names.ts +6 -0
  44. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  45. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  46. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  47. package/packages/selector/src/runtime/triage/types.ts +125 -0
  48. package/packages/selector/src/runtime/types.ts +28 -0
  49. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  50. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  51. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  52. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  53. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  54. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  55. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  56. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  57. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  58. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  59. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  60. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  61. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  62. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  63. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  64. package/packages/selector/tests/public/package-contract.client.spec.ts +7 -4
  65. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  66. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  67. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  68. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  69. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  70. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  71. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  72. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  73. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  74. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  75. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  76. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  77. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  78. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  79. package/scripts/hosts.d.mts +3 -0
  80. package/scripts/sediment-latency-report.mjs +63 -0
  81. package/scripts/verify-release.mjs +7 -2
  82. package/$null +0 -1
@@ -1,8 +1,10 @@
1
- import { $ as isValidAutoCompactThresholdPercent, A as officialRequestUsage, At as recordRecertified, B as unavailableCount, Ct as getAdvisorState, D as dedupePlaceholder, Dt as invalidateOnTaskChange, E as dedupeHash, Et as getSummaryOverride, F as onlyTextBlocks, Ft as priceOfficialDeepSeekUsage, G as ContextCompressionSettingsSchema, H as countOmittedLines, I as pressureCost, It as resolveOfficialDeepSeekPrice, J as PRUNE_MARKER, K as DEFAULTS, L as recoveryMarker, Lt as getSavingsLedger, M as emptyResult, N as nativePruneContent, Nt as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, O as flattenPlainText, Ot as observeIntentEnabled, P as onlyTextBlock, Pt as decimalRateNanoUnits, Q as isCompressionProfile, R as sameProviderMeasurementKey, St as evaluateIntentGate, T as DedupeTable, U as AUTO_COMPACT_THRESHOLD_LIMITS, V as CAPACITY_PRESSURE_RATIO, W as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, X as charsToTokens, Y as charsForTokens, Z as codePointLength, _ as scheduleUsageFlush, at as resolveCustomPolicy, ct as COMPRESSION_PROFILES, d as claimFromLand, et as parseContextCompressionSettings, f as claimOffset, ft as deepSeekV4TokenizerForModel, g as reclaimFromTailTrim, it as DEFAULT_CUSTOM_COMPRESSION_POLICY, j as countToolContent, jt as recordScore, k as measureForCompaction, kt as recordIntentFold, lt as countExactCanonicalTextFields, m as flushUsageOnDispose, n as sampleIntegralBoundary, nt as resolvePolicy, o as kickStatsBackfillOnDispose, ot as assertNever, rt as CustomCompressionPolicySchema, st as deepFreeze, tt as resolveConfig, v as setStatsLivePathBusy, w as projectSessionSavings, yt as observeContextUsage, z as summarize } from "./savings-integral.js";
1
+ import { $ as isValidAutoCompactThresholdPercent, A as officialRequestUsage, At as recordIntentFold, B as unavailableCount, Ct as evaluateIntentGate, D as dedupePlaceholder, Dt as getSummaryOverride, E as dedupeHash, F as onlyTextBlocks, Ft as decimalRateNanoUnits, G as ContextCompressionSettingsSchema, H as countOmittedLines, I as pressureCost, It as priceOfficialDeepSeekUsage, J as PRUNE_MARKER, K as DEFAULTS, L as recoveryMarker, Lt as resolveOfficialDeepSeekPrice, M as emptyResult, Mt as recordScore, N as nativePruneContent, O as flattenPlainText, Ot as invalidateOnTaskChange, P as onlyTextBlock, Pt as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, Q as isCompressionProfile, R as sameProviderMeasurementKey, Rt as getSavingsLedger, T as DedupeTable, U as AUTO_COMPACT_THRESHOLD_LIMITS, V as CAPACITY_PRESSURE_RATIO, W as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, X as charsToTokens, Y as charsForTokens, Z as codePointLength, _ as scheduleUsageFlush, at as resolveCustomPolicy, bt as setSedimentObservation, ct as COMPRESSION_PROFILES, d as claimFromLand, et as parseContextCompressionSettings, f as claimOffset, ft as deepSeekV4TokenizerForModel, g as reclaimFromTailTrim, it as DEFAULT_CUSTOM_COMPRESSION_POLICY, j as countToolContent, jt as recordRecertified, k as measureForCompaction, kt as observeIntentEnabled, lt as countExactCanonicalTextFields, m as flushUsageOnDispose, n as sampleIntegralBoundary, nt as resolvePolicy, o as kickStatsBackfillOnDispose, ot as assertNever, rt as CustomCompressionPolicySchema, st as deepFreeze, tt as resolveConfig, v as setStatsLivePathBusy, w as projectSessionSavings, wt as getAdvisorState, yt as observeContextUsage, z as summarize } from "./savings-integral.js";
2
2
  import { c as eventBySeq, l as sessionEvents, n as viewToolResult, o as PTC_BINDING_NOTE, s as RUNTIME_TOOL_NAMES, t as compressionMessageSource } from "./tool-result.js";
3
3
  import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as createUserMessage, r as tailTrimRef, s as freezeMessage, t as parseTailTrimRef } from "./tail-trim.js";
4
4
  import z from "@deepseek-ai/schemastery";
5
+ import path from "node:path";
5
6
  import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
7
+ import fs from "node:fs/promises";
6
8
  import { Service } from "@deepseek-ai/cordis";
7
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
10
  z.object({
@@ -10,7 +12,7 @@ z.object({
10
12
  maxScanChars: z.number().step(1).min(1).default(25e4),
11
13
  maxQueryChars: z.number().step(1).min(1).default(256)
12
14
  });
13
- const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/;
15
+ const REF_PATTERN$1 = /^session:\/\/([^/]+)\/event\/(\d+)$/;
14
16
  const MAX_LINES = 1e3;
15
17
  const DEFAULT_MAX_CHARS = 12e3;
16
18
  const DEFAULT_MAX_SCAN_CHARS = 25e4;
@@ -65,7 +67,7 @@ function installContextCompressionRetrieve(ctx, config = {}) {
65
67
  isConcurrencySafe: () => true,
66
68
  execute(args, exec) {
67
69
  if (exec.agent === void 0) throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE} requires an agent session`);
68
- const match = REF_PATTERN.exec(args.ref);
70
+ const match = REF_PATTERN$1.exec(args.ref);
69
71
  const tailTrimRef = parseTailTrimRef(args.ref);
70
72
  if (match === null && tailTrimRef === null) throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: ref must be session://<session-id>/(event|tailtrim)/<seq>`);
71
73
  if ((match?.[1] ?? tailTrimRef?.sessionId) !== String(exec.agent.session.id)) throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: a compression reference may only read the caller's current session`);
@@ -361,152 +363,129 @@ function codePointLength$1(text) {
361
363
  return count;
362
364
  }
363
365
  //#endregion
364
- //#region src/pruner/session.ts
365
- /** Check whether the session currently has an open (unterminated) turn. */
366
- function hasOpenTurn(session) {
367
- let open = false;
368
- for (const event of sessionEvents(session)) if (event.type === "turn/start") open = true;
369
- else if (event.type === "turn/end") open = false;
370
- return open;
371
- }
372
- /** Walk the tool-result source chain to find the root result seq. */
373
- function rootToolResultSeq(session, seq) {
374
- const events = sessionEvents(session);
375
- let current = seq;
376
- const seen = /* @__PURE__ */ new Set();
377
- while (!seen.has(current)) {
378
- seen.add(current);
379
- const event = events[current];
380
- if (event?.type !== "tool/result" || typeof event.surfaceOp !== "object") return current;
381
- const previous = event.sourceEventSeqs?.[0];
382
- if (previous === void 0) return current;
383
- current = previous;
384
- }
385
- return seq;
386
- }
387
- /** Build a session:// event reference string for a given seq. */
388
- function sourceRef(session, seq) {
389
- return `session://${session.id}/event/${String(seq)}`;
390
- }
391
- /** Find the latest completed step number for a given turn. */
392
- function latestCompletedToolStep(session, turn) {
393
- let latest;
394
- for (const event of sessionEvents(session)) if (event.type === "step/end" && event.data.turn === turn) latest = event.data.step;
395
- return latest;
396
- }
397
- /** Routed provider/model when the durable request header names one route. */
398
- function routeAuditFact(session) {
399
- const header = session.requestHeader()?.config;
400
- if (header === void 0 || header.provider.length === 0 || header.model.length === 0) return void 0;
401
- return {
402
- provider: header.provider,
403
- model: header.model
366
+ //#region src/runtime/triage/shallow.ts
367
+ /** Windows-first corpus; forward slashes accepted everywhere. */
368
+ function normalizeToolPath(raw) {
369
+ const unified = raw.replace(/\\/g, "/").replace(/^\.\//, "");
370
+ const collapsed = (/^[A-Za-z]:\//.test(unified) ? `${unified[0].toLowerCase()}${unified.slice(1)}` : unified).replace(/\/{2,}/g, "/").replace(/\/$/, "");
371
+ const segments = collapsed.split("/");
372
+ const out = [];
373
+ for (const segment of segments) if (segment === "..") out.pop();
374
+ else if (segment !== "." && segment !== "") out.push(segment);
375
+ const joined = out.join("/");
376
+ return collapsed.startsWith("/") ? `/${joined}` : joined;
377
+ }
378
+ const JSON_START = /^[{[]/;
379
+ const CSV_HINT = /^[^\n,]*,.*\n(?:[^\n,]*,.*){2,}/;
380
+ const FRONTMATTER_HINT = /^---\n/;
381
+ /** Classify from a bounded header sample only — the body is never opened here. */
382
+ function classifyShallowSample(head, ext, totalBytes) {
383
+ const extension = ext.toLowerCase().replace(/^\./, "");
384
+ const trimmed = head.replace(/^\uFEFF/, "").trimStart();
385
+ if (extension === "json" || extension === "jsonc" || JSON_START.test(trimmed) && (extension === "" || extension === "jsonl")) return {
386
+ method: "json-skeleton",
387
+ reason: "structured JSON: key skeleton beats raw text"
388
+ };
389
+ if (extension === "jsonl" || extension === "ndjson") return {
390
+ method: "code-skeleton",
391
+ reason: "record stream: head/tail records with counts"
392
+ };
393
+ if (extension === "csv" || extension === "tsv" || totalBytes > 2e3 && CSV_HINT.test(trimmed)) return {
394
+ method: "csv-header",
395
+ reason: "tabular: header row + row count, rows elided"
396
+ };
397
+ if ([
398
+ "md",
399
+ "markdown",
400
+ "rst",
401
+ "txt",
402
+ "adoc"
403
+ ].includes(extension)) return {
404
+ method: "toc-lines",
405
+ reason: "prose: heading outline, bodies elided"
406
+ };
407
+ if ([
408
+ "ts",
409
+ "tsx",
410
+ "js",
411
+ "jsx",
412
+ "mjs",
413
+ "py",
414
+ "go",
415
+ "rs",
416
+ "java",
417
+ "c",
418
+ "h",
419
+ "cc",
420
+ "cpp",
421
+ "cs",
422
+ "kt",
423
+ "swift",
424
+ "php",
425
+ "rb"
426
+ ].includes(extension) || FRONTMATTER_HINT.test(trimmed) === false && /^\s*(?:import|from|package|use|def|fn|class|const|function)/.test(trimmed)) return {
427
+ method: "code-skeleton",
428
+ reason: "source code: declarations kept, bodies elided"
429
+ };
430
+ if (totalBytes < 4e3) return {
431
+ method: "head-tail",
432
+ reason: "small enough that a plain slice is the honest view"
404
433
  };
405
- }
406
- /** Bundled tokenizer identity for one route, when the route is eligible. */
407
- function tokenizerAuditFact(route) {
408
- const identity = route.provider === "deepseek" || route.provider === "deepseek-official" ? deepSeekV4TokenizerForModel(route.model)?.countText("") : void 0;
409
- if (identity?.kind === "exact-tokenizer") return { tokenizer: {
410
- repository: identity.tokenizerId,
411
- revision: identity.tokenizerRevision
412
- } };
413
- return { tokenizer: {
414
- repository: "unavailable",
415
- revision: "unavailable"
416
- } };
417
- }
418
- /** Check whether a snapshot candidate represents an error result. */
419
- function isError(candidate) {
420
- return viewToolResult(candidate.event.data.message).isError || candidate.event.data.error !== void 0;
421
- }
422
- /** Wrap a plan list into a HistoryPlanOutcome. */
423
- function historyOutcome(plans) {
424
434
  return {
425
- kind: "planned",
426
- plans: [...plans]
435
+ method: "toc-lines",
436
+ reason: "unknown shape: line-structure outline as safe default"
427
437
  };
428
438
  }
429
- //#endregion
430
- //#region src/runtime/tokenpilot/locator.ts
431
- /** Files touched by read/grep-style tool calls inside the range. */
432
- const TOUCHED_FILE_TOOL = /(?:^|[-_])?(?:read|write|edit|glob|grep|view|str_replace_editor)(?:$|[-_])/i;
433
- /** Spill notice paths emitted by the Harness output-retention policy. */
434
- const SPILL_PATH = /stored at:\s*([^\s)\]]+)/g;
435
- /** Tool call arguments keys that commonly carry a file path. */
436
- const PATH_KEYS$1 = ["path", "file_path"];
437
439
  /**
438
- * Find the latest compaction/summary event matching the compaction id of a
439
- * compaction/end event. Returns undefined when the transaction cannot be
440
- * identified — the caller must skip rather than guess.
440
+ * The asymmetric guard (findings F6): losing the map costs far more than the
441
+ * saved bytes. Discarding the map requires the covering read to span it
442
+ * fully; equal paths after normalization are a precondition, never assumed.
441
443
  */
442
- function findCompactionTrace(events, compactionId) {
443
- let trace;
444
- for (const event of events) if (event.type === "compaction/summary" && event.data.compactionId === compactionId) trace = {
445
- compactionId,
446
- summarySeq: event.seq,
447
- summaryShadowedRange: event.data.shadowedRange
444
+ function evaluateDiscardGuard(input) {
445
+ const mapPath = normalizeToolPath(input.map.path);
446
+ const coveringPath = normalizeToolPath(input.covering.path);
447
+ if (mapPath === "" || coveringPath === "" || mapPath !== coveringPath) return {
448
+ allowed: false,
449
+ reason: `path-mismatch:${input.map.path}|${input.covering.path}`
448
450
  };
449
- return trace;
450
- }
451
- /** Extract spill file paths from one text chunk. */
452
- function extractSpillPaths(text) {
453
- const paths = [];
454
- for (const match of text.matchAll(SPILL_PATH)) {
455
- const path = match[1]?.replace(/[.,;]+$/, "");
456
- if (path !== void 0 && path.length > 0) paths.push(path);
451
+ if (input.map.coverage.kind === "full") {
452
+ if (input.covering.coverage.kind === "full") return {
453
+ allowed: true,
454
+ reason: "covered-full"
455
+ };
456
+ return {
457
+ allowed: false,
458
+ reason: "map-is-full-need-full-coverage"
459
+ };
457
460
  }
458
- return paths;
461
+ if (input.covering.coverage.kind === "full") return {
462
+ allowed: true,
463
+ reason: "covered-by-full"
464
+ };
465
+ const fromOk = input.covering.coverage.from <= input.map.coverage.from;
466
+ const toOk = input.covering.coverage.to >= input.map.coverage.to;
467
+ return fromOk && toOk ? {
468
+ allowed: true,
469
+ reason: "covered-by-window"
470
+ } : {
471
+ allowed: false,
472
+ reason: `window-gap:${input.map.coverage.from}-${input.map.coverage.to} vs ${input.covering.coverage.from}-${input.covering.coverage.to}`
473
+ };
459
474
  }
460
- /** Extract touched file paths from one tool/call event's arguments. */
461
- function extractTouchedPath(name, argumentsText) {
462
- if (!TOUCHED_FILE_TOOL.test(name)) return void 0;
463
- let parsed;
464
- try {
465
- parsed = JSON.parse(argumentsText);
466
- } catch {
467
- return;
468
- }
469
- if (typeof parsed !== "object" || parsed === null) return void 0;
470
- const record = parsed;
471
- for (const key of PATH_KEYS$1) {
472
- const value = record[key];
473
- if (typeof value === "string" && value.length > 0) return value;
474
- }
475
+ /** Footer riding a full read that pairs with a live shallow map (T4.8). */
476
+ function buildShallowFooter(checkpoint, savedTokens) {
477
+ return `[cci-shallow-pair] 同文件的浅读视图 ${checkpoint.ref}(≈${savedTokens} tok)仍在上下文;确认不再需要时可调 context_compression_discard 释放(检查点行会保留)。被省略的输出不要凭本行推测补写。`;
475
478
  }
476
- /**
477
- * Build the Exact Sources block for one shadowed range, or null when the
478
- * range locates nothing concrete (no spill files and no touched files).
479
- */
480
- function buildLocatorBlock(events, shadowedRange) {
481
- const spillFiles = /* @__PURE__ */ new Set();
482
- const touchedFiles = /* @__PURE__ */ new Set();
483
- for (let seq = shadowedRange.start; seq <= shadowedRange.end && seq < events.length; seq += 1) {
484
- const event = events[seq];
485
- if (event === void 0) continue;
486
- if (event.type === "tool/call") {
487
- const path = extractTouchedPath(event.data.name, event.data.arguments);
488
- if (path !== void 0) touchedFiles.add(path);
489
- continue;
490
- }
491
- if (event.type === "tool/result" || event.type === "user/message") {
492
- const data = event.data;
493
- const content = Array.isArray(data.content) ? data.content : data.message?.content;
494
- if (!Array.isArray(content)) continue;
495
- for (const block of content) if (block.type === "text") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
496
- }
497
- }
498
- if (spillFiles.size === 0 && touchedFiles.size === 0) return null;
499
- return {
500
- text: [
501
- "## Exact Sources (locators)",
502
- `- seq range: ${String(shadowedRange.start)}-${String(shadowedRange.end)}`,
503
- ...[...spillFiles].map((path) => `- spill file: ${path}`),
504
- ...[...touchedFiles].map((path) => `- file touched: ${path}`),
505
- `(Use \`read <spill file>\` or \`${RUNTIME_TOOL_NAMES.RETRIEVE}\` with a \`session://\` source — pass start_line/max_lines to window the text — to restore exact text.)`
506
- ].join("\n"),
507
- spillFiles: spillFiles.size,
508
- touchedFiles: touchedFiles.size
509
- };
479
+ /** The one permanent line a discarded map leaves behind (R11). */
480
+ function renderCheckpointLine(checkpoint) {
481
+ return `[cci-checkpoint] ${checkpoint.path} | ${checkpoint.coverage} | ref ${checkpoint.ref} | fp ${checkpoint.fingerprint}`;
482
+ }
483
+ /** Cheap order-sensitive header hash + size; staleness hint only, never authority. */
484
+ function shallowFingerprint(text) {
485
+ const head = text.slice(0, 512);
486
+ let hash = 5381;
487
+ for (let index = 0; index < head.length; index += 1) hash = (hash << 5) + hash + head.charCodeAt(index) >>> 0;
488
+ return `${text.length.toString(16)}-${hash.toString(16)}`;
510
489
  }
511
490
  //#endregion
512
491
  //#region src/runtime/toolclass.ts
@@ -2111,103 +2090,943 @@ function buildPattern() {
2111
2090
  ].join(""), "i");
2112
2091
  }
2113
2092
  //#endregion
2114
- //#region src/runtime/tokenpilot/read-state.ts
2115
- /** Write-style tool names whose success supersedes earlier reads. */
2116
- const WRITE_TOOLS = /(?:^|[-_])?(?:write|edit|apply_patch|file_write|file_edit|str_replace|replace|multiedit)(?:$|[-_])/i;
2117
- const PATH_KEYS = ["path", "file_path"];
2118
- /** Parse one path out of a tool-call arguments JSON blob. */
2119
- function toolCallPath(argumentsText) {
2093
+ //#region src/runtime/triage/masks.ts
2094
+ /**
2095
+ * Line-C deterministic masks (plan cci-sedimentation-triage, Phase 2).
2096
+ *
2097
+ * Two extractions replace enumeration (findings F5 "extraction over
2098
+ * enumeration"):
2099
+ * 1. `manifestFromCall` — write-family results collapse to the touched-file
2100
+ * list. Paths come from CALL ARGS first: result text usually says "written"
2101
+ * without full paths (replay round-1 failure mode).
2102
+ * 2. `skeletonFromRead` — large read results collapse to declaration lines.
2103
+ * Matching runs on the gutter-stripped view (the host's `N: ` prefix defeats
2104
+ * naive declaration regexes — the CCI JSON-skeleton trap), while CAPTURED
2105
+ * lines keep their gutter because it is the model's inline locator into the
2106
+ * original file, same convention as `hasReadGutter` in reducers.
2107
+ *
2108
+ * Both fail open: returning `null` means "not maskable", the caller keeps the
2109
+ * normal reduction path. Zero-hit is a normal outcome, not an error.
2110
+ *
2111
+ * @module runtime/triage/masks
2112
+ */
2113
+ /** Write-family tool names whose results are pure "what changed" manifests. */
2114
+ const WRITE_TOOLS$1 = /^(write|edit|apply_patch|multi_edit|create|search_replace)$/i;
2115
+ /** Read results below this char length stay verbatim (masking would lose more than it saves). */
2116
+ const MASK_READ_MIN_CHARS = 3e3;
2117
+ /** Declaration-ish line starts across the languages this corpus exercises. */
2118
+ const SKELETON_PATTERN = /^\s*(?:import |from \S+ import |export |package |use |fn |func |def |class |interface |type |impl |enum |pub |const |let |var |async function|public |private |protected |static |#define|template)/;
2119
+ /** Hard caps keep one card section bounded regardless of input size. */
2120
+ const MANIFEST_MAX_PATHS = 12;
2121
+ const SKELETON_MAX_LINES = 40;
2122
+ /** Gutter prefix added by the host's `formatReadOutput`; strip for MATCHING only. */
2123
+ const GUTTER_STRIP = /^(\d+): /;
2124
+ /** Text-fallback path pattern: absolute-ish paths and extension-bearing names. */
2125
+ const PATH_FALLBACK = /((?:[A-Za-z]:)?[\\/][^\s"'`,:]{3,}|\.?[\w./\\-]+\.(?:ts|tsx|js|mjs|py|go|rs|md|json|ya?ml|css|html))(?::\d+)?/g;
2126
+ function collectArgPaths(argsJson) {
2120
2127
  let parsed;
2121
2128
  try {
2122
- parsed = JSON.parse(argumentsText);
2129
+ parsed = JSON.parse(argsJson);
2123
2130
  } catch {
2124
- return;
2131
+ return [];
2125
2132
  }
2126
- if (typeof parsed !== "object" || parsed === null) return void 0;
2133
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return [];
2127
2134
  const record = parsed;
2128
- for (const key of PATH_KEYS) {
2129
- const value = record[key];
2130
- if (typeof value === "string" && value.length > 0) return value;
2131
- }
2135
+ const singles = [
2136
+ record.file_path,
2137
+ record.path,
2138
+ record.filePath
2139
+ ];
2140
+ const list = Array.isArray(record.paths) ? record.paths : [];
2141
+ const edits = Array.isArray(record.edits) ? record.edits : [];
2142
+ const out = [];
2143
+ for (const entry of [
2144
+ ...singles,
2145
+ ...list,
2146
+ ...edits.map((item) => item?.path)
2147
+ ]) if (typeof entry === "string" && entry.trim() !== "") out.push(entry.trim());
2148
+ return out;
2132
2149
  }
2133
2150
  /**
2134
- * Decide whether an oversized read result was superseded by a later mutation
2135
- * of the same file. `readPath` is the read call's target path; events after
2136
- * `readSeq` are scanned for a write-style call on it.
2151
+ * Collapse a write-family result to its touched-file manifest.
2152
+ * Args first, result text only as fallback; never throws on broken args.
2137
2153
  */
2138
- function isSupersededRead(events, readSeq, readPath) {
2139
- if (readPath === void 0) return false;
2140
- for (let seq = readSeq + 1; seq < events.length; seq += 1) {
2141
- const event = events[seq];
2142
- if (event?.type !== "tool/call") continue;
2143
- if (!WRITE_TOOLS.test(event.data.name)) continue;
2144
- if (toolCallPath(event.data.arguments) === readPath) return true;
2145
- }
2146
- return false;
2154
+ function manifestFromCall(name, argsJson, text, seq = 0) {
2155
+ if (!WRITE_TOOLS$1.test(name)) return null;
2156
+ const fromArgs = collectArgPaths(argsJson);
2157
+ const candidates = fromArgs.length > 0 ? fromArgs : (text.match(PATH_FALLBACK) ?? []).map((entry) => entry.replace(/:\d+$/, ""));
2158
+ const paths = [...new Set(candidates)].slice(0, MANIFEST_MAX_PATHS);
2159
+ if (paths.length === 0) return null;
2160
+ return {
2161
+ kind: "manifest",
2162
+ paths,
2163
+ seq
2164
+ };
2147
2165
  }
2148
- /** Error/warning/info line classifiers used by the omission summary. */
2149
- const ERROR_LINE = /\b(error|failed|failure|fatal|exception|traceback|cannot|unable|denied)\b/i;
2150
- const WARN_LINE = /\b(warn|warning|deprecated)\b/i;
2151
- const SECTION_HEADING = /^#{1,3}\s+(.{1,80})/;
2152
2166
  /**
2153
- * Cluster one omitted line-count into a summary appended to a placeholder
2154
- * marker, giving the model meta-knowledge about what was dropped. Document
2155
- * content (R8) swaps the error/warn/info census for a section-heading list —
2156
- * `0 error, 0 warn, N info` carries no information about a dropped document,
2157
- * while its heading list does.
2167
+ * Collapse a large read result to its declaration skeleton. Returns `null`
2168
+ * for small reads, non-read content, and zero-hit bodies (prose dumps) —
2169
+ * fail-open to the normal reducer path. Captured lines keep the gutter.
2170
+ * With a target `path`, the verdict carries the permanent checkpoint layer
2171
+ * (plan R11): path/coverage/fingerprint survive any later `discard`.
2158
2172
  */
2159
- function clusterOmittedLines(text, omittedLines) {
2160
- if (omittedLines <= 0) return void 0;
2161
- if (looksLikeDocument(text)) return documentCensus(text, omittedLines);
2162
- let errors = 0;
2163
- let warns = 0;
2164
- let infos = 0;
2165
- for (const line of text.split("\n")) if (ERROR_LINE.test(line)) errors += 1;
2166
- else if (WARN_LINE.test(line)) warns += 1;
2167
- else infos += 1;
2168
- const parts = [];
2169
- if (errors > 0) parts.push(`${String(errors)} error`);
2170
- if (warns > 0) parts.push(`${String(warns)} warn`);
2171
- if (infos > 0) parts.push(`${String(infos)} info`);
2172
- if (parts.length === 0) return void 0;
2173
- return `${String(omittedLines)} lines omitted (${parts.join(", ")})`;
2174
- }
2175
- /** Bounded section-heading list for an omitted document (R8 census). */
2176
- function documentCensus(text, omittedLines) {
2177
- const titles = [];
2178
- for (const line of text.split("\n")) {
2179
- const match = SECTION_HEADING.exec(line);
2180
- if (match === null) continue;
2181
- titles.push(match[1].trim());
2182
- if (titles.length >= 8) break;
2173
+ function skeletonFromRead(text, seq = 0, path) {
2174
+ if (text.length < MASK_READ_MIN_CHARS) return null;
2175
+ const lines = text.replace(/\n+$/, "").split("\n");
2176
+ const guttered = hasReadGutter(lines);
2177
+ const kept = [];
2178
+ for (const line of lines) {
2179
+ const matchView = guttered ? line.replace(GUTTER_STRIP, "") : line;
2180
+ if (SKELETON_PATTERN.test(matchView)) {
2181
+ kept.push(line);
2182
+ if (kept.length >= SKELETON_MAX_LINES) break;
2183
+ }
2183
2184
  }
2184
- if (titles.length === 0) return `${String(omittedLines)} lines omitted (document content)`;
2185
- let summary = titles.join(" · ");
2186
- if (summary.length > 240) summary = `${summary.slice(0, 240)}…`;
2187
- return `${String(omittedLines)} lines omitted (sections: ${summary})`;
2185
+ if (kept.length === 0) return null;
2186
+ const keptChars = kept.reduce((sum, line) => sum + line.length + 1, 0);
2187
+ return {
2188
+ kind: "skeleton",
2189
+ lines: kept,
2190
+ totalLines: lines.length,
2191
+ elidedChars: Math.max(0, text.length - keptChars),
2192
+ seq,
2193
+ ...path === void 0 || path.trim() === "" ? {} : { checkpoint: {
2194
+ path: normalizeToolPath(path),
2195
+ coverage: `${lines.length} lines`,
2196
+ ref: `event/${seq}`,
2197
+ fingerprint: shallowFingerprint(text)
2198
+ } }
2199
+ };
2200
+ }
2201
+ /** Write-family predicate for the wiring site. */
2202
+ function isWriteToolName(name) {
2203
+ return WRITE_TOOLS$1.test(name);
2188
2204
  }
2189
2205
  //#endregion
2190
- //#region src/runtime/tokenpilot/sidechannel.ts
2191
- /** One bound side channel. `ask` resolves `undefined` on ANY failure. */
2192
- var SideChannel = class {
2193
- ctx;
2194
- options;
2195
- overrides;
2196
- /**
2197
- * @param overrides - per-consumer overrides of the estimator-named options.
2198
- * The estimator itself never passes them (byte-identical behavior); the
2199
- * advisory advisor passes its own mode/timeout/output budget so both
2200
- * consumers share one transport without sharing one configuration.
2201
- */
2202
- constructor(ctx, options, overrides) {
2203
- this.ctx = ctx;
2204
- this.options = options;
2205
- this.overrides = overrides;
2206
- }
2207
- get mode() {
2208
- return this.overrides?.mode ?? this.options.estimatorMode ?? "";
2206
+ //#region src/runtime/shallow-tools.ts
2207
+ /**
2208
+ * Shallow-read tool surface (plan cci-sedimentation-triage, Phase 4.5).
2209
+ *
2210
+ * Registers the upgrade-discard primitives next to the existing retrieve tool:
2211
+ * - `context_compression_probe` — O(1) header sample → recommended shallow view
2212
+ * - `context_compression_shallow` — the map: classified shallow view + checkpoint
2213
+ * - `context_compression_discard` — drops one side of a shallow/full pair,
2214
+ * guarded so the MAP only dies under full coverage; the checkpoint line
2215
+ * always survives (R11).
2216
+ *
2217
+ * The decision core is exported pure (`buildShallowView`, `parseReadCoverage`,
2218
+ * registry helpers) so the guard arithmetic is unit-testable without a host;
2219
+ * `installShallowTools` only adapts those to `defineTool`.
2220
+ */
2221
+ const PROBE_SAMPLE_BYTES = 2048;
2222
+ const SHALLOW_MAX_BYTES = 2e6;
2223
+ const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/;
2224
+ const registry = /* @__PURE__ */ new WeakMap();
2225
+ function shallowRegistryFor(session) {
2226
+ let map = registry.get(session);
2227
+ if (map === void 0) {
2228
+ map = /* @__PURE__ */ new Map();
2229
+ registry.set(session, map);
2230
+ }
2231
+ return map;
2232
+ }
2233
+ /** The live (undiscarded) map for a path, if any — footer pairing source. */
2234
+ function liveShallowFor(session, rawPath) {
2235
+ const entry = shallowRegistryFor(session).get(normalizeToolPath(rawPath));
2236
+ return entry !== void 0 && !entry.discarded ? entry : void 0;
2237
+ }
2238
+ /** Pure view builder shared by the shallow tool and tests. */
2239
+ function buildShallowView(text, method, rawPath, seq) {
2240
+ const lines = text.replace(/\n+$/, "").split("\n");
2241
+ const checkpointBase = {
2242
+ path: normalizeToolPath(rawPath),
2243
+ coverage: `${lines.length} lines`,
2244
+ ref: `event/${seq}`,
2245
+ fingerprint: shallowFingerprint(text)
2246
+ };
2247
+ if (method === "code-skeleton") {
2248
+ const verdict = skeletonFromRead(text, seq, rawPath);
2249
+ if (verdict !== null && verdict.kind === "skeleton") return {
2250
+ body: `${verdict.lines.join("\n")}\n[… body elided: ${verdict.totalLines - verdict.lines.length} lines / ${verdict.elidedChars} chars]`,
2251
+ checkpoint: verdict.checkpoint ?? { ...checkpointBase }
2252
+ };
2253
+ return headTailView(lines, checkpointBase);
2209
2254
  }
2210
- get enabled() {
2255
+ if (method === "json-skeleton") try {
2256
+ const parsed = JSON.parse(text);
2257
+ const keys = [];
2258
+ collectJsonKeys(parsed, "", keys, 40);
2259
+ if (keys.length === 0) return headTailView(lines, checkpointBase);
2260
+ return {
2261
+ body: `${keys.join("\n")}\n[… ${lines.length} lines of JSON values elided]`,
2262
+ checkpoint: { ...checkpointBase }
2263
+ };
2264
+ } catch {
2265
+ return headTailView(lines, checkpointBase);
2266
+ }
2267
+ if (method === "csv-header") return {
2268
+ body: `${lines.slice(0, 3).join("\n")}\n[… ${Math.max(0, lines.length - 3)} data rows elided]`,
2269
+ checkpoint: { ...checkpointBase }
2270
+ };
2271
+ if (method === "toc-lines") {
2272
+ const headings = lines.filter((line) => /^#{1,6} |^\s*\*\*\w/.test(line)).slice(0, 60);
2273
+ if (headings.length === 0) return headTailView(lines, checkpointBase);
2274
+ return {
2275
+ body: `${headings.join("\n")}\n[… ${lines.length} lines under the outline elided]`,
2276
+ checkpoint: { ...checkpointBase }
2277
+ };
2278
+ }
2279
+ return headTailView(lines, checkpointBase);
2280
+ }
2281
+ function headTailView(lines, base) {
2282
+ const head = lines.slice(0, 20);
2283
+ const tail = lines.slice(-10);
2284
+ const middle = Math.max(0, lines.length - head.length - tail.length);
2285
+ return {
2286
+ body: [
2287
+ ...head,
2288
+ ...middle > 0 ? [`[… ${middle} lines elided]`] : [],
2289
+ ...tail
2290
+ ].join("\n"),
2291
+ checkpoint: base
2292
+ };
2293
+ }
2294
+ function collectJsonKeys(node, prefix, out, cap) {
2295
+ if (out.length >= cap) return;
2296
+ if (Array.isArray(node)) {
2297
+ out.push(`${prefix}[] (${node.length})`);
2298
+ if (node.length > 0) collectJsonKeys(node[0], `${prefix}[]`, out, cap);
2299
+ return;
2300
+ }
2301
+ if (node !== null && typeof node === "object") for (const [key, value] of Object.entries(node)) {
2302
+ if (out.length >= cap) return;
2303
+ const at = `${prefix}.${key}`.replace(/^\./, "");
2304
+ if (value !== null && typeof value === "object") collectJsonKeys(value, at, out, cap);
2305
+ else out.push(at);
2306
+ }
2307
+ }
2308
+ /** Coverage of a host `read` call from its arguments JSON (pairing input). */
2309
+ function parseReadCoverage(argsJson) {
2310
+ let args;
2311
+ try {
2312
+ args = JSON.parse(argsJson);
2313
+ } catch {
2314
+ return {
2315
+ kind: "slice",
2316
+ from: 1,
2317
+ to: 0
2318
+ };
2319
+ }
2320
+ const offset = typeof args.offset === "number" && Number.isSafeInteger(args.offset) ? Math.max(0, args.offset) : 0;
2321
+ const limit = typeof args.limit === "number" && Number.isSafeInteger(args.limit) ? args.limit : void 0;
2322
+ if (limit === void 0 && offset === 0) return { kind: "full" };
2323
+ return {
2324
+ kind: "slice",
2325
+ from: offset + 1,
2326
+ to: limit === void 0 ? Number.MAX_SAFE_INTEGER : offset + limit
2327
+ };
2328
+ }
2329
+ /**
2330
+ * Register probe/shallow/discard. Reachability and the pairing registry are
2331
+ * in-process truth; every tool call stays inside the caller's own session.
2332
+ */
2333
+ function installShallowTools(ctx) {
2334
+ const OUTPUT = {
2335
+ schema: { type: "string" },
2336
+ render: (_args, value) => [{
2337
+ type: "text",
2338
+ text: value
2339
+ }]
2340
+ };
2341
+ ctx.systemPrompt.section({
2342
+ name: "tool:context-compression-shallow",
2343
+ order: 115,
2344
+ text: `Before reading a large unknown file, call ${RUNTIME_TOOL_NAMES.PROBE} with its path to pick the right shallow view, then ${RUNTIME_TOOL_NAMES.SHALLOW} to get the map (declaration/outline/keys + checkpoint line) instead of the full body. After a full read supersedes a live map, or a map's body is no longer needed, ${RUNTIME_TOOL_NAMES.DISCARD} frees it — the checkpoint line always remains and ${RUNTIME_TOOL_NAMES.RETRIEVE} can still recover the body. Never reconstitute discarded output from memory or guesswork; use the ref. ` + PTC_BINDING_NOTE
2345
+ });
2346
+ ctx.tools.register(defineTool({
2347
+ name: RUNTIME_TOOL_NAMES.PROBE,
2348
+ description: `Read at most the first ${PROBE_SAMPLE_BYTES} bytes of a file and return the recommended shallow view method with reasons. ${PTC_BINDING_NOTE}`,
2349
+ parameters: { path: {
2350
+ type: "string",
2351
+ required: true,
2352
+ description: "File path to probe."
2353
+ } },
2354
+ output: OUTPUT,
2355
+ isConcurrencySafe: () => true,
2356
+ async execute(args) {
2357
+ const handle = await fs.open(args.path, "r");
2358
+ try {
2359
+ const buffer = Buffer.alloc(PROBE_SAMPLE_BYTES);
2360
+ const { bytesRead } = await handle.read(buffer, 0, PROBE_SAMPLE_BYTES, 0);
2361
+ const stat = await handle.stat();
2362
+ const verdict = classifyShallowSample(buffer.subarray(0, bytesRead).toString("utf8"), path.extname(args.path), stat.size);
2363
+ return `${verdict.method} | ${verdict.reason} | size ${stat.size} B`;
2364
+ } finally {
2365
+ await handle.close();
2366
+ }
2367
+ }
2368
+ }));
2369
+ ctx.tools.register(defineTool({
2370
+ name: RUNTIME_TOOL_NAMES.SHALLOW,
2371
+ description: "Return a shallow view (declaration skeleton / JSON keys / outline / csv header + head/tail) of a file plus its permanent checkpoint line. Cheaper than a full read; pairs with discard and retrieve. " + PTC_BINDING_NOTE,
2372
+ parameters: {
2373
+ path: {
2374
+ type: "string",
2375
+ required: true,
2376
+ description: "File path to view shallowly."
2377
+ },
2378
+ method: {
2379
+ type: "string",
2380
+ description: `Override the classified view: json-skeleton | code-skeleton | csv-header | toc-lines | head-tail.`
2381
+ }
2382
+ },
2383
+ output: OUTPUT,
2384
+ isConcurrencySafe: () => true,
2385
+ async execute(args, exec) {
2386
+ if (exec.agent === void 0) throw new Error(`${RUNTIME_TOOL_NAMES.SHALLOW} requires an agent session`);
2387
+ const stat = await fs.stat(args.path);
2388
+ if (stat.size > SHALLOW_MAX_BYTES) throw new Error(`${RUNTIME_TOOL_NAMES.SHALLOW}: file is ${stat.size} B, above the ${SHALLOW_MAX_BYTES} B shallow cap; read slices instead`);
2389
+ const text = await fs.readFile(args.path, "utf8");
2390
+ const method = args.method ?? classifyShallowSample(text.slice(0, PROBE_SAMPLE_BYTES), path.extname(args.path), stat.size).method;
2391
+ const seq = sessionEvents(exec.agent.session).length;
2392
+ const { body, checkpoint } = buildShallowView(text, method, args.path, seq);
2393
+ if (checkpoint !== null) {
2394
+ shallowRegistryFor(exec.agent.session).set(checkpoint.path, {
2395
+ seq,
2396
+ checkpoint,
2397
+ bodyTokens: Math.ceil((body.length + checkpoint.path.length) / 4),
2398
+ discarded: false
2399
+ });
2400
+ return `${body}\n\n${renderCheckpointLine(checkpoint)}`;
2401
+ }
2402
+ return body;
2403
+ }
2404
+ }));
2405
+ ctx.tools.register(defineTool({
2406
+ name: RUNTIME_TOOL_NAMES.DISCARD,
2407
+ description: "Free one side of a shallow/full read pair from the context: the live shallow map (only when a covering full read spans it) or a full read whose map suffices. The checkpoint line always remains; retrieve can recover bodies by ref. " + PTC_BINDING_NOTE,
2408
+ parameters: {
2409
+ ref: {
2410
+ type: "string",
2411
+ required: true,
2412
+ description: "session://<current-session-id>/event/<seq> of the shallow map to discard."
2413
+ },
2414
+ covering_ref: {
2415
+ type: "string",
2416
+ description: "event ref of the full read that supersedes the map (required to discard the map)."
2417
+ }
2418
+ },
2419
+ output: OUTPUT,
2420
+ isConcurrencySafe: () => false,
2421
+ async execute(args, exec) {
2422
+ if (exec.agent === void 0) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD} requires an agent session`);
2423
+ const session = exec.agent.session;
2424
+ const match = REF_PATTERN.exec(args.ref);
2425
+ if (match === null || match[1] !== String(session.id)) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: ref must be session://<current-session-id>/event/<seq>`);
2426
+ const targetSeq = Number(match[2]);
2427
+ const entry = [...shallowRegistryFor(session).values()].find((candidate) => candidate.seq === targetSeq);
2428
+ if (entry === void 0) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: ${args.ref} is not a live shallow map of this session (only ${RUNTIME_TOOL_NAMES.SHALLOW} results are discardable here)`);
2429
+ if (entry.discarded) return `${renderCheckpointLine(entry.checkpoint)} (already discarded)`;
2430
+ const coveringRef = args.covering_ref;
2431
+ if (coveringRef === void 0) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: discarding the map requires covering_ref of the full read that supersedes it`);
2432
+ const coveringMatch = REF_PATTERN.exec(coveringRef);
2433
+ if (coveringMatch === null || coveringMatch[1] !== String(session.id)) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: covering_ref must be in the current session`);
2434
+ const events = sessionEvents(session);
2435
+ const coveringEvent = events[Number(coveringMatch[2])];
2436
+ if (coveringEvent?.type !== "tool/result") throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: covering_ref does not cite a tool/result`);
2437
+ const coveringMessage = coveringEvent.data?.message;
2438
+ const coveringArgs = typeof coveringMessage?.toolCallId === "string" ? findCallArgs(events, coveringMessage.toolCallId) : void 0;
2439
+ const covering = {
2440
+ seq: Number(coveringMatch[2]),
2441
+ path: coveringArgs?.path ?? "",
2442
+ coverage: coveringArgs === void 0 ? {
2443
+ kind: "slice",
2444
+ from: 1,
2445
+ to: 0
2446
+ } : parseReadCoverage(coveringArgs.argsJson)
2447
+ };
2448
+ const guard = evaluateDiscardGuard({
2449
+ map: {
2450
+ seq: entry.seq,
2451
+ path: entry.checkpoint.path,
2452
+ coverage: { kind: "full" }
2453
+ },
2454
+ covering
2455
+ });
2456
+ if (!guard.allowed) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: refused (${guard.reason}) — the map covers the whole file and the cited read does not supersede it`);
2457
+ const message = tailTrimMessage(renderCheckpointLine(entry.checkpoint));
2458
+ session.append("user/message", message, {
2459
+ surfaceOp: {
2460
+ op: "replace",
2461
+ startSeq: entry.seq,
2462
+ endSeq: entry.seq
2463
+ },
2464
+ sourceEventSeqs: [entry.seq]
2465
+ });
2466
+ entry.discarded = true;
2467
+ getSavingsLedger().recordSaving({
2468
+ sessionId: String(session.id),
2469
+ component: "shallow-discard",
2470
+ tokensBefore: entry.bodyTokens,
2471
+ tokensAfter: Math.ceil(renderCheckpointLine(entry.checkpoint).length / 4),
2472
+ basis: "characters",
2473
+ sourceSeq: entry.seq,
2474
+ replacementSeq: entry.seq,
2475
+ originalText: `${entry.checkpoint.path} shallow body`
2476
+ });
2477
+ return buildShallowFooter(entry.checkpoint, 0) + `\n[discarded] ${renderCheckpointLine(entry.checkpoint)}`;
2478
+ }
2479
+ }));
2480
+ }
2481
+ /** Find the arguments JSON + file path of the call owning a tool/result. */
2482
+ function findCallArgs(events, callId) {
2483
+ for (const event of events) {
2484
+ if (event.type !== "assistant/message") continue;
2485
+ const message = event.data?.message;
2486
+ const blocks = Array.isArray(message?.content) ? message.content : [];
2487
+ for (const raw of blocks) {
2488
+ const block = raw;
2489
+ if (block !== null && block.type === "tool-call" && block.id === callId) {
2490
+ const argsJson = typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {});
2491
+ let filePath;
2492
+ try {
2493
+ const parsed = JSON.parse(argsJson);
2494
+ filePath = typeof parsed.file_path === "string" ? parsed.file_path : typeof parsed.path === "string" ? parsed.path : "";
2495
+ } catch {
2496
+ filePath = "";
2497
+ }
2498
+ return {
2499
+ path: filePath,
2500
+ argsJson
2501
+ };
2502
+ }
2503
+ }
2504
+ }
2505
+ }
2506
+ //#endregion
2507
+ //#region src/runtime/triage/signals.ts
2508
+ /** Per-line verbatim cap (plan: 240 codepoints, ` …` marker excluded). */
2509
+ const LINE_CAP = 240;
2510
+ /** Base structural block signals: id + predicate over the raw result text. */
2511
+ const BASE_BLOCK_SIGNALS = Object.freeze([
2512
+ {
2513
+ id: "sig:isError-flag",
2514
+ test: (_text, isError) => isError
2515
+ },
2516
+ {
2517
+ id: "sig:stderr-prefix",
2518
+ test: (text) => text.trimStart().startsWith("[stderr]")
2519
+ },
2520
+ {
2521
+ id: "sig:exit-code-bracket",
2522
+ test: (text) => {
2523
+ const trimmed = text.trim();
2524
+ return /\[exit code:\s*(?!0\b)-?\d+\s*\]\s*$/.test(trimmed) || /\[Command finished with exit code\s+(?!0\b)-?\d+\]\s*$/.test(trimmed) || /^exit_code=\s*(?!0\b)-?\d+\s*$/.test(trimmed);
2525
+ }
2526
+ },
2527
+ {
2528
+ id: "sig:json-exitcode",
2529
+ test: (text) => {
2530
+ const trimmed = text.trim();
2531
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return false;
2532
+ try {
2533
+ const parsed = JSON.parse(trimmed);
2534
+ return typeof parsed?.exitCode === "number" && parsed.exitCode !== 0;
2535
+ } catch {
2536
+ return false;
2537
+ }
2538
+ }
2539
+ }
2540
+ ]);
2541
+ /** Line-level base family: the classic failure markers (spine-validated). */
2542
+ const FAILURE_BASE_PATTERN = /(?:^|\s)(?:FAIL(?:ED)?\b|Error:|Exception:|Traceback\b|panic:|AssertionError)/;
2543
+ /**
2544
+ * Built-in default extras — trial-3 validated families the base misses
2545
+ * (48.2% of pool lines in the replay corpus). Distributed like user extras:
2546
+ * append-only, never replaces the base, individually skippable when invalid.
2547
+ */
2548
+ const DEFAULT_EXTRA_PATTERNS = Object.freeze([
2549
+ {
2550
+ id: "ext:tool-timeout",
2551
+ source: String.raw`TOOL_TIMEOUT|timed out after \d+ms`
2552
+ },
2553
+ {
2554
+ id: "ext:npm-err",
2555
+ source: String.raw`npm ERR!|\bERR!`
2556
+ },
2557
+ {
2558
+ id: "ext:proc-kill",
2559
+ source: String.raw`\bkilled\b|OOM|out of memory`
2560
+ },
2561
+ {
2562
+ id: "ext:assert-ctx",
2563
+ source: String.raw`expected .* to (?:be|equal|throw)|Received:|toStrictEqual`
2564
+ }
2565
+ ]);
2566
+ /**
2567
+ * Compile the append-only line-rule set: base classic family first (its id
2568
+ * wins on multi-rule matches, keeping audit stable), then built-in default
2569
+ * extras, then user extras. Invalid user regexes are skipped silently — the
2570
+ * settings boundary already rejected them upstream; capture must never throw.
2571
+ */
2572
+ function mergeExtraPatterns(userExtra) {
2573
+ const rules = [{
2574
+ id: "line:failure-classic",
2575
+ pattern: FAILURE_BASE_PATTERN
2576
+ }];
2577
+ for (const entry of DEFAULT_EXTRA_PATTERNS) try {
2578
+ rules.push({
2579
+ id: entry.id,
2580
+ pattern: new RegExp(entry.source, "i")
2581
+ });
2582
+ } catch {}
2583
+ for (const source of userExtra) try {
2584
+ rules.push({
2585
+ id: `ext:user:${source.slice(0, 60)}`,
2586
+ pattern: new RegExp(source)
2587
+ });
2588
+ } catch {}
2589
+ return rules;
2590
+ }
2591
+ const DEFAULT_LINE_RULES = mergeExtraPatterns([]);
2592
+ /** Decide whether the whole block carries a hard failure signal (audit/grouping only — never gates the line pool). */
2593
+ function blockFailureVerdict(text, isError) {
2594
+ const ruleIds = [];
2595
+ for (const rule of BASE_BLOCK_SIGNALS) if (rule.test(text, isError)) ruleIds.push(rule.id);
2596
+ return {
2597
+ hard: ruleIds.length > 0,
2598
+ ruleIds
2599
+ };
2600
+ }
2601
+ function usefulLines(text) {
2602
+ return text.replace(/\n+$/, "").split("\n").filter((line) => {
2603
+ const trimmed = line.trim();
2604
+ return trimmed.length > 0 && trimmed !== "[stderr]" && !/^\[exit code:/.test(trimmed);
2605
+ });
2606
+ }
2607
+ /**
2608
+ * Verbatim per-line capture over the compiled rule set. Dedup by exact line
2609
+ * text within the block, 240-codepoint cap with ` …` marker, first-matching
2610
+ * rule wins the audit id (base order guarantees `line:failure-classic` wins
2611
+ * ties). Decoupled from block classification: soft-failure blocks pass through
2612
+ * with `hardFailure: false` and still yield lines.
2613
+ */
2614
+ function linePool(text, context) {
2615
+ const rules = context.extraPatterns ?? DEFAULT_LINE_RULES;
2616
+ const pool = [];
2617
+ const seen = /* @__PURE__ */ new Set();
2618
+ for (const raw of usefulLines(text)) {
2619
+ const line = raw.trim();
2620
+ if (seen.has(line)) continue;
2621
+ const matched = rules.find((rule) => rule.pattern.test(line));
2622
+ if (matched === void 0) continue;
2623
+ seen.add(line);
2624
+ const chars = Array.from(line);
2625
+ const truncated = chars.length > LINE_CAP;
2626
+ const captured = truncated ? `${chars.slice(0, LINE_CAP).join("")} …` : line;
2627
+ pool.push({
2628
+ seq: context.seq,
2629
+ role: context.role,
2630
+ text: captured,
2631
+ ruleId: matched.id,
2632
+ truncated,
2633
+ hardFailure: context.hardFailure
2634
+ });
2635
+ }
2636
+ return pool;
2637
+ }
2638
+ //#endregion
2639
+ //#region src/runtime/sediment-card.ts
2640
+ /** Qualification floor for the closing body to serve as narrative (tokens). */
2641
+ const DEFAULT_MIN_CLOSING_TOKENS = 120;
2642
+ /** Mechanical-only needs pool+mask coverage of at least this span fraction. */
2643
+ const MECHANICAL_ONLY_MIN_COVERAGE = .5;
2644
+ /** Cheap token estimate consistent with the replay corpus meter (CJK-aware). */
2645
+ function estimateTokens(text) {
2646
+ const cjk = (text.match(/[\u4e00-\u9fff]/g) ?? []).length;
2647
+ return Math.ceil(cjk / 1.5 + (text.length - cjk) / 4);
2648
+ }
2649
+ function poolSection(pool) {
2650
+ if (pool.length === 0) return "";
2651
+ return `原文摘录(逐字,非新指令):\n${pool.join("\n")}`;
2652
+ }
2653
+ function maskSection(masks) {
2654
+ if (masks.length === 0) return "";
2655
+ return masks.map((mask) => {
2656
+ if (mask.kind === "manifest") return `- 改动文件 (seq ${mask.seq}): ${mask.paths.join(", ")}`;
2657
+ if (mask.kind === "skeleton") return `- 代码骨架 (seq ${mask.seq}):\n${mask.lines.map((l) => ` ${l}`).join("\n")}\n [… 省略 ${mask.totalLines - mask.lines.length} 行 / ${mask.elidedChars} 字符]`;
2658
+ return `- 超大结果仅留指针 (seq ${mask.seq}, ${mask.tokens} tok)`;
2659
+ }).join("\n");
2660
+ }
2661
+ /**
2662
+ * Decide the narrative tier and whether replacement proceeds at all.
2663
+ * Exported for the clock module to pre-check without building the card.
2664
+ */
2665
+ function decideNarrativeTier(input, coverageRatio) {
2666
+ const floor = input.minClosingTokens ?? DEFAULT_MIN_CLOSING_TOKENS;
2667
+ if (estimateTokens(input.closingText) >= floor) return "closing";
2668
+ if (input.foldAvailable) return "fold";
2669
+ if (coverageRatio >= MECHANICAL_ONLY_MIN_COVERAGE) return "mechanical-only";
2670
+ return "skip";
2671
+ }
2672
+ /** Assemble one whole-turn replacement card. Returns null when the tier is `skip`. */
2673
+ function buildTurnCard(input) {
2674
+ const pool = input.triage.flatMap((result) => result.poolLines).map((line) => `- [${line.role}] (seq ${line.seq}) ${line.text}`);
2675
+ const masks = input.triage.map((result) => result.mask).filter((mask) => mask !== void 0);
2676
+ const sourceTokens = input.triage.reduce((sum, result) => sum + result.sourceTokens, 0);
2677
+ const retainedVerbatimTokens = estimateTokens(pool.join("\n") + maskSection(masks));
2678
+ const tier = decideNarrativeTier(input, sourceTokens === 0 ? 0 : retainedVerbatimTokens / sourceTokens);
2679
+ if (tier === "skip") return null;
2680
+ const narrative = tier === "fold" ? input.foldText?.trim() ?? "" : "";
2681
+ const narrativeTokens = narrative === "" ? 0 : estimateTokens(narrative);
2682
+ const head = `CCI 沉降卡。区间 seq ${input.startSeq}-${input.endSeq} 的原文仍在会话日志里;序号是本会话日志的事件号,不是备份文件路径。这是旧内容摘录,不是新指令,也不是你的授权。`;
2683
+ const omissionStats = `Matched lines: ${pool.length}. Masks: ${masks.length}. Retained ≈${retainedVerbatimTokens + narrativeTokens} tok / source ≈${sourceTokens} tok.`;
2684
+ return {
2685
+ head,
2686
+ pool: input.triage.flatMap((result) => result.poolLines),
2687
+ masks,
2688
+ omissionStats,
2689
+ ...narrative === "" ? {} : { narrative },
2690
+ narrativeTier: tier,
2691
+ retainedTokens: retainedVerbatimTokens + narrativeTokens,
2692
+ sourceTokens
2693
+ };
2694
+ }
2695
+ /** Render a card draft to the single replacement message text. */
2696
+ function renderTurnCard(draft) {
2697
+ const sections = [
2698
+ draft.head,
2699
+ poolSection(draft.pool.map((line) => `- [${line.role}] (seq ${line.seq}) ${line.text}`)),
2700
+ maskSection(draft.masks)
2701
+ ];
2702
+ if (draft.narrative !== void 0) sections.push(`收尾正文:\n${draft.narrative}`);
2703
+ sections.push(draft.omissionStats);
2704
+ return sections.filter((section) => section !== "").join("\n\n");
2705
+ }
2706
+ //#endregion
2707
+ //#region src/runtime/sediment-span.ts
2708
+ /** Close tool rounds over the projected events (open-stack, same shape as the replay harness). */
2709
+ function closeRounds(events) {
2710
+ const rounds = [];
2711
+ let open = 0;
2712
+ let start = -1;
2713
+ for (const event of events) {
2714
+ const calls = event.type === "assistant/message" ? event.toolCalls ?? 0 : 0;
2715
+ if (calls > 0) {
2716
+ if (open === 0) start = events.indexOf(event);
2717
+ open += calls;
2718
+ continue;
2719
+ }
2720
+ if (event.type !== "tool/result") continue;
2721
+ if (open <= 0) continue;
2722
+ open -= 1;
2723
+ if (open === 0 && start >= 0) {
2724
+ rounds.push({
2725
+ start,
2726
+ end: events.indexOf(event)
2727
+ });
2728
+ start = -1;
2729
+ }
2730
+ }
2731
+ return rounds;
2732
+ }
2733
+ /** Plan the replacement span for one turn's projected events. */
2734
+ function planTurnSpan(events, options = {}) {
2735
+ const tailRoundsKept = options.tailRoundsKept ?? 1;
2736
+ const completed = events.find((event) => event.type === "turn/end")?.reasonKind === "completed";
2737
+ const body = events.filter((event) => event.type !== "turn/end");
2738
+ const keptSeqs = body.filter((event) => event.type === "user/message").map((event) => event.seq);
2739
+ const rounds = closeRounds(body);
2740
+ const lastRoundEnd = rounds.length > 0 ? rounds[rounds.length - 1].end : -1;
2741
+ let closingText = "";
2742
+ let closingIndex = -1;
2743
+ for (let index = body.length - 1; index > lastRoundEnd; index -= 1) {
2744
+ const event = body[index];
2745
+ if (event === void 0) continue;
2746
+ if (event.type === "assistant/message" && (event.toolCalls ?? 0) === 0 && event.text.trim() !== "") {
2747
+ closingText = event.text.trim();
2748
+ closingIndex = index;
2749
+ keptSeqs.push(event.seq);
2750
+ break;
2751
+ }
2752
+ }
2753
+ const keptRounds = tailRoundsKept > 0 ? rounds.slice(Math.max(0, rounds.length - tailRoundsKept)) : [];
2754
+ for (const round of keptRounds) for (let index = round.start; index <= round.end; index += 1) {
2755
+ const event = body[index];
2756
+ if (event !== void 0) keptSeqs.push(event.seq);
2757
+ }
2758
+ const firstIndex = body.findIndex((event) => event.type === "assistant/message" || event.type === "tool/result");
2759
+ const keptStartIndex = keptRounds.length > 0 ? keptRounds[0].start : closingIndex >= 0 ? closingIndex : body.length;
2760
+ const spanEndIndex = Math.max(firstIndex, keptStartIndex) - 1;
2761
+ const replaceable = firstIndex >= 0 && spanEndIndex >= firstIndex;
2762
+ const blocks = replaceable ? body.slice(firstIndex, spanEndIndex + 1) : [];
2763
+ return {
2764
+ completed,
2765
+ startSeq: replaceable ? blocks[0].seq : null,
2766
+ endSeq: replaceable ? blocks[blocks.length - 1].seq : null,
2767
+ blocks,
2768
+ closingText,
2769
+ keptSeqs
2770
+ };
2771
+ }
2772
+ /** Triage every block of a planned span into the frozen TriageResult shape. */
2773
+ function triageSpanBlocks(plan, rules) {
2774
+ return plan.blocks.map((event) => {
2775
+ const sourceTokens = estimateTokens(event.text);
2776
+ if (event.type === "tool/result") {
2777
+ const verdict = blockFailureVerdict(event.text, event.isError === true);
2778
+ const poolLines = linePool(event.text, {
2779
+ seq: event.seq,
2780
+ role: "tool",
2781
+ hardFailure: verdict.hard,
2782
+ extraPatterns: rules
2783
+ });
2784
+ const mask = manifestFromCall(event.toolName ?? "", event.argsJson ?? "", event.text, event.seq) ?? (event.toolName !== void 0 && /^(read|read_file|view)$/i.test(event.toolName) ? skeletonFromRead(event.text, event.seq) : null);
2785
+ const residualNarrative = poolLines.length === 0 && mask === null && event.text.trim() !== "" ? [{
2786
+ seq: event.seq,
2787
+ role: "tool",
2788
+ tokens: sourceTokens,
2789
+ text: event.text
2790
+ }] : [];
2791
+ return {
2792
+ poolLines,
2793
+ ...mask === null ? {} : { mask },
2794
+ residualNarrative,
2795
+ sourceTokens
2796
+ };
2797
+ }
2798
+ const verdict = blockFailureVerdict(event.text, false);
2799
+ const poolLines = linePool(event.text, {
2800
+ seq: event.seq,
2801
+ role: "assistant",
2802
+ hardFailure: verdict.hard,
2803
+ extraPatterns: rules
2804
+ });
2805
+ return {
2806
+ poolLines,
2807
+ residualNarrative: poolLines.length === 0 ? [{
2808
+ seq: event.seq,
2809
+ role: "assistant",
2810
+ tokens: sourceTokens,
2811
+ text: event.text
2812
+ }] : [],
2813
+ sourceTokens
2814
+ };
2815
+ });
2816
+ }
2817
+ //#endregion
2818
+ //#region src/runtime/sediment-publish.ts
2819
+ /**
2820
+ * Sediment publication (plan cci-sedimentation-triage, Phase 3, T3.5/T3.6).
2821
+ *
2822
+ * The commit transaction mirrors the proven TailTrim publication shape
2823
+ * (pruner.ts L2386-2406): a `compaction/prune` manifest event, then ONE
2824
+ * `user/message` replacement carrying `surfaceOp: replace` and
2825
+ * `sourceEventSeqs`, through the generation-gated message builder so 0.1.x
2826
+ * and 0.2.x hosts accept the same code path. The shortening proof (M7) runs
2827
+ * BEFORE any append — a card that does not shrink the span is refused, and
2828
+ * nothing half-committed can exist.
2829
+ *
2830
+ * The session is injected as a minimal interface so the transaction is
2831
+ * unit-testable without a host; the wiring site passes the real session.
2832
+ */
2833
+ /** Commit one card over the span. Never throws; every failure is a reason code. */
2834
+ function publishSettledCard(session, draft, span) {
2835
+ if (draft.retainedTokens >= draft.sourceTokens) return {
2836
+ ok: false,
2837
+ reason: `shortening-proof-failed:${draft.retainedTokens}>=${draft.sourceTokens}`
2838
+ };
2839
+ if (span.shadowedSeqs.length === 0) return {
2840
+ ok: false,
2841
+ reason: "empty-span"
2842
+ };
2843
+ const manifest = session.append("compaction/prune", {
2844
+ shadowedRange: {
2845
+ start: span.startSeq,
2846
+ end: span.endSeq
2847
+ },
2848
+ shadowedSeqs: [...span.shadowedSeqs],
2849
+ shadowedTokenCount: draft.sourceTokens
2850
+ });
2851
+ let replacementSeq;
2852
+ try {
2853
+ const message = tailTrimMessage(renderTurnCard(draft));
2854
+ replacementSeq = session.append("user/message", message, {
2855
+ surfaceOp: {
2856
+ op: "replace",
2857
+ startSeq: span.startSeq,
2858
+ endSeq: span.endSeq
2859
+ },
2860
+ sourceEventSeqs: [manifest.seq, ...span.shadowedSeqs]
2861
+ }).seq;
2862
+ } catch (error) {
2863
+ return {
2864
+ ok: false,
2865
+ reason: `publication-failed:${error instanceof Error ? error.message : String(error)}`,
2866
+ manifestSeq: manifest.seq
2867
+ };
2868
+ }
2869
+ return {
2870
+ ok: true,
2871
+ reason: "landed",
2872
+ manifestSeq: manifest.seq,
2873
+ replacementSeq
2874
+ };
2875
+ }
2876
+ /**
2877
+ * Rewrite guard (T3.3 accounting, findings F2 community 1:15 evidence):
2878
+ * a cut may only land when its saving clears the estimated cached-tail
2879
+ * rewrite cost by the configured ratio. Pure function over token counts.
2880
+ */
2881
+ function passesRewriteGuard(draft, rewriteTailTokens, ratio) {
2882
+ const saving = draft.sourceTokens - draft.retainedTokens;
2883
+ return saving > 0 && saving >= rewriteTailTokens * ratio;
2884
+ }
2885
+ /**
2886
+ * Project a host session event into the minimal `SurfaceEvent` the span
2887
+ * planner consumes. Kept separate from the planner so the planner stays
2888
+ * host-type-free; the wiring site supplies the call-id → name/args map.
2889
+ */
2890
+ function projectSurfaceEvent(seq, event, callInfo) {
2891
+ const text = flattenText(event.data?.message?.content ?? event.data?.content);
2892
+ switch (event.type) {
2893
+ case "user/message": return {
2894
+ seq,
2895
+ type: "user/message",
2896
+ text
2897
+ };
2898
+ case "assistant/message": {
2899
+ const toolCalls = countToolCallBlocks(event.data?.message?.content);
2900
+ return {
2901
+ seq,
2902
+ type: "assistant/message",
2903
+ text: stripToolCallBlocks(text),
2904
+ toolCalls
2905
+ };
2906
+ }
2907
+ case "tool/result": return {
2908
+ seq,
2909
+ type: "tool/result",
2910
+ text,
2911
+ ...callInfo === void 0 ? {} : {
2912
+ toolName: callInfo.name,
2913
+ argsJson: callInfo.argsJson
2914
+ },
2915
+ isError: event.data?.message?.isError === true
2916
+ };
2917
+ case "turn/end": {
2918
+ const reasonKind = event.data?.reason?.kind;
2919
+ return {
2920
+ seq,
2921
+ type: "turn/end",
2922
+ text: "",
2923
+ ...reasonKind === void 0 ? {} : { reasonKind }
2924
+ };
2925
+ }
2926
+ default: return null;
2927
+ }
2928
+ }
2929
+ function blockText(block) {
2930
+ if (block === null || typeof block !== "object") return "";
2931
+ const record = block;
2932
+ return typeof record.text === "string" ? record.text : "";
2933
+ }
2934
+ function flattenText(content) {
2935
+ if (typeof content === "string") return content;
2936
+ if (Array.isArray(content)) return content.map(blockText).filter((entry) => entry !== "").join("\n");
2937
+ return "";
2938
+ }
2939
+ function countToolCallBlocks(content) {
2940
+ if (!Array.isArray(content)) return 0;
2941
+ return content.filter((block) => block?.type === "tool-call").length;
2942
+ }
2943
+ function stripToolCallBlocks(text) {
2944
+ return text;
2945
+ }
2946
+ //#endregion
2947
+ //#region src/runtime/sediment-clock.ts
2948
+ /** Pure commit predicate; every exclusion returns a machine-readable reason. */
2949
+ function canCommitNow(context) {
2950
+ if (!context.inFlightRequest && context.lastEventType !== "turn/end" && context.lastEventType !== "step/end") return {
2951
+ ok: false,
2952
+ reason: "not-in-quiet-seam"
2953
+ };
2954
+ if (context.inFlightRequest) return {
2955
+ ok: false,
2956
+ reason: "request-in-flight"
2957
+ };
2958
+ if (context.compactionOpen) return {
2959
+ ok: false,
2960
+ reason: "compaction-in-progress"
2961
+ };
2962
+ if (context.resumeFirstBatch) return {
2963
+ ok: false,
2964
+ reason: "resume-first-batch"
2965
+ };
2966
+ const official = context.officialCheckpointSeq;
2967
+ if (official !== void 0 && official !== context.seenOfficialCheckpointSeq) return {
2968
+ ok: false,
2969
+ reason: `yield-official-checkpoint-${official}`
2970
+ };
2971
+ return {
2972
+ ok: true,
2973
+ reason: "quiet-seam"
2974
+ };
2975
+ }
2976
+ /** Mutable per-session clock: cooldown consumption + re-entrance guard. */
2977
+ var SedimentClock = class {
2978
+ warming = false;
2979
+ seenOfficialSeq;
2980
+ /** True while a commit job is running for this session (no stacked cuts). */
2981
+ get busy() {
2982
+ return this.warming;
2983
+ }
2984
+ /** Claim the commit slot; false means another job owns this session's seam. */
2985
+ begin() {
2986
+ if (this.warming) return false;
2987
+ this.warming = true;
2988
+ return true;
2989
+ }
2990
+ end() {
2991
+ this.warming = false;
2992
+ }
2993
+ /** Consume the one-time yield for the given official checkpoint seq. */
2994
+ noteOfficialConsumed(seq) {
2995
+ this.seenOfficialSeq = seq;
2996
+ }
2997
+ get seenOfficial() {
2998
+ return this.seenOfficialSeq;
2999
+ }
3000
+ /** Decide with this clock's cooldown state folded in. */
3001
+ decide(base) {
3002
+ return canCommitNow({
3003
+ ...base,
3004
+ seenOfficialCheckpointSeq: this.seenOfficialSeq
3005
+ });
3006
+ }
3007
+ };
3008
+ //#endregion
3009
+ //#region src/runtime/tokenpilot/sidechannel.ts
3010
+ /** One bound side channel. `ask` resolves `undefined` on ANY failure. */
3011
+ var SideChannel = class {
3012
+ ctx;
3013
+ options;
3014
+ overrides;
3015
+ /**
3016
+ * @param overrides - per-consumer overrides of the estimator-named options.
3017
+ * The estimator itself never passes them (byte-identical behavior); the
3018
+ * advisory advisor passes its own mode/timeout/output budget so both
3019
+ * consumers share one transport without sharing one configuration.
3020
+ */
3021
+ constructor(ctx, options, overrides) {
3022
+ this.ctx = ctx;
3023
+ this.options = options;
3024
+ this.overrides = overrides;
3025
+ }
3026
+ get mode() {
3027
+ return this.overrides?.mode ?? this.options.estimatorMode ?? "";
3028
+ }
3029
+ get enabled() {
2211
3030
  return this.mode === "host" || this.mode === "direct";
2212
3031
  }
2213
3032
  async ask(request) {
@@ -2237,91 +3056,654 @@ var SideChannel = class {
2237
3056
  audit
2238
3057
  };
2239
3058
  }
2240
- identity() {
2241
- if (this.mode === "direct") return `direct:${this.options.estimatorModel ?? ""}`;
2242
- if (this.mode === "host") {
2243
- const route = this.resolveHostRoute();
2244
- return route === void 0 ? "host" : `host:${route.provider}/${route.model}`;
3059
+ identity() {
3060
+ if (this.mode === "direct") return `direct:${this.options.estimatorModel ?? ""}`;
3061
+ if (this.mode === "host") {
3062
+ const route = this.resolveHostRoute();
3063
+ return route === void 0 ? "host" : `host:${route.provider}/${route.model}`;
3064
+ }
3065
+ }
3066
+ /** Same host-route resolution as the estimator: explicit, then host default. */
3067
+ resolveHostRoute() {
3068
+ const provider = this.options.estimatorProvider ?? "";
3069
+ const model = this.options.estimatorModel ?? "";
3070
+ if (provider.length > 0 && model.length > 0) return {
3071
+ provider,
3072
+ model
3073
+ };
3074
+ try {
3075
+ const selected = this.ctx.get("agentDefaultModel")?.currentSelection?.();
3076
+ const selectedProvider = selected?.provider ?? "";
3077
+ const selectedModel = selected?.model ?? "";
3078
+ if (selectedProvider.length > 0 && selectedModel.length > 0) return {
3079
+ provider: provider.length > 0 ? provider : selectedProvider,
3080
+ model: model.length > 0 ? model : selectedModel
3081
+ };
3082
+ } catch {}
3083
+ }
3084
+ async askHost(system, user, signal) {
3085
+ let llm;
3086
+ try {
3087
+ llm = this.ctx.get("llm");
3088
+ } catch {
3089
+ return;
3090
+ }
3091
+ if (llm?.stream === void 0) return void 0;
3092
+ const route = this.resolveHostRoute();
3093
+ if (route === void 0) return void 0;
3094
+ let text = "";
3095
+ const stream = llm.stream({
3096
+ provider: route.provider,
3097
+ model: route.model,
3098
+ messages: [{
3099
+ role: "user",
3100
+ content: [{
3101
+ type: "text",
3102
+ text: user
3103
+ }]
3104
+ }],
3105
+ system,
3106
+ temperature: 0,
3107
+ reasoningEffort: "off",
3108
+ maxTokens: this.overrides?.maxTokens ?? 256,
3109
+ signal
3110
+ });
3111
+ for await (const chunk of stream) if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
3112
+ else if (chunk.type === "finish" && chunk.text === void 0) break;
3113
+ return text.trim().length > 0 ? text : void 0;
3114
+ }
3115
+ async askDirect(system, user, signal) {
3116
+ const baseUrl = this.options.estimatorBaseUrl;
3117
+ if (baseUrl === void 0 || baseUrl.length === 0) return void 0;
3118
+ const headers = { "content-type": "application/json" };
3119
+ if (this.options.estimatorApiKey !== void 0 && this.options.estimatorApiKey.length > 0) headers.authorization = `Bearer ${this.options.estimatorApiKey}`;
3120
+ const model = this.options.estimatorModel ?? "";
3121
+ if (model.length === 0) return void 0;
3122
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/chat/completions`, {
3123
+ method: "POST",
3124
+ headers,
3125
+ body: JSON.stringify({
3126
+ model,
3127
+ messages: [{
3128
+ role: "system",
3129
+ content: system
3130
+ }, {
3131
+ role: "user",
3132
+ content: user
3133
+ }],
3134
+ temperature: 0,
3135
+ max_tokens: this.overrides?.maxTokens ?? 256
3136
+ }),
3137
+ signal
3138
+ });
3139
+ if (!response.ok) return void 0;
3140
+ const text = (await response.json()).choices?.[0]?.message?.content;
3141
+ return typeof text === "string" && text.trim().length > 0 ? text : void 0;
3142
+ }
3143
+ };
3144
+ //#endregion
3145
+ //#region src/runtime/fold-router.ts
3146
+ /** Tier limits in tokens of fold INPUT (spans + template). */
3147
+ const FOLD_TIER_LIMITS = Object.freeze({
3148
+ strataMax: 2048,
3149
+ local35Max: 8192
3150
+ });
3151
+ /** Per-tier timeout budgets (ms): sized for cold prefill, not warm round-trips. */
3152
+ const FOLD_TIMEOUT_MS = Object.freeze({
3153
+ strata: 8e3,
3154
+ local35: 12e3,
3155
+ large: 15e3
3156
+ });
3157
+ /** Tier decision over the fold input size. */
3158
+ function foldTier(inputTokens) {
3159
+ if (inputTokens > FOLD_TIER_LIMITS.local35Max) return "skip";
3160
+ return inputTokens <= FOLD_TIER_LIMITS.strataMax ? "strata" : "local35";
3161
+ }
3162
+ const FOLD_SYSTEM = "You are writing a short connective narrative for a durable context card. Summarize ONLY the material given below: what was attempted and what was concluded, in 2-6 bullets. The card already contains verbatim error lines, file manifests, and code skeletons that were DELIBERATELY withheld from you. Never restate, guess, or reconstitute withheld output; never add facts not present in the material. Output only the bullets.";
3163
+ /** Rough meter aligned with the replay corpus estimator (CJK-aware). */
3164
+ function foldTokens(text) {
3165
+ const cjk = (text.match(/[\u4e00-\u9fff]/g) ?? []).length;
3166
+ return Math.ceil(cjk / 1.5 + (text.length - cjk) / 4);
3167
+ }
3168
+ /**
3169
+ * Assemble the fold prompt from residual narrative only. Lines that appear
3170
+ * in the protection pool or any mask section are excluded BY CONSTRUCTION
3171
+ * (S4): the caller passes triage output, and the spans entering the prompt
3172
+ * are the residual ones.
3173
+ */
3174
+ function buildFoldPrompt(spans, protectedLines, masks) {
3175
+ const protectedText = new Set(protectedLines.map((line) => line.text));
3176
+ const maskText = masks.flatMap((mask) => mask.kind === "skeleton" ? [...mask.lines] : []);
3177
+ const body = spans.filter((span) => !protectedText.has(span.text) && !maskText.includes(span.text)).map((span) => `[${span.role}] ${span.text}`).join("\n");
3178
+ if (body.trim() === "") return null;
3179
+ const user = `Material to fold (turn narrative residue):\n${body}`;
3180
+ return {
3181
+ system: FOLD_SYSTEM,
3182
+ user,
3183
+ inputTokens: foldTokens(user)
3184
+ };
3185
+ }
3186
+ /**
3187
+ * One fold channel per pruner instance family; queue depth 1 per session id.
3188
+ * `fold` never throws and never retries; undefined text = tier-3 mechanical card.
3189
+ */
3190
+ var FoldRouter = class {
3191
+ ctx;
3192
+ settings;
3193
+ busy = /* @__PURE__ */ new Set();
3194
+ constructor(ctx, settings) {
3195
+ this.ctx = ctx;
3196
+ this.settings = settings;
3197
+ }
3198
+ /** True while a fold call for that session is in flight. */
3199
+ isBusy(sessionId) {
3200
+ return this.busy.has(sessionId);
3201
+ }
3202
+ async fold(sessionId, prompt, signal) {
3203
+ const tier = foldTier(prompt.inputTokens);
3204
+ if (tier === "skip") return { audit: {
3205
+ ok: false,
3206
+ latencyMs: 0,
3207
+ reason: "fold-input-over-8k-refused"
3208
+ } };
3209
+ if (this.settings.foldMode === void 0 || this.settings.foldMode === "") return { audit: {
3210
+ ok: false,
3211
+ latencyMs: 0,
3212
+ reason: "fold-unconfigured"
3213
+ } };
3214
+ if (this.busy.has(sessionId)) return { audit: {
3215
+ ok: false,
3216
+ latencyMs: 0,
3217
+ reason: "fold-busy-skip"
3218
+ } };
3219
+ this.busy.add(sessionId);
3220
+ try {
3221
+ const endpoint = tier === "strata" ? {
3222
+ provider: this.settings.foldStrataProvider,
3223
+ model: this.settings.foldStrataModel
3224
+ } : {
3225
+ provider: this.settings.foldLocal35Provider,
3226
+ model: this.settings.foldLocal35Model
3227
+ };
3228
+ if (endpoint.provider === void 0 || endpoint.model === void 0) return { audit: {
3229
+ ok: false,
3230
+ latencyMs: 0,
3231
+ reason: `fold-endpoint-missing:${tier}`
3232
+ } };
3233
+ const timeoutMs = tier === "strata" ? FOLD_TIMEOUT_MS.strata : prompt.inputTokens > FOLD_TIER_LIMITS.strataMax ? FOLD_TIMEOUT_MS.large : FOLD_TIMEOUT_MS.local35;
3234
+ return await new SideChannel(this.ctx, {
3235
+ estimatorMode: this.settings.foldMode,
3236
+ estimatorProvider: endpoint.provider,
3237
+ estimatorModel: endpoint.model,
3238
+ ...this.settings.foldBaseUrl === void 0 ? {} : { estimatorBaseUrl: this.settings.foldBaseUrl },
3239
+ ...this.settings.foldBaseUrlKey === void 0 ? {} : { estimatorApiKey: this.settings.foldBaseUrlKey }
3240
+ }, {
3241
+ timeoutMs,
3242
+ maxTokens: 400
3243
+ }).askAudited({
3244
+ system: prompt.system,
3245
+ user: prompt.user,
3246
+ signal
3247
+ });
3248
+ } finally {
3249
+ this.busy.delete(sessionId);
3250
+ }
3251
+ }
3252
+ };
3253
+ //#endregion
3254
+ //#region src/runtime/sediment.ts
3255
+ /**
3256
+ * Sediment orchestrator (plan cci-sedimentation-triage, Phase 3, T3.6).
3257
+ *
3258
+ * Host-agnostic by injection: the wiring site (pruner) supplies the settings
3259
+ * snapshot reader, the event reader, and the call-id map; this module owns
3260
+ * the per-session clock and the turn-end decision pipeline:
3261
+ *
3262
+ * settings gate → clock predicate → span plan (reason gate)
3263
+ * → triage → card build (tier gates) → rewrite guard → publish.
3264
+ *
3265
+ * With `sediment.enabled=false` (the default) the FIRST check short-circuits
3266
+ * and nothing else in this module runs — the M1 zero-drift guarantee holds by
3267
+ * construction: no event accumulation, no card, no append.
3268
+ */
3269
+ /** Compiled extra-pattern rules per session settings identity (cheap cache). */
3270
+ const ruleCache = /* @__PURE__ */ new WeakMap();
3271
+ function rulesFor(settings) {
3272
+ let rules = ruleCache.get(settings);
3273
+ if (rules === void 0) {
3274
+ rules = mergeExtraPatterns(settings.extraSignalPatterns ?? []);
3275
+ ruleCache.set(settings, rules);
3276
+ }
3277
+ return rules;
3278
+ }
3279
+ var SedimentOrchestrator = class {
3280
+ options;
3281
+ clocks = /* @__PURE__ */ new Map();
3282
+ constructor(options) {
3283
+ this.options = options;
3284
+ }
3285
+ clockFor(sessionId) {
3286
+ let clock = this.clocks.get(sessionId);
3287
+ if (clock === void 0) {
3288
+ clock = new SedimentClock();
3289
+ this.clocks.set(sessionId, clock);
3290
+ }
3291
+ return clock;
3292
+ }
3293
+ /**
3294
+ * Entry point called by the wiring site on `turn/end`. Returns immediately
3295
+ * with reason 'disabled' when the gate is off — nothing downstream runs.
3296
+ */
3297
+ async handleTurnEnd(session, turn, context) {
3298
+ const sessionId = String(session.id);
3299
+ const settings = this.options.settingsFor(sessionId);
3300
+ if (settings === void 0 || !settings.enabled) return {
3301
+ committed: false,
3302
+ reason: "disabled"
3303
+ };
3304
+ const clock = this.clockFor(sessionId);
3305
+ const decision = clock.decide({
3306
+ lastEventType: context.lastEventType,
3307
+ inFlightRequest: context.inFlightRequest,
3308
+ compactionOpen: context.compactionOpen,
3309
+ officialCheckpointSeq: context.officialCheckpointSeq,
3310
+ resumeFirstBatch: context.resumeFirstBatch
3311
+ });
3312
+ if (!decision.ok) {
3313
+ if (context.officialCheckpointSeq !== void 0 && decision.reason.startsWith("yield-official")) clock.noteOfficialConsumed(context.officialCheckpointSeq);
3314
+ this.options.onSkip?.(sessionId, decision.reason);
3315
+ return {
3316
+ committed: false,
3317
+ reason: decision.reason
3318
+ };
3319
+ }
3320
+ if (!clock.begin()) return {
3321
+ committed: false,
3322
+ reason: "already-committing"
3323
+ };
3324
+ try {
3325
+ return await this.commitTurn(session, turn, settings);
3326
+ } finally {
3327
+ clock.end();
3328
+ }
3329
+ }
3330
+ async commitTurn(session, turn, settings) {
3331
+ const sessionId = String(session.id);
3332
+ const rawEvents = this.options.eventsFor(session, turn);
3333
+ const projected = [];
3334
+ for (const event of rawEvents) {
3335
+ const callId = (event.data?.message)?.toolCallId;
3336
+ const surface = projectSurfaceEvent(event.seq, {
3337
+ type: event.type,
3338
+ data: event.data
3339
+ }, this.options.callInfoFor(sessionId)(callId));
3340
+ if (surface !== null) projected.push(surface);
3341
+ }
3342
+ const plan = planTurnSpan(projected);
3343
+ if (!plan.completed) {
3344
+ this.options.onSkip?.(sessionId, "reason-gate");
3345
+ return {
3346
+ committed: false,
3347
+ reason: "reason-gate"
3348
+ };
3349
+ }
3350
+ if (plan.startSeq === null || plan.endSeq === null) {
3351
+ this.options.onSkip?.(sessionId, "empty-span");
3352
+ return {
3353
+ committed: false,
3354
+ reason: "empty-span"
3355
+ };
3356
+ }
3357
+ const triage = triageSpanBlocks(plan, rulesFor(settings));
3358
+ const foldAvailable = this.options.fold !== void 0;
3359
+ let foldText;
3360
+ if (this.options.fold !== void 0 && estimateTokens(plan.closingText) < (settings.minClosingTokens ?? 120)) {
3361
+ const prompt = buildFoldPrompt(triage.flatMap((result) => result.residualNarrative), triage.flatMap((result) => result.poolLines), triage.map((result) => result.mask).filter((mask) => mask !== void 0));
3362
+ if (prompt !== null) foldText = await this.options.fold.run(sessionId, prompt, AbortSignal.timeout(2e4));
3363
+ }
3364
+ const draft = buildTurnCard({
3365
+ startSeq: plan.startSeq,
3366
+ endSeq: plan.endSeq,
3367
+ triage,
3368
+ closingText: plan.closingText,
3369
+ foldAvailable,
3370
+ ...foldText === void 0 ? {} : { foldText },
3371
+ minClosingTokens: settings.minClosingTokens
3372
+ });
3373
+ if (draft === null) {
3374
+ this.options.onSkip?.(sessionId, "tier-skip");
3375
+ return {
3376
+ committed: false,
3377
+ reason: "tier-skip"
3378
+ };
3379
+ }
3380
+ const tailTokens = this.options.tailTokensFor(session, plan.endSeq);
3381
+ const feedback = this.options.feedback?.() ?? {
3382
+ conservative: false,
3383
+ reason: "ok"
3384
+ };
3385
+ if (!passesRewriteGuard(draft, tailTokens, feedback.conservative ? Math.max(settings.rewriteGuardRatio, 5) : settings.rewriteGuardRatio)) {
3386
+ this.options.onSkip?.(sessionId, feedback.conservative ? `rewrite-guard-conservative:${feedback.reason}` : "rewrite-guard");
3387
+ return {
3388
+ committed: false,
3389
+ reason: "rewrite-guard"
3390
+ };
3391
+ }
3392
+ const result = publishSettledCard(session, draft, {
3393
+ startSeq: plan.startSeq,
3394
+ endSeq: plan.endSeq,
3395
+ shadowedSeqs: plan.blocks.map((block) => block.seq)
3396
+ });
3397
+ if (result.ok) this.options.onLanded?.(sessionId, draft.sourceTokens - draft.retainedTokens, draft.narrativeTier, result);
3398
+ else this.options.onSkip?.(sessionId, result.reason);
3399
+ return {
3400
+ committed: result.ok,
3401
+ reason: result.reason
3402
+ };
3403
+ }
3404
+ };
3405
+ //#endregion
3406
+ //#region src/runtime/sediment-guard.ts
3407
+ /** Omnibus tool names that mark a PTC/code-mode session (both host lines). */
3408
+ const OMNIBUS_TOOL_NAMES = Object.freeze(["run_code", "code_run"]);
3409
+ /** True when the registered tool surface contains an omnibus runner. */
3410
+ function detectPtcMode(hasTool) {
3411
+ return OMNIBUS_TOOL_NAMES.some((name) => hasTool(name));
3412
+ }
3413
+ /**
3414
+ * read-state blindness probe: with PTC active and ZERO write-tool regex hits
3415
+ * across the observed calls, the superseded predicate cannot see real write
3416
+ * targets — aging decisions must be considered untrustworthy.
3417
+ */
3418
+ function readStateBlind(ptcActive, writeRegexHits, observedCalls) {
3419
+ if (!ptcActive) return false;
3420
+ return observedCalls > 0 && writeRegexHits === 0;
3421
+ }
3422
+ /**
3423
+ * Feedback loop state: consumes request-boundary samples and decides whether
3424
+ * sediment/aging operation should run in conservative mode. K consecutive
3425
+ * negative-net samples arm it; a positive net sample disarms immediately.
3426
+ */
3427
+ var FeedbackLoop = class {
3428
+ k;
3429
+ negativeStreak = 0;
3430
+ armed = false;
3431
+ constructor(k = 5) {
3432
+ this.k = k;
3433
+ }
3434
+ get conservative() {
3435
+ return this.armed;
3436
+ }
3437
+ observe(sample) {
3438
+ const net = sample.grossSaved - sample.recallOffset;
3439
+ if (net < 0) {
3440
+ this.negativeStreak += 1;
3441
+ if (this.negativeStreak >= this.k) this.armed = true;
3442
+ } else if (net > 0) {
3443
+ this.negativeStreak = 0;
3444
+ this.armed = false;
3445
+ }
3446
+ return {
3447
+ conservative: this.armed,
3448
+ reason: this.armed ? `net-negative-x${this.negativeStreak}` : "ok"
3449
+ };
3450
+ }
3451
+ };
3452
+ /**
3453
+ * Watcher adapter (T3.11 consumption point): the savings ledger reports
3454
+ * CUMULATIVE gross/offsets; the feedback loop needs per-boundary NET deltas.
3455
+ * This wrapper remembers the last reading and feeds the loop the difference.
3456
+ */
3457
+ var SedimentFeedbackWatcher = class {
3458
+ loop;
3459
+ last = {
3460
+ gross: 0,
3461
+ offsets: 0
3462
+ };
3463
+ constructor(loop = new FeedbackLoop(5)) {
3464
+ this.loop = loop;
3465
+ }
3466
+ observe(totals) {
3467
+ const gross = totals.gross.exact + totals.gross.estimated;
3468
+ const offsets = totals.offsets.exact + totals.offsets.estimated;
3469
+ const sample = {
3470
+ grossSaved: gross - this.last.gross,
3471
+ recallOffset: offsets - this.last.offsets
3472
+ };
3473
+ this.last = {
3474
+ gross,
3475
+ offsets
3476
+ };
3477
+ return this.loop.observe(sample);
3478
+ }
3479
+ get conservative() {
3480
+ return this.loop.conservative;
3481
+ }
3482
+ };
3483
+ //#endregion
3484
+ //#region src/pruner/session.ts
3485
+ /** Check whether the session currently has an open (unterminated) turn. */
3486
+ function hasOpenTurn(session) {
3487
+ let open = false;
3488
+ for (const event of sessionEvents(session)) if (event.type === "turn/start") open = true;
3489
+ else if (event.type === "turn/end") open = false;
3490
+ return open;
3491
+ }
3492
+ /** Walk the tool-result source chain to find the root result seq. */
3493
+ function rootToolResultSeq(session, seq) {
3494
+ const events = sessionEvents(session);
3495
+ let current = seq;
3496
+ const seen = /* @__PURE__ */ new Set();
3497
+ while (!seen.has(current)) {
3498
+ seen.add(current);
3499
+ const event = events[current];
3500
+ if (event?.type !== "tool/result" || typeof event.surfaceOp !== "object") return current;
3501
+ const previous = event.sourceEventSeqs?.[0];
3502
+ if (previous === void 0) return current;
3503
+ current = previous;
3504
+ }
3505
+ return seq;
3506
+ }
3507
+ /** Build a session:// event reference string for a given seq. */
3508
+ function sourceRef(session, seq) {
3509
+ return `session://${session.id}/event/${String(seq)}`;
3510
+ }
3511
+ /** Find the latest completed step number for a given turn. */
3512
+ function latestCompletedToolStep(session, turn) {
3513
+ let latest;
3514
+ for (const event of sessionEvents(session)) if (event.type === "step/end" && event.data.turn === turn) latest = event.data.step;
3515
+ return latest;
3516
+ }
3517
+ /** Routed provider/model when the durable request header names one route. */
3518
+ function routeAuditFact(session) {
3519
+ const header = session.requestHeader()?.config;
3520
+ if (header === void 0 || header.provider.length === 0 || header.model.length === 0) return void 0;
3521
+ return {
3522
+ provider: header.provider,
3523
+ model: header.model
3524
+ };
3525
+ }
3526
+ /** Bundled tokenizer identity for one route, when the route is eligible. */
3527
+ function tokenizerAuditFact(route) {
3528
+ const identity = route.provider === "deepseek" || route.provider === "deepseek-official" ? deepSeekV4TokenizerForModel(route.model)?.countText("") : void 0;
3529
+ if (identity?.kind === "exact-tokenizer") return { tokenizer: {
3530
+ repository: identity.tokenizerId,
3531
+ revision: identity.tokenizerRevision
3532
+ } };
3533
+ return { tokenizer: {
3534
+ repository: "unavailable",
3535
+ revision: "unavailable"
3536
+ } };
3537
+ }
3538
+ /** Check whether a snapshot candidate represents an error result. */
3539
+ function isError(candidate) {
3540
+ return viewToolResult(candidate.event.data.message).isError || candidate.event.data.error !== void 0;
3541
+ }
3542
+ /** Wrap a plan list into a HistoryPlanOutcome. */
3543
+ function historyOutcome(plans) {
3544
+ return {
3545
+ kind: "planned",
3546
+ plans: [...plans]
3547
+ };
3548
+ }
3549
+ //#endregion
3550
+ //#region src/runtime/tokenpilot/locator.ts
3551
+ /** Files touched by read/grep-style tool calls inside the range. */
3552
+ const TOUCHED_FILE_TOOL = /(?:^|[-_])?(?:read|write|edit|glob|grep|view|str_replace_editor)(?:$|[-_])/i;
3553
+ /** Spill notice paths emitted by the Harness output-retention policy. */
3554
+ const SPILL_PATH = /stored at:\s*([^\s)\]]+)/g;
3555
+ /** Tool call arguments keys that commonly carry a file path. */
3556
+ const PATH_KEYS$1 = ["path", "file_path"];
3557
+ /**
3558
+ * Find the latest compaction/summary event matching the compaction id of a
3559
+ * compaction/end event. Returns undefined when the transaction cannot be
3560
+ * identified — the caller must skip rather than guess.
3561
+ */
3562
+ function findCompactionTrace(events, compactionId) {
3563
+ let trace;
3564
+ for (const event of events) if (event.type === "compaction/summary" && event.data.compactionId === compactionId) trace = {
3565
+ compactionId,
3566
+ summarySeq: event.seq,
3567
+ summaryShadowedRange: event.data.shadowedRange
3568
+ };
3569
+ return trace;
3570
+ }
3571
+ /** Extract spill file paths from one text chunk. */
3572
+ function extractSpillPaths(text) {
3573
+ const paths = [];
3574
+ for (const match of text.matchAll(SPILL_PATH)) {
3575
+ const path = match[1]?.replace(/[.,;]+$/, "");
3576
+ if (path !== void 0 && path.length > 0) paths.push(path);
3577
+ }
3578
+ return paths;
3579
+ }
3580
+ /** Extract touched file paths from one tool/call event's arguments. */
3581
+ function extractTouchedPath(name, argumentsText) {
3582
+ if (!TOUCHED_FILE_TOOL.test(name)) return void 0;
3583
+ let parsed;
3584
+ try {
3585
+ parsed = JSON.parse(argumentsText);
3586
+ } catch {
3587
+ return;
3588
+ }
3589
+ if (typeof parsed !== "object" || parsed === null) return void 0;
3590
+ const record = parsed;
3591
+ for (const key of PATH_KEYS$1) {
3592
+ const value = record[key];
3593
+ if (typeof value === "string" && value.length > 0) return value;
3594
+ }
3595
+ }
3596
+ /**
3597
+ * Build the Exact Sources block for one shadowed range, or null when the
3598
+ * range locates nothing concrete (no spill files and no touched files).
3599
+ */
3600
+ function buildLocatorBlock(events, shadowedRange) {
3601
+ const spillFiles = /* @__PURE__ */ new Set();
3602
+ const touchedFiles = /* @__PURE__ */ new Set();
3603
+ for (let seq = shadowedRange.start; seq <= shadowedRange.end && seq < events.length; seq += 1) {
3604
+ const event = events[seq];
3605
+ if (event === void 0) continue;
3606
+ if (event.type === "tool/call") {
3607
+ const path = extractTouchedPath(event.data.name, event.data.arguments);
3608
+ if (path !== void 0) touchedFiles.add(path);
3609
+ continue;
3610
+ }
3611
+ if (event.type === "tool/result" || event.type === "user/message") {
3612
+ const data = event.data;
3613
+ const content = Array.isArray(data.content) ? data.content : data.message?.content;
3614
+ if (!Array.isArray(content)) continue;
3615
+ for (const block of content) if (block.type === "text") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
2245
3616
  }
2246
3617
  }
2247
- /** Same host-route resolution as the estimator: explicit, then host default. */
2248
- resolveHostRoute() {
2249
- const provider = this.options.estimatorProvider ?? "";
2250
- const model = this.options.estimatorModel ?? "";
2251
- if (provider.length > 0 && model.length > 0) return {
2252
- provider,
2253
- model
2254
- };
2255
- try {
2256
- const selected = this.ctx.get("agentDefaultModel")?.currentSelection?.();
2257
- const selectedProvider = selected?.provider ?? "";
2258
- const selectedModel = selected?.model ?? "";
2259
- if (selectedProvider.length > 0 && selectedModel.length > 0) return {
2260
- provider: provider.length > 0 ? provider : selectedProvider,
2261
- model: model.length > 0 ? model : selectedModel
2262
- };
2263
- } catch {}
3618
+ if (spillFiles.size === 0 && touchedFiles.size === 0) return null;
3619
+ return {
3620
+ text: [
3621
+ "## Exact Sources (locators)",
3622
+ `- seq range: ${String(shadowedRange.start)}-${String(shadowedRange.end)}`,
3623
+ ...[...spillFiles].map((path) => `- spill file: ${path}`),
3624
+ ...[...touchedFiles].map((path) => `- file touched: ${path}`),
3625
+ `(Use \`read <spill file>\` or \`${RUNTIME_TOOL_NAMES.RETRIEVE}\` with a \`session://\` source — pass start_line/max_lines to window the text — to restore exact text.)`
3626
+ ].join("\n"),
3627
+ spillFiles: spillFiles.size,
3628
+ touchedFiles: touchedFiles.size
3629
+ };
3630
+ }
3631
+ //#endregion
3632
+ //#region src/runtime/tokenpilot/read-state.ts
3633
+ /** Write-style tool names whose success supersedes earlier reads. */
3634
+ const WRITE_TOOLS = /(?:^|[-_])?(?:write|edit|apply_patch|file_write|file_edit|str_replace|replace|multiedit)(?:$|[-_])/i;
3635
+ const PATH_KEYS = ["path", "file_path"];
3636
+ /** Parse one path out of a tool-call arguments JSON blob. */
3637
+ function toolCallPath(argumentsText) {
3638
+ let parsed;
3639
+ try {
3640
+ parsed = JSON.parse(argumentsText);
3641
+ } catch {
3642
+ return;
2264
3643
  }
2265
- async askHost(system, user, signal) {
2266
- let llm;
2267
- try {
2268
- llm = this.ctx.get("llm");
2269
- } catch {
2270
- return;
2271
- }
2272
- if (llm?.stream === void 0) return void 0;
2273
- const route = this.resolveHostRoute();
2274
- if (route === void 0) return void 0;
2275
- let text = "";
2276
- const stream = llm.stream({
2277
- provider: route.provider,
2278
- model: route.model,
2279
- messages: [{
2280
- role: "user",
2281
- content: [{
2282
- type: "text",
2283
- text: user
2284
- }]
2285
- }],
2286
- system,
2287
- temperature: 0,
2288
- reasoningEffort: "off",
2289
- maxTokens: this.overrides?.maxTokens ?? 256,
2290
- signal
2291
- });
2292
- for await (const chunk of stream) if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
2293
- else if (chunk.type === "finish" && chunk.text === void 0) break;
2294
- return text.trim().length > 0 ? text : void 0;
3644
+ if (typeof parsed !== "object" || parsed === null) return void 0;
3645
+ const record = parsed;
3646
+ for (const key of PATH_KEYS) {
3647
+ const value = record[key];
3648
+ if (typeof value === "string" && value.length > 0) return value;
2295
3649
  }
2296
- async askDirect(system, user, signal) {
2297
- const baseUrl = this.options.estimatorBaseUrl;
2298
- if (baseUrl === void 0 || baseUrl.length === 0) return void 0;
2299
- const headers = { "content-type": "application/json" };
2300
- if (this.options.estimatorApiKey !== void 0 && this.options.estimatorApiKey.length > 0) headers.authorization = `Bearer ${this.options.estimatorApiKey}`;
2301
- const model = this.options.estimatorModel ?? "";
2302
- if (model.length === 0) return void 0;
2303
- const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/chat/completions`, {
2304
- method: "POST",
2305
- headers,
2306
- body: JSON.stringify({
2307
- model,
2308
- messages: [{
2309
- role: "system",
2310
- content: system
2311
- }, {
2312
- role: "user",
2313
- content: user
2314
- }],
2315
- temperature: 0,
2316
- max_tokens: this.overrides?.maxTokens ?? 256
2317
- }),
2318
- signal
2319
- });
2320
- if (!response.ok) return void 0;
2321
- const text = (await response.json()).choices?.[0]?.message?.content;
2322
- return typeof text === "string" && text.trim().length > 0 ? text : void 0;
3650
+ }
3651
+ /**
3652
+ * Decide whether an oversized read result was superseded by a later mutation
3653
+ * of the same file. `readPath` is the read call's target path; events after
3654
+ * `readSeq` are scanned for a write-style call on it.
3655
+ */
3656
+ function isSupersededRead(events, readSeq, readPath) {
3657
+ if (readPath === void 0) return false;
3658
+ for (let seq = readSeq + 1; seq < events.length; seq += 1) {
3659
+ const event = events[seq];
3660
+ if (event?.type !== "tool/call") continue;
3661
+ if (!WRITE_TOOLS.test(event.data.name)) continue;
3662
+ if (toolCallPath(event.data.arguments) === readPath) return true;
2323
3663
  }
2324
- };
3664
+ return false;
3665
+ }
3666
+ /** Error/warning/info line classifiers used by the omission summary. */
3667
+ const ERROR_LINE = /\b(error|failed|failure|fatal|exception|traceback|cannot|unable|denied)\b/i;
3668
+ const WARN_LINE = /\b(warn|warning|deprecated)\b/i;
3669
+ const SECTION_HEADING = /^#{1,3}\s+(.{1,80})/;
3670
+ /**
3671
+ * Cluster one omitted line-count into a summary appended to a placeholder
3672
+ * marker, giving the model meta-knowledge about what was dropped. Document
3673
+ * content (R8) swaps the error/warn/info census for a section-heading list —
3674
+ * `0 error, 0 warn, N info` carries no information about a dropped document,
3675
+ * while its heading list does.
3676
+ */
3677
+ function clusterOmittedLines(text, omittedLines) {
3678
+ if (omittedLines <= 0) return void 0;
3679
+ if (looksLikeDocument(text)) return documentCensus(text, omittedLines);
3680
+ let errors = 0;
3681
+ let warns = 0;
3682
+ let infos = 0;
3683
+ for (const line of text.split("\n")) if (ERROR_LINE.test(line)) errors += 1;
3684
+ else if (WARN_LINE.test(line)) warns += 1;
3685
+ else infos += 1;
3686
+ const parts = [];
3687
+ if (errors > 0) parts.push(`${String(errors)} error`);
3688
+ if (warns > 0) parts.push(`${String(warns)} warn`);
3689
+ if (infos > 0) parts.push(`${String(infos)} info`);
3690
+ if (parts.length === 0) return void 0;
3691
+ return `${String(omittedLines)} lines omitted (${parts.join(", ")})`;
3692
+ }
3693
+ /** Bounded section-heading list for an omitted document (R8 census). */
3694
+ function documentCensus(text, omittedLines) {
3695
+ const titles = [];
3696
+ for (const line of text.split("\n")) {
3697
+ const match = SECTION_HEADING.exec(line);
3698
+ if (match === null) continue;
3699
+ titles.push(match[1].trim());
3700
+ if (titles.length >= 8) break;
3701
+ }
3702
+ if (titles.length === 0) return `${String(omittedLines)} lines omitted (document content)`;
3703
+ let summary = titles.join(" · ");
3704
+ if (summary.length > 240) summary = `${summary.slice(0, 240)}…`;
3705
+ return `${String(omittedLines)} lines omitted (sections: ${summary})`;
3706
+ }
2325
3707
  //#endregion
2326
3708
  //#region src/runtime/tokenpilot/estimator.ts
2327
3709
  /** Exponential backoff with a 5-minute cap: 1s, 2s, 4s, … */
@@ -3277,6 +4659,24 @@ function sanitizeAuditMessage(error) {
3277
4659
  */
3278
4660
  const dshSessionSoft = dshSessionNamespace;
3279
4661
  const SessionSeq = dshSessionSoft.SessionSeq ?? dshSessionSoft.default?.SessionSeq ?? ((value) => value);
4662
+ function looseEvents(session) {
4663
+ return sessionEvents(session);
4664
+ }
4665
+ function looseData(event) {
4666
+ return event?.data;
4667
+ }
4668
+ function looseContent(event) {
4669
+ const data = looseData(event);
4670
+ const content = (data?.message ?? data)?.content;
4671
+ return Array.isArray(content) ? content : [];
4672
+ }
4673
+ /** Flatten the visible text of any surface event for sediment accounting. */
4674
+ function sedimentEventText(event) {
4675
+ return looseContent(event).filter((block) => {
4676
+ const record = block;
4677
+ return record !== null && record.type === "text" && typeof record.text === "string";
4678
+ }).map((block) => block.text).join("\n");
4679
+ }
3280
4680
  /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
3281
4681
  function originalTextForSavings(candidate) {
3282
4682
  return flattenPlainText(viewToolResult(candidate.event.data.message).blocks);
@@ -3337,6 +4737,7 @@ var ToolResultPruner = class extends Service {
3337
4737
  super(ctx, "toolResultPruner");
3338
4738
  ctx.inject(["tools", "systemPrompt"], (recoveryCtx) => {
3339
4739
  installContextCompressionRetrieve(recoveryCtx);
4740
+ installShallowTools(recoveryCtx);
3340
4741
  });
3341
4742
  this.state = {
3342
4743
  config: resolveConfig(config),
@@ -3382,6 +4783,12 @@ var ToolResultPruner = class extends Service {
3382
4783
  this.auditFailure(session, "pressure", "summary-locator", error);
3383
4784
  ctx.logger.warn("context-compression summary locator failed open: %o", error);
3384
4785
  }
4786
+ if (event.type === "turn/end") try {
4787
+ this.sedimentTurnEnd(session);
4788
+ } catch (error) {
4789
+ this.auditFailure(session, "pressure", "sediment", error);
4790
+ ctx.logger.warn("context-compression sediment pass failed open: %o", error);
4791
+ }
3385
4792
  });
3386
4793
  ctx.on("agent/pre-step", async ({ agent, signal, turn, step }, next) => {
3387
4794
  const boundary = {};
@@ -3417,6 +4824,21 @@ var ToolResultPruner = class extends Service {
3417
4824
  try {
3418
4825
  getSavingsLedger().observeActive(String(agent.session.id), new Set([...agent.session.surface.nodes].map(Number)));
3419
4826
  } catch {}
4827
+ try {
4828
+ const feedbackSessionId = String(agent.session.id);
4829
+ let watcher = this.sedimentWatchers.get(agent.session);
4830
+ if (watcher === void 0) {
4831
+ watcher = new SedimentFeedbackWatcher();
4832
+ this.sedimentWatchers.set(agent.session, watcher);
4833
+ }
4834
+ const mode = watcher.observe(getSavingsLedger().snapshot(feedbackSessionId));
4835
+ setSedimentObservation(feedbackSessionId, {
4836
+ conservative: mode.conservative,
4837
+ reason: mode.reason,
4838
+ cuts: this.sedimentCuts.get(feedbackSessionId) ?? 0
4839
+ });
4840
+ if (mode.conservative) this.warnOnce(agent.session, "sediment:conservative", "context-compression sediment feedback armed conservative mode: %s", mode.reason);
4841
+ } catch {}
3420
4842
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
3421
4843
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
3422
4844
  this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
@@ -3557,6 +4979,203 @@ var ToolResultPruner = class extends Service {
3557
4979
  });
3558
4980
  return snapshot;
3559
4981
  }
4982
+ sedimentOrchestrators = /* @__PURE__ */ new WeakMap();
4983
+ sedimentWatchers = /* @__PURE__ */ new WeakMap();
4984
+ sedimentCuts = /* @__PURE__ */ new Map();
4985
+ ptcAgingMemo = /* @__PURE__ */ new WeakMap();
4986
+ /**
4987
+ * PTC aging short-circuit (T3.10): when an omnibus runner is registered and
4988
+ * no direct write-family tool call is observed in the session, the regex
4989
+ * superseded predicate is blind (writes fold into run_code bodies) — the
4990
+ * rule-based aging branch is disabled for that session. Active only while
4991
+ * the sediment gate is on: with default-off settings the existing readState
4992
+ * behavior is byte-identical.
4993
+ */
4994
+ ptcAgingBlocked(session) {
4995
+ if (this.activeSettings(session).sediment?.enabled !== true) return false;
4996
+ const events = looseEvents(session);
4997
+ const memo = this.ptcAgingMemo.get(session);
4998
+ if (memo !== void 0 && memo.events === events.length) return memo.blocked;
4999
+ let blocked = false;
5000
+ const hasTool = (name) => {
5001
+ try {
5002
+ return this.ctx.get("tools")?.get?.(name) !== void 0;
5003
+ } catch {
5004
+ return false;
5005
+ }
5006
+ };
5007
+ if (detectPtcMode(hasTool)) {
5008
+ let observedCalls = 0;
5009
+ let writeHits = 0;
5010
+ for (const event of events) {
5011
+ if (event.type !== "assistant/message") continue;
5012
+ for (const raw of looseContent(event)) {
5013
+ const block = raw;
5014
+ if (block !== null && block.type === "tool-call") {
5015
+ observedCalls += 1;
5016
+ if (isWriteToolName(String(block.name ?? ""))) writeHits += 1;
5017
+ }
5018
+ }
5019
+ }
5020
+ blocked = readStateBlind(true, writeHits, observedCalls);
5021
+ }
5022
+ this.ptcAgingMemo.set(session, {
5023
+ events: events.length,
5024
+ blocked
5025
+ });
5026
+ return blocked;
5027
+ }
5028
+ /**
5029
+ * Sedimentation entry (plan cci-sedimentation-triage T3.6): whole-turn
5030
+ * replacement decided at `turn/end`, inside the quiet seam before the next
5031
+ * request derives. Disabled sessions exit at the settings gate with zero
5032
+ * downstream work; committed cards flush like any other surface write.
5033
+ */
5034
+ sedimentTurnEnd(session) {
5035
+ const settings = this.activeSettings(session).sediment;
5036
+ if (settings === void 0 || settings.enabled !== true) return;
5037
+ const events = sessionEvents(session);
5038
+ let turn;
5039
+ for (let index = events.length - 1; index >= 0; index -= 1) {
5040
+ const candidate = events[index];
5041
+ if (candidate?.type === "turn/end") {
5042
+ const value = candidate.data.turn;
5043
+ if (typeof value === "number") {
5044
+ turn = value;
5045
+ break;
5046
+ }
5047
+ }
5048
+ }
5049
+ if (turn === void 0) return;
5050
+ const orchestrator = this.sedimentOrchestratorFor(session, settings);
5051
+ let officialCheckpointSeq;
5052
+ for (const seq of [...session.surface.nodes].reverse()) {
5053
+ const event = events[seq];
5054
+ if (event?.type !== "user/message") continue;
5055
+ if (event.data.source?.kind === "compact-checkpoint") {
5056
+ officialCheckpointSeq = seq;
5057
+ break;
5058
+ }
5059
+ }
5060
+ let compactionOpen = false;
5061
+ for (let index = events.length - 1; index >= 0; index -= 1) {
5062
+ const type = events[index]?.type;
5063
+ if (type === "compaction/end") break;
5064
+ if (type === "compaction/start") {
5065
+ compactionOpen = true;
5066
+ break;
5067
+ }
5068
+ }
5069
+ orchestrator.handleTurnEnd(session, turn, {
5070
+ lastEventType: "turn/end",
5071
+ inFlightRequest: this.state.activeRequestBoundaries.get(session) !== void 0,
5072
+ compactionOpen,
5073
+ officialCheckpointSeq,
5074
+ resumeFirstBatch: false
5075
+ }).then((outcome) => {
5076
+ if (outcome.committed) try {
5077
+ this.ctx.sessions?.flush?.(session);
5078
+ } catch {}
5079
+ }).catch((error) => {
5080
+ this.auditFailure(session, "pressure", "sediment", error);
5081
+ this.ctx.logger.warn("context-compression sediment commit failed open: %o", error);
5082
+ });
5083
+ }
5084
+ sedimentOrchestratorFor(session, settings) {
5085
+ let orchestrator = this.sedimentOrchestrators.get(session);
5086
+ if (orchestrator !== void 0) return orchestrator;
5087
+ orchestrator = new SedimentOrchestrator({
5088
+ settingsFor: () => this.activeSettings(session).sediment,
5089
+ eventsFor: (_s, turn) => looseEvents(session).filter((event) => looseData(event)?.turn === turn).map((event) => {
5090
+ const data = looseData(event);
5091
+ return {
5092
+ seq: event.seq,
5093
+ type: event.type,
5094
+ ...data === void 0 ? {} : { data }
5095
+ };
5096
+ }),
5097
+ callInfoFor: () => {
5098
+ const map = /* @__PURE__ */ new Map();
5099
+ for (const event of looseEvents(session)) {
5100
+ if (event.type !== "assistant/message") continue;
5101
+ for (const raw of looseContent(event)) {
5102
+ const block = raw;
5103
+ if (block !== null && block.type === "tool-call" && typeof block.id === "string") map.set(block.id, {
5104
+ name: String(block.name ?? "tool"),
5105
+ argsJson: typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {})
5106
+ });
5107
+ }
5108
+ }
5109
+ return (callId) => callId === void 0 ? void 0 : map.get(callId);
5110
+ },
5111
+ tailTokensFor: (_s, endSeq) => {
5112
+ let tail = 0;
5113
+ for (const event of looseEvents(session)) {
5114
+ if (typeof event.seq !== "number" || event.seq <= endSeq) continue;
5115
+ tail += estimateTokens(sedimentEventText(event));
5116
+ }
5117
+ return tail;
5118
+ },
5119
+ ...settings.foldMode === void 0 || settings.foldMode === "" ? {} : { fold: { run: async (sessionId, prompt, signal) => {
5120
+ const started = Date.now();
5121
+ const outcome = await new FoldRouter(this.ctx, settings).fold(sessionId, prompt, signal);
5122
+ this.ctx.logger.info("context-compression sediment fold (%s): tier=%s ok=%s latencyMs=%d%s", sessionId, foldTier(prompt.inputTokens), outcome.text !== void 0, Date.now() - started, outcome.audit.ok ? "" : ` reason=${outcome.audit.reason ?? "unknown"}`);
5123
+ return outcome.text;
5124
+ } } },
5125
+ feedback: () => {
5126
+ const watcher = this.sedimentWatchers.get(session);
5127
+ return watcher === void 0 ? {
5128
+ conservative: false,
5129
+ reason: "ok"
5130
+ } : {
5131
+ conservative: watcher.conservative,
5132
+ reason: watcher.conservative ? "net-negative-streak" : "ok"
5133
+ };
5134
+ },
5135
+ onLanded: (sessionId, savedTokens, tier, result) => {
5136
+ this.sedimentCuts.set(sessionId, (this.sedimentCuts.get(sessionId) ?? 0) + 1);
5137
+ this.ctx.logger.info("context-compression sediment landed (%s): turn saved %d tok via %s narrative", sessionId, savedTokens, tier);
5138
+ const allEvents = looseEvents(session);
5139
+ const manifestEvent = allEvents.find((event) => event.seq === result.manifestSeq);
5140
+ const originalText = (looseData(manifestEvent)?.shadowedSeqs ?? []).map((seq) => sedimentEventText(allEvents[seq])).join("\n");
5141
+ const tokensBefore = looseData(manifestEvent)?.shadowedTokenCount ?? savedTokens;
5142
+ if (originalText.length > 0) getSavingsLedger().recordSaving({
5143
+ sessionId,
5144
+ component: "sediment",
5145
+ tokensBefore,
5146
+ tokensAfter: Math.max(0, tokensBefore - savedTokens),
5147
+ basis: "characters",
5148
+ sourceSeq: result.manifestSeq ?? 0,
5149
+ replacementSeq: result.replacementSeq ?? 0,
5150
+ originalText
5151
+ });
5152
+ },
5153
+ onSkip: (sessionId, reason) => {
5154
+ this.ctx.logger.debug?.("context-compression sediment skipped (%s): %s", sessionId, reason);
5155
+ }
5156
+ });
5157
+ this.sedimentOrchestrators.set(session, orchestrator);
5158
+ return orchestrator;
5159
+ }
5160
+ /**
5161
+ * T4.8 pairing footer: when a read-class result supersedes a live shallow
5162
+ * map of the same file, the reduced text carries the data-shaped reminder
5163
+ * (sibling ref + discard hint). Non-read calls, unparseable arguments, and
5164
+ * sessions without a live map all return undefined — zero side effects.
5165
+ */
5166
+ shallowPairFooter(session, candidate) {
5167
+ if (/^(read|read_file|view)$/i.test(candidate.call.name) === false) return void 0;
5168
+ let filePath;
5169
+ try {
5170
+ const parsed = JSON.parse(candidate.call.arguments);
5171
+ filePath = typeof parsed.file_path === "string" ? parsed.file_path : typeof parsed.path === "string" ? parsed.path : "";
5172
+ } catch {
5173
+ return;
5174
+ }
5175
+ if (filePath === "") return void 0;
5176
+ const entry = liveShallowFor(session, filePath);
5177
+ return entry === void 0 ? void 0 : buildShallowFooter(entry.checkpoint, entry.bodyTokens);
5178
+ }
3560
5179
  /**
3561
5180
  * TokenPilot-inspired A2: replace the compaction summary checkpoint node
3562
5181
  * with the same summary plus an Exact Sources locator block. Fails open:
@@ -3626,6 +5245,7 @@ var ToolResultPruner = class extends Service {
3626
5245
  const policy = this.activePolicy(session);
3627
5246
  const presetOptions = policy?.presetOptions;
3628
5247
  if (policy === void 0 || presetOptions?.readState !== true) return;
5248
+ if (this.ptcAgingBlocked(session)) return;
3629
5249
  const estimatorMode = presetOptions.estimator?.mode ?? "";
3630
5250
  if (estimatorMode === "") return;
3631
5251
  const failures = this.state.estimatorFailures.get(session);
@@ -4503,9 +6123,11 @@ var ToolResultPruner = class extends Service {
4503
6123
  codeSkeleton
4504
6124
  });
4505
6125
  if (output !== null) {
6126
+ const footer = this.shallowPairFooter(session, candidate);
6127
+ const reducedText = footer === void 0 ? output.text : `${output.text}\n\n${footer}`;
4506
6128
  const plan = this.plan(candidate, [{
4507
6129
  ...textBlock,
4508
- text: output.text
6130
+ text: reducedText
4509
6131
  }], sourceSeq, output.reducer, "fresh", "fresh", void 0, view, {
4510
6132
  noNetSavingsGuard: policy.presetOptions?.noNetSavingsGuard === true,
4511
6133
  ...output.elidedLines === void 0 ? {} : { elidedLines: output.elidedLines }
@@ -4619,7 +6241,7 @@ var ToolResultPruner = class extends Service {
4619
6241
  for (const candidate of eligible) {
4620
6242
  const resultView = viewToolResult(candidate.event.data.message);
4621
6243
  const block = onlyTextBlock(resultView.blocks);
4622
- if (policy.presetOptions?.readState === true && block !== null) {
6244
+ if (policy.presetOptions?.readState === true && block !== null && !this.ptcAgingBlocked(session)) {
4623
6245
  const readPath = toolCallPath(candidate.call.arguments);
4624
6246
  const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true;
4625
6247
  if (readPath !== void 0 && (isSupersededRead(events, candidate.seq, readPath) || estimatorExpired)) {