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 @@
17
17
  import { execFileSync } from "node:child_process";
18
18
  import { Type } from "typebox";
19
19
  import { createLogger } from "../../lib/core/logger.js";
20
- import { acquireLock, releaseLock, getConflicts, getAllLocks, createWorkerBranch, deleteWorkerBranch, getDiff, getCurrentBranch, findRepoRoot, branchExists, gitAvailable, worktreeForBranch, scanAddedLinesForSlop, registerWorker, updateWorker, closeWorker, recordWorkerMerge, readWorkers, checkWorker, parseWorkerStatus, parseWorkerOutcome, decideAdmission, recordAdmissionRefusal, resolveRequestId, computeWorkerStats, workerEffectEvidenceForEntry, WORKER_EFFECT_EVIDENCE_FLAG, WORKER_SPECS, WORKER_OUTCOMES, WORKER_STATUSES, WORKER_STATUS_LAYERS, } from "../../lib/orchestrator/index.js";
20
+ import { acquireLock, releaseLock, getConflicts, getAllLocks, createWorkerBranch, deleteWorkerBranch, getDiff, getCurrentBranch, findRepoRoot, branchExists, gitAvailable, worktreeForBranch, scanAddedLinesForSlop, registerWorker, updateWorker, closeWorker, recordWorkerMerge, readWorkers, checkWorker, parseWorkerStatus, parseWorkerOutcome, decideAdmission, recordAdmissionRefusal, resolveRequestId, computeWorkerStats, workerEffectEvidenceForEntry, locateResultSchema, readPopulationStamps, populationRefusalDetail, WORKER_EFFECT_EVIDENCE_FLAG, WORKER_SPECS, WORKER_OUTCOMES, WORKER_STATUSES, WORKER_STATUS_LAYERS, } from "../../lib/orchestrator/index.js";
21
21
  const log = createLogger("orchestrator");
22
22
  // Helpers
23
23
  /**
@@ -94,12 +94,42 @@ function isAncestor(ancestor, descendant, repoRoot) {
94
94
  function isSafeRef(ref) {
95
95
  return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref);
96
96
  }
97
+ /**
98
+ * The commit census: how many entries the tree at `revision` holds. This is
99
+ * the index-independent equivalent of `git ls-files | wc -l` at that revision
100
+ * — it reads the named revision's tree rather than the caller's index, since
101
+ * the caller's worktree is not necessarily checked out where the gate scanned.
102
+ * Null when git cannot resolve the revision.
103
+ */
104
+ function censusAt(revision, repoRoot) {
105
+ if (!repoRoot)
106
+ return null;
107
+ const out = git(repoRoot, ["ls-tree", "-r", "--name-only", revision]);
108
+ if (out === undefined)
109
+ return null;
110
+ return out === "" ? 0 : out.split("\n").length;
111
+ }
112
+ /**
113
+ * The gate rows the merge path reads its population record from. A row that
114
+ * was already closed carries its recorded gates, and those win; the normal
115
+ * flow merges before close-worker, so the fallback is the worker's result
116
+ * block — the result contract's `gate_evidence`, located in the session the
117
+ * row names. No session and no gates is an empty read, not an error: the
118
+ * comparison is a reader, and a missing record prints as one.
119
+ */
120
+ function closeGateRows(entry) {
121
+ if (entry && Array.isArray(entry.gates) && entry.gates.length > 0)
122
+ return entry.gates;
123
+ const located = locateResultSchema(entry?.workerSession ?? null);
124
+ const rows = located?.schema.gate_evidence;
125
+ return Array.isArray(rows) ? rows : [];
126
+ }
97
127
  /**
98
128
  * Resolve the merge base explicitly, then merge the worker branch into it and
99
129
  * assert the base actually moved. Never infers the base from HEAD; never leaves
100
130
  * the worktree on a different branch; never claims a merge it did not perform.
101
131
  */
102
- function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
132
+ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot, population) {
103
133
  /** A refusal or no-op: nothing was merged, so nothing may be marked merged. */
104
134
  const nothingMerged = (report) => ({
105
135
  report,
@@ -126,6 +156,10 @@ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
126
156
  const short = (sha) => sha.slice(0, 12);
127
157
  const diff = getDiff(workerBranch, base, repoRoot);
128
158
  const scan = surfaceScanReport(diff);
159
+ // The population read rides directly under the outcome line: it is the
160
+ // reason a refusal happened, and on a merge it is the recorded-versus-git
161
+ // pair the merge claim is certified against.
162
+ const populationNote = population.lines.length > 0 ? `\n${population.lines.join("\n")}` : "";
129
163
  const finish = (lead, deletedLead, mergeSha, extraWorktreeNote = "") => {
130
164
  // Where the caller's tree sits is part of the merge result, not a detail:
131
165
  // this tool never switches the shared worktree's branch, so after a merge
@@ -146,7 +180,7 @@ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
146
180
  // what the registry now says.
147
181
  const audit = mergeAuditNote(workerId, mergeSha, repoRoot);
148
182
  return {
149
- report: `${lead}${audit}\nBranch: ${workerBranch} (${deleted ? "deleted" : onWorkerBranch ? "kept: this worktree is on it" : deletedLead})${worktreeNote}${settleBlock}\nDiff summary:\n${diff.slice(0, 2000)}\n${scan}`,
183
+ report: `${lead}${audit}${populationNote}\nBranch: ${workerBranch} (${deleted ? "deleted" : onWorkerBranch ? "kept: this worktree is on it" : deletedLead})${worktreeNote}${settleBlock}\nDiff summary:\n${diff.slice(0, 2000)}\n${scan}`,
150
184
  mergeSha,
151
185
  worktreeBranch: head,
152
186
  };
@@ -156,6 +190,14 @@ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
156
190
  if (isAncestor(tip, base, repoRoot)) {
157
191
  return finish(`Worker ${workerId} already contained in ${base}: ${short(tip)} is an ancestor of ${base} (${short(baseBefore)}). Nothing merged.`, "kept: still checked out", null);
158
192
  }
193
+ // A recorded population below the census at its own revision is the claim
194
+ // this read exists to test: the gate certified fewer tracked entries than
195
+ // that revision holds, so the merge waits for a re-run on the staged tree.
196
+ const standingDetail = populationRefusalDetail(population);
197
+ if (standingDetail) {
198
+ return nothingMerged(`NOT merged: ${standingDetail}\n` +
199
+ `Base unchanged at ${short(baseBefore)}. Locks and branch kept.\n${population.lines.join("\n")}`);
200
+ }
159
201
  // Set when the fast-forward happened in a worktree other than the caller's;
160
202
  // the report names where the base's tree moved, so a reader can act on it.
161
203
  let settleNote = "";
@@ -357,7 +399,7 @@ const orchestrateTool = {
357
399
  name: "orchestrate",
358
400
  label: "Orchestrate",
359
401
  promptSnippet: "Coordinate parallel agent workers (spawn/check/merge, locks)",
360
- description: "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. " +
402
+ description: "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. " +
361
403
  `Worker lifecycle speaks in four vocabularies: ${renderStatusLayers()}.`,
362
404
  parameters: Type.Object({
363
405
  action: Type.Union([
@@ -414,10 +456,28 @@ const orchestrateTool = {
414
456
  outcome: Type.Optional(Type.String({
415
457
  description: `Terminal outcome for close-worker (${WORKER_OUTCOMES.join("|")}).`,
416
458
  })),
417
- gates: Type.Optional(Type.Array(Type.Object({ cmd: Type.String(), exit: Type.Number() }), {
459
+ gates: Type.Optional(Type.Array(Type.Object({
460
+ cmd: Type.String(),
461
+ exit: Type.Number(),
462
+ stamp: Type.Optional(Type.String({
463
+ description: "Population record for a gate whose subject is a file or row population: " +
464
+ '"scanned <n> <unit> at <revision>" (n a non-negative integer, unit one ' +
465
+ "lowercase word, revision a 7-to-40-char hex sha or a ref name). " +
466
+ "verify-and-merge reads a stamped `files` row against that revision's " +
467
+ "tracked-entry census and refuses the merge when the recorded number sits " +
468
+ "below it.",
469
+ })),
470
+ }), {
418
471
  description: "Gate evidence for close-worker: command plus exit code, recorded with a timestamp. " +
419
472
  `A completed close whose entry carries none of a fresh output file, a branch advance or ` +
420
- `merge, and a passing gate is flagged "${WORKER_EFFECT_EVIDENCE_FLAG}" (advisory, non-blocking).`,
473
+ `merge, and a passing gate is flagged "${WORKER_EFFECT_EVIDENCE_FLAG}" (advisory, non-blocking). ` +
474
+ "Every row is also read for well-formedness at close time (parses under sh -n, first token " +
475
+ "resolves, no top-level decoration, exit 0 under a completed outcome); the read ships in " +
476
+ "shadow mode, so a failing row is logged and the close proceeds, until " +
477
+ 'braid.orchestrator.closeGateWellFormedness is set to "enforce". ' +
478
+ "Rows the seat's production-write class marks as writes are refused unless the close " +
479
+ "records every named preflight piece somewhere in its rows; the class data is the seat's, " +
480
+ "and no class data means no refusal.",
421
481
  })),
422
482
  includeClosed: Type.Optional(Type.Boolean({ description: "list-workers: include closed entries (default false)." })),
423
483
  includeStats: Type.Optional(Type.Boolean({
@@ -695,13 +755,18 @@ Register the worker (orchestrate action=register-worker) for a structured verdic
695
755
  // of the three yields one.
696
756
  const lockRows = getAllLocks(repoRoot);
697
757
  const lockBranch = Object.values(lockRows).find((row) => row.workerId === workerId)?.branch;
698
- const entryBranch = readWorkers(repoRoot).workers[workerId]?.branch ?? undefined;
758
+ const entry = readWorkers(repoRoot).workers[workerId];
759
+ const entryBranch = entry?.branch ?? undefined;
699
760
  const workerBranch = branch ?? entryBranch ?? lockBranch;
700
761
  if (!workerBranch) {
701
762
  return textResult(`Worker ${workerId} has no branch to verify: no branch argument, no branch on its ` +
702
763
  `registry entry, and no lock rows. Nothing to verify.`);
703
764
  }
704
- const outcome = verifyAndMergeBase(workerId, workerBranch, baseBranch ?? "main", repoRoot);
765
+ // The close's population record is read before the merge: the stamped
766
+ // rows are the reporter's own numbers, and the census they are compared
767
+ // against comes from git alone.
768
+ const population = readPopulationStamps(closeGateRows(entry), (revision) => censusAt(revision, repoRoot));
769
+ const outcome = verifyAndMergeBase(workerId, workerBranch, baseBranch ?? "main", repoRoot, population);
705
770
  // The merge sha travels in details as well as in the report, so a
706
771
  // parent can verify the claim it was handed without parsing prose; the
707
772
  // worktree branch travels with it, because a merge that leaves the
@@ -24,20 +24,101 @@ const EVOLVE_ACTIONS = [
24
24
  const healthMaintenanceSchema = Type.Object({
25
25
  action: StringEnum([...EVOLVE_ACTIONS], { description: "Action to perform" }),
26
26
  checkpoint: Type.Optional(Type.String({ description: "Checkpoint hash for rollback" })),
27
+ // Numeric bounds where 0 is meaningless: a blank selector is converted to
28
+ // 0 by argument validation, and 0 outside a field's band turns the blank
29
+ // into a refusal before any handler runs. errorRateMax stays unbounded here
30
+ // because its legal band is (0,1] and a schema minimum cannot express it;
31
+ // the handler guard owns that one.
27
32
  config: Type.Optional(Type.Object({
28
- healthcheckMinScore: Type.Optional(Type.Number({ description: "Minimum healthcheck score (0-100)" })),
29
- errorRateMax: Type.Optional(Type.Number({ description: "Maximum error rate (0-1)" })),
30
- toolSuccessMin: Type.Optional(Type.Number({ description: "Minimum tool success rate (0-100)" })),
31
- maxConsecutiveErrors: Type.Optional(Type.Number({ description: "Max consecutive errors before degradation" })),
33
+ healthcheckMinScore: Type.Optional(Type.Number({
34
+ minimum: 1,
35
+ maximum: 100,
36
+ description: "Minimum healthcheck score (1-100)",
37
+ })),
38
+ errorRateMax: Type.Optional(Type.Number({ description: "Maximum error rate (0-1]" })),
39
+ toolSuccessMin: Type.Optional(Type.Number({
40
+ minimum: 1,
41
+ maximum: 100,
42
+ description: "Minimum tool success rate (1-100)",
43
+ })),
44
+ maxConsecutiveErrors: Type.Optional(Type.Number({
45
+ minimum: 1,
46
+ description: "Max consecutive errors before degradation (>= 1)",
47
+ })),
32
48
  })),
33
49
  benchmark: Type.Optional(Type.Object({
34
- passRate: Type.Optional(Type.Number({ description: "Benchmark pass rate (0-100)" })),
35
- totalCases: Type.Optional(Type.Number({ description: "Total number of test cases" })),
36
- passedCases: Type.Optional(Type.Number({ description: "Number of cases that passed" })),
50
+ passRate: Type.Optional(Type.Number({ minimum: 1, maximum: 100, description: "Benchmark pass rate (1-100)" })),
51
+ totalCases: Type.Optional(Type.Number({ minimum: 1, description: "Number of cases in the benchmark run (>= 1)" })),
52
+ passedCases: Type.Optional(Type.Number({ minimum: 0, description: "Number of cases that passed (>= 0)" })),
37
53
  failedCases: Type.Optional(Type.Array(Type.String(), { description: "Names of failed cases" })),
38
54
  })),
39
55
  force: Type.Optional(Type.Boolean({ default: false, description: "Force action without confirmation" })),
40
56
  });
57
+ const CONFIG_FIELD_BANDS = {
58
+ healthcheckMinScore: { min: 1, max: 100 },
59
+ errorRateMax: { min: 0, max: 1, minExclusive: true },
60
+ toolSuccessMin: { min: 1, max: 100 },
61
+ maxConsecutiveErrors: { min: 1, max: null },
62
+ checkIntervalMs: { min: 1, max: null },
63
+ };
64
+ function bandText(band) {
65
+ if (band.max === null)
66
+ return band.minExclusive ? `> ${band.min}` : `>= ${band.min}`;
67
+ if (band.minExclusive)
68
+ return `(${band.min}, ${band.max}]`;
69
+ return `${band.min}-${band.max}`;
70
+ }
71
+ /** The refusal sentence for `value` under `band`, or null when it is inside it. */
72
+ function bandRefusal(field, value, band) {
73
+ if (typeof value !== "number" || !Number.isFinite(value)) {
74
+ return `${field} must be a finite number; got ${JSON.stringify(value)}.`;
75
+ }
76
+ const below = band.minExclusive ? value <= band.min : value < band.min;
77
+ const above = band.max !== null && value > band.max;
78
+ if (below || above) {
79
+ return `${field} must be ${bandText(band)}; got ${value}. A blank selector arrives as 0 and is refused.`;
80
+ }
81
+ return null;
82
+ }
83
+ /**
84
+ * Validate a config patch: provided fields must be finite numbers inside their
85
+ * documented band. Absent/null fields are not provided. Returns the accepted
86
+ * subset (so unknown keys never reach the merge), or the error naming the
87
+ * first offending field.
88
+ */
89
+ function validateConfigPatch(config) {
90
+ const values = {};
91
+ for (const key of Object.keys(CONFIG_FIELD_BANDS)) {
92
+ const raw = config[key];
93
+ if (raw === undefined || raw === null)
94
+ continue;
95
+ const refusal = bandRefusal(String(key), raw, CONFIG_FIELD_BANDS[key]);
96
+ if (refusal)
97
+ return { error: refusal };
98
+ values[key] = raw;
99
+ }
100
+ return { values };
101
+ }
102
+ /** The benchmark's numeric rule: same bands, same refusal class as config. */
103
+ function validateBenchmark(benchmark) {
104
+ const passRate = bandRefusal("benchmark.passRate", benchmark.passRate, { min: 1, max: 100 });
105
+ if (passRate)
106
+ return passRate;
107
+ if (benchmark.totalCases !== undefined && benchmark.totalCases !== null) {
108
+ const total = bandRefusal("benchmark.totalCases", benchmark.totalCases, { min: 1, max: null });
109
+ if (total)
110
+ return total;
111
+ }
112
+ if (benchmark.passedCases !== undefined && benchmark.passedCases !== null) {
113
+ const passed = bandRefusal("benchmark.passedCases", benchmark.passedCases, {
114
+ min: 0,
115
+ max: null,
116
+ });
117
+ if (passed)
118
+ return passed;
119
+ }
120
+ return null;
121
+ }
41
122
  export default function healthMaintenanceExtension(pi) {
42
123
  startMetricsPersistence();
43
124
  pi.on(SESSION_SHUTDOWN, async () => {
@@ -201,8 +282,26 @@ async function executeRollback() {
201
282
  };
202
283
  }
203
284
  function executeConfig(newConfig) {
204
- if (newConfig)
205
- updateConfig(newConfig);
285
+ if (newConfig !== undefined && newConfig !== null) {
286
+ if (typeof newConfig !== "object" || Array.isArray(newConfig)) {
287
+ return {
288
+ action: "config",
289
+ success: false,
290
+ error: "config must be an object of numeric thresholds.",
291
+ };
292
+ }
293
+ const verdict = validateConfigPatch(newConfig);
294
+ if ("error" in verdict) {
295
+ // Atomic: nothing is merged when any provided field is refused. The
296
+ // merge below stays where it was (the process-global config the tool has
297
+ // always written and reports, and the one carried into new sessions).
298
+ return { action: "config", success: false, error: verdict.error };
299
+ }
300
+ if (Object.keys(verdict.values).length === 0) {
301
+ return { action: "config", success: false, error: "no config values provided" };
302
+ }
303
+ updateConfig(verdict.values);
304
+ }
206
305
  return { action: "config", success: true, data: { config: getConfig() } };
207
306
  }
208
307
  function executeReset() {
@@ -219,6 +318,10 @@ function executeBenchmark(params) {
219
318
  data: { history: BENCHMARK_HISTORY.slice(-5), totalRuns: BENCHMARK_HISTORY.length },
220
319
  };
221
320
  }
321
+ const refusal = validateBenchmark(params);
322
+ if (refusal) {
323
+ return { action: "benchmark", success: false, error: refusal };
324
+ }
222
325
  const result = {
223
326
  timestamp: Date.now(),
224
327
  passRate: params.passRate,
@@ -95,6 +95,27 @@ export declare function resolveOverCorrectionGate(raw: unknown): OverCorrectionG
95
95
  * on every call (no caching), like the other readers. Default: mode "off".
96
96
  */
97
97
  export declare function getOverCorrectionGateConfig(): OverCorrectionGateConfig;
98
+ /** Close-gate modes: off (inert), shadow (log only), enforce (refuse). */
99
+ export type CloseGateWellFormednessMode = "off" | "shadow" | "enforce";
100
+ export interface CloseGateWellFormednessConfig {
101
+ mode: CloseGateWellFormednessMode;
102
+ }
103
+ /** Default mode: shadow; the validator logs before it is allowed to refuse. */
104
+ export declare const CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS: CloseGateWellFormednessConfig;
105
+ /**
106
+ * Pure resolver for braid.orchestrator.closeGateWellFormedness. Absent value
107
+ * ⇒ mode "shadow". A value outside the enum warns once and falls back to
108
+ * "shadow", so a typo can neither silently disarm the validator (off) nor
109
+ * arm it (enforce). Kept pure so the default merge is unit-testable without
110
+ * touching live settings.json.
111
+ */
112
+ export declare function resolveCloseGateWellFormedness(raw: unknown): CloseGateWellFormednessConfig;
113
+ /**
114
+ * Read the effective close-gate well-formedness mode from settings.json,
115
+ * fresh on every call (no caching), like the other readers. Default: mode
116
+ * "shadow".
117
+ */
118
+ export declare function getCloseGateWellFormedness(): CloseGateWellFormednessConfig;
98
119
  /**
99
120
  * Read the braid.memory.writeGate block from settings.json.
100
121
  *
@@ -110,6 +110,42 @@ export function resolveOverCorrectionGate(raw) {
110
110
  export function getOverCorrectionGateConfig() {
111
111
  return resolveOverCorrectionGate(readSettings().braid?.enforcement?.overCorrectionGate);
112
112
  }
113
+ /** Default mode: shadow; the validator logs before it is allowed to refuse. */
114
+ export const CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS = {
115
+ mode: "shadow",
116
+ };
117
+ /** Warned once per process about an invalid closeGateWellFormedness value. */
118
+ let _warnedInvalidCloseGateWellFormedness = false;
119
+ function _warnInvalidCloseGateWellFormedness(value) {
120
+ if (_warnedInvalidCloseGateWellFormedness)
121
+ return;
122
+ _warnedInvalidCloseGateWellFormedness = true;
123
+ _log.warn("Invalid braid.orchestrator.closeGateWellFormedness in settings.json - ignoring " +
124
+ 'and using the default (mode "shadow"). Expected "off" | "shadow" | "enforce".', { value });
125
+ }
126
+ /**
127
+ * Pure resolver for braid.orchestrator.closeGateWellFormedness. Absent value
128
+ * ⇒ mode "shadow". A value outside the enum warns once and falls back to
129
+ * "shadow", so a typo can neither silently disarm the validator (off) nor
130
+ * arm it (enforce). Kept pure so the default merge is unit-testable without
131
+ * touching live settings.json.
132
+ */
133
+ export function resolveCloseGateWellFormedness(raw) {
134
+ if (raw === undefined || raw === null)
135
+ return { ...CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS };
136
+ if (raw === "off" || raw === "shadow" || raw === "enforce")
137
+ return { mode: raw };
138
+ _warnInvalidCloseGateWellFormedness(raw);
139
+ return { ...CLOSE_GATE_WELL_FORMEDNESS_DEFAULTS };
140
+ }
141
+ /**
142
+ * Read the effective close-gate well-formedness mode from settings.json,
143
+ * fresh on every call (no caching), like the other readers. Default: mode
144
+ * "shadow".
145
+ */
146
+ export function getCloseGateWellFormedness() {
147
+ return resolveCloseGateWellFormedness(readSettings().braid?.orchestrator?.closeGateWellFormedness);
148
+ }
113
149
  /**
114
150
  * Read the braid.memory.writeGate block from settings.json.
115
151
  *
@@ -19,9 +19,8 @@ export declare const NUDGE_COOLDOWN_MS: number;
19
19
  * retry end). Distinct from the 5-minute `NUDGE_COOLDOWN_MS` which is
20
20
  * a cross-session cap; this is the per-site rate-limit value.
21
21
  *
22
- * EW-7.8: promote to constant. The "remove" path (delete the field,
23
- * rely on NudgeManager) needs per-NudgeType cooldown decisions and
24
- * is deferred.
22
+ * Promote to constant is deferred: the "remove" path (delete the field,
23
+ * rely on NudgeManager) needs per-NudgeType cooldown decisions.
25
24
  */
26
25
  export declare const ERROR_TRACKING_NUDGE_COOLDOWN_MS = 60000;
27
26
  /**
@@ -22,9 +22,8 @@ export const NUDGE_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes
22
22
  * retry end). Distinct from the 5-minute `NUDGE_COOLDOWN_MS` which is
23
23
  * a cross-session cap; this is the per-site rate-limit value.
24
24
  *
25
- * EW-7.8: promote to constant. The "remove" path (delete the field,
26
- * rely on NudgeManager) needs per-NudgeType cooldown decisions and
27
- * is deferred.
25
+ * Promote to constant is deferred: the "remove" path (delete the field,
26
+ * rely on NudgeManager) needs per-NudgeType cooldown decisions.
28
27
  */
29
28
  export const ERROR_TRACKING_NUDGE_COOLDOWN_MS = 60_000; // 1 minute
30
29
  // ═════════════════════════════════════════════════════════════════════════════
@@ -53,8 +53,8 @@ export declare const PER_SOURCE_CAP = 2;
53
53
  * caps than PER_SOURCE_CAP are NOT supported via overrides - if a
54
54
  * source needs a lower cap, add a new explicit value here.
55
55
  *
56
- * EW-7.13: drop the all-sources-share cap so high-priority sources
57
- * can get through during a degraded turn.
56
+ * Drop the all-sources-share cap so high-priority sources can get
57
+ * through during a degraded turn.
58
58
  */
59
59
  export declare const PER_SOURCE_CAP_OVERRIDES: Record<string, number>;
60
60
  /** Resolve the per-source cap for a given source (override or default). */
@@ -52,8 +52,8 @@ export const PER_SOURCE_CAP = 2;
52
52
  * caps than PER_SOURCE_CAP are NOT supported via overrides - if a
53
53
  * source needs a lower cap, add a new explicit value here.
54
54
  *
55
- * EW-7.13: drop the all-sources-share cap so high-priority sources
56
- * can get through during a degraded turn.
55
+ * Drop the all-sources-share cap so high-priority sources can get
56
+ * through during a degraded turn.
57
57
  */
58
58
  export const PER_SOURCE_CAP_OVERRIDES = {
59
59
  // Enforcement whispers are critical/high priority. A 3rd
@@ -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
- * 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
@@ -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
@@ -9,6 +9,6 @@ export type { LockEntry, LockRegistry, Conflict } from "./locks.js";
9
9
  export { createWorkerBranch, deleteWorkerBranch, getDiff, branchExists, getCurrentBranch, findRepoRoot, gitAvailable, worktreeForBranch, } from "./branch.js";
10
10
  export { scanAddedLinesForSlop } from "./slop-scanner.js";
11
11
  export type { SlopHit } from "./slop-scanner.js";
12
- export { WORKER_REGISTRY_VERSION, WORKER_SPECS, WORKER_STATUSES, WORKER_OUTCOMES, WORKER_VERDICT_STATUSES, WORKER_STATUS_LAYERS, RESULT_SCHEMA_STATUSES, parseWorkerStatus, parseWorkerOutcome, readWorkers, writeWorkers, deriveRequestId, resolveRequestId, decideAdmission, recordAdmissionRefusal, registerWorker, updateWorker, closeWorker, recordWorkerMerge, validateResultSchema, evaluateWorker, checkWorker, computeWorkerStats, WORKER_EFFECT_EVIDENCE_FLAG, workerEffectEvidence, workerEffectEvidenceForEntry, } from "./workers.js";
13
- export type { WorkerStatus, WorkerVerdictStatus, WorkerOutcome, WorkerStatusLayer, WorkerStatusLayerRole, WorkerGate, WorkerCheckpoint, WorkerCheckpointInput, WorkerAdmissionDecision, WorkerAdmissionRefusal, WorkerEntry, WorkerRegistry, RegisterWorkerInput, RegisterWorkerResult, UpdateWorkerPatch, WorkerCheckOptions, WorkerCheckResult, WorkerEffectEvidence, WorkerEffectFacts, WorkerStats, WorkerLatencySummary, } from "./workers.js";
12
+ export { WORKER_REGISTRY_VERSION, WORKER_SPECS, WORKER_STATUSES, WORKER_OUTCOMES, WORKER_VERDICT_STATUSES, WORKER_STATUS_LAYERS, RESULT_SCHEMA_STATUSES, parseWorkerStatus, parseWorkerOutcome, readWorkers, writeWorkers, deriveRequestId, resolveRequestId, decideAdmission, recordAdmissionRefusal, registerWorker, updateWorker, closeWorker, recordWorkerMerge, validateResultSchema, locateResultSchema, evaluateWorker, checkWorker, computeWorkerStats, WORKER_EFFECT_EVIDENCE_FLAG, workerEffectEvidence, workerEffectEvidenceForEntry, firstCommandToken, findTopLevelDecoration, findGateRowViolation, closeGateRefusalLogPath, logCloseGateRefusal, parsePopulationStamp, readPopulationStamps, populationRefusalDetail, productionWriteClassPath, readProductionWriteClass, readProductionWrites, productionWriteRefusalDetail, } from "./workers.js";
13
+ export type { WorkerStatus, WorkerVerdictStatus, WorkerOutcome, WorkerStatusLayer, WorkerStatusLayerRole, WorkerGate, WorkerCheckpoint, WorkerCheckpointInput, WorkerAdmissionDecision, WorkerAdmissionRefusal, WorkerEntry, WorkerRegistry, RegisterWorkerInput, RegisterWorkerResult, UpdateWorkerPatch, WorkerCheckOptions, WorkerCheckResult, WorkerEffectEvidence, WorkerEffectFacts, WorkerStats, WorkerLatencySummary, GateRowPredicate, GateRowViolation, CloseGateRefusalRecord, ResultSchemaLocation, PopulationStamp, PopulationVerdict, PopulationRowRead, PopulationRead, PopulationCensus, ProductionWriteRule, ProductionWriteClass, ProductionWriteRowRead, ProductionWriteRead, } from "./workers.js";
14
14
  //# sourceMappingURL=index.d.ts.map
@@ -7,5 +7,5 @@
7
7
  export { acquireLock, releaseLock, getConflicts, getAllLocks } from "./locks.js";
8
8
  export { createWorkerBranch, deleteWorkerBranch, getDiff, branchExists, getCurrentBranch, findRepoRoot, gitAvailable, worktreeForBranch, } from "./branch.js";
9
9
  export { scanAddedLinesForSlop } from "./slop-scanner.js";
10
- export { WORKER_REGISTRY_VERSION, WORKER_SPECS, WORKER_STATUSES, WORKER_OUTCOMES, WORKER_VERDICT_STATUSES, WORKER_STATUS_LAYERS, RESULT_SCHEMA_STATUSES, parseWorkerStatus, parseWorkerOutcome, readWorkers, writeWorkers, deriveRequestId, resolveRequestId, decideAdmission, recordAdmissionRefusal, registerWorker, updateWorker, closeWorker, recordWorkerMerge, validateResultSchema, evaluateWorker, checkWorker, computeWorkerStats, WORKER_EFFECT_EVIDENCE_FLAG, workerEffectEvidence, workerEffectEvidenceForEntry, } from "./workers.js";
10
+ export { WORKER_REGISTRY_VERSION, WORKER_SPECS, WORKER_STATUSES, WORKER_OUTCOMES, WORKER_VERDICT_STATUSES, WORKER_STATUS_LAYERS, RESULT_SCHEMA_STATUSES, parseWorkerStatus, parseWorkerOutcome, readWorkers, writeWorkers, deriveRequestId, resolveRequestId, decideAdmission, recordAdmissionRefusal, registerWorker, updateWorker, closeWorker, recordWorkerMerge, validateResultSchema, locateResultSchema, evaluateWorker, checkWorker, computeWorkerStats, WORKER_EFFECT_EVIDENCE_FLAG, workerEffectEvidence, workerEffectEvidenceForEntry, firstCommandToken, findTopLevelDecoration, findGateRowViolation, closeGateRefusalLogPath, logCloseGateRefusal, parsePopulationStamp, readPopulationStamps, populationRefusalDetail, productionWriteClassPath, readProductionWriteClass, readProductionWrites, productionWriteRefusalDetail, } from "./workers.js";
11
11
  //# sourceMappingURL=index.js.map