teapot-coding-agent 0.35.15 → 0.35.17

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.
@@ -17,6 +17,7 @@ import { mcp } from "./mcp-registry.js";
17
17
  import { flattenToolName } from "./mcp-registry.js";
18
18
  import { metaToolSpecs } from "./meta-tools.js";
19
19
  import { skillRootsFingerprint, foreignSkillRoots } from "./skills.js";
20
+ import { extractRules, enforceRules, RULES_HEADING } from "./compact-rules.js";
20
21
  import { bus } from "../bus.js";
21
22
  /**
22
23
  * Harness nudges, named and exported so they can be asserted on directly.
@@ -196,10 +197,24 @@ const COMPACT_INSTRUCTION = [
196
197
  "## Current work",
197
198
  "## Next step",
198
199
  "## Durable lessons",
200
+ /**
201
+ * Hard constraints, as their own section with a fixed shape.
202
+ *
203
+ * "must/must-not" rules are the one thing a summary cannot recover from losing: everything else
204
+ * can be re-derived by reading the code again, but a constraint the operator stated once and
205
+ * never repeated is simply gone. Reported as "compact時にルール(must/must notが中心だけど、should
206
+ * レベルのものも)が確実に引き継げる機構があると良いねって思った".
207
+ *
208
+ * So they get a dedicated heading with a MACHINE-CHECKABLE shape (one `MUST`/`MUST NOT`/`SHOULD`
209
+ * keyword per line, see `RULES_SECTION` + `extractRules`): the summarizer cannot merge them into
210
+ * prose, and `enforceRules` re-inserts any that went missing instead of trusting it did not.
211
+ */
212
+ "## Hard constraints",
199
213
  "",
200
214
  "Rules: be terse bullet points, no prose flourishes. Quote file paths and key numbers exactly.",
201
215
  "All user messages are listed nearly verbatim — they carry intent that must survive every future compaction.",
202
216
  "Durable lessons lists reusable insights worth keeping forever (gotchas, preferences, what worked); omit the section if empty.",
217
+ "Hard constraints lists EVERY rule the operator stated, one per line, each beginning with exactly `MUST`, `MUST NOT` or `SHOULD` — include rules that were already obeyed and rules from earlier in the conversation. Never drop one because it seems satisfied: a constraint that is not repeated is lost forever, and this section is the only place it survives.",
203
218
  "Output only the checkpoint text: do not call any tool, and do not mention this request or that the context was compacted.",
204
219
  "The <analysis> block is discarded before your notes are stored, so think freely there.",
205
220
  ].join("\n");
@@ -595,6 +610,19 @@ export class Agent {
595
610
  * Recovered from the log so the continuity survives a restart.
596
611
  */
597
612
  lastCompactSummary;
613
+ /**
614
+ * The accumulated hard rules, kept INDEPENDENTLY of the summary.
615
+ *
616
+ * Codex's `retained_instructions.rs` states the property that matters: retained instructions are
617
+ * selected "independently of compaction", with the host owning storage and lifecycle, so
618
+ * "restrictions are never truncated into partial permissions".
619
+ *
620
+ * The first version of this re-derived the rules from `lastCompactSummary` on each pass, which
621
+ * fails in exactly the case the mechanism exists for: a pass that drops every rule leaves
622
+ * nothing to re-insert. Keeping the set here (and re-seeding it from the log on restart) makes
623
+ * it survive any single pass, and lets a pass add to it without ever removing from it.
624
+ */
625
+ compactRules = [];
598
626
  /**
599
627
  * A short human title for this session (#155), derived from the operator's first
600
628
  * prompt. Undefined until the log is read (or when there is no usable prompt).
@@ -1337,6 +1365,21 @@ export class Agent {
1337
1365
  const d = e.data;
1338
1366
  if (d.event === "context-compacted")
1339
1367
  this.stats.compactions++;
1368
+ /**
1369
+ * Re-seed the durable rule set so it survives a restart.
1370
+ *
1371
+ * The newest `compaction-rules` note is the accumulated set; without this a reload starts
1372
+ * empty and the first compaction after it has nothing to enforce — the failure the whole
1373
+ * mechanism exists to prevent. Seeded through `extractRules` rather than trusting the
1374
+ * stored shape, so the note is the same one a human can read in the log.
1375
+ */
1376
+ if (d.event === "compaction-rules" && Array.isArray(d.rules)) {
1377
+ const seeded = d.rules
1378
+ .map((line) => extractRules(`${RULES_HEADING}\n- ${String(line)}`)[0])
1379
+ .filter((r) => !!r);
1380
+ if (seeded.length)
1381
+ this.compactRules = seeded;
1382
+ }
1340
1383
  }
1341
1384
  else if (e.type === "compaction") {
1342
1385
  // keep the NEWEST notes: they are what the next compaction updates, and
@@ -2289,21 +2332,31 @@ export class Agent {
2289
2332
  await this.sleepInterruptible(this.opts.continueDelayMs);
2290
2333
  if (this.stopRequested)
2291
2334
  break;
2292
- // #95: do NOT pair this with a progress request. Both fire at the turn
2293
- // boundary and both inject a user message, so the model received two
2294
- // harness instructions back to back — "Continue working toward the
2295
- // current goal" immediately followed by "Please give a brief progress
2296
- // report now", which reads as the harness talking to itself.
2335
+ // #95: do NOT pair this with a progress request.
2336
+ //
2337
+ // Both fire at the turn boundary and both inject a user message, so the model received two
2338
+ // harness instructions back to back — "Continue working toward the current goal"
2339
+ // immediately followed by "Please give a brief progress report now", which reads as the
2340
+ // harness talking to itself.
2297
2341
  //
2298
- // The progress request already re-enters the loop, so it IS the
2299
- // continuation: suppressing the nudge when one is pending costs nothing
2300
- // and leaves exactly one instruction per boundary.
2342
+ // MEASURED why `break` was wrong here (session tyb2-8-0161a4af, seq 18778-18780):
2343
+ // `maybeRequestProgress` runs its OWN `llmCall` at the top of the turn, so the assistant
2344
+ // message it produces is a progress REPORT, not a continuation. The round then ended,
2345
+ // this branch saw the flag, logged `auto-continue-suppressed`, and BROKE — leaving the
2346
+ // agent idle with the work unfinished. The operator asked "何故 auto-continue が効いてない?"
2347
+ // and the log shows exactly one such note, at the very end.
2348
+ //
2349
+ // The suppression is still right (one instruction per boundary); breaking is not. What is
2350
+ // already in flight IS the continuation, so there is nothing left to add — but the loop
2351
+ // must keep going, or a progress request silently ends the session's work.
2301
2352
  if (this.progressRequestedThisRound) {
2302
2353
  await this.log.append("system_note", this.currentSession, this.currentBranch, {
2303
2354
  event: "auto-continue-suppressed",
2304
- detail: "a progress report was already requested this round (#95)",
2355
+ detail: "a progress report was already requested this round (#95) — the round that carried it already continues the work, so no nudge is added and the loop goes on",
2305
2356
  });
2306
- break;
2357
+ // consume the flag: it authorised skipping THIS boundary's nudge, not every later one
2358
+ this.progressRequestedThisRound = false;
2359
+ continue;
2307
2360
  }
2308
2361
  const isSub = !!this.opts.parent;
2309
2362
  // #136: the ROOT nudge now restates the goal too, exactly as the sub-agent
@@ -4095,6 +4148,47 @@ export class Agent {
4095
4148
  reasoning: "",
4096
4149
  });
4097
4150
  }, previousSummary);
4151
+ /**
4152
+ * Rules a pass dropped are put BACK.
4153
+ *
4154
+ * The summarizer is asked for one keyword per line, but it is still generated text:
4155
+ * a pass can merge three constraints into a sentence, or simply not mention one.
4156
+ * Facts survive that (the code can be re-read); a rule cannot — "never install this
4157
+ * into Wine" was stated once and is nowhere else. Reported as "compact時にルール
4158
+ * (must/must notが中心だけど、shouldレベルのものも)が確実に引き継げる機構があると良いね".
4159
+ *
4160
+ * So the rules known BEFORE this pass are compared against the ones it produced, and
4161
+ * any missing are appended. A pass may add and reword freely; it cannot lose one.
4162
+ */
4163
+ {
4164
+ /**
4165
+ * Seed from the previous summary ONCE, for a session that compacted before this
4166
+ * mechanism existed — after that the stored set is the authority.
4167
+ *
4168
+ * The set lives in `this.compactRules`, not in the previous summary: a pass that
4169
+ * dropped every rule would otherwise leave nothing to restore from, which is the
4170
+ * exact failure this exists to prevent.
4171
+ */
4172
+ if (!this.compactRules.length && previousSummary) {
4173
+ this.compactRules = extractRules(previousSummary);
4174
+ }
4175
+ const enforced = enforceRules(summary, this.compactRules);
4176
+ summary = enforced.summary;
4177
+ // a pass may ADD rules (the operator said something new); it may never remove one
4178
+ this.compactRules = extractRules(summary);
4179
+ if (enforced.restored.length) {
4180
+ await this.log.append("system_note", this.currentSession, this.currentBranch, {
4181
+ event: "compaction-rules-restored",
4182
+ count: enforced.restored.length,
4183
+ rules: enforced.restored.map((r) => `${r.level} ${r.text}`),
4184
+ });
4185
+ }
4186
+ await this.log.append("system_note", this.currentSession, this.currentBranch, {
4187
+ event: "compaction-rules",
4188
+ count: this.compactRules.length,
4189
+ rules: this.compactRules.map((r) => `${r.level} ${r.text}`),
4190
+ });
4191
+ }
4098
4192
  break;
4099
4193
  }
4100
4194
  catch (e) {
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Keep the operator's hard rules alive across a compaction.
3
+ *
4
+ * ## Why this is not just another summary section
5
+ *
6
+ * A compaction summary is generated text: everything in it was re-derived by a model from the
7
+ * conversation it was shown. That is fine for facts, because facts can be re-checked against the
8
+ * code. A RULE cannot — "never install this into Wine", "do not clone repositories to study them"
9
+ * were each stated once, obeyed silently for dozens of turns, and are not repeated anywhere the
10
+ * next pass could find them. When the summary drops one, nothing downstream notices; the agent
11
+ * just starts doing it.
12
+ *
13
+ * So the rules get a section with a SHAPE the code can check (`MUST` / `MUST NOT` / `SHOULD` at the
14
+ * start of each line), extracted on the way out and RE-INSERTED on the way in if a pass lost them.
15
+ * The summarizer is still the thing that decides what the rules ARE; this module only makes sure
16
+ * that once known they cannot disappear.
17
+ *
18
+ * ## Why the shape matters more than the wording
19
+ *
20
+ * A free-form section lets a model merge three rules into one sentence, which is how a `MUST NOT`
21
+ * turns into a `SHOULD avoid` and then into nothing. A fixed keyword per line keeps each rule a
22
+ * separate, checkable item. `should` is included deliberately — the operator asked for it — but it
23
+ * is ranked below the musts so a squeeze drops the weakest first.
24
+ */
25
+ export const RULES_HEADING = "## Hard constraints";
26
+ /** the levels, strongest first — the order a squeeze must respect */
27
+ const LEVELS = ["MUST NOT", "MUST", "SHOULD"];
28
+ /**
29
+ * Parse the `## Hard constraints` section out of a summary.
30
+ *
31
+ * Tolerant on purpose: the summarizer is asked for a shape, not guaranteed to produce it. A line
32
+ * that does not start with a keyword is ignored rather than guessed at, because inventing a rule
33
+ * from prose is worse than losing one — a wrong rule is obeyed.
34
+ */
35
+ export function extractRules(summary) {
36
+ const lines = summary.split("\n");
37
+ const start = lines.findIndex((l) => l.trim().toLowerCase() === RULES_HEADING.toLowerCase());
38
+ if (start < 0)
39
+ return [];
40
+ const out = [];
41
+ const seen = new Set();
42
+ for (let i = start + 1; i < lines.length; i++) {
43
+ const raw = lines[i];
44
+ // a new `##` heading ends the section
45
+ if (/^#{1,6}\s/.test(raw.trim()))
46
+ break;
47
+ const line = raw.replace(/^\s*[-*+]\s*/, "").trim();
48
+ if (!line)
49
+ continue;
50
+ // longest keyword first, or `MUST NOT` parses as `MUST` + "NOT …"
51
+ const m = /^(MUST NOT|MUST|SHOULD)\b[:\s]*(.*)$/i.exec(line);
52
+ if (!m)
53
+ continue;
54
+ const level = m[1].toUpperCase().replace(/\s+/g, " ");
55
+ const text = m[2].trim();
56
+ if (!text)
57
+ continue;
58
+ // de-duplicate on the normalised text: two paraphrases of one rule is one rule
59
+ const key = text.toLowerCase().replace(/[^a-z0-9 ]+/g, "").replace(/\s+/g, " ").trim();
60
+ if (seen.has(key))
61
+ continue;
62
+ seen.add(key);
63
+ out.push({ level, text, line });
64
+ }
65
+ return out;
66
+ }
67
+ /** the section body for a set of rules, in strongest-first order */
68
+ export function renderRules(rules) {
69
+ const rank = (r) => LEVELS.indexOf(r.level);
70
+ return [...rules]
71
+ .sort((a, b) => rank(a) - rank(b))
72
+ .map((r) => `- ${r.level} ${r.text}`)
73
+ .join("\n");
74
+ }
75
+ /**
76
+ * Re-insert rules a compaction pass dropped.
77
+ *
78
+ * `before` is what was known going in, `after` is the section the new summary produced. Anything in
79
+ * `before` whose text is not present in `after` is appended (strongest first) so a pass can add
80
+ * rules and reword them, but can never lose one. Returns the summary with the section rewritten.
81
+ *
82
+ * Rewriting rather than appending is what makes this idempotent: running it twice on the same
83
+ * summary produces the same summary, which matters because the update path compacts repeatedly.
84
+ */
85
+ export function enforceRules(summary, before) {
86
+ const after = extractRules(summary);
87
+ const present = new Set(after.map((r) => r.text.toLowerCase().replace(/[^a-z0-9 ]+/g, "").replace(/\s+/g, " ").trim()));
88
+ const restored = before.filter((r) => {
89
+ const key = r.text.toLowerCase().replace(/[^a-z0-9 ]+/g, "").replace(/\s+/g, " ").trim();
90
+ return !present.has(key);
91
+ });
92
+ const merged = [...after, ...restored];
93
+ const body = renderRules(merged);
94
+ const section = body ? `${RULES_HEADING}\n${body}` : RULES_HEADING;
95
+ const lines = summary.split("\n");
96
+ const start = lines.findIndex((l) => l.trim().toLowerCase() === RULES_HEADING.toLowerCase());
97
+ if (start < 0) {
98
+ // no section at all — append one rather than silently keeping nothing
99
+ return { summary: `${summary.trimEnd()}\n\n${section}`, restored };
100
+ }
101
+ let end = lines.length;
102
+ for (let i = start + 1; i < lines.length; i++) {
103
+ if (/^#{1,6}\s/.test(lines[i].trim())) {
104
+ end = i;
105
+ break;
106
+ }
107
+ }
108
+ return {
109
+ summary: [...lines.slice(0, start), ...section.split("\n"), "", ...lines.slice(end)].join("\n"),
110
+ restored,
111
+ };
112
+ }
113
+ /**
114
+ * The rules as a line the summarizer is asked to keep, for the UPDATE path.
115
+ *
116
+ * Passed as part of the prior checkpoint so a pass that is told "preserve what is still true" can
117
+ * see the rules explicitly instead of having to find them in prose.
118
+ */
119
+ export function rulesForPrompt(rules) {
120
+ if (!rules.length)
121
+ return "";
122
+ return `${RULES_HEADING}\n${renderRules(rules)}`;
123
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.35.15",
3
+ "version": "0.35.17",
4
4
  "description": "A lightweight, always-on multi-agent harness for AI coding agents",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-or-later",