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.
- package/CONTRIBUTING.md +27 -3
- package/README.md +13 -13
- package/TOOLS.md +27 -3
- package/build-info.json +9 -0
- package/dist/extensions/cognitive/metacognition/handlers/claim-verification.js +7 -1
- package/dist/extensions/cognitive/metacognition/handlers/finalize.js +20 -0
- package/dist/extensions/cognitive/metacognition/handlers/hypothesize.d.ts +9 -0
- package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +13 -1
- package/dist/extensions/cognitive/metacognition/handlers/verify.js +35 -4
- package/dist/extensions/cognitive/topic-drift/index.js +19 -2
- package/dist/extensions/core/prompt-builder/inspect.js +9 -3
- package/dist/extensions/core/prompt-builder/top-level-extensions.d.ts +6 -5
- package/dist/extensions/core/prompt-builder/top-level-extensions.js +64 -29
- package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +1 -1
- package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +1 -1
- package/dist/extensions/enforcement/handlers/turn-end-handler.js +1 -1
- package/dist/extensions/enforcement/self-state-claims.d.ts +1 -1
- package/dist/extensions/enforcement/self-state-claims.js +3 -2
- package/dist/extensions/manifest.js +2 -2
- package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +22 -5
- package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +43 -11
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +174 -50
- package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.js +7 -1
- package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +4 -1
- package/dist/extensions/memory/memory-agent-bridge/explore-paths.d.ts +2 -24
- package/dist/extensions/memory/memory-agent-bridge/explore-paths.js +33 -2
- package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +16 -0
- package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +21 -9
- package/dist/extensions/memory/scratchpad/format.js +8 -2
- package/dist/extensions/memory/scratchpad/index.js +11 -2
- package/dist/extensions/memory/session-recall/index.js +19 -6
- package/dist/extensions/memory/three-memory-stores/episodes.d.ts +1 -1
- package/dist/extensions/memory/three-memory-stores/episodes.js +2 -2
- package/dist/extensions/orchestrator/index.js +73 -8
- package/dist/extensions/scheduling/timer/index.js +9 -1
- package/dist/extensions/self/error-tracking/index.js +8 -1
- package/dist/extensions/self/health-maintenance/handlers/session-health-tool.js +9 -2
- package/dist/extensions/self/health-maintenance/index.js +112 -9
- package/dist/lib/config/braid-settings.d.ts +21 -0
- package/dist/lib/config/braid-settings.js +36 -0
- package/dist/lib/constants/session-thresholds.d.ts +2 -3
- package/dist/lib/constants/session-thresholds.js +2 -3
- package/dist/lib/enforcement/turn-dedup.d.ts +2 -2
- package/dist/lib/enforcement/turn-dedup.js +2 -2
- package/dist/lib/harness/index.d.ts +1 -1
- package/dist/lib/harness/index.js +1 -1
- package/dist/lib/harness/types.d.ts +1 -1
- package/dist/lib/harness/types.js +1 -1
- package/dist/lib/orchestrator/index.d.ts +2 -2
- package/dist/lib/orchestrator/index.js +1 -1
- package/dist/lib/orchestrator/workers.d.ts +184 -2
- package/dist/lib/orchestrator/workers.js +521 -6
- package/dist/lib/utils/injection-tracker.js +1 -1
- package/docs/CONTEXT-POLICY.md +13 -5
- package/docs/LOCAL_DEV.md +31 -5
- package/docs/ROADMAP.md +10 -7
- package/docs/SETUP.md +3 -2
- package/package.json +11 -8
- package/skills/braid-reference/SKILL.md +23 -23
- package/skills/release-pipeline/SKILL.md +46 -37
- package/skills/subagent-orchestration/SKILL.md +51 -1
- package/src/extensions/cognitive/metacognition/handlers/claim-verification.ts +8 -1
- package/src/extensions/cognitive/metacognition/handlers/finalize.ts +21 -0
- package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +14 -1
- package/src/extensions/cognitive/metacognition/handlers/verify.ts +39 -5
- package/src/extensions/cognitive/topic-drift/index.ts +20 -2
- package/src/extensions/core/prompt-builder/AGENTS.md +1 -1
- package/src/extensions/core/prompt-builder/inspect.ts +10 -3
- package/src/extensions/core/prompt-builder/top-level-extensions.ts +68 -29
- package/src/extensions/enforcement/AGENTS.md +25 -19
- package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +1 -1
- package/src/extensions/enforcement/handlers/turn-end-handler.ts +1 -1
- package/src/extensions/enforcement/self-state-claims.ts +3 -2
- package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +6 -3
- package/src/extensions/manifest.ts +2 -2
- package/src/extensions/memory/AGENTS.md +13 -5
- package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +45 -11
- package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +202 -60
- package/src/extensions/memory/context-manager/handlers/tools/context-inspect.ts +8 -1
- package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +4 -1
- package/src/extensions/memory/memory-agent-bridge/explore-paths.ts +37 -3
- package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +16 -0
- package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +22 -9
- package/src/extensions/memory/scratchpad/format.ts +8 -2
- package/src/extensions/memory/scratchpad/index.ts +12 -2
- package/src/extensions/memory/session-recall/index.ts +20 -8
- package/src/extensions/memory/three-memory-stores/episodes.ts +2 -2
- package/src/extensions/orchestrator/index.ts +100 -11
- package/src/extensions/scheduling/timer/AGENTS.md +7 -0
- package/src/extensions/scheduling/timer/index.ts +10 -1
- package/src/extensions/self/error-tracking/index.ts +9 -1
- package/src/extensions/self/health-maintenance/handlers/session-health-tool.ts +10 -2
- package/src/extensions/self/health-maintenance/index.ts +143 -14
- package/src/extensions/self/watchdog/AGENTS.md +1 -0
- package/src/lib/AGENTS.md +21 -21
- package/src/lib/config/braid-settings.ts +74 -0
- package/src/lib/constants/session-thresholds.ts +2 -3
- package/src/lib/enforcement/turn-dedup.ts +2 -2
- package/src/lib/harness/AGENTS.md +1 -1
- package/src/lib/harness/index.ts +1 -1
- package/src/lib/harness/types.ts +1 -1
- package/src/lib/orchestrator/index.ts +26 -0
- package/src/lib/orchestrator/workers.ts +705 -7
- package/src/lib/utils/AGENTS.md +1 -1
- package/src/lib/utils/injection-tracker.ts +1 -1
|
@@ -48,6 +48,16 @@ interface ScratchpadCache {
|
|
|
48
48
|
pad: TaskScratchpad | null;
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/**
|
|
52
|
+
* A blank string is "not provided". A client that emits every schema key sends
|
|
53
|
+
* "" for the keys it does not use, and `??` alone keeps that "" as a real value
|
|
54
|
+
* (a blank id would then be looked up literally instead of falling back to the
|
|
55
|
+
* text). Whitespace-only counts as blank: the handlers refuse such text anyway.
|
|
56
|
+
*/
|
|
57
|
+
function nonBlank(value: unknown): string | undefined {
|
|
58
|
+
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
51
61
|
function getCache(ctx?: ExtensionContext): ScratchpadCache {
|
|
52
62
|
if (!ctx) return { pad: null };
|
|
53
63
|
return getExtensionState(ctx, "scratchpad-cache", () => ({ pad: null }));
|
|
@@ -169,8 +179,8 @@ async function scratchpadExecute(
|
|
|
169
179
|
ctx: ExtensionContext,
|
|
170
180
|
): Promise<AgentToolResult<unknown>> {
|
|
171
181
|
const action = params.action as string;
|
|
172
|
-
const text = (params.text
|
|
173
|
-
const idOrText = (params.id
|
|
182
|
+
const text = nonBlank(params.text) ?? "";
|
|
183
|
+
const idOrText = nonBlank(params.id) ?? text;
|
|
174
184
|
|
|
175
185
|
const pad = await getOrCreateScratchpad(ctx);
|
|
176
186
|
|
|
@@ -124,11 +124,22 @@ const sessionSchema = Type.Object({
|
|
|
124
124
|
until: Type.Optional(
|
|
125
125
|
Type.String({ description: "Only include sessions until this date (YYYY-MM-DD). Optional." }),
|
|
126
126
|
),
|
|
127
|
-
limit: Type.Optional(
|
|
128
|
-
Type.Number({ description: "Max sessions in output (default: 10). Use 0 for all." }),
|
|
129
|
-
),
|
|
127
|
+
limit: Type.Optional(Type.Number({ description: "Max sessions in output (default: 10)" })),
|
|
130
128
|
});
|
|
131
129
|
|
|
130
|
+
/**
|
|
131
|
+
* Read an optional session limit. Argument validation converts a blank string
|
|
132
|
+
* to 0 for `Type.Optional(Type.Number())` and the converted value passes, so
|
|
133
|
+
* the handler cannot tell a blank from a typed 0. 0 used to select the
|
|
134
|
+
* documented "all sessions" mode, which a blank then triggered silently; a
|
|
135
|
+
* deliberate 0 is indistinguishable from a blank after conversion, so the
|
|
136
|
+
* documented default is the safe reading and the unbounded mode is no longer
|
|
137
|
+
* reachable through this selector.
|
|
138
|
+
*/
|
|
139
|
+
function positiveLimit(value: unknown): number | undefined {
|
|
140
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
132
143
|
// Extension
|
|
133
144
|
|
|
134
145
|
export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
@@ -478,9 +489,10 @@ export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
|
478
489
|
// Total matches
|
|
479
490
|
const totalMatches = filtered.reduce((sum, m) => sum + m.count, 0);
|
|
480
491
|
|
|
481
|
-
// Top N sessions
|
|
482
|
-
|
|
483
|
-
const
|
|
492
|
+
// Top N sessions. A blank limit is read as absent (see positiveLimit),
|
|
493
|
+
// never as the old unbounded mode.
|
|
494
|
+
const limit = positiveLimit(params.limit) ?? 10;
|
|
495
|
+
const topSessions = filtered.slice(0, limit);
|
|
484
496
|
|
|
485
497
|
const lines: string[] = [
|
|
486
498
|
`## Batch: "${params.pattern}"`,
|
|
@@ -720,7 +732,7 @@ export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
|
720
732
|
since: params.since,
|
|
721
733
|
until: params.until,
|
|
722
734
|
project: params.project === "all" ? null : (params.project ?? null),
|
|
723
|
-
maxFiles: params.limit
|
|
735
|
+
maxFiles: positiveLimit(params.limit),
|
|
724
736
|
});
|
|
725
737
|
return {
|
|
726
738
|
content: [{ type: "text" as const, text: formatContextAggregate(aggregate) }],
|
|
@@ -793,7 +805,7 @@ export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
|
793
805
|
byMonth[month].size += s.size;
|
|
794
806
|
}
|
|
795
807
|
|
|
796
|
-
const limit = params.limit ?? 10;
|
|
808
|
+
const limit = positiveLimit(params.limit) ?? 10;
|
|
797
809
|
const topSessions = [...sessionStats].sort((a, b) => b.size - a.size).slice(0, limit);
|
|
798
810
|
|
|
799
811
|
function formatSize(bytes: number): string {
|
|
@@ -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
|
|
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
|
|
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(
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
@@ -63,6 +63,11 @@ import {
|
|
|
63
63
|
import { formatLocalTime } from "../../../lib/utils/local-time.js";
|
|
64
64
|
import { describeFireTiming } from "./fire-timing.js";
|
|
65
65
|
|
|
66
|
+
/** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
|
|
67
|
+
function optionalString(v: unknown): string | undefined {
|
|
68
|
+
return typeof v === "string" && v.trim().length > 0 ? v : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
66
71
|
type PersistedTimer = {
|
|
67
72
|
id: string;
|
|
68
73
|
sessionId: string;
|
|
@@ -880,7 +885,11 @@ function createTimerTool(sessionState: {
|
|
|
880
885
|
}
|
|
881
886
|
switch (params?.action) {
|
|
882
887
|
case "set": {
|
|
883
|
-
const { delay_seconds, reason,
|
|
888
|
+
const { delay_seconds, reason, interval_seconds, count, wake } = params;
|
|
889
|
+
// A blank tag is no tag: stored as "" it reads as [] in the list
|
|
890
|
+
// rendering instead of (untagged), and cancelTimersByTag("") would
|
|
891
|
+
// match every blank-tagged timer in the session.
|
|
892
|
+
const tag = optionalString(params.tag);
|
|
884
893
|
if (tag && !/^[a-zA-Z0-9_-]+$/.test(tag)) {
|
|
885
894
|
throw new Error(`Invalid tag "${tag}" - use alphanumeric + dash/underscore`);
|
|
886
895
|
}
|
|
@@ -100,6 +100,11 @@ async function captureError(
|
|
|
100
100
|
return entry;
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/** A numeric selector read as absent when it names no positive count. */
|
|
104
|
+
function positiveNumber(v: unknown): number | undefined {
|
|
105
|
+
return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
|
|
106
|
+
}
|
|
107
|
+
|
|
103
108
|
const errorSchema = Type.Object({
|
|
104
109
|
action: Type.Union(
|
|
105
110
|
[Type.Literal("list"), Type.Literal("get"), Type.Literal("clear"), Type.Literal("stats")],
|
|
@@ -161,7 +166,10 @@ export default function errorCaptureExtension(pi: ExtensionAPI): void {
|
|
|
161
166
|
switch (params.action) {
|
|
162
167
|
case "list": {
|
|
163
168
|
const entries = await loadErrors();
|
|
164
|
-
|
|
169
|
+
// The framework converts "" to 0 before the handler (no `minimum`
|
|
170
|
+
// on the schema), and slice(-0) is slice(0): a blank limit returned
|
|
171
|
+
// every captured error, the opposite of the documented cap.
|
|
172
|
+
const limit = positiveNumber(params.limit) ?? 10;
|
|
165
173
|
const source = params.source;
|
|
166
174
|
const unhandledOnly = params.unhandledOnly ?? false;
|
|
167
175
|
|
|
@@ -28,6 +28,11 @@ import {
|
|
|
28
28
|
type SessionHealthState,
|
|
29
29
|
} from "../../../enforcement/session-health.js";
|
|
30
30
|
|
|
31
|
+
/** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
|
|
32
|
+
function optionalString(v: unknown): string | undefined {
|
|
33
|
+
return typeof v === "string" && v.trim().length > 0 ? v : undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
31
36
|
const sessionHealthSchema = Type.Object({
|
|
32
37
|
action: Type.Union([Type.Literal("get"), Type.Literal("diagnose"), Type.Literal("recover")], {
|
|
33
38
|
description: "Action: get, diagnose (with history), or recover (force reset)",
|
|
@@ -143,7 +148,10 @@ export function registerSessionHealthTool(pi: ExtensionAPI): void {
|
|
|
143
148
|
details,
|
|
144
149
|
};
|
|
145
150
|
}
|
|
146
|
-
|
|
151
|
+
// A blank reason is no reason: stored (and echoed) as "" it reads as
|
|
152
|
+
// an audit note the operator never wrote.
|
|
153
|
+
const reason = optionalString(params.reason);
|
|
154
|
+
setSessionHealthMode(ctx, "healthy", reason);
|
|
147
155
|
const after = getSessionHealth(ctx);
|
|
148
156
|
const details: SessionHealthToolDetails = {
|
|
149
157
|
mode: after.mode,
|
|
@@ -155,7 +163,7 @@ export function registerSessionHealthTool(pi: ExtensionAPI): void {
|
|
|
155
163
|
content: [
|
|
156
164
|
{
|
|
157
165
|
type: "text" as const,
|
|
158
|
-
text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${
|
|
166
|
+
text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${reason ? `\n\nReason: ${reason}` : ""}`,
|
|
159
167
|
},
|
|
160
168
|
],
|
|
161
169
|
details,
|
|
@@ -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({
|
|
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({
|
|
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({
|
|
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(
|
|
64
|
-
|
|
65
|
-
|
|
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?:
|
|
274
|
-
if (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?:
|
|
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.
|