teapot-coding-agent 0.32.5 → 0.34.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.
@@ -228,8 +228,9 @@ Most session state is not injected into prompts — fetch it with tools instead:
228
228
  → your durable notes (memory.md). add_memory appends and cannot lose earlier
229
229
  notes; forget_memory removes the lines matching a substring, so a stale note can
230
230
  be corrected instead of piling up; set_memory REPLACES the whole file. Pass a
231
- query to read_memory to search rather than dumping everything. The notes are NOT
232
- in your prompt — read them.
231
+ query to read_memory to search rather than dumping everything. Your prompt carries
232
+ a DIGEST (headings and one line each) — the notes themselves are not in it, so
233
+ read_memory(query) is how you actually get one.
233
234
  - get_todo() / set_todo(content) → the operator-maintained task list
234
235
  (todo.md); check it when picking up work, keep it current as you go.
235
236
  - When corrected, add_feedback(rule) so it sticks; review via get_feedback().
@@ -276,10 +277,21 @@ Most session state is not injected into prompts — fetch it with tools instead:
276
277
  panel) — do NOT also repeat the same content as a chat message; end the
277
278
  turn right after the call (a short "reported." is fine).
278
279
  - Be frugal: prefer small precise edits, avoid runaway loops.
279
- - When the operator asks you to remember something, WRITE it with add_memory. When
280
- earlier context might be relevant again (a decision, a gotcha, where you left off),
281
- SEARCH it with read_memory(query) and use what you find. Nothing is injected: an
282
- unread note is an unwritten note.`;
280
+ - When the operator asks you to remember something, WRITE it with add_memory.
281
+ Write the KIND of thing that stays true and saves work later: a decision and
282
+ why, a gotcha that cost time, a command that works here, where you left off.
283
+ Do not write a narrative of what you did — the log already has that.
284
+ - WHEN to consult your notes — a decision boundary, not "always search":
285
+ skip it for a self-contained request (a one-line shell command, a simple
286
+ rewrite, a question about the current file). Use it by DEFAULT when the task
287
+ touches this workspace's history, conventions or prior choices; when the
288
+ operator asks for consistency with earlier work; when the task is ambiguous in
289
+ a way earlier context would settle; or when you are picking up something you
290
+ started before. If unsure, do one quick pass.
291
+ - A quick pass is cheap and bounded: search the digest in your prompt with
292
+ read_memory(query), open at most one or two of the notes that match, and stop.
293
+ If nothing is relevant, carry on — do not keep searching, and do not read the
294
+ whole file "just in case". An unread note is an unwritten note.`;
283
295
  /**
284
296
  * A message whose ENTIRE text is parenthesised is an acknowledgement, not work.
285
297
  *
@@ -477,6 +489,15 @@ export class Agent {
477
489
  */
478
490
  auditAttempts = 0;
479
491
  lastRejectedAudit = null;
492
+ /**
493
+ * What the agent had done BEFORE an audit rejected its first finish (#94).
494
+ *
495
+ * Captured at rejection time because that is the last moment the pre-rejection work is still
496
+ * the bulk of the history. The eventual approved final would otherwise report only the retry,
497
+ * which is a narrow fix-up — the parent would be judging hours of work from its last few
498
+ * minutes.
499
+ */
500
+ preRejectionTurns = [];
480
501
  lastAuditOutcome = null;
481
502
  constructor(opts) {
482
503
  this.opts = {
@@ -605,6 +626,66 @@ export class Agent {
605
626
  * against, so a skill with a poor description is effectively undiscoverable;
606
627
  * that is worth knowing when authoring one.
607
628
  */
629
+ /**
630
+ * A bounded DIGEST of memory.md: every heading, plus its first line.
631
+ *
632
+ * MEASURED reason this exists. The notes are agent-scoped now (they outlive a session) and
633
+ * they are genuinely long — 2.6KB is the median, and the largest hold full project briefs. A
634
+ * model that never sees them cannot decide to consult them: that is the whole finding of #48
635
+ * (182 writes, 13 reads after a write). A model that sees the WHOLE file pays for it on every
636
+ * request and breaks the prefix cache.
637
+ *
638
+ * Codex solves this with a `MEMORY_SUMMARY` in the prompt plus a searchable registry on disk.
639
+ * This is the same shape: the digest says what memory HOLDS, `read_memory(query)` fetches the
640
+ * part that matters.
641
+ *
642
+ * The budget is deliberately small. This is an index, and an index that costs as much as the
643
+ * content has no reason to be an index.
644
+ */
645
+ memoryDigestText() {
646
+ let text;
647
+ try {
648
+ text = readFileSync(this.memoryFile, "utf8");
649
+ }
650
+ catch {
651
+ return ""; // no notes yet
652
+ }
653
+ if (!text.trim())
654
+ return "";
655
+ const MAX_CHARS = 1_400;
656
+ const lines = text.split(/\r?\n/);
657
+ const out = [];
658
+ let used = 0;
659
+ for (let i = 0; i < lines.length; i++) {
660
+ const line = lines[i].trim();
661
+ if (!line)
662
+ continue;
663
+ // provenance markers are bookkeeping, not content
664
+ // bookkeeping, not content: an old-style provenance comment, or a `_from:_` line — the
665
+ // latter is reachable through read_memory(query), where it is useful, but in a DIGEST it
666
+ // would be noise under every heading
667
+ if (/^<!--/.test(line) || /^_from:/.test(line))
668
+ continue;
669
+ const isHeading = /^#{1,6}\s/.test(line);
670
+ const isBullet = /^[-*]\s/.test(line);
671
+ // headings and the FIRST line under one: enough to recognise a topic without
672
+ // reproducing the note. A bullet is included only as a one-line sample.
673
+ if (!isHeading && !isBullet) {
674
+ // a continuation of the previous line — skip, the heading already names the topic
675
+ if (!out.length)
676
+ out.push(line.slice(0, 100));
677
+ continue;
678
+ }
679
+ const rendered = isHeading ? line.slice(0, 90) : ` · ${line.slice(0, 80)}`;
680
+ if (used + rendered.length > MAX_CHARS) {
681
+ out.push(`(… ${lines.length} lines total — call read_memory(query) to search the rest)`);
682
+ break;
683
+ }
684
+ out.push(rendered);
685
+ used += rendered.length + 1;
686
+ }
687
+ return out.join("\n").trim();
688
+ }
608
689
  skillCatalogueText() {
609
690
  if (!this.skillsCache.length)
610
691
  return "";
@@ -693,8 +774,21 @@ export class Agent {
693
774
  get workspace() {
694
775
  return this.opts.workspace;
695
776
  }
696
- /** true while the workspace directory does not exist on disk yet */
777
+ /**
778
+ * True while the workspace directory does not exist on disk.
779
+ *
780
+ * Re-checked here rather than trusting the flag set at `init()`: the directory can come BACK
781
+ * (the operator recreates it, another agent in the same project makes it, a new session is
782
+ * created in it), and a boot-time snapshot then leaves every older session flagged 👻 forever.
783
+ * That is the reported symptom: a recreated directory shows its session count, but the sidebar
784
+ * lists only the session that was just created, because all the older ones still say "ghost".
785
+ */
697
786
  get isGhost() {
787
+ const exists = existsSync(this.workspace);
788
+ // only ever CLEAR from here: a sync getter must not claim a directory exists when it does
789
+ // not, but it can safely notice that it does again
790
+ if (exists)
791
+ this.workspaceMissing = false;
698
792
  return this.workspaceMissing;
699
793
  }
700
794
  /** Create the workspace on demand — before any tool touches the fs. */
@@ -910,6 +1004,7 @@ export class Agent {
910
1004
  }
911
1005
  async init() {
912
1006
  await this.log.load();
1007
+ await this.migrateMemoryToAgentScope();
913
1008
  // NOTE: the workspace is NOT created here. Boot-time mkdir resurrected
914
1009
  // deleted project directories on every restart, which operators hated.
915
1010
  // It is created lazily in ensureWorkspace() when the agent first needs
@@ -1019,7 +1114,29 @@ export class Agent {
1019
1114
  get goalFile() {
1020
1115
  return path.join(this.opts.sessionDir, "goal.md");
1021
1116
  }
1117
+ /**
1118
+ * Durable notes — AGENT-scoped, not session-scoped.
1119
+ *
1120
+ * MEASURED: memory.md lived in `sessionDir`, so starting a new session for an agent
1121
+ * silently orphaned everything it had learned. Across this machine, 66 agents had more
1122
+ * than one session (median 6 each) and only 5 of them had notes in any session at all —
1123
+ * the notes were written, then abandoned when the next session was minted. A "durable
1124
+ * note" that dies with the timeline is not durable.
1125
+ *
1126
+ * The file lives next to the agent's session DIRECTORY (`sessions/<agent>/memory.md`),
1127
+ * a level above the per-session dirs, so every session of that agent sees the same
1128
+ * notes. A session's own `memory.md` from an older build is migrated on first read.
1129
+ */
1022
1130
  get memoryFile() {
1131
+ const perSession = path.join(this.opts.sessionDir, "memory.md");
1132
+ const agentWide = path.join(path.dirname(this.opts.sessionDir), "memory.md");
1133
+ // `sessionDir` may itself be the agent-level directory in older layouts; only use the
1134
+ // parent when the basename looks like a session (<agent>-<hex>)
1135
+ const looksPerSession = /-[0-9a-f]{6,}$/i.test(path.basename(this.opts.sessionDir));
1136
+ return looksPerSession ? agentWide : perSession;
1137
+ }
1138
+ /** the pre-migration location, read once so notes are not lost on upgrade */
1139
+ get legacyMemoryFile() {
1023
1140
  return path.join(this.opts.sessionDir, "memory.md");
1024
1141
  }
1025
1142
  get todoFile() {
@@ -1058,6 +1175,42 @@ export class Agent {
1058
1175
  to: this.goalFile,
1059
1176
  });
1060
1177
  }
1178
+ /**
1179
+ * Move notes from the per-session file into the agent-wide one — once.
1180
+ *
1181
+ * Older builds wrote memory.md inside the session dir. Those notes are real knowledge and
1182
+ * must not be abandoned by the upgrade that makes them durable, so the session's file is
1183
+ * APPENDED to the agent-wide one (never replacing it: the agent-wide file may already hold
1184
+ * notes from other sessions) and then removed so a later session does not re-import it.
1185
+ */
1186
+ async migrateMemoryToAgentScope() {
1187
+ const from = this.legacyMemoryFile;
1188
+ const to = this.memoryFile;
1189
+ if (from === to)
1190
+ return;
1191
+ let legacy;
1192
+ try {
1193
+ legacy = (await fs.readFile(from, "utf8")).trim();
1194
+ }
1195
+ catch {
1196
+ return; // nothing to migrate
1197
+ }
1198
+ if (!legacy) {
1199
+ await fs.rm(from, { force: true }).catch(() => { });
1200
+ return;
1201
+ }
1202
+ try {
1203
+ const existing = (await fs.readFile(to, "utf8").catch(() => "")).trim();
1204
+ const merged = (existing ? `${existing}\n` : "") +
1205
+ `<!-- migrated from session ${path.basename(this.opts.sessionDir)} -->\n${legacy}\n`;
1206
+ await fs.writeFile(to, merged, "utf8");
1207
+ await fs.rm(from, { force: true });
1208
+ console.log(`[teapot] memory: migrated ${legacy.length} bytes to ${path.basename(to)} (agent scope)`);
1209
+ }
1210
+ catch {
1211
+ /* keep the session copy if the agent-wide write failed — losing notes is worse */
1212
+ }
1213
+ }
1061
1214
  /**
1062
1215
  * Rebuild the in-memory conversation from the JSONL event log so a restart
1063
1216
  * continues where the agent left off instead of starting blank.
@@ -1557,7 +1710,8 @@ export class Agent {
1557
1710
  */
1558
1711
  live: this.isLive(),
1559
1712
  workspace: this.workspace,
1560
- workspaceMissing: this.workspaceMissing,
1713
+ // through the getter, so a workspace that came back stops being reported as 👻
1714
+ workspaceMissing: this.isGhost,
1561
1715
  session: this.currentSession,
1562
1716
  // #155: a human label for this session, so the sidebar does not ask the
1563
1717
  // operator to read `teapot-10-16854917`. Absent when the first prompt had
@@ -2515,11 +2669,44 @@ export class Agent {
2515
2669
  return "next";
2516
2670
  }
2517
2671
  const needle = query.toLowerCase();
2518
- const hits = mem
2519
- .split(/\r?\n/)
2520
- .filter((line) => line.toLowerCase().includes(needle));
2672
+ const lines = mem.split(/\r?\n/);
2673
+ const hits = lines.filter((line) => line.toLowerCase().includes(needle));
2674
+ /**
2675
+ * Give each hit its CONTEXT, not just the bare line.
2676
+ *
2677
+ * A matching line on its own is often meaningless — "the cache lies" says nothing
2678
+ * without the heading it sits under. And a note needs to be dateable to be usable: a
2679
+ * lesson harvested from a compaction three weeks ago should not read with the same
2680
+ * authority as one from today. So each hit is reported with its nearest preceding
2681
+ * heading and any `_from:_` provenance line.
2682
+ */
2683
+ const headingAt = (idx) => {
2684
+ for (let i = idx; i >= 0; i--) {
2685
+ const l = lines[i].trim();
2686
+ if (/^#{1,6}\s/.test(l))
2687
+ return l;
2688
+ }
2689
+ return "";
2690
+ };
2691
+ const provenanceAt = (idx) => {
2692
+ // the `_from:_` line lives within a few lines above its lesson block
2693
+ for (let i = idx; i >= Math.max(0, idx - 6); i--) {
2694
+ const l = lines[i].trim();
2695
+ if (/^_from:/.test(l))
2696
+ return l.replace(/^_|_$/g, "");
2697
+ }
2698
+ return "";
2699
+ };
2700
+ const rendered = hits.slice(0, 40).map((line) => {
2701
+ const idx = lines.indexOf(line);
2702
+ const head = headingAt(idx);
2703
+ const prov = provenanceAt(idx);
2704
+ const where = [head, prov].filter(Boolean).join(" · ");
2705
+ return where ? `${line}\n ↳ ${where}` : line;
2706
+ });
2521
2707
  await this.answerMeta(call, hits.length
2522
- ? `${hits.length} line(s) matching ${JSON.stringify(query)}:\n${hits.join("\n")}`
2708
+ ? `${hits.length} line(s) matching ${JSON.stringify(query)}` +
2709
+ `${hits.length > 40 ? ` (showing the first 40)` : ""}:\n${rendered.join("\n")}`
2523
2710
  : `(no line in memory.md matches ${JSON.stringify(query)} — ${mem.split(/\r?\n/).length} lines searched; call read_memory with no query to see all of it)`);
2524
2711
  return "next";
2525
2712
  },
@@ -2991,6 +3178,8 @@ export class Agent {
2991
3178
  * for the session and the provider prefix cache survives.
2992
3179
  */
2993
3180
  skillCatalogue = "";
3181
+ /** the compact digest of memory.md put into the frozen prompt (Codex's MEMORY_SUMMARY) */
3182
+ memoryDigest = "";
2994
3183
  systemPrompt() {
2995
3184
  if (!this.agentsMdLoaded) {
2996
3185
  this.agentsMdLoaded = true;
@@ -3064,6 +3253,7 @@ export class Agent {
3064
3253
  // #31: capture the skill catalogue in the SAME one-shot block, so the
3065
3254
  // system prompt stays byte-identical for the session (prefix cache).
3066
3255
  this.skillCatalogue = this.skillCatalogueText();
3256
+ this.memoryDigest = this.memoryDigestText();
3067
3257
  }
3068
3258
  let sys = SYSTEM_TEMPLATE;
3069
3259
  if (this.agentsMd.trim()) {
@@ -3088,6 +3278,27 @@ export class Agent {
3088
3278
  `pass what you want done so the instructions arrive with the playbook. ` +
3089
3279
  `list_skills() shows the full detail.`;
3090
3280
  }
3281
+ /**
3282
+ * A DIGEST of the durable notes — Codex's `MEMORY_SUMMARY`, not the notes themselves.
3283
+ *
3284
+ * The full file cannot go here (it is unbounded, and re-injecting it every turn is the
3285
+ * prefix-cache break that made takos' design a bad fit). But leaving the notes entirely
3286
+ * behind a tool call was measured to fail the other way: the model never learned they
3287
+ * existed, so it never asked. Codex resolves exactly this by injecting a compact summary
3288
+ * and telling the model to search the rest — the summary names WHAT is in memory, the tool
3289
+ * fetches the detail.
3290
+ *
3291
+ * Captured in the same one-shot block as AGENTS.md and the skills catalogue, so the prompt
3292
+ * stays byte-identical for the session.
3293
+ */
3294
+ if (this.memoryDigest) {
3295
+ sys +=
3296
+ `\n\n## Your durable notes (memory.md — a DIGEST, not the whole file)\n${this.memoryDigest}\n` +
3297
+ `The full notes are NOT in this prompt. When any of the above may bear on the task — ` +
3298
+ `prior decisions, gotchas, where you left off — search them: ` +
3299
+ `read_memory(query) returns the matching lines, read_memory() with no query returns everything. ` +
3300
+ `Write with add_memory(text) (appends; never loses an earlier note).`;
3301
+ }
3091
3302
  return sys;
3092
3303
  }
3093
3304
  /**
@@ -3250,6 +3461,14 @@ export class Agent {
3250
3461
  // #94: the rejection survives in memory so the eventual approved
3251
3462
  // final can name what the first attempt was told
3252
3463
  this.lastRejectedAudit = { feedback, attempt: this.auditAttempts };
3464
+ /**
3465
+ * …AND capture the work that was just rejected, once. This runs before the retry
3466
+ * prompt is queued, so the history still holds the original task; capturing later
3467
+ * (at the approved finish) would read only the fix-up.
3468
+ */
3469
+ if (!this.preRejectionTurns.length) {
3470
+ this.preRejectionTurns = await this.captureRecentTurns();
3471
+ }
3253
3472
  }
3254
3473
  // `operatorFacing: true` — the verdict is written for the TIMELINE
3255
3474
  // only. The audit ran in its own side conversation (a tools-less call
@@ -3357,6 +3576,29 @@ export class Agent {
3357
3576
  /** The `final: true` event — the parent's notification (#89: never before the goal settles). */
3358
3577
  async appendFinalMessage(args) {
3359
3578
  const recent = await this.captureRecentTurns();
3579
+ /**
3580
+ * #94: an APPROVED finish after a REJECTION must describe the WHOLE task.
3581
+ *
3582
+ * `captureRecentTurns()` reads the last six meaningful messages, which after a
3583
+ * changes-required verdict is exactly the RETRY — so the parent was told about the last few
3584
+ * minutes of work and nothing about the hours that came before it. The rejection branch
3585
+ * already queues the auditor's feedback as the retry prompt, so the retry is a narrow fix-up;
3586
+ * reporting only that makes the work look trivial and the parent has no basis to judge it.
3587
+ *
3588
+ * The pre-rejection activity is captured when the reject arrives (`preRejectionTurns`) and is
3589
+ * prepended here, clearly labelled, so the parent reads "this is what was done, and this is
3590
+ * what the audit then required". Bounded to the same six entries so the report stays a report.
3591
+ */
3592
+ const before = this.preRejectionTurns;
3593
+ this.preRejectionTurns = [];
3594
+ const combined = before.length
3595
+ ? [
3596
+ `[before the audit rejected the first finish — ${before.length} entries]`,
3597
+ ...before,
3598
+ `[after the rejection — the retry — ${recent.length} entries]`,
3599
+ ...recent,
3600
+ ]
3601
+ : recent;
3360
3602
  // #91/#94: the final says how it relates to the audit — approved on which
3361
3603
  // attempt, what the previous attempt was told. Cleared on emit: a later
3362
3604
  // unaudited finish must not inherit stale lineage.
@@ -3366,7 +3608,7 @@ export class Agent {
3366
3608
  role: "assistant",
3367
3609
  final: true,
3368
3610
  content: String(args.summary ?? ""),
3369
- ...(recent.length ? { recentContext: recent } : {}),
3611
+ ...(combined.length ? { recentContext: combined } : {}),
3370
3612
  ...(outcome
3371
3613
  ? {
3372
3614
  audited: outcome.audited,
@@ -4137,7 +4379,22 @@ export class Agent {
4137
4379
  const lessons = m?.[1]?.trim();
4138
4380
  if (!lessons)
4139
4381
  return;
4140
- const stamped = `\n<!-- lessons harvested from compaction ${new Date().toISOString()} -->\n${lessons}\n`;
4382
+ /**
4383
+ * PROVENANCE, in a form the model can READ.
4384
+ *
4385
+ * The stamp used to be an HTML comment. It recorded exactly the right thing — which
4386
+ * session and which compaction a note came from — and nothing ever read it back: a
4387
+ * `read_memory(query)` returned the lesson with no way to tell whether it was observed
4388
+ * today or inherited from a compaction three weeks ago. A note you cannot date is a note
4389
+ * you cannot safely act on.
4390
+ *
4391
+ * It is now a visible `_from:_` line, which survives search, survives the digest (it is
4392
+ * indented under the heading and skipped as a continuation), and answers "where did this
4393
+ * come from?" in the reply itself.
4394
+ */
4395
+ const session = path.basename(this.opts.sessionDir);
4396
+ const stamped = `\n## lessons from compaction ${new Date().toISOString().slice(0, 16).replace("T", " ")}\n` +
4397
+ `_from: session ${session}, branch ${this.currentBranch}_\n${lessons}\n`;
4141
4398
  await fs.appendFile(this.memoryFile, stamped, "utf8").catch(() => { });
4142
4399
  }
4143
4400
  async recordProgress(argsJson) {
@@ -474,6 +474,73 @@ function trailingWsMatches(srcLines, patLines) {
474
474
  }
475
475
  return hits;
476
476
  }
477
+ /**
478
+ * Did `anchor` resolve to a span far larger than it asked for? Returns the refusal, or null.
479
+ *
480
+ * ## Why this is a separate function
481
+ *
482
+ * The first version was inlined and measured `text.indexOf(anchor)` — which by definition finds
483
+ * exactly `anchor.length` characters, so it could NEVER fire, and its test passed with the guard
484
+ * disabled. The overshoot does not come from the exact match: it comes from the TOLERANT path,
485
+ * where a model that omits indentation or trailing spaces hands over a short anchor and the
486
+ * per-line comparison then accepts a much longer region.
487
+ *
488
+ * So the question is: how many file lines does the anchor's FIRST line's text actually cover
489
+ * once tolerance is applied? If that region is more than twice the anchor's own line count, the
490
+ * anchor is not specific enough and the edit would rewrite something unintended.
491
+ *
492
+ * MEASURED basis (#83): `old_text not found` is 117 of 168 edit failures, and the near-miss
493
+ * cases are exactly the ones where tolerance decides what matched. Being wrong there is silent.
494
+ */
495
+ export function disproportionateSpan(text, anchor) {
496
+ const anchorLines = anchor.split("\n");
497
+ const askedLines = anchorLines.length;
498
+ if (askedLines < 2)
499
+ return null; // a single line cannot span disproportionately
500
+ /**
501
+ * Do NOT require an exact substring match.
502
+ *
503
+ * The whole point is the near-miss case: the anchor does not appear verbatim, which is why the
504
+ * tolerant path is consulted at all and why it can overshoot. Requiring `indexOf` here made
505
+ * the guard unreachable exactly when it matters.
506
+ */
507
+ const anchorFirst = anchorLines[0].trimEnd();
508
+ const start = text.split("\n").findIndex((l) => l.trimEnd() === anchorFirst);
509
+ if (start < 0)
510
+ return null; // its first line is not in the file at all: not this guard's case
511
+ /**
512
+ * How many file lines does the anchor COVER, allowing the same trailing-whitespace tolerance
513
+ * the tolerant matcher uses?
514
+ *
515
+ * This walks the file and the anchor together, and counts file lines consumed. If matching
516
+ * the anchor requires consuming more than twice its own line count, the anchor is too loose:
517
+ * applying it would replace a region the model did not point at.
518
+ */
519
+ const srcLines = text.split("\n");
520
+ const firstLine = start;
521
+ let fileAt = firstLine;
522
+ let consumed = 0;
523
+ for (let a = 0; a < anchorLines.length; a++) {
524
+ const want = anchorLines[a].trimEnd();
525
+ let found = -1;
526
+ for (let f = fileAt; f < srcLines.length; f++) {
527
+ if (srcLines[f].trimEnd() === want) {
528
+ found = f;
529
+ break;
530
+ }
531
+ }
532
+ if (found < 0)
533
+ return null; // did not resolve under tolerance; not this guard's business
534
+ consumed = found - firstLine + 1;
535
+ if (consumed > askedLines * 2) {
536
+ return (`old_text spans ${askedLines} line(s) but only resolves after covering ${consumed} ` +
537
+ `lines of the file — refusing a disproportionate match. An anchor this loose would ` +
538
+ `rewrite a region you did not intend. Re-read the file and copy a tighter block.`);
539
+ }
540
+ fileAt = found + 1;
541
+ }
542
+ return null;
543
+ }
477
544
  export const DEFAULT_TIMEOUT_MS = 120_000;
478
545
  /* ---------- read_url cache ---------- */
479
546
  const URL_CACHE_TTL_MS = 3_600_000;
@@ -1335,6 +1402,29 @@ export const TOOLS = [
1335
1402
  }
1336
1403
  }
1337
1404
  let count = hashNote ? 0 : text.split(oldText).length - 1;
1405
+ /**
1406
+ * A MINIMUM ANCHOR LENGTH, from Gemini's `edit.ts`.
1407
+ *
1408
+ * Below this, an anchor cannot identify anything: " }" or "\n\n" appear everywhere, and
1409
+ * any tolerant matching on them either fails ambiguously or picks a wrong span. MEASURED
1410
+ * across every session (#83): `old_text not found` is 117 of 168 edit failures, and a
1411
+ * large share of those are anchors too short to be unique, sent by a model that believed
1412
+ * them specific.
1413
+ *
1414
+ * Short anchors are still ACCEPTED when they match exactly once — a one-character edit is
1415
+ * legitimate. What is refused is trying to make a short anchor work by relaxing the match.
1416
+ */
1417
+ const MIN_FUZZY_ANCHOR = 10;
1418
+ /**
1419
+ * A MULTI-LINE anchor is specific by construction: two matching lines pin both a start
1420
+ * and a continuation, which is far stronger evidence than 10 characters on one line.
1421
+ * Gemini's floor is about single-line anchors, where " }" and "foo();" genuinely cannot
1422
+ * identify anything. Applying it by raw character count rejected `foo\nbar` — a perfectly
1423
+ * unambiguous two-line anchor — which is the guard making normal editing harder, the
1424
+ * exact failure mode #157 warns about.
1425
+ */
1426
+ const anchorLines = oldText.split("\n").length;
1427
+ const anchorTooShort = anchorLines < 2 && oldText.trim().length < MIN_FUZZY_ANCHOR;
1338
1428
  let normalized = false;
1339
1429
  if (count === 0 && oldText.includes("\n") && text.includes("\r\n")) {
1340
1430
  const lf = text.replace(/\r\n/g, "\n");
@@ -1347,7 +1437,7 @@ export const TOOLS = [
1347
1437
  }
1348
1438
  // tolerate patterns whose only difference is trailing whitespace per line
1349
1439
  // (the most common near-miss) — applied only when it resolves uniquely
1350
- if (count === 0) {
1440
+ if (count === 0 && !anchorTooShort) {
1351
1441
  const srcLines = text.replace(/\r\n/g, "\n").split("\n");
1352
1442
  const patLines = oldText.replace(/\r\n/g, "\n").split("\n");
1353
1443
  const hits = trailingWsMatches(srcLines, patLines);
@@ -1397,6 +1487,18 @@ export const TOOLS = [
1397
1487
  result: `old_text matched ${count} times (lines ${at.slice(0, 5).join(", ")}) and must be unique — add surrounding lines to old_text, or pass replace_all=true`,
1398
1488
  };
1399
1489
  }
1490
+ /**
1491
+ * DISPROPORTIONATE MATCH guard, from OpenCode's `isDisproportionateMatch`.
1492
+ *
1493
+ * The dangerous shape is not "no match" — that is loud and recoverable — but a match far
1494
+ * LARGER than the anchor, where asking to change one call site silently rewrites a whole
1495
+ * function. A confident wrong edit is worse than a failed one.
1496
+ */
1497
+ if (!hashSpan) {
1498
+ const over = disproportionateSpan(text, oldText);
1499
+ if (over)
1500
+ return { ok: false, result: over };
1501
+ }
1400
1502
  // A verified hashline block is addressed BY LINE INDEX: the anchors
1401
1503
  // already proved which lines it means, so a block whose content occurs
1402
1504
  // twice must still edit the anchored occurrence rather than fail the
package/dist/master.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * Agents are in-process async loops (I/O bound only); all CPU-heavy work is
4
4
  * delegated to subprocesses managed by the bash tool with hard timeouts.
5
5
  */
6
+ import { closeAllTerminals, closeTerminalsFor } from "./server/terminals.js";
6
7
  import { readFileSync, existsSync, mkdirSync, writeFileSync, readdirSync, statSync, lstatSync, renameSync, unlinkSync, openSync, closeSync, readSync, fsyncSync, rmSync, } from "node:fs";
7
8
  import { randomUUID } from "node:crypto";
8
9
  import { currentKey, makeKeyPool, resetPool } from "./agent/key-pool.js";
@@ -1962,6 +1963,9 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
1962
1963
  this.agents.delete(one);
1963
1964
  await live.dispose();
1964
1965
  }
1966
+ // an archived agent's shells are unreachable from the UI (its tabs go with it), so
1967
+ // leaving the ptys running would strand them until the idle reaper noticed
1968
+ closeTerminalsFor(one);
1965
1969
  const ac = this.config.agents.find((a) => a.id === one);
1966
1970
  if (!ac)
1967
1971
  continue;
@@ -2267,6 +2271,17 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2267
2271
  finally {
2268
2272
  if (timer)
2269
2273
  clearTimeout(timer);
2274
+ /**
2275
+ * Close the human terminals too.
2276
+ *
2277
+ * Their ptys are spawned `detached` so one close can signal the whole process group (see
2278
+ * terminals.ts). The cost of that is that they do NOT die with this process — a restart
2279
+ * would leave every open shell orphaned and unreachable, still holding the operator's
2280
+ * workspace. Closing here is what makes `detached` safe.
2281
+ */
2282
+ const n = closeAllTerminals();
2283
+ if (n)
2284
+ console.log(`[teapot] ⌨ closed ${n} terminal(s)`);
2270
2285
  }
2271
2286
  }
2272
2287
  /** Restart the server process (spawns a new master, keeps this one alive until ready). */