pi-braid 0.40.0 → 0.40.2

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 (85) hide show
  1. package/CONTRIBUTING.md +27 -3
  2. package/README.md +39 -33
  3. package/TOOLS.md +27 -3
  4. package/build-info.json +9 -0
  5. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.d.ts +9 -0
  6. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +13 -1
  7. package/dist/extensions/cognitive/metacognition/handlers/verify.js +35 -4
  8. package/dist/extensions/core/prompt-builder/inspect.js +9 -3
  9. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +1 -1
  10. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +1 -1
  11. package/dist/extensions/enforcement/handlers/turn-end-handler.js +1 -1
  12. package/dist/extensions/enforcement/self-state-claims.d.ts +1 -1
  13. package/dist/extensions/enforcement/self-state-claims.js +3 -2
  14. package/dist/extensions/manifest.js +2 -2
  15. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +22 -5
  16. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +43 -11
  17. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +174 -50
  18. package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +4 -1
  19. package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +16 -0
  20. package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +21 -9
  21. package/dist/extensions/memory/scratchpad/format.js +8 -2
  22. package/dist/extensions/memory/scratchpad/index.js +11 -2
  23. package/dist/extensions/memory/session-recall/index.js +19 -6
  24. package/dist/extensions/memory/three-memory-stores/episodes.d.ts +1 -1
  25. package/dist/extensions/memory/three-memory-stores/episodes.js +2 -2
  26. package/dist/extensions/orchestrator/index.js +73 -8
  27. package/dist/extensions/self/health-maintenance/index.js +112 -9
  28. package/dist/lib/config/braid-settings.d.ts +21 -0
  29. package/dist/lib/config/braid-settings.js +36 -0
  30. package/dist/lib/constants/session-thresholds.d.ts +2 -3
  31. package/dist/lib/constants/session-thresholds.js +2 -3
  32. package/dist/lib/enforcement/turn-dedup.d.ts +2 -2
  33. package/dist/lib/enforcement/turn-dedup.js +2 -2
  34. package/dist/lib/harness/index.d.ts +1 -1
  35. package/dist/lib/harness/index.js +1 -1
  36. package/dist/lib/harness/types.d.ts +1 -1
  37. package/dist/lib/harness/types.js +1 -1
  38. package/dist/lib/orchestrator/index.d.ts +2 -2
  39. package/dist/lib/orchestrator/index.js +1 -1
  40. package/dist/lib/orchestrator/workers.d.ts +184 -2
  41. package/dist/lib/orchestrator/workers.js +521 -6
  42. package/dist/lib/utils/injection-tracker.js +1 -1
  43. package/docs/BEGINNERS.md +22 -0
  44. package/docs/CONTEXT-POLICY.md +13 -5
  45. package/docs/LOCAL_DEV.md +31 -5
  46. package/docs/ROADMAP.md +10 -7
  47. package/docs/SETUP.md +86 -42
  48. package/package.json +11 -8
  49. package/skills/braid-reference/SKILL.md +23 -23
  50. package/skills/release-pipeline/SKILL.md +46 -37
  51. package/skills/subagent-orchestration/SKILL.md +51 -1
  52. package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +14 -1
  53. package/src/extensions/cognitive/metacognition/handlers/verify.ts +39 -5
  54. package/src/extensions/core/prompt-builder/inspect.ts +10 -3
  55. package/src/extensions/enforcement/AGENTS.md +25 -19
  56. package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +1 -1
  57. package/src/extensions/enforcement/handlers/turn-end-handler.ts +1 -1
  58. package/src/extensions/enforcement/self-state-claims.ts +3 -2
  59. package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +6 -3
  60. package/src/extensions/manifest.ts +2 -2
  61. package/src/extensions/memory/AGENTS.md +13 -5
  62. package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +45 -11
  63. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +202 -60
  64. package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +4 -1
  65. package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +16 -0
  66. package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +22 -9
  67. package/src/extensions/memory/scratchpad/format.ts +8 -2
  68. package/src/extensions/memory/scratchpad/index.ts +12 -2
  69. package/src/extensions/memory/session-recall/index.ts +20 -8
  70. package/src/extensions/memory/three-memory-stores/episodes.ts +2 -2
  71. package/src/extensions/orchestrator/index.ts +100 -11
  72. package/src/extensions/scheduling/timer/AGENTS.md +7 -0
  73. package/src/extensions/self/health-maintenance/index.ts +143 -14
  74. package/src/extensions/self/watchdog/AGENTS.md +1 -0
  75. package/src/lib/AGENTS.md +21 -21
  76. package/src/lib/config/braid-settings.ts +74 -0
  77. package/src/lib/constants/session-thresholds.ts +2 -3
  78. package/src/lib/enforcement/turn-dedup.ts +2 -2
  79. package/src/lib/harness/AGENTS.md +1 -1
  80. package/src/lib/harness/index.ts +1 -1
  81. package/src/lib/harness/types.ts +1 -1
  82. package/src/lib/orchestrator/index.ts +26 -0
  83. package/src/lib/orchestrator/workers.ts +705 -7
  84. package/src/lib/utils/AGENTS.md +1 -1
  85. package/src/lib/utils/injection-tracker.ts +1 -1
@@ -17,7 +17,7 @@ const log = createLogger("three-memory-stores:episodes");
17
17
  /**
18
18
  * Sanitize a string by decoding literal `\uXXXX` escape sequences that
19
19
  * may have been written by a previous code path that double-encoded
20
- * unicode (BUG-M3). The agent-facing `recall_search` and `episodes_search`
20
+ * unicode. The agent-facing `recall_search` and `episodes_search`
21
21
  * displays otherwise show literal `\u2192` instead of the real character
22
22
  * `->`. Applied at load time AND at write time (in `addEpisode`) so both
23
23
  * existing data files and new writes are healed.
@@ -88,7 +88,7 @@ export function addEpisode(
88
88
  100;
89
89
 
90
90
  // Sanitize string fields before storing so newly-added episodes
91
- // never reintroduce literal \uXXXX sequences (BUG-M3 hardening).
91
+ // never reintroduce literal \uXXXX sequences.
92
92
  // The load-time sanitizer in index.ts:loadPastEpisodes handles
93
93
  // already-stored entries.
94
94
  const episode: Episode = sanitizeEpisode({
@@ -46,6 +46,9 @@ import {
46
46
  resolveRequestId,
47
47
  computeWorkerStats,
48
48
  workerEffectEvidenceForEntry,
49
+ locateResultSchema,
50
+ readPopulationStamps,
51
+ populationRefusalDetail,
49
52
  WORKER_EFFECT_EVIDENCE_FLAG,
50
53
  WORKER_SPECS,
51
54
  WORKER_OUTCOMES,
@@ -58,6 +61,7 @@ import {
58
61
  type WorkerEffectEvidence,
59
62
  type WorkerEntry,
60
63
  type WorkerStats,
64
+ type PopulationRead,
61
65
  } from "../../lib/orchestrator/index.js";
62
66
 
63
67
  const log = createLogger("orchestrator");
@@ -149,6 +153,35 @@ function isSafeRef(ref: string): boolean {
149
153
  return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref);
150
154
  }
151
155
 
156
+ /**
157
+ * The commit census: how many entries the tree at `revision` holds. This is
158
+ * the index-independent equivalent of `git ls-files | wc -l` at that revision
159
+ * — it reads the named revision's tree rather than the caller's index, since
160
+ * the caller's worktree is not necessarily checked out where the gate scanned.
161
+ * Null when git cannot resolve the revision.
162
+ */
163
+ function censusAt(revision: string, repoRoot: string | undefined): number | null {
164
+ if (!repoRoot) return null;
165
+ const out = git(repoRoot, ["ls-tree", "-r", "--name-only", revision]);
166
+ if (out === undefined) return null;
167
+ return out === "" ? 0 : out.split("\n").length;
168
+ }
169
+
170
+ /**
171
+ * The gate rows the merge path reads its population record from. A row that
172
+ * was already closed carries its recorded gates, and those win; the normal
173
+ * flow merges before close-worker, so the fallback is the worker's result
174
+ * block — the result contract's `gate_evidence`, located in the session the
175
+ * row names. No session and no gates is an empty read, not an error: the
176
+ * comparison is a reader, and a missing record prints as one.
177
+ */
178
+ function closeGateRows(entry: WorkerEntry | undefined): unknown[] {
179
+ if (entry && Array.isArray(entry.gates) && entry.gates.length > 0) return entry.gates;
180
+ const located = locateResultSchema(entry?.workerSession ?? null);
181
+ const rows = located?.schema.gate_evidence;
182
+ return Array.isArray(rows) ? rows : [];
183
+ }
184
+
152
185
  /**
153
186
  * What a merge attempt produced: the report to print, plus the base tip when
154
187
  * this call actually advanced the base. The two travel together so the audit
@@ -172,6 +205,7 @@ function verifyAndMergeBase(
172
205
  workerBranch: string,
173
206
  base: string,
174
207
  repoRoot: string | undefined,
208
+ population: PopulationRead,
175
209
  ): MergeOutcome {
176
210
  /** A refusal or no-op: nothing was merged, so nothing may be marked merged. */
177
211
  const nothingMerged = (report: string): MergeOutcome => ({
@@ -211,6 +245,11 @@ function verifyAndMergeBase(
211
245
  const diff = getDiff(workerBranch, base, repoRoot);
212
246
  const scan = surfaceScanReport(diff);
213
247
 
248
+ // The population read rides directly under the outcome line: it is the
249
+ // reason a refusal happened, and on a merge it is the recorded-versus-git
250
+ // pair the merge claim is certified against.
251
+ const populationNote = population.lines.length > 0 ? `\n${population.lines.join("\n")}` : "";
252
+
214
253
  const finish = (
215
254
  lead: string,
216
255
  deletedLead: string,
@@ -238,7 +277,7 @@ function verifyAndMergeBase(
238
277
  // what the registry now says.
239
278
  const audit = mergeAuditNote(workerId, mergeSha, repoRoot);
240
279
  return {
241
- report: `${lead}${audit}\nBranch: ${workerBranch} (${
280
+ report: `${lead}${audit}${populationNote}\nBranch: ${workerBranch} (${
242
281
  deleted ? "deleted" : onWorkerBranch ? "kept: this worktree is on it" : deletedLead
243
282
  })${worktreeNote}${settleBlock}\nDiff summary:\n${diff.slice(0, 2000)}\n${scan}`,
244
283
  mergeSha,
@@ -256,6 +295,19 @@ function verifyAndMergeBase(
256
295
  );
257
296
  }
258
297
 
298
+ // A recorded population below the census at its own revision is the claim
299
+ // this read exists to test: the gate certified fewer tracked entries than
300
+ // that revision holds, so the merge waits for a re-run on the staged tree.
301
+ const standingDetail = populationRefusalDetail(population);
302
+ if (standingDetail) {
303
+ return nothingMerged(
304
+ `NOT merged: ${standingDetail}\n` +
305
+ `Base unchanged at ${short(baseBefore)}. Locks and branch kept.\n${population.lines.join(
306
+ "\n",
307
+ )}`,
308
+ );
309
+ }
310
+
259
311
  // Set when the fast-forward happened in a worktree other than the caller's;
260
312
  // the report names where the base's tree moved, so a reader can act on it.
261
313
  let settleNote = "";
@@ -501,7 +553,7 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
501
553
  label: "Orchestrate",
502
554
  promptSnippet: "Coordinate parallel agent workers (spawn/check/merge, locks)",
503
555
  description:
504
- "Coordinate parallel agent workers to prevent edit conflicts. Auto-detects the repo root (cwd overrides); without git, lock-only. verify-and-merge requires workerId, merges into an explicit base branch (default main), and claims success only when that base ref actually advanced. It never switches a worktree's branch: the caller's tree is left on the branch it was on, named in the report, and a branch is dropped only when it is actually gone. " +
556
+ "Coordinate parallel agent workers to prevent edit conflicts. Auto-detects the repo root (cwd overrides); without git, lock-only. verify-and-merge requires workerId, merges into an explicit base branch (default main), and claims success only when that base ref actually advanced. A close's stamped `files` row is compared against the census of the revision it names, and a number below that census refuses the merge before any ref moves. It never switches a worktree's branch: the caller's tree is left on the branch it was on, named in the report, and a branch is dropped only when it is actually gone. " +
505
557
  `Worker lifecycle speaks in four vocabularies: ${renderStatusLayers()}.`,
506
558
  parameters: Type.Object({
507
559
  action: Type.Union(
@@ -602,12 +654,36 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
602
654
  }),
603
655
  ),
604
656
  gates: Type.Optional(
605
- Type.Array(Type.Object({ cmd: Type.String(), exit: Type.Number() }), {
606
- description:
607
- "Gate evidence for close-worker: command plus exit code, recorded with a timestamp. " +
608
- `A completed close whose entry carries none of a fresh output file, a branch advance or ` +
609
- `merge, and a passing gate is flagged "${WORKER_EFFECT_EVIDENCE_FLAG}" (advisory, non-blocking).`,
610
- }),
657
+ Type.Array(
658
+ Type.Object({
659
+ cmd: Type.String(),
660
+ exit: Type.Number(),
661
+ stamp: Type.Optional(
662
+ Type.String({
663
+ description:
664
+ "Population record for a gate whose subject is a file or row population: " +
665
+ '"scanned <n> <unit> at <revision>" (n a non-negative integer, unit one ' +
666
+ "lowercase word, revision a 7-to-40-char hex sha or a ref name). " +
667
+ "verify-and-merge reads a stamped `files` row against that revision's " +
668
+ "tracked-entry census and refuses the merge when the recorded number sits " +
669
+ "below it.",
670
+ }),
671
+ ),
672
+ }),
673
+ {
674
+ description:
675
+ "Gate evidence for close-worker: command plus exit code, recorded with a timestamp. " +
676
+ `A completed close whose entry carries none of a fresh output file, a branch advance or ` +
677
+ `merge, and a passing gate is flagged "${WORKER_EFFECT_EVIDENCE_FLAG}" (advisory, non-blocking). ` +
678
+ "Every row is also read for well-formedness at close time (parses under sh -n, first token " +
679
+ "resolves, no top-level decoration, exit 0 under a completed outcome); the read ships in " +
680
+ "shadow mode, so a failing row is logged and the close proceeds, until " +
681
+ 'braid.orchestrator.closeGateWellFormedness is set to "enforce". ' +
682
+ "Rows the seat's production-write class marks as writes are refused unless the close " +
683
+ "records every named preflight piece somewhere in its rows; the class data is the seat's, " +
684
+ "and no class data means no refusal.",
685
+ },
686
+ ),
611
687
  ),
612
688
  includeClosed: Type.Optional(
613
689
  Type.Boolean({ description: "list-workers: include closed entries (default false)." }),
@@ -645,7 +721,7 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
645
721
  lastStep?: string;
646
722
  requestId?: string;
647
723
  outcome?: string;
648
- gates?: Array<{ cmd: string; exit: number }>;
724
+ gates?: Array<{ cmd: string; exit: number; stamp?: string }>;
649
725
  includeClosed?: boolean;
650
726
  includeStats?: boolean;
651
727
  liveStatus?: string;
@@ -1020,7 +1096,8 @@ Register the worker (orchestrate action=register-worker) for a structured verdic
1020
1096
  // of the three yields one.
1021
1097
  const lockRows = getAllLocks(repoRoot);
1022
1098
  const lockBranch = Object.values(lockRows).find((row) => row.workerId === workerId)?.branch;
1023
- const entryBranch = readWorkers(repoRoot).workers[workerId]?.branch ?? undefined;
1099
+ const entry = readWorkers(repoRoot).workers[workerId];
1100
+ const entryBranch = entry?.branch ?? undefined;
1024
1101
  const workerBranch = branch ?? entryBranch ?? lockBranch;
1025
1102
 
1026
1103
  if (!workerBranch) {
@@ -1030,7 +1107,19 @@ Register the worker (orchestrate action=register-worker) for a structured verdic
1030
1107
  );
1031
1108
  }
1032
1109
 
1033
- const outcome = verifyAndMergeBase(workerId, workerBranch, baseBranch ?? "main", repoRoot);
1110
+ // The close's population record is read before the merge: the stamped
1111
+ // rows are the reporter's own numbers, and the census they are compared
1112
+ // against comes from git alone.
1113
+ const population = readPopulationStamps(closeGateRows(entry), (revision) =>
1114
+ censusAt(revision, repoRoot),
1115
+ );
1116
+ const outcome = verifyAndMergeBase(
1117
+ workerId,
1118
+ workerBranch,
1119
+ baseBranch ?? "main",
1120
+ repoRoot,
1121
+ population,
1122
+ );
1034
1123
  // The merge sha travels in details as well as in the report, so a
1035
1124
  // parent can verify the claim it was handed without parsing prose; the
1036
1125
  // worktree branch travels with it, because a merge that leaves the
@@ -200,6 +200,13 @@ untouched either way. Observer call sites are guarded: alerting never breaks
200
200
  retry arming or outcome resolution. Fixture:
201
201
  `test/runtime/self/test-watchdog-wake-delivery.mjs`.
202
202
 
203
+ ### Wake guard settings
204
+
205
+ | Setting | Default | Effect | Read cadence |
206
+ | ----------------------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
207
+ | `braid.session.terminalBreaker.threshold` | `3` (enabled by default) | After this many terminal-class LLM errors, a timer wake is delivered as a non-waking steer until a clean turn resets the gate. Set `enabled: false` to disable the breaker. | Re-read at use time, once per fire checked by the breaker. |
208
+ | `braid.timers.wakeAlert.mode` | `"on"` | Enables the watchdog wake-delivery alert feed. `"off"` disables alerting only; timer delivery and retries continue unchanged. | Re-read at use time for each alert check. |
209
+
203
210
  The post-compaction stack overflow was caused by `triggerTurn: true` firing **mid-tool-execution**. The fix is the **busy guard** (below). The compaction-resume timer was removed in 2026-07-11 because pi-core's agent loop automatically continues after **auto**-compaction (`_runAutoCompaction()` continues on `willRetry`/overflow or queued messages); the 3-minute fallback timer was firing as spurious noise on that path. That does NOT cover the manual `ctx.compact()` path (agent-initiated `context_compress` tool): manual compaction aborts the loop and never resumes it - the resume there is the enforcement `session_compact` re-orientation whisper with `triggerTurn: true` (see `enforcement/handlers/register-session-compact.ts`), which was verified and fixed 2026-08-02.
204
211
 
205
212
  ## Tag conventions
@@ -11,6 +11,7 @@ import {
11
11
  resetMetrics,
12
12
  saveMetrics,
13
13
  updateConfig,
14
+ type DegradationConfig,
14
15
  } from "../../../lib/detection/degradation-detector.js";
15
16
  import { createLogger } from "../../../lib/core/logger.js";
16
17
  import { getLogBuffer, clearLogBuffer, setConsoleLogLevel } from "../../../lib/core/logger.js";
@@ -44,25 +45,47 @@ const EVOLVE_ACTIONS = [
44
45
  const healthMaintenanceSchema = Type.Object({
45
46
  action: StringEnum([...EVOLVE_ACTIONS], { description: "Action to perform" }),
46
47
  checkpoint: Type.Optional(Type.String({ description: "Checkpoint hash for rollback" })),
48
+ // Numeric bounds where 0 is meaningless: a blank selector is converted to
49
+ // 0 by argument validation, and 0 outside a field's band turns the blank
50
+ // into a refusal before any handler runs. errorRateMax stays unbounded here
51
+ // because its legal band is (0,1] and a schema minimum cannot express it;
52
+ // the handler guard owns that one.
47
53
  config: Type.Optional(
48
54
  Type.Object({
49
55
  healthcheckMinScore: Type.Optional(
50
- Type.Number({ description: "Minimum healthcheck score (0-100)" }),
56
+ Type.Number({
57
+ minimum: 1,
58
+ maximum: 100,
59
+ description: "Minimum healthcheck score (1-100)",
60
+ }),
51
61
  ),
52
- errorRateMax: Type.Optional(Type.Number({ description: "Maximum error rate (0-1)" })),
62
+ errorRateMax: Type.Optional(Type.Number({ description: "Maximum error rate (0-1]" })),
53
63
  toolSuccessMin: Type.Optional(
54
- Type.Number({ description: "Minimum tool success rate (0-100)" }),
64
+ Type.Number({
65
+ minimum: 1,
66
+ maximum: 100,
67
+ description: "Minimum tool success rate (1-100)",
68
+ }),
55
69
  ),
56
70
  maxConsecutiveErrors: Type.Optional(
57
- Type.Number({ description: "Max consecutive errors before degradation" }),
71
+ Type.Number({
72
+ minimum: 1,
73
+ description: "Max consecutive errors before degradation (>= 1)",
74
+ }),
58
75
  ),
59
76
  }),
60
77
  ),
61
78
  benchmark: Type.Optional(
62
79
  Type.Object({
63
- passRate: Type.Optional(Type.Number({ description: "Benchmark pass rate (0-100)" })),
64
- totalCases: Type.Optional(Type.Number({ description: "Total number of test cases" })),
65
- passedCases: Type.Optional(Type.Number({ description: "Number of cases that passed" })),
80
+ passRate: Type.Optional(
81
+ Type.Number({ minimum: 1, maximum: 100, description: "Benchmark pass rate (1-100)" }),
82
+ ),
83
+ totalCases: Type.Optional(
84
+ Type.Number({ minimum: 1, description: "Number of cases in the benchmark run (>= 1)" }),
85
+ ),
86
+ passedCases: Type.Optional(
87
+ Type.Number({ minimum: 0, description: "Number of cases that passed (>= 0)" }),
88
+ ),
66
89
  failedCases: Type.Optional(
67
90
  Type.Array(Type.String(), { description: "Names of failed cases" }),
68
91
  ),
@@ -73,6 +96,89 @@ const healthMaintenanceSchema = Type.Object({
73
96
  ),
74
97
  });
75
98
 
99
+ // ── Numeric config guard ────────────────────────────────────────────────────
100
+ //
101
+ // The framework validates tool arguments before the handler runs and converts
102
+ // "" to 0 for Type.Number, so a client that sends "" for an unused threshold
103
+ // delivers a real 0. 0 is outside every legal band below (a minimum of 1, or
104
+ // the open lower bound of errorRateMax), which is what makes the conversion
105
+ // detectable: the call named nothing usable, so the whole patch is refused
106
+ // rather than rewriting degradation thresholds (errorRateMax: 0 would degrade
107
+ // on the first error; healthcheckMinScore: 0 would disable the score floor).
108
+ // The merge itself stays permissive - this is the untrusted-input boundary.
109
+
110
+ interface FieldBand {
111
+ min: number;
112
+ max: number | null;
113
+ /** True when the minimum itself is illegal (errorRateMax's (0,1] band). */
114
+ minExclusive?: boolean;
115
+ }
116
+
117
+ const CONFIG_FIELD_BANDS: Record<keyof DegradationConfig, FieldBand> = {
118
+ healthcheckMinScore: { min: 1, max: 100 },
119
+ errorRateMax: { min: 0, max: 1, minExclusive: true },
120
+ toolSuccessMin: { min: 1, max: 100 },
121
+ maxConsecutiveErrors: { min: 1, max: null },
122
+ checkIntervalMs: { min: 1, max: null },
123
+ };
124
+
125
+ function bandText(band: FieldBand): string {
126
+ if (band.max === null) return band.minExclusive ? `> ${band.min}` : `>= ${band.min}`;
127
+ if (band.minExclusive) return `(${band.min}, ${band.max}]`;
128
+ return `${band.min}-${band.max}`;
129
+ }
130
+
131
+ /** The refusal sentence for `value` under `band`, or null when it is inside it. */
132
+ function bandRefusal(field: string, value: unknown, band: FieldBand): string | null {
133
+ if (typeof value !== "number" || !Number.isFinite(value)) {
134
+ return `${field} must be a finite number; got ${JSON.stringify(value)}.`;
135
+ }
136
+ const below = band.minExclusive ? value <= band.min : value < band.min;
137
+ const above = band.max !== null && value > band.max;
138
+ if (below || above) {
139
+ return `${field} must be ${bandText(band)}; got ${value}. A blank selector arrives as 0 and is refused.`;
140
+ }
141
+ return null;
142
+ }
143
+
144
+ /**
145
+ * Validate a config patch: provided fields must be finite numbers inside their
146
+ * documented band. Absent/null fields are not provided. Returns the accepted
147
+ * subset (so unknown keys never reach the merge), or the error naming the
148
+ * first offending field.
149
+ */
150
+ function validateConfigPatch(
151
+ config: Record<string, unknown>,
152
+ ): { values: Partial<DegradationConfig> } | { error: string } {
153
+ const values: Partial<DegradationConfig> = {};
154
+ for (const key of Object.keys(CONFIG_FIELD_BANDS) as (keyof DegradationConfig)[]) {
155
+ const raw = config[key];
156
+ if (raw === undefined || raw === null) continue;
157
+ const refusal = bandRefusal(String(key), raw, CONFIG_FIELD_BANDS[key]);
158
+ if (refusal) return { error: refusal };
159
+ values[key] = raw as number;
160
+ }
161
+ return { values };
162
+ }
163
+
164
+ /** The benchmark's numeric rule: same bands, same refusal class as config. */
165
+ function validateBenchmark(benchmark: Record<string, unknown>): string | null {
166
+ const passRate = bandRefusal("benchmark.passRate", benchmark.passRate, { min: 1, max: 100 });
167
+ if (passRate) return passRate;
168
+ if (benchmark.totalCases !== undefined && benchmark.totalCases !== null) {
169
+ const total = bandRefusal("benchmark.totalCases", benchmark.totalCases, { min: 1, max: null });
170
+ if (total) return total;
171
+ }
172
+ if (benchmark.passedCases !== undefined && benchmark.passedCases !== null) {
173
+ const passed = bandRefusal("benchmark.passedCases", benchmark.passedCases, {
174
+ min: 0,
175
+ max: null,
176
+ });
177
+ if (passed) return passed;
178
+ }
179
+ return null;
180
+ }
181
+
76
182
  export default function healthMaintenanceExtension(pi: ExtensionAPI) {
77
183
  startMetricsPersistence();
78
184
 
@@ -270,8 +376,27 @@ async function executeRollback(): Promise<HealthMaintenanceResult> {
270
376
  };
271
377
  }
272
378
 
273
- function executeConfig(newConfig?: any): HealthMaintenanceResult {
274
- if (newConfig) updateConfig(newConfig);
379
+ function executeConfig(newConfig?: unknown): HealthMaintenanceResult {
380
+ if (newConfig !== undefined && newConfig !== null) {
381
+ if (typeof newConfig !== "object" || Array.isArray(newConfig)) {
382
+ return {
383
+ action: "config",
384
+ success: false,
385
+ error: "config must be an object of numeric thresholds.",
386
+ };
387
+ }
388
+ const verdict = validateConfigPatch(newConfig as Record<string, unknown>);
389
+ if ("error" in verdict) {
390
+ // Atomic: nothing is merged when any provided field is refused. The
391
+ // merge below stays where it was (the process-global config the tool has
392
+ // always written and reports, and the one carried into new sessions).
393
+ return { action: "config", success: false, error: verdict.error };
394
+ }
395
+ if (Object.keys(verdict.values).length === 0) {
396
+ return { action: "config", success: false, error: "no config values provided" };
397
+ }
398
+ updateConfig(verdict.values);
399
+ }
275
400
  return { action: "config", success: true, data: { config: getConfig() } };
276
401
  }
277
402
 
@@ -280,7 +405,7 @@ function executeReset(): HealthMaintenanceResult {
280
405
  return { action: "reset", success: true, data: { note: "Metrics reset to defaults." } };
281
406
  }
282
407
 
283
- function executeBenchmark(params?: any): HealthMaintenanceResult {
408
+ function executeBenchmark(params?: Record<string, unknown>): HealthMaintenanceResult {
284
409
  const BENCHMARK_HISTORY: BenchmarkResult[] = [];
285
410
  const MAX_BENCHMARK_HISTORY = 20;
286
411
 
@@ -291,12 +416,16 @@ function executeBenchmark(params?: any): HealthMaintenanceResult {
291
416
  data: { history: BENCHMARK_HISTORY.slice(-5), totalRuns: BENCHMARK_HISTORY.length },
292
417
  };
293
418
  }
419
+ const refusal = validateBenchmark(params);
420
+ if (refusal) {
421
+ return { action: "benchmark", success: false, error: refusal };
422
+ }
294
423
  const result: BenchmarkResult = {
295
424
  timestamp: Date.now(),
296
- passRate: params.passRate,
297
- totalCases: params.totalCases ?? 0,
298
- passedCases: params.passedCases ?? 0,
299
- failedCases: params.failedCases ?? [],
425
+ passRate: params.passRate as number,
426
+ totalCases: (params.totalCases as number | undefined) ?? 0,
427
+ passedCases: (params.passedCases as number | undefined) ?? 0,
428
+ failedCases: (params.failedCases as string[] | undefined) ?? [],
300
429
  };
301
430
  BENCHMARK_HISTORY.push(result);
302
431
  if (BENCHMARK_HISTORY.length > MAX_BENCHMARK_HISTORY) BENCHMARK_HISTORY.shift();
@@ -25,3 +25,4 @@ The Session watchdog is purely a **passive observer** (it doesn't act).
25
25
  - Module is opt-in (`disabledByDefault: true`).
26
26
  - Module id: `watchdog` (kebab-case).
27
27
  - Not LLM-callable. The agent cannot trigger it - only the user can, via the `watchdog-status` command.
28
+ - `broker.watchdog` is read when the extension factory loads. Restart the agent after changing it.
package/src/lib/AGENTS.md CHANGED
@@ -9,27 +9,27 @@ shared conventions.
9
9
 
10
10
  ## Subdirectory Index
11
11
 
12
- | Subdir | Purpose |
13
- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
14
- | [`ai/`](./ai/AGENTS.md) | LLM utilities - critic registry, model resolution, text classification, structured LLM call wrapper. |
15
- | [`memory/`](./memory/AGENTS.md) | Memory engine - the underlying storage and reasoning layer for memory-related extensions. |
16
- | [`config/`](./config/AGENTS.md) | Configuration loading and merging. |
17
- | [`constants/`](./constants/AGENTS.md) | Project-wide constants and enums. |
18
- | [`core/`](./core/AGENTS.md) | Foundation utilities - logger, event-name constants. Anything that's truly cross-cutting lives here. |
19
- | [`detection/`](./detection/AGENTS.md) | Detection primitives - degradation detection, topic-drift, context density, compression strategies. |
20
- | [`enforcement/`](./enforcement/AGENTS.md) | Cross-extension enforcement utilities - turn-dedup registry, whisper capping. |
21
- | [`events/`](./events/AGENTS.md) | Event-bus and channel infrastructure - consolidation, timer, turn-end coordination. |
22
- | [`reasoning/`](./reasoning/AGENTS.md) | Reasoning engines - dreamer (loop prediction), belief policy, MARS reflector, summarization, advice tracker. |
23
- | [`state/`](./state/AGENTS.md) | Per-extension state, session state, global state, checkpointing. |
24
- | [`store/`](./store/AGENTS.md) | Persistent stores - claims, evidence, conflicts, beliefs. |
25
- | [`types/`](./types/AGENTS.md) | Shared type definitions and result wrappers. |
26
- | [`utils/`](./utils/AGENTS.md) | Misc utilities - injection tracker, mutation queue, filter helpers, SOP extraction. |
27
- | [`cognitive/`](./cognitive/AGENTS.md) | Whisper-delivery libraries - project-relevant hints and active OpenSpec specs for the prompt. |
28
- | `errors/` | Unified LLM error classifier - provider-failure taxonomy (balance, rate-limit, context-window, transient). |
29
- | [`harness/`](./harness/AGENTS.md) | Self-harness loop - failure-trace collection, weakness mining, candidate proposal and validation. |
30
- | `orchestrator/` | Multi-agent coordination - file-lock registry, worker branches, conflict detection, merge verification. |
31
- | [`telemetry/`](./telemetry/AGENTS.md) | Bounded telemetry accumulators for the degradation-detection loop (drift signals, context/RSS heartbeat). |
32
- | `verification/` | Cross-file verification - downstream import tracing and derived-file coordination checks. |
12
+ | Subdir | Purpose |
13
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
14
+ | [`ai/`](./ai/AGENTS.md) | LLM utilities - critic registry, model resolution, text classification, structured LLM call wrapper. |
15
+ | [`memory/`](./memory/AGENTS.md) | Memory engine - the underlying storage and reasoning layer for memory-related extensions. |
16
+ | [`config/`](./config/AGENTS.md) | Configuration loading and merging. |
17
+ | [`constants/`](./constants/AGENTS.md) | Project-wide constants and enums. |
18
+ | [`core/`](./core/AGENTS.md) | Foundation utilities - logger, event-name constants. Anything that's truly cross-cutting lives here. |
19
+ | [`detection/`](./detection/AGENTS.md) | Detection primitives - degradation detection, topic-drift, context density, compression strategies. |
20
+ | [`enforcement/`](./enforcement/AGENTS.md) | Cross-extension enforcement utilities - turn-dedup registry, whisper capping. |
21
+ | [`events/`](./events/AGENTS.md) | Event-bus and channel infrastructure - consolidation, timer, turn-end coordination. |
22
+ | [`reasoning/`](./reasoning/AGENTS.md) | Reasoning engines - dreamer (loop prediction), belief policy, MARS reflector, summarization, advice tracker. |
23
+ | [`state/`](./state/AGENTS.md) | Per-extension state, session state, global state, checkpointing. |
24
+ | [`store/`](./store/AGENTS.md) | Persistent stores - claims, evidence, conflicts, beliefs. |
25
+ | [`types/`](./types/AGENTS.md) | Shared type definitions and result wrappers. |
26
+ | [`utils/`](./utils/AGENTS.md) | Misc utilities - injection tracker, mutation queue, filter helpers, SOP extraction. |
27
+ | [`cognitive/`](./cognitive/AGENTS.md) | Whisper-delivery libraries - project-relevant hints and active OpenSpec specs for the prompt. |
28
+ | `errors/` | Unified LLM error classifier - provider-failure taxonomy (balance, rate-limit, context-window, transient). |
29
+ | [`harness/`](./harness/AGENTS.md) | Self-harness loop - failure-trace collection, weakness mining, candidate proposal and validation. |
30
+ | `orchestrator/` | Multi-agent coordination - file-lock registry, worker registry with close-time gate-row well-formedness, the production-write preflight read, and the population-stamp read the merge path compares against the repo, worker branches, conflict detection, merge verification. |
31
+ | [`telemetry/`](./telemetry/AGENTS.md) | Bounded telemetry accumulators for the degradation-detection loop (drift signals, context/RSS heartbeat). |
32
+ | `verification/` | Cross-file verification - downstream import tracing and derived-file coordination checks. |
33
33
 
34
34
  ## Conventions
35
35
 
@@ -66,6 +66,24 @@ interface BraidConfig {
66
66
  mode?: string;
67
67
  };
68
68
  };
69
+ /**
70
+ * Orchestrator-layer config. `closeGateWellFormedness` gates the close
71
+ * path's gate evidence at close time: every recorded `{cmd, exit}` row is
72
+ * read as a string (parse, first-token resolution, no top-level
73
+ * decoration) and a completed close's exits must be 0. No gate is re-run.
74
+ *
75
+ * Example:
76
+ * "braid": { "orchestrator": { "closeGateWellFormedness": "shadow" } }
77
+ */
78
+ orchestrator?: {
79
+ /**
80
+ * "shadow" (default) logs a failing row to the refusal log and lets the
81
+ * close proceed; "enforce" refuses the close naming the row, predicate
82
+ * and cmd; "off" skips the read entirely. An unknown value warns once
83
+ * and falls back to "shadow".
84
+ */
85
+ closeGateWellFormedness?: string;
86
+ };
69
87
  /**
70
88
  * Memory-layer config. Review-before-write quality gate on durable episode
71
89
  * writes: `writeGate` controls the per-site policies (repair/dedupe/reject)
@@ -415,6 +433,62 @@ export function getOverCorrectionGateConfig(): OverCorrectionGateConfig {
415
433
  return resolveOverCorrectionGate(readSettings().braid?.enforcement?.overCorrectionGate);
416
434
  }
417
435
 
436
+ // ── close-gate well-formedness (braid.orchestrator.closeGateWellFormedness) ──
437
+ // The close path reads every recorded gate evidence row {cmd, exit} against
438
+ // four string predicates before the row is stamped (see
439
+ // lib/orchestrator/workers.ts). Shipped default: shadow, so a failing row is
440
+ // logged and the close proceeds, and a first ship cannot refuse honest closes.
441
+
442
+ /** Close-gate modes: off (inert), shadow (log only), enforce (refuse). */
443
+ export type CloseGateWellFormednessMode = "off" | "shadow" | "enforce";
444
+
445
+ export interface CloseGateWellFormednessConfig {
446
+ mode: CloseGateWellFormednessMode;
447
+ }
448
+
449
+ /** Default mode: shadow; the validator logs before it is allowed to refuse. */
450
+ export const CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS: CloseGateWellFormednessConfig = {
451
+ mode: "shadow",
452
+ };
453
+
454
+ /** Warned once per process about an invalid closeGateWellFormedness value. */
455
+ let _warnedInvalidCloseGateWellFormedness = false;
456
+
457
+ function _warnInvalidCloseGateWellFormedness(value: unknown): void {
458
+ if (_warnedInvalidCloseGateWellFormedness) return;
459
+ _warnedInvalidCloseGateWellFormedness = true;
460
+ _log.warn(
461
+ "Invalid braid.orchestrator.closeGateWellFormedness in settings.json - ignoring " +
462
+ 'and using the default (mode "shadow"). Expected "off" | "shadow" | "enforce".',
463
+ { value },
464
+ );
465
+ }
466
+
467
+ /**
468
+ * Pure resolver for braid.orchestrator.closeGateWellFormedness. Absent value
469
+ * ⇒ mode "shadow". A value outside the enum warns once and falls back to
470
+ * "shadow", so a typo can neither silently disarm the validator (off) nor
471
+ * arm it (enforce). Kept pure so the default merge is unit-testable without
472
+ * touching live settings.json.
473
+ */
474
+ export function resolveCloseGateWellFormedness(raw: unknown): CloseGateWellFormednessConfig {
475
+ if (raw === undefined || raw === null) return { ...CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS };
476
+ if (raw === "off" || raw === "shadow" || raw === "enforce") return { mode: raw };
477
+ _warnInvalidCloseGateWellFormedness(raw);
478
+ return { ...CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS };
479
+ }
480
+
481
+ /**
482
+ * Read the effective close-gate well-formedness mode from settings.json,
483
+ * fresh on every call (no caching), like the other readers. Default: mode
484
+ * "shadow".
485
+ */
486
+ export function getCloseGateWellFormedness(): CloseGateWellFormednessConfig {
487
+ return resolveCloseGateWellFormedness(
488
+ readSettings().braid?.orchestrator?.closeGateWellFormedness,
489
+ );
490
+ }
491
+
418
492
  /**
419
493
  * Read the braid.memory.writeGate block from settings.json.
420
494
  *
@@ -27,9 +27,8 @@ export const NUDGE_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes
27
27
  * retry end). Distinct from the 5-minute `NUDGE_COOLDOWN_MS` which is
28
28
  * a cross-session cap; this is the per-site rate-limit value.
29
29
  *
30
- * EW-7.8: promote to constant. The "remove" path (delete the field,
31
- * rely on NudgeManager) needs per-NudgeType cooldown decisions and
32
- * is deferred.
30
+ * Promote to constant is deferred: the "remove" path (delete the field,
31
+ * rely on NudgeManager) needs per-NudgeType cooldown decisions.
33
32
  */
34
33
  export const ERROR_TRACKING_NUDGE_COOLDOWN_MS = 60_000; // 1 minute
35
34
 
@@ -80,8 +80,8 @@ export const PER_SOURCE_CAP = 2;
80
80
  * caps than PER_SOURCE_CAP are NOT supported via overrides - if a
81
81
  * source needs a lower cap, add a new explicit value here.
82
82
  *
83
- * EW-7.13: drop the all-sources-share cap so high-priority sources
84
- * can get through during a degraded turn.
83
+ * Drop the all-sources-share cap so high-priority sources can get
84
+ * through during a degraded turn.
85
85
  */
86
86
  export const PER_SOURCE_CAP_OVERRIDES: Record<string, number> = {
87
87
  // Enforcement whispers are critical/high priority. A 3rd
@@ -1,6 +1,6 @@
1
1
  <!-- status: current -->
2
2
 
3
- # Self-Harness Loop (LP-1): src/lib/harness/
3
+ # Self-Harness Loop: src/lib/harness/
4
4
 
5
5
  Failure collection and weakness mining. `failure-trace-collector.ts` observes the
6
6
  tool-loop detector's per-session state (written by the enforcement extension on
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Self-Harness Loop (LP-1) — Public API
2
+ * Self-Harness Loop — Public API
3
3
  *
4
4
  * Failure Trace Collection + Weakness Mining.
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Types for the Self-Harness Loop (LP-1).
2
+ * Types for the Self-Harness Loop.
3
3
  *
4
4
  * Failure signatures represent concrete failure events detected during
5
5
  * agent operation. Weakness clusters group similar signatures to identify