ceulen 0.29.2 → 0.31.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,66 @@
1
+ ## 0.30.0 — 2026-11-22
2
+
3
+ Three DeepSeek Harness enrichments in the **repair** module — all-model, all
4
+ handlers (no new tool, no new module), plus the hardening that live panes and
5
+ review forced out of the spill recovery hint.
6
+
7
+ - **`repair.spillMaxTokens`** (default 12500 = DSH's base-preset
8
+ `maxInlineTokens`, `0` disables) — a tool result over the budget keeps its
9
+ head and tail (DSH's half-budget-per-end retention, surrogate-pair-safe), the
10
+ full text lands in a private per-process temp file, and the notice names the
11
+ path. Estimation is DSH's fixed density (`ceil(chars/4) + 4` per text block),
12
+ so there is no tokenizer dependency. **Scope is returned content**: pi's
13
+ `read`/`bash` truncate inside the tool before `tool_result` fires, so their
14
+ dropped bytes are unrecoverable at this seam and those results are excluded —
15
+ keyed on `details.truncation.truncated` / `details.fullOutputPath` METADATA,
16
+ never on notice text, so a wrapped read of a file that merely *contains*
17
+ "Use offset=" still spills. The beneficiaries are the tools with no
18
+ self-truncation (subagent reports, `github pr_diff`, `web_extract`, `munin_*`).
19
+ - **`repair.repeatReminder`** (default on) — an advisory footer on the
20
+ 3rd/5th/8th consecutive call with identical arguments (deep key-sorted
21
+ canonicalization, so property order is irrelevant). It never blocks: the call
22
+ runs and its real output survives, which is what distinguishes it from the two
23
+ guards that refuse (permission's doom-loop on denied calls, munin's dampener —
24
+ whose `munin_*` tools are excluded here). A new user message resets the chain;
25
+ nested calls are skipped.
26
+ - **`repair.clock`** (default off) + `repair.clockRefreshMs` (default 600000) —
27
+ pi injects no model-visible date/time anywhere (`system-prompt.js` renders with
28
+ `timestamp: 0`), so a long goal/cron session cannot tell when "today" is. A
29
+ `ceulen-clock` custom message carries an ISO stamp with numeric offset + IANA
30
+ zone and the elapsed span, one injection per refresh window so the appended
31
+ message stays out of the cache-churn path.
32
+
33
+ **Spill recovery is an executable hint, and it took four rounds of live-pane
34
+ findings to get right.** Each was measured, not theorised:
35
+
36
+ 1. A hardcoded `head -c 50000` costs 12,504 estimated tokens — *over* the
37
+ 12,500 default — so the recovery re-spilled and the model looped. The page
38
+ size is now derived from the ACTIVE budget.
39
+ 2. `read` is never a safe recovery: the spill file exceeds the budget by
40
+ definition, and pi's read has no byte-budget parameter. A 100-line read at
41
+ budget 2000 cost 2,254 tokens and respilled live. The hint always pages by
42
+ bytes through `bash`.
43
+ 3. A raw `head -c` splits multibyte characters at the page boundary, and bash
44
+ decodes each page independently, so a 3-byte character straddling the cut is
45
+ lost in **both** pages. Pages now pass through `iconv -c` and print their own
46
+ next offset, so a trimmed byte is re-read whole.
47
+ 4. pi's bash caps at **both** 2000 lines and 50 KiB, truncating with
48
+ `truncateTail` — it drops the page's HEAD while the offset has already
49
+ advanced past it (measured: 2,083 lines → 83 lines / 247 bytes lost). Pages
50
+ are now clamped on three axes (token budget, `minLine × 1900`, and 45,000
51
+ bytes) and piped through `head -n`.
52
+
53
+ - **Tests** — `spill`, `repeat-reminder`, `clock`, `dsh-enrichments` and
54
+ `spill-utf8` suites (66 new cases). The spill tests run the notice's OWN
55
+ emitted command and reassemble, and every page is validated by passing its RAW
56
+ output — offset marker included — through pi's real `truncateTail`, because a
57
+ text assertion cannot see any of the four failures above.
58
+ - **AGENTS.md** — the repair section documents the three features, the
59
+ returned-content scope, the metadata-only exclusions, and the binding
60
+ thresholds of the page clamps (the 99,996-byte window requires `minLine ≥ 53`;
61
+ the over-cap region starts at 27) so the documented blast radius cannot drift
62
+ from the code.
63
+
1
64
  # Changelog
2
65
  ## 0.29.2 — 2026-11-22
3
66
 
@@ -1565,3 +1628,28 @@ Wave 1: first two production modules merged into the bundle.
1565
1628
  ## 0.1.0 — 2026-09-21
1566
1629
 
1567
1630
  Name reservation + bundle scaffold.
1631
+ ## 0.31.0 — 2026-11-23
1632
+
1633
+ DeepSeek V4 tool-selection guidance stops overriding a prerequisite read, and
1634
+ the `bash`-first hint stops mis-firing on "after" clauses.
1635
+
1636
+ - **Selection guidance** (`steering.selectionGuidance`, DeepSeek V4 only) no
1637
+ longer pushes one `codemode` script for every batch. It now says "use a
1638
+ direct call for one simple step; batch independent calls in one round
1639
+ (parallel direct calls, **or** codemode with `Promise.allSettled` to filter
1640
+ or compute in place)". Live Herdr run on `router/combo/deepseek-v4.1-flash`:
1641
+ the four-file sum task dropped from 2 tool rounds to 1 (four parallel
1642
+ `read` calls, then one `bash`), which the previous codemode-first wording
1643
+ never produced.
1644
+ - **`runTaskFirstToolHint`** used to fire on any execution verb anywhere in the
1645
+ prompt, so "Read `fixtures/runbook.txt`, then run its command" got a
1646
+ "FIRST tool call MUST be bash … Do NOT call read first" hint that directly
1647
+ contradicted the read the task requires (live-observed: Flash read the file,
1648
+ then re-read it because the reminder demanded compliance). Suppressed when a
1649
+ read/open/review/check precedes the first execution verb, and when an
1650
+ `after you read` / `after reading` clause makes the read a prerequisite.
1651
+ - **Scoped to the first execution clause**: "Run the tests, then deploy after
1652
+ reviewing the results" keeps the `bash`-first hint — the review gates the
1653
+ deploy, not the tests. An earlier revision scanned the whole suffix and
1654
+ silently dropped the hint there.
1655
+
@@ -0,0 +1,103 @@
1
+ #!/bin/sh
2
+ # Contract test for scripts/smoke-install.sh.
3
+ #
4
+ # The script's whole value is that EVERY wrong answer is fatal — a version
5
+ # mismatch, a missing file, or a file that should have been deleted must all
6
+ # exit non-zero. These cases were added because a hand-rolled version of this
7
+ # check reported success while only printing its failures.
8
+ #
9
+ # Network-dependent (it installs from the registry), so it targets versions that
10
+ # already exist and keeps the assertion set small. Set SMOKE_TEST_VERSION to
11
+ # override the version under test.
12
+ #
13
+ # DELIBERATELY NOT wired into `npm test`: the rest of the suite is offline (the
14
+ # audit test points AUDIT_REGISTRY at a local fake server, the fixture check has
15
+ # no network at all), and a registry dependency in CI would make every push
16
+ # slower and flakier than the checks it protects. Run this as part of the RELEASE
17
+ # flow, after the tarball resolves — that is the moment it has something to
18
+ # prove.
19
+ set -eu
20
+
21
+ ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd)"
22
+ SCRIPT="$ROOT/scripts/smoke-install.sh"
23
+ VER="${SMOKE_TEST_VERSION:-0.29.2}"
24
+
25
+ fail=0
26
+ # expect <desc> <want-rc> [--expect-msg <substring>] -- <script args>...
27
+ #
28
+ # Exit status ALONE is not enough: every failure path in the script exits 1, so a
29
+ # transient registry error makes "missing --require" pass for the wrong reason.
30
+ # A case that cares WHICH check fired asserts its message too.
31
+ expect() {
32
+ desc="$1"; want="$2"; shift 2
33
+ wantMsg=""
34
+ if [ "${1:-}" = "--expect-msg" ]; then wantMsg="$2"; shift 2; fi
35
+ [ "${1:-}" = "--" ] && shift
36
+
37
+ set +e
38
+ sh "$SCRIPT" "$@" > "$TMPOUT" 2>&1
39
+ rc=$?
40
+ set -e
41
+
42
+ # Exact comparison, not a "did it fail at all" test. Collapsing every negative
43
+ # case to "non-zero" would let the usage path (2) pass while reporting 1, i.e.
44
+ # it would stop pinning the documented distinction between a usage error and a
45
+ # failed check.
46
+ if [ "$rc" -ne "$want" ]; then
47
+ echo "FAIL [$desc] expected rc=$want, got $rc"; sed 's/^/ /' "$TMPOUT"; fail=1; return
48
+ fi
49
+ if [ -n "$wantMsg" ] && ! grep -qF "$wantMsg" "$TMPOUT"; then
50
+ echo "FAIL [$desc] exited $rc but without the expected message: $wantMsg"
51
+ echo " (a different failure — e.g. a registry error — cannot satisfy this case)"
52
+ sed 's/^/ /' "$TMPOUT"; fail=1; return
53
+ fi
54
+ echo "ok [$desc] rc=$rc${wantMsg:+ [$wantMsg]}"
55
+ }
56
+
57
+ TMPOUT=$(mktemp)
58
+ trap 'rm -f "$TMPOUT"' EXIT INT TERM
59
+
60
+ # Baseline: the real payload asserts clean.
61
+ expect "real payload => exit 0" 0 -- \
62
+ "$VER" \
63
+ --require extensions/modules/repair/lib/persistent-bash.ts \
64
+ --forbid extensions/modules/steering/lib/anchor.ts
65
+
66
+ # A missing --require path must be fatal (this is the defect being pinned: the
67
+ # old inline check printed the miss and still exited 0).
68
+ expect "missing --require => its own message" 1 \
69
+ --expect-msg "FAIL: missing scripts/does-not-exist.sh" -- \
70
+ "$VER" --require scripts/does-not-exist.sh
71
+
72
+ # A --forbid path that IS present must be fatal (a deleted file must stay gone).
73
+ expect "violated --forbid => its own message" 1 \
74
+ --expect-msg "unexpected extensions/modules/repair/lib/persistent-bash.ts" -- \
75
+ "$VER" --forbid extensions/modules/repair/lib/persistent-bash.ts
76
+
77
+ # An install failure must be fatal, not silently skipped.
78
+ expect "nonexistent version => install-failure message" 1 \
79
+ --expect-msg "FAIL: npm install ceulen@9.9.9 exited non-zero" -- \
80
+ "9.9.9"
81
+
82
+ # A version mismatch must be fatal, exercised through the real CLI via
83
+ # --expect-version (install one version, assert another).
84
+ expect "version mismatch => its own message" 1 \
85
+ --expect-msg "installed version $VER != requested 0.0.0-deliberately-wrong" -- \
86
+ "$VER" --expect-version 0.0.0-deliberately-wrong
87
+
88
+ # Usage errors are distinguishable from check failures.
89
+ expect "no version argument => usage message" 2 \
90
+ --expect-msg "usage: smoke-install.sh"
91
+
92
+ # The success path must actually SAY it checked the version, so a reader can
93
+ # tell a real pass from a vacuous one.
94
+ set +e
95
+ sh "$SCRIPT" "$VER" > "$TMPOUT" 2>&1
96
+ set -e
97
+ if grep -q "ok version $VER" "$TMPOUT"; then
98
+ echo "ok [report] version assertion reported"
99
+ else
100
+ echo "FAIL [report] no version line in the output"; sed 's/^/ /' "$TMPOUT"; fail=1
101
+ fi
102
+
103
+ [ "$fail" -eq 0 ] && { echo; echo "ALL PASS"; } || { echo >&2; echo "FAILURES PRESENT" >&2; exit 1; }
@@ -78,13 +78,41 @@ export function buildRepairGroups(cfg: RepairSettings): PanelGroup[] {
78
78
  description: "One bash per session: cwd, exported variables, functions, and background jobs survive across calls (DeepSeek Harness parity). Plan mode always runs one-shot.",
79
79
  warning: "Binds at session start — applies to the next session. While on, auto-background bash is suspended: background long jobs inside the shell with '&'.",
80
80
  }),
81
+ row("repair.spillMaxTokens", "Tool-result token budget", "number", cfg.spillMaxTokens, (v) => {
82
+ // Mirror the autoBgSecs guard: non-numeric input must not persist NaN.
83
+ const n = Math.floor(Number(v));
84
+ if (Number.isFinite(n) && n >= 0) cfg.spillMaxTokens = n;
85
+ }, {
86
+ defaultValue: DEFAULT_REPAIR_SETTINGS.spillMaxTokens,
87
+ description: "Results over this many estimated tokens keep their head and tail; the full text is saved to a file the model can read. 0 disables. (DeepSeek Harness spill-policy.)",
88
+ }),
89
+ row("repair.repeatReminder", "Repeat-call reminder", "toggle", cfg.repeatReminder, (v) => {
90
+ cfg.repeatReminder = v === true;
91
+ }, {
92
+ defaultValue: DEFAULT_REPAIR_SETTINGS.repeatReminder,
93
+ description: "Advisory footer when the same tool call repeats with identical arguments (3rd/5th/8th). Never blocks — targeting DeepSeek Flash's loop failure mode.",
94
+ }),
95
+ row("repair.clock", "Model-visible clock", "toggle", cfg.clock, (v) => {
96
+ cfg.clock = v === true;
97
+ }, {
98
+ defaultValue: DEFAULT_REPAIR_SETTINGS.clock,
99
+ description: "Inject the current date/time and elapsed-since-last-activity into the request. Pi injects no clock anywhere (DeepSeek Harness time-context).",
100
+ }),
101
+ row("repair.clockRefreshMs", "Clock refresh interval", "number", cfg.clockRefreshMs, (v) => {
102
+ const n = Math.floor(Number(v));
103
+ if (Number.isFinite(n) && n >= 0) cfg.clockRefreshMs = n;
104
+ }, {
105
+ defaultValue: DEFAULT_REPAIR_SETTINGS.clockRefreshMs,
106
+ description: "Minimum milliseconds between clock injections in one session (default 600000 = 10 min). Keeps the appended clock out of the cache-churn path.",
107
+ }),
81
108
  ],
82
109
  },
83
110
  ];
84
111
  }
85
112
 
86
113
  const OWNED_PREFIX = "repair.";
87
- const BOOL_KEYS = ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash"] as const;
114
+ const BOOL_KEYS = ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash", "repeatReminder", "clock"] as const;
115
+ const NUMBER_KEYS = ["autoBgSecs", "spillMaxTokens", "clockRefreshMs"] as const;
88
116
 
89
117
  /** repair's ModuleConfig for the central /config panel. The factory receives
90
118
  * the module's guarded pi but needs nothing from it — settings live in the
@@ -100,7 +128,9 @@ export function repairConfig(_pi: ExtensionAPI): ModuleConfig {
100
128
  for (const key of BOOL_KEYS) {
101
129
  if (working[key] !== before[key]) patch[key] = working[key];
102
130
  }
103
- if (working.autoBgSecs !== before.autoBgSecs) patch.autoBgSecs = working.autoBgSecs;
131
+ for (const key of NUMBER_KEYS) {
132
+ if (working[key] !== before[key]) patch[key] = working[key];
133
+ }
104
134
  const file = writeRepairSection(patch);
105
135
  const notes = [`Repair settings saved to ${file}.`];
106
136
  if (patch.autoBg !== undefined || patch.autoBgSecs !== undefined) {
@@ -17,6 +17,13 @@
17
17
  * - apply_patch (Codex-style V4D diffs) and str_replace_editor (DSH Minimal
18
18
  * pair) as new tools.
19
19
  * - a `tool_call` guard hook and the `/repair` status command.
20
+ * - three DeepSeek Harness enrichments (2026-11): a `tool_result` SPILL policy
21
+ * (oversized results keep head+tail, the full text lands in a retrievable
22
+ * file), a `tool_result` REPEAT-CALL reminder (advisory footer at the
23
+ * 3rd/5th/8th identical call — targets Flash's loop failure mode), and a
24
+ * `before_agent_start` CLOCK (pi injects no date/time anywhere). Spill is
25
+ * scoped to RETURNED content: stock read/bash truncate inside the tool
26
+ * before `tool_result` fires, so their dropped bytes are already gone.
20
27
  *
21
28
  * Settings (`repair` section, lib/settings.ts) are read PER TOOL CALL, so the
22
29
  * /config toggles apply to the next turn. Exception: the bash description
@@ -43,6 +50,10 @@ import {
43
50
  import { Type } from "typebox";
44
51
  import { abortAllBgJobs, bashAutoBgClause, setBgDeliveryEnabled, wrapWithAutoBg } from "./lib/auto-bg.js";
45
52
  import { killPersistentShells, persistentBashClause, wrapWithPersistentShell } from "./lib/persistent-bash.js";
53
+ import { DEFAULT_CLOCK_REFRESH_MS, renderClock, shouldInject, type ClockState } from "./lib/clock.js";
54
+ import { advanceChain, type RepeatChain } from "./lib/repeat-reminder.js";
55
+ import { DEFAULT_SPILL_MAX_TOKENS, estimateTokens, formatSpillNotice, longestLineLength, retainContent, shortestLineLength } from "./lib/spill.js";
56
+ import { saveSpill } from "./lib/spill-store.js";
46
57
  import {
47
58
  computeRetryEdit,
48
59
  isEditMismatchError,
@@ -668,6 +679,15 @@ export default function repairModule(pi: ExtensionAPI) {
668
679
  // unresolvable misses on the same file (26% retry-fail tail).
669
680
  const editMismatchCounts = new Map<string, number>();
670
681
 
682
+ // Per-session advisory/awareness state, keyed by session id (persistent-bash
683
+ // pattern). Keyed maps cannot collide across sessions, so no isChildSession
684
+ // gate is needed — the a2a contamination incident was UNKEYED module scope.
685
+ const repeatChains = new Map<string, RepeatChain>();
686
+ const clockStates = new Map<string, ClockState>();
687
+ const sessionKey = (id?: string): string => id ?? process.env.PI_SESSION_ID ?? "_default_";
688
+ /** Separator between retained head and tail in a spilled result. */
689
+ const GAP_TEXT = "\n\n[...]\n\n";
690
+
671
691
  const onRepair = (toolName: string, repairs: readonly RepairKind[]) => {
672
692
  repairCounts.set(toolName, (repairCounts.get(toolName) ?? 0) + 1);
673
693
  };
@@ -867,6 +887,109 @@ export default function repairModule(pi: ExtensionAPI) {
867
887
  }
868
888
  });
869
889
 
890
+ // ── tool_result: spill + repeat-tool-reminder (ALL models) ──
891
+ // Both are ADVISORY: they rewrite the model-visible result and never block.
892
+ pi.on("tool_result", async (event, ctx) => {
893
+ const live = readRepairSettings(ctx?.cwd);
894
+ const key = sessionKey(ctx?.sessionManager?.getSessionId?.());
895
+ // Nested calls (a codemode script fanning out) are the parent's business;
896
+ // DSH skips them for both features and so do we.
897
+ const nested = typeof (event as any).parentToolCallId === "string";
898
+
899
+ let content = [...event.content];
900
+ let changed = false;
901
+
902
+ // Repeat-tool-reminder: counts EXACT repeats of ALLOWED calls, which the
903
+ // blocking guards (permission doom-loop, munin dampener) never see.
904
+ if (live.repeatReminder && !nested) {
905
+ const advanced = advanceChain(repeatChains.get(key), event.toolName, event.input);
906
+ if (advanced) {
907
+ repeatChains.set(key, advanced.chain);
908
+ if (advanced.footer) {
909
+ const lastText = [...content].reverse().find((b): b is { type: "text"; text: string } => b.type === "text");
910
+ content = lastText
911
+ ? content.map((b) => (b === lastText ? { ...b, text: `${lastText.text}${advanced.footer}` } : b))
912
+ : [...content, { type: "text", text: advanced.footer }];
913
+ changed = true;
914
+ }
915
+ }
916
+ }
917
+
918
+ // Spill: bound an oversized result and name the file holding it. Scope is
919
+ // RETURNED content — stock read/bash truncate inside the tool before this
920
+ // hook fires, so their dropped bytes are unrecoverable here and those
921
+ // results are excluded (see lib/spill.ts header).
922
+ if (live.spillMaxTokens > 0) {
923
+ const details = event.details as { fullOutputPath?: unknown; truncation?: { truncated?: unknown } } | undefined;
924
+ // Any tool that already spilled itself (bash, codemode, grep…) reports
925
+ // fullOutputPath in details. codemode is the one that surprised a live
926
+ // probe: it truncates at 10,000 tokens (execute.js:248) and sets this
927
+ // too, so it can never reach the seam oversized.
928
+ const selfTruncated = typeof details?.fullOutputPath === "string";
929
+ // Metadata, never notice text: a wrapped read of a file CONTAINING
930
+ // "Use offset=" must still spill (the wrapper strips details.truncation
931
+ // on its own views; the stock pass-through keeps it).
932
+ const selfTruncatedByRead = event.toolName === "read" && details?.truncation?.truncated === true;
933
+ const hasImages = content.some((b) => b.type === "image");
934
+ if (!selfTruncated && !selfTruncatedByRead && !hasImages) {
935
+ const textBlocks = content.filter((b): b is { type: "text"; text: string } => b.type === "text" && typeof b.text === "string");
936
+ if (textBlocks.length > 0 && estimateTokens(textBlocks) > live.spillMaxTokens) {
937
+ const full = textBlocks.map((b) => b.text).join("\n");
938
+ try {
939
+ const file = await saveSpill(event.toolName, event.toolCallId, full);
940
+ // Reserve the notice + gap BEFORE retaining so the patched result
941
+ // fits the caller's budget rather than overshooting it.
942
+ const longest = longestLineLength(full);
943
+ // Shortest line drives the LINE cap: short lines mean many lines
944
+ // per byte window, and pi's bash drops a page's HEAD past 2000
945
+ // lines while our offset has already advanced past it.
946
+ const shortest = shortestLineLength(full);
947
+ const worstNotice = formatSpillNotice(full.length, file, longest, live.spillMaxTokens, shortest);
948
+ const reserved = estimateTokens([{ type: "text", text: GAP_TEXT }, { type: "text", text: worstNotice }]);
949
+ const retained = retainContent(textBlocks.map((b) => b.text), Math.max(0, live.spillMaxTokens - reserved));
950
+ const notice = formatSpillNotice(retained.omittedBytes, file, longest, live.spillMaxTokens, shortest);
951
+ content =
952
+ retained.head.length + retained.tail.length === 0
953
+ ? [{ type: "text", text: notice.trimStart() }]
954
+ : [...retained.head, { type: "text", text: GAP_TEXT }, ...retained.tail, { type: "text", text: notice }];
955
+ changed = true;
956
+ } catch {
957
+ /* fail-open: an unwritable store must never cost the model its result */
958
+ }
959
+ }
960
+ }
961
+ }
962
+
963
+ return changed ? { content } : undefined;
964
+ });
965
+
966
+ // ── before_agent_start: clock injection + repeat-chain reset ──
967
+ pi.on("before_agent_start", (event, ctx) => {
968
+ const key = sessionKey(ctx?.sessionManager?.getSessionId?.());
969
+ // A new user message means the previous context is gone: repetition across
970
+ // an interjection is not a loop (DSH's reset rule). Only real user runs
971
+ // reset — cron fires and follow-ups are not interjections.
972
+ if (event.messageType === "user") repeatChains.delete(key);
973
+
974
+ const live = readRepairSettings(ctx?.cwd);
975
+ const now = Date.now();
976
+ const state = clockStates.get(key);
977
+ const refreshMs = live.clockRefreshMs === undefined ? DEFAULT_CLOCK_REFRESH_MS : live.clockRefreshMs;
978
+ if (live.clock && shouldInject(state, now, refreshMs)) {
979
+ const elapsed = state?.lastActivity === undefined ? undefined : now - state.lastActivity;
980
+ clockStates.set(key, { lastInjection: now, lastActivity: now });
981
+ return {
982
+ message: {
983
+ customType: "ceulen-clock",
984
+ content: renderClock(now, elapsed),
985
+ display: false,
986
+ },
987
+ };
988
+ }
989
+ if (state) clockStates.set(key, { ...state, lastActivity: now });
990
+ return undefined;
991
+ });
992
+
870
993
  // ── /repair (bare = status) ──
871
994
  pi.registerCommand("repair", {
872
995
  description: "Show tool-hardening status: repair counts, guards, bash auto-background, persistent shell.",
@@ -883,6 +1006,9 @@ export default function repairModule(pi: ExtensionAPI) {
883
1006
  ` Auto-generated write guard: ${live.autoGenGuard ? "on" : "off"}`,
884
1007
  ` Auto-background bash: ${live.autoBg ? `on @${live.autoBgSecs}s` : "off"}${live.autoBg !== autoBgOn || live.autoBgSecs !== autoBgSecs ? ` (bound at load: ${autoBgOn ? `on @${autoBgSecs}s` : "off"} — next session applies)` : ""}`,
885
1008
  ` Persistent bash: ${live.persistentBash ? "on" : "off"}${live.persistentBash !== persistentBashOn ? ` (bound at load: ${persistentBashOn ? "on" : "off"} — next session applies)` : ""}${persistentBashOn && (live.autoBg || autoBgOn) ? " · auto-background suspended while persistent is on" : ""}`,
1009
+ ` Tool-result spill: ${live.spillMaxTokens > 0 ? `over ${live.spillMaxTokens} tok → saved to a file` : "off"}`,
1010
+ ` Repeat-call reminder: ${live.repeatReminder ? "on (3rd/5th/8th identical call)" : "off"}`,
1011
+ ` Model-visible clock: ${live.clock ? `on @${Math.round(live.clockRefreshMs / 1000)}s` : "off"}`,
886
1012
  "",
887
1013
  `**Repairs this session:** ${total} total`,
888
1014
  ];
@@ -0,0 +1,106 @@
1
+ // Time context — the model-visible clock pi does not inject anywhere.
2
+ //
3
+ // Ported from DeepSeek Harness `packages/context/time-context` (renderText +
4
+ // the 10-minute durable refresh). pi's system prompt carries no date/time at
5
+ // all (dist/core/system-prompt.js renders with `timestamp: 0`), so a long
6
+ // session — goal mode, cron loops, multi-hour refactors — has no way to know
7
+ // when "today" is or how long it has been running.
8
+ //
9
+ // Deliberate reductions from DSH: no browser-timezone negotiation (that is a
10
+ // web-app concept; a TUI has one process zone), no session projection (pi
11
+ // rehydrates nothing here — the maps are per-process and per-session-id), and
12
+ // no turn/step numbering in the line (pi's turn index is not model-meaningful
13
+ // and would churn with every turn).
14
+ //
15
+ // Cache-safety: one injected message per refresh WINDOW (default 10 minutes),
16
+ // appended after the user message, so a long session adds a handful of small
17
+ // messages instead of one per turn. This is DSH's append-only policy verbatim.
18
+
19
+ /** Default minutes-scale refresh window (DSH refreshIntervalMs default). */
20
+ export const DEFAULT_CLOCK_REFRESH_MS = 600_000;
21
+
22
+ /** Compact whole-second duration: `2d 3h 5m 7s` (DSH formatDuration). */
23
+ export function formatDuration(elapsedMs: number): string {
24
+ // A backward wall-clock reading is a property of the clock, not the span.
25
+ const total = Math.max(0, Math.floor(elapsedMs / 1000));
26
+ const days = Math.floor(total / 86_400);
27
+ const hours = Math.floor((total % 86_400) / 3_600);
28
+ const minutes = Math.floor((total % 3_600) / 60);
29
+ const seconds = total % 60;
30
+ const parts: string[] = [];
31
+ if (days > 0) parts.push(`${days}d`);
32
+ if (hours > 0) parts.push(`${hours}h`);
33
+ if (minutes > 0) parts.push(`${minutes}m`);
34
+ parts.push(`${seconds}s`);
35
+ return parts.join(" ");
36
+ }
37
+
38
+ /**
39
+ * ISO-8601 timestamp with a numeric UTC offset and the IANA zone name.
40
+ * The numeric offset is what a model does arithmetic with; the zone name is
41
+ * what makes a DST boundary legible — DSH keeps both for the same reason.
42
+ */
43
+ export function formatTimestamp(now: number, timeZone?: string): string {
44
+ const date = new Date(now);
45
+ const zone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
46
+ const iso = isoWithOffset(date, zone);
47
+ return `${iso} (${zone})`;
48
+ }
49
+
50
+ /** `YYYY-MM-DDTHH:mm:ss±HH:MM` for an instant rendered in `timeZone`. */
51
+ function isoWithOffset(date: Date, timeZone: string): string {
52
+ let parts: Intl.DateTimeFormatPart[];
53
+ try {
54
+ parts = new Intl.DateTimeFormat("en-CA", {
55
+ timeZone,
56
+ year: "numeric",
57
+ month: "2-digit",
58
+ day: "2-digit",
59
+ hour: "2-digit",
60
+ minute: "2-digit",
61
+ second: "2-digit",
62
+ hour12: false,
63
+ }).formatToParts(date);
64
+ } catch {
65
+ // Unknown zone → fall back to the process zone rather than dropping the clock.
66
+ return isoWithOffset(date, Intl.DateTimeFormat().resolvedOptions().timeZone);
67
+ }
68
+ const get = (type: string): string => parts.find((p) => p.type === type)?.value ?? "00";
69
+ // Intl renders midnight as 24 in some ICU builds; normalise to 00.
70
+ const hour = get("hour") === "24" ? "00" : get("hour");
71
+ const stamp = `${get("year")}-${get("month")}-${get("day")}T${hour}:${get("minute")}:${get("second")}`;
72
+ return `${stamp}${offsetFor(date, timeZone)}`;
73
+ }
74
+
75
+ /** Numeric UTC offset (`+07:00`) of `timeZone` at instant `date`. */
76
+ function offsetFor(date: Date, timeZone: string): string {
77
+ try {
78
+ const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" })
79
+ .formatToParts(date)
80
+ .find((p) => p.type === "timeZoneName")?.value;
81
+ const match = name?.match(/GMT([+-]\d{2}:\d{2})?/);
82
+ if (match) return match[1] ?? "+00:00";
83
+ } catch { /* fall through to UTC */ }
84
+ return "+00:00";
85
+ }
86
+
87
+ /** The two-line clock message body. */
88
+ export function renderClock(now: number, elapsedMs: number | undefined, timeZone?: string): string {
89
+ const elapsed = elapsedMs === undefined ? "unavailable" : formatDuration(elapsedMs);
90
+ return `Time: ${formatTimestamp(now, timeZone)}\nElapsed since last activity: ${elapsed}`;
91
+ }
92
+
93
+ /** Per-session clock bookkeeping. */
94
+ export interface ClockState {
95
+ lastInjection: number;
96
+ lastActivity?: number;
97
+ }
98
+
99
+ /** Whether this session is due for an injection given its refresh window. */
100
+ export function shouldInject(state: ClockState | undefined, now: number, refreshMs: number): boolean {
101
+ if (refreshMs <= 0) return true;
102
+ if (state === undefined) return true;
103
+ const since = now - state.lastInjection;
104
+ // A backward clock reading must not park the clock forever.
105
+ return since < 0 || since >= refreshMs;
106
+ }
@@ -0,0 +1,90 @@
1
+ // Repeat-tool-reminder — advisory loop guard for EXACT repeated tool calls.
2
+ //
3
+ // Ported from DeepSeek Harness `packages/guard/repeat-tool-reminder`. The pi
4
+ // seam differs from DSH's (`tools/post-execute` can attach additionalContexts
5
+ // there; pi's `tool_result` result can only patch content), so the advisory
6
+ // channel is a FOOTER appended to the result text: the call still executes and
7
+ // its real output survives — unlike ceulen's two blocking guards (permission's
8
+ // doom-loop on denied calls, munin's dampener on munin tools), which refuse.
9
+ //
10
+ // Counting is on post-execution for that reason: a model hammering a call that
11
+ // SUCCEEDS is the DeepSeek Flash loop failure mode, and a refusal would erase
12
+ // the evidence the model needs to change approach.
13
+
14
+ /** Consecutive-repeat counts that trigger a reminder (DSH default). */
15
+ export const REPEAT_THRESHOLDS = [3, 5, 8] as const;
16
+ /** Canonical arguments quoted in the detailed reminder (DSH cap). */
17
+ export const ARGUMENTS_PREVIEW_CHARS = 500;
18
+ /** The munin module's own dampener owns its tools — never double-advise. */
19
+ const MUNIN_PREFIX = "munin_";
20
+
21
+ /** Deep key-sort so two argument objects differing only in property order
22
+ * canonicalize identically (DSH sortJsonValue; arguments arrive as the loop's
23
+ * JSON.parse output, so JSON's value domain is the whole input domain). */
24
+ export function sortJsonValue(value: unknown): unknown {
25
+ if (Array.isArray(value)) return value.map(sortJsonValue);
26
+ if (value !== null && typeof value === "object") {
27
+ const record = value as Record<string, unknown>;
28
+ const sorted: Record<string, unknown> = {};
29
+ for (const key of Object.keys(record).sort()) sorted[key] = sortJsonValue(record[key]);
30
+ return sorted;
31
+ }
32
+ return value;
33
+ }
34
+
35
+ /** Canonical string form of a call's arguments: deep key-sort, then stringify. */
36
+ export function canonicalizeArguments(args: unknown): string {
37
+ return JSON.stringify(sortJsonValue(args));
38
+ }
39
+
40
+ /** Identity key of one call: tool name + canonical arguments. */
41
+ export function callKey(toolName: string, args: unknown): string {
42
+ return JSON.stringify([toolName, canonicalizeArguments(args)]);
43
+ }
44
+
45
+ /** Whether a tool participates in the chain (munin tools are excluded). */
46
+ export function isTrackedTool(toolName: string): boolean {
47
+ return !toolName.startsWith(MUNIN_PREFIX);
48
+ }
49
+
50
+ const GENTLE_REMINDER =
51
+ "Same tool call repeated with identical arguments — analyze the previous result "
52
+ + "before calling again: if the task is not complete, try a different approach or "
53
+ + "different arguments instead of repeating the call.";
54
+
55
+ function previewArguments(canonical: string): string {
56
+ if (canonical.length <= ARGUMENTS_PREVIEW_CHARS) return canonical;
57
+ return `${canonical.slice(0, ARGUMENTS_PREVIEW_CHARS)}… (+${canonical.length - ARGUMENTS_PREVIEW_CHARS} more chars)`;
58
+ }
59
+
60
+ /** The reminder text for a chain that just hit `count`, or undefined. */
61
+ export function reminderFor(toolName: string, count: number, canonical: string): string | undefined {
62
+ if (!(REPEAT_THRESHOLDS as readonly number[]).includes(count)) return undefined;
63
+ const body = count === REPEAT_THRESHOLDS[0]
64
+ ? GENTLE_REMINDER
65
+ : `Repeated tool call detected:\n- tool: ${toolName}\n- consecutive_calls: ${count}\n- arguments: ${previewArguments(canonical)}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again — inspect the latest result and choose a different action, different arguments, or finish the task.`;
66
+ return `\n\n[ceulen] ${body}`;
67
+ }
68
+
69
+ /** One session's consecutive-repeat chain. */
70
+ export interface RepeatChain {
71
+ key: string;
72
+ count: number;
73
+ }
74
+
75
+ /**
76
+ * Advance a chain for one call and return the footer to append, if any.
77
+ * Untracked tools are TRANSPARENT (neither count nor reset), matching DSH.
78
+ */
79
+ export function advanceChain(
80
+ chain: RepeatChain | undefined,
81
+ toolName: string,
82
+ args: unknown,
83
+ ): { chain: RepeatChain; footer?: string } | undefined {
84
+ if (!isTrackedTool(toolName)) return undefined;
85
+ const key = callKey(toolName, args);
86
+ const count = chain !== undefined && chain.key === key ? chain.count + 1 : 1;
87
+ const next: RepeatChain = { key, count };
88
+ const footer = reminderFor(toolName, count, canonicalizeArguments(args));
89
+ return footer === undefined ? { chain: next } : { chain: next, footer };
90
+ }
@@ -34,6 +34,14 @@ export interface RepairSettings {
34
34
  /** One persistent bash shell per session (cwd/env/jobs survive across calls).
35
35
  * Binds at load — the shell description sits in the cache-safe request head. */
36
36
  persistentBash: boolean;
37
+ /** Token budget for one tool result; excess is spilled to a retrievable file. 0 = off. */
38
+ spillMaxTokens: number;
39
+ /** Advisory footer when the same tool call repeats with identical arguments. */
40
+ repeatReminder: boolean;
41
+ /** Inject a model-visible clock (pi injects no date/time anywhere). */
42
+ clock: boolean;
43
+ /** Minimum milliseconds between clock injections in one session. */
44
+ clockRefreshMs: number;
37
45
  }
38
46
 
39
47
  export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
@@ -44,6 +52,11 @@ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
44
52
  autoBg: false,
45
53
  autoBgSecs: 120,
46
54
  persistentBash: false,
55
+ // DSH base-preset value (packages/bundle/base/cordis.patch.yml maxInlineTokens).
56
+ spillMaxTokens: 12_500,
57
+ repeatReminder: true,
58
+ clock: false,
59
+ clockRefreshMs: 600_000,
47
60
  };
48
61
 
49
62
  function agentDir(): string {
@@ -67,7 +80,7 @@ function section(json: Record<string, unknown> | null, key: string): Record<stri
67
80
  /** Merge one settings layer's `repair` keys over out (field-wise override). */
68
81
  function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
69
82
  const s = section(json, "repair");
70
- for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash"] as const) {
83
+ for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash", "repeatReminder", "clock"] as const) {
71
84
  if (typeof s[key] === "boolean") out[key] = s[key];
72
85
  }
73
86
  if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {
@@ -75,6 +88,14 @@ function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null):
75
88
  // everything (upstream's env reader clamped for the same reason).
76
89
  out.autoBgSecs = Math.max(1, Math.floor(s.autoBgSecs));
77
90
  }
91
+ if (typeof s.spillMaxTokens === "number" && Number.isFinite(s.spillMaxTokens)) {
92
+ // Clamp at 0 (= disabled). A negative budget would otherwise mean "spill
93
+ // everything to nothing", the opposite of what a typo intended.
94
+ out.spillMaxTokens = Math.max(0, Math.floor(s.spillMaxTokens));
95
+ }
96
+ if (typeof s.clockRefreshMs === "number" && Number.isFinite(s.clockRefreshMs)) {
97
+ out.clockRefreshMs = Math.max(0, Math.floor(s.clockRefreshMs));
98
+ }
78
99
  }
79
100
 
80
101
  /** The agent-dir settings.json (the file /config saves into). */