pi-braid 0.40.1 → 0.40.3

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 (105) hide show
  1. package/CONTRIBUTING.md +27 -3
  2. package/README.md +13 -13
  3. package/TOOLS.md +27 -3
  4. package/build-info.json +9 -0
  5. package/dist/extensions/cognitive/metacognition/handlers/claim-verification.js +7 -1
  6. package/dist/extensions/cognitive/metacognition/handlers/finalize.js +20 -0
  7. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.d.ts +9 -0
  8. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +13 -1
  9. package/dist/extensions/cognitive/metacognition/handlers/verify.js +35 -4
  10. package/dist/extensions/cognitive/topic-drift/index.js +19 -2
  11. package/dist/extensions/core/prompt-builder/inspect.js +9 -3
  12. package/dist/extensions/core/prompt-builder/top-level-extensions.d.ts +6 -5
  13. package/dist/extensions/core/prompt-builder/top-level-extensions.js +64 -29
  14. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +1 -1
  15. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +1 -1
  16. package/dist/extensions/enforcement/handlers/turn-end-handler.js +1 -1
  17. package/dist/extensions/enforcement/self-state-claims.d.ts +1 -1
  18. package/dist/extensions/enforcement/self-state-claims.js +3 -2
  19. package/dist/extensions/manifest.js +2 -2
  20. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +22 -5
  21. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +43 -11
  22. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +174 -50
  23. package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.js +7 -1
  24. package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +4 -1
  25. package/dist/extensions/memory/memory-agent-bridge/explore-paths.d.ts +2 -24
  26. package/dist/extensions/memory/memory-agent-bridge/explore-paths.js +33 -2
  27. package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +16 -0
  28. package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +21 -9
  29. package/dist/extensions/memory/scratchpad/format.js +8 -2
  30. package/dist/extensions/memory/scratchpad/index.js +11 -2
  31. package/dist/extensions/memory/session-recall/index.js +19 -6
  32. package/dist/extensions/memory/three-memory-stores/episodes.d.ts +1 -1
  33. package/dist/extensions/memory/three-memory-stores/episodes.js +2 -2
  34. package/dist/extensions/orchestrator/index.js +73 -8
  35. package/dist/extensions/scheduling/timer/index.js +9 -1
  36. package/dist/extensions/self/error-tracking/index.js +8 -1
  37. package/dist/extensions/self/health-maintenance/handlers/session-health-tool.js +9 -2
  38. package/dist/extensions/self/health-maintenance/index.js +112 -9
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +36 -0
  41. package/dist/lib/constants/session-thresholds.d.ts +2 -3
  42. package/dist/lib/constants/session-thresholds.js +2 -3
  43. package/dist/lib/enforcement/turn-dedup.d.ts +2 -2
  44. package/dist/lib/enforcement/turn-dedup.js +2 -2
  45. package/dist/lib/harness/index.d.ts +1 -1
  46. package/dist/lib/harness/index.js +1 -1
  47. package/dist/lib/harness/types.d.ts +1 -1
  48. package/dist/lib/harness/types.js +1 -1
  49. package/dist/lib/orchestrator/index.d.ts +2 -2
  50. package/dist/lib/orchestrator/index.js +1 -1
  51. package/dist/lib/orchestrator/workers.d.ts +184 -2
  52. package/dist/lib/orchestrator/workers.js +521 -6
  53. package/dist/lib/utils/injection-tracker.js +1 -1
  54. package/docs/CONTEXT-POLICY.md +13 -5
  55. package/docs/LOCAL_DEV.md +31 -5
  56. package/docs/ROADMAP.md +10 -7
  57. package/docs/SETUP.md +3 -2
  58. package/package.json +11 -8
  59. package/skills/braid-reference/SKILL.md +23 -23
  60. package/skills/release-pipeline/SKILL.md +46 -37
  61. package/skills/subagent-orchestration/SKILL.md +51 -1
  62. package/src/extensions/cognitive/metacognition/handlers/claim-verification.ts +8 -1
  63. package/src/extensions/cognitive/metacognition/handlers/finalize.ts +21 -0
  64. package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +14 -1
  65. package/src/extensions/cognitive/metacognition/handlers/verify.ts +39 -5
  66. package/src/extensions/cognitive/topic-drift/index.ts +20 -2
  67. package/src/extensions/core/prompt-builder/AGENTS.md +1 -1
  68. package/src/extensions/core/prompt-builder/inspect.ts +10 -3
  69. package/src/extensions/core/prompt-builder/top-level-extensions.ts +68 -29
  70. package/src/extensions/enforcement/AGENTS.md +25 -19
  71. package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +1 -1
  72. package/src/extensions/enforcement/handlers/turn-end-handler.ts +1 -1
  73. package/src/extensions/enforcement/self-state-claims.ts +3 -2
  74. package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +6 -3
  75. package/src/extensions/manifest.ts +2 -2
  76. package/src/extensions/memory/AGENTS.md +13 -5
  77. package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +45 -11
  78. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +202 -60
  79. package/src/extensions/memory/context-manager/handlers/tools/context-inspect.ts +8 -1
  80. package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +4 -1
  81. package/src/extensions/memory/memory-agent-bridge/explore-paths.ts +37 -3
  82. package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +16 -0
  83. package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +22 -9
  84. package/src/extensions/memory/scratchpad/format.ts +8 -2
  85. package/src/extensions/memory/scratchpad/index.ts +12 -2
  86. package/src/extensions/memory/session-recall/index.ts +20 -8
  87. package/src/extensions/memory/three-memory-stores/episodes.ts +2 -2
  88. package/src/extensions/orchestrator/index.ts +100 -11
  89. package/src/extensions/scheduling/timer/AGENTS.md +7 -0
  90. package/src/extensions/scheduling/timer/index.ts +10 -1
  91. package/src/extensions/self/error-tracking/index.ts +9 -1
  92. package/src/extensions/self/health-maintenance/handlers/session-health-tool.ts +10 -2
  93. package/src/extensions/self/health-maintenance/index.ts +143 -14
  94. package/src/extensions/self/watchdog/AGENTS.md +1 -0
  95. package/src/lib/AGENTS.md +21 -21
  96. package/src/lib/config/braid-settings.ts +74 -0
  97. package/src/lib/constants/session-thresholds.ts +2 -3
  98. package/src/lib/enforcement/turn-dedup.ts +2 -2
  99. package/src/lib/harness/AGENTS.md +1 -1
  100. package/src/lib/harness/index.ts +1 -1
  101. package/src/lib/harness/types.ts +1 -1
  102. package/src/lib/orchestrator/index.ts +26 -0
  103. package/src/lib/orchestrator/workers.ts +705 -7
  104. package/src/lib/utils/AGENTS.md +1 -1
  105. package/src/lib/utils/injection-tracker.ts +1 -1
@@ -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
@@ -19,6 +19,7 @@
19
19
  * Writes are atomic (temp file + rename) with mode 0600. Reads tolerate a
20
20
  * missing or corrupt file by returning an empty registry, like locks.ts.
21
21
  */
22
+ import type { CloseGateWellFormednessMode } from "../config/braid-settings.js";
22
23
  export type WorkerStatus = "admitted" | "working" | "merged" | "completed" | "error" | "stalled" | "false-done" | "closed";
23
24
  /** Terminal outcomes accepted by closeWorker. */
24
25
  export type WorkerOutcome = "completed" | "error" | "stalled" | "false-done" | "closed";
@@ -26,6 +27,14 @@ export interface WorkerGate {
26
27
  cmd: string;
27
28
  exit: number;
28
29
  at: string;
30
+ /**
31
+ * What the gate's population scan recorded, in the contract's shape
32
+ * (`scanned <n> <unit> at <revision>`). Optional: a gate with no population
33
+ * subject carries none, and a row recorded before the field existed stays
34
+ * valid. Stored verbatim; the read that compares it against the repo lives
35
+ * on the merge path.
36
+ */
37
+ stamp?: string;
29
38
  }
30
39
  /** One duplicate admission a live entry turned away, and the request it refused. */
31
40
  export interface WorkerAdmissionRefusal {
@@ -289,6 +298,162 @@ export declare function recordWorkerMerge(workerId: string, info: {
289
298
  mergeSha: string;
290
299
  cwd?: string;
291
300
  }): WorkerEntry | null;
301
+ /** Predicate letters, in the order the four are evaluated. */
302
+ export type GateRowPredicate = "a" | "b" | "c" | "d";
303
+ export interface GateRowViolation {
304
+ predicate: GateRowPredicate;
305
+ detail: string;
306
+ }
307
+ /** The first whitespace-delimited token after leading env assignments, or null. */
308
+ export declare function firstCommandToken(cmd: string): string | null;
309
+ /**
310
+ * The (c) instrument: a top-level decoration that makes the field more than
311
+ * the command, so the recorded exit cannot be attributed to what the field
312
+ * names: an unquoted `;` or newline (whatever follows owns the exit), a
313
+ * background `&` (the shell owns it), or a word-starting `#` (the field
314
+ * carries a comment). Quotes, command substitutions and redirections are
315
+ * shell syntax rather than decorations and are skipped, so `2>&1 | tail`,
316
+ * `cd x && npm run ci:check` and a quoted `';'` stay accepted. Returns the
317
+ * decoration found, or null when the field carries none.
318
+ */
319
+ export declare function findTopLevelDecoration(cmd: string): string | null;
320
+ /**
321
+ * Run the four predicates over one recorded row and return the first
322
+ * violation, or null when the row is well formed. (a)/(b) need `sh`; when the
323
+ * shell cannot be spawned they are left unjudged (the string-only (c) and (d)
324
+ * still run), so a missing instrument cannot fail every row.
325
+ */
326
+ export declare function findGateRowViolation(cmd: string, exit: number, outcome: WorkerOutcome): GateRowViolation | null;
327
+ /** Where close-gate refusals land: one JSONL line per failing row. */
328
+ export declare function closeGateRefusalLogPath(): string;
329
+ export interface CloseGateRefusalRecord {
330
+ at: string;
331
+ workerId: string;
332
+ /** Zero-based index into the close's gate evidence rows. */
333
+ row: number;
334
+ predicate: GateRowPredicate;
335
+ cmd: string;
336
+ mode: CloseGateWellFormednessMode;
337
+ outcome: WorkerOutcome;
338
+ detail: string;
339
+ }
340
+ /**
341
+ * Append one refusal line. Never throws: a failed append warns once and
342
+ * leaves the close's own behavior untouched, so an unwritable braid root
343
+ * cannot refuse a close that shadow mode would have accepted.
344
+ */
345
+ export declare function logCloseGateRefusal(record: CloseGateRefusalRecord): void;
346
+ /** One named pattern in the production-write table, as the seat publishes it. */
347
+ export interface ProductionWriteRule {
348
+ id: string;
349
+ label: string;
350
+ pattern: string;
351
+ /** Seat-side metadata (its guard prints this default); unread here. */
352
+ registry?: string;
353
+ }
354
+ /** The seat-owned table: what is a write, and what a preflight records. */
355
+ export interface ProductionWriteClass {
356
+ members: ProductionWriteRule[];
357
+ pieces: ProductionWriteRule[];
358
+ }
359
+ /** One write row and what the close recorded for it. */
360
+ export interface ProductionWriteRowRead {
361
+ row: number;
362
+ cmd: string;
363
+ member: string;
364
+ /** Indices of the rows carrying at least one preflight piece. */
365
+ preflightRows: number[];
366
+ /** Piece ids no row in the close carries. */
367
+ missingPieces: string[];
368
+ }
369
+ export interface ProductionWriteRead {
370
+ rows: ProductionWriteRowRead[];
371
+ /** The write rows still missing at least one piece; the first one refuses. */
372
+ unsatisfied: ProductionWriteRowRead[];
373
+ }
374
+ /** Where the seat publishes the production-write class it owns. */
375
+ export declare function productionWriteClassPath(): string;
376
+ /**
377
+ * Load the class table the seat owns. Never throws: a braid home that cannot be
378
+ * resolved, a missing file, an unreadable file and a malformed one all yield an
379
+ * empty class, which refuses nothing.
380
+ */
381
+ export declare function readProductionWriteClass(file?: string): ProductionWriteClass;
382
+ /**
383
+ * Read a close's gate rows for production writes and their preflight evidence.
384
+ * A row is a write when any member pattern matches its cmd — a field carrying a
385
+ * write beside reads is still a write, because the members match the write
386
+ * verbs only. A piece is recorded when any row's cmd matches its pattern, so
387
+ * one composed preflight row and several separate ones both satisfy. Pure over
388
+ * the rows and the table.
389
+ */
390
+ export declare function readProductionWrites(rows: Array<{
391
+ cmd: string;
392
+ exit: number;
393
+ stamp?: string;
394
+ }> | undefined, table?: ProductionWriteClass): ProductionWriteRead;
395
+ /**
396
+ * The refusal sentence for the first write row missing a piece: its index, the
397
+ * member, the missing piece ids and the command. Null when every write row is
398
+ * satisfied, so a caller cannot refuse on an empty read.
399
+ */
400
+ export declare function productionWriteRefusalDetail(read: ProductionWriteRead): string | null;
401
+ export interface PopulationStamp {
402
+ /** Population size the gate recorded. */
403
+ n: number;
404
+ /** The population's unit, one lowercase word. */
405
+ unit: string;
406
+ /** Commit sha or ref name the gate read. */
407
+ revision: string;
408
+ }
409
+ /** Parse the stamp shape above; null when the value is not that shape. */
410
+ export declare function parsePopulationStamp(value: unknown): PopulationStamp | null;
411
+ /** What one gate row's stamp read decided. */
412
+ export type PopulationVerdict = "absent" | "unreadable" | "other-subject" | "unresolved" | "match" | "below" | "above";
413
+ export interface PopulationRowRead {
414
+ /** Zero-based index into the close's gate rows. */
415
+ row: number;
416
+ /** The row's command, as recorded (empty when the row carries none). */
417
+ cmd: string;
418
+ /** The raw stamp value, as recorded; undefined when the field is absent. */
419
+ raw: unknown;
420
+ /** True when the row carries a stamp field at all (even an unreadable one). */
421
+ present: boolean;
422
+ /** The parsed stamp, or null when absent or unreadable. */
423
+ stamp: PopulationStamp | null;
424
+ /** The census at the stamp's revision, or null when not compared. */
425
+ census: number | null;
426
+ /** `census - recorded`, or null when there is no comparison. */
427
+ delta: number | null;
428
+ verdict: PopulationVerdict;
429
+ }
430
+ export interface PopulationRead {
431
+ rows: PopulationRowRead[];
432
+ /** Rows whose unit is `files` and whose revision resolved (the comparisons). */
433
+ comparisons: PopulationRowRead[];
434
+ /** The first comparison recorded below its census; null when none stands. */
435
+ standing: PopulationRowRead | null;
436
+ /** True when any row carries a parseable `files` stamp. */
437
+ recorded: boolean;
438
+ /** The report lines, one per readable row, in row order. */
439
+ lines: string[];
440
+ }
441
+ /** The census lookup the caller supplies: revision to tree size, or null. */
442
+ export type PopulationCensus = (revision: string) => number | null;
443
+ /**
444
+ * Read every gate row for a population stamp and compare the `files` ones
445
+ * against the census the caller supplies for their named revision. Pure: the
446
+ * count is a lookup parameter, so the parse and the comparison are testable
447
+ * without a repository. Rows of another unit are not census subjects and are
448
+ * left uncompared; an unreadable stamp is named, never silently dropped.
449
+ */
450
+ export declare function readPopulationStamps(gates: unknown, censusAt: PopulationCensus): PopulationRead;
451
+ /**
452
+ * The refusal sentence for the first standing delta: row index, stamp, census,
453
+ * delta, and the remedy. Null when no comparison sits below its census, so a
454
+ * caller cannot refuse on an empty read.
455
+ */
456
+ export declare function populationRefusalDetail(read: PopulationRead): string | null;
292
457
  /**
293
458
  * Close an entry with a terminal outcome and optional gate evidence.
294
459
  * Already-closed entries are left untouched (first close wins); the checks
@@ -298,8 +463,24 @@ export declare function recordWorkerMerge(workerId: string, info: {
298
463
  * A completed close carries evidence: the reporter contract requires a
299
464
  * non-empty `gate_evidence` block, and a probe measured this path storing a
300
465
  * bare `completed` with no gates at all. That contradiction is refused now,
301
- * and each provided gate is shape-checked (non-empty `cmd`, numeric `exit`)
302
- * before any write — a violation leaves the row and the lock table untouched.
466
+ * and each provided gate is shape-checked (non-empty `cmd`, numeric `exit`,
467
+ * string `stamp` when present) before any write — a violation leaves the row
468
+ * and the lock table untouched. A valid `stamp` is stored verbatim, so the
469
+ * merge path can read the recorded population off the row.
470
+ *
471
+ * Every provided row is then read for well-formedness: its `cmd` must parse
472
+ * under `sh -n`, resolve its first token, and name the command alone, and a
473
+ * completed close's exits must be 0. The mode is settings-driven
474
+ * (`braid.orchestrator.closeGateWellFormedness`): "shadow" (default) records
475
+ * a refusal line and proceeds, "enforce" refuses before any write or lock
476
+ * release, "off" skips the read. No gate is re-run; replay stays the
477
+ * sampler's sampled job.
478
+ *
479
+ * Every row is also read against the seat's production-write class: a row the
480
+ * class marks as a write is refused unless the close records every named
481
+ * preflight piece (identity, registry, dry-run) somewhere in its rows. The
482
+ * class lives in the seat's data file; when it is absent the class is empty and
483
+ * nothing is refused.
303
484
  *
304
485
  * Releases the worker's file locks: close is terminal, and a lock that
305
486
  * survives it blocks the next spawn on the same files. The release runs with
@@ -309,6 +490,7 @@ export declare function recordWorkerMerge(workerId: string, info: {
309
490
  export declare function closeWorker(workerId: string, outcome: WorkerOutcome, gates?: Array<{
310
491
  cmd: string;
311
492
  exit: number;
493
+ stamp?: string;
312
494
  }>, cwd?: string): WorkerEntry | null;
313
495
  /** A located result block plus where it sat in the assistant-message tail. */
314
496
  export interface ResultSchemaLocation {