pi-braid 0.40.3 → 0.40.6
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/AGENTS.md +17 -18
- package/README.md +116 -130
- package/TOOLS.md +35 -35
- package/build-info.json +4 -4
- package/dist/extensions/core/agent-environment/index.js +4 -3
- package/dist/extensions/core/prompt-builder/index.js +12 -7
- package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
- package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
- package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
- package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
- package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
- package/dist/extensions/core/skills-tool/auto-inject.d.ts +178 -17
- package/dist/extensions/core/skills-tool/auto-inject.js +264 -23
- package/dist/extensions/core/skills-tool/index.d.ts +70 -2
- package/dist/extensions/core/skills-tool/index.js +149 -15
- package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
- package/dist/extensions/core/skills-tool/reach.js +213 -0
- package/dist/extensions/core/skills-tool/skill-triggers.d.ts +74 -13
- package/dist/extensions/core/skills-tool/skill-triggers.js +105 -24
- package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
- package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
- package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
- package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
- package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
- package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
- package/dist/extensions/enforcement/resume-state.d.ts +76 -0
- package/dist/extensions/enforcement/resume-state.js +90 -0
- package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
- package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
- package/dist/extensions/enforcement/whisper.d.ts +12 -0
- package/dist/extensions/enforcement/whisper.js +16 -1
- package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
- package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
- package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
- package/dist/lib/config/braid-paths.d.ts +14 -0
- package/dist/lib/config/braid-paths.js +18 -0
- package/dist/lib/config/braid-settings.d.ts +21 -0
- package/dist/lib/config/braid-settings.js +16 -0
- package/dist/lib/detection/context-tiers.d.ts +47 -3
- package/dist/lib/detection/context-tiers.js +122 -13
- package/dist/lib/events/turn-boundary.d.ts +78 -0
- package/dist/lib/events/turn-boundary.js +91 -0
- package/dist/lib/orchestrator/workers.d.ts +3 -2
- package/dist/lib/orchestrator/workers.js +22 -4
- package/dist/lib/state/global-state.d.ts +1 -1
- package/docs/CONTEXT-POLICY.md +8 -0
- package/docs/LOCAL_DEV.md +0 -1
- package/docs/ROADMAP.md +5 -5
- package/docs/SETUP.md +19 -18
- package/package.json +2 -1
- package/skills/herdr-topology/SKILL.md +6 -1
- package/skills/research/SKILL.md +32 -0
- package/skills/subagent-orchestration/SKILL.md +2 -2
- package/src/extensions/core/agent-environment/index.ts +4 -3
- package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
- package/src/extensions/core/prompt-builder/index.ts +12 -7
- package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
- package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
- package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
- package/src/extensions/core/skills-tool/auto-inject.ts +350 -27
- package/src/extensions/core/skills-tool/index.ts +217 -15
- package/src/extensions/core/skills-tool/reach.ts +256 -0
- package/src/extensions/core/skills-tool/skill-triggers.ts +130 -23
- package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
- package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
- package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
- package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
- package/src/extensions/enforcement/resume-state.ts +127 -0
- package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
- package/src/extensions/enforcement/whisper.ts +21 -1
- package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
- package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
- package/src/extensions/memory/AGENTS.md +25 -1
- package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
- package/src/lib/config/braid-paths.ts +20 -0
- package/src/lib/config/braid-settings.ts +46 -0
- package/src/lib/detection/context-tiers.ts +186 -13
- package/src/lib/events/AGENTS.md +1 -0
- package/src/lib/events/turn-boundary.ts +115 -0
- package/src/lib/orchestrator/workers.ts +33 -12
- package/src/lib/state/global-state.ts +1 -0
- package/src/lib/utils/AGENTS.md +1 -1
- package/src/types/extension-context.d.ts +22 -79
|
@@ -8,12 +8,15 @@
|
|
|
8
8
|
* scratchpad + write resume.json) to guarantee zero data loss.
|
|
9
9
|
*
|
|
10
10
|
* Safety gates, checked in order:
|
|
11
|
-
* - Loop-done gate: the act
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* runaway loop before
|
|
11
|
+
* - Loop-done gate: the act aborts the run through ctx.compact(), so it only
|
|
12
|
+
* fires at a boundary the shared rule accepts
|
|
13
|
+
* (lib/events/turn-boundary.ts, the same rule the context_compress drain
|
|
14
|
+
* reads). That rule fires on a loop-done stop reason and parks on a live
|
|
15
|
+
* loop ("toolUse") or on a boundary it cannot read. The only exception is
|
|
16
|
+
* the 0.90W backstop, which deliberately stops a runaway loop before
|
|
17
|
+
* overflow. The rule's residual section names the cases a loop-done stop
|
|
18
|
+
* reason does not rule out: a tool call riding a non-"toolUse" stop
|
|
19
|
+
* reason, and a steer queued at any boundary.
|
|
17
20
|
* - Mode awareness: the DETERMINISTIC slide path carries none of the
|
|
18
21
|
* abort/corruption risk that justifies standing down, so it fires at
|
|
19
22
|
* the act arm regardless of pi's compaction.enabled. Only the LLM
|
|
@@ -21,42 +24,48 @@
|
|
|
21
24
|
* per act decision from the merged settings), native compaction owns
|
|
22
25
|
* LLM compaction and the act stands down to nudge-only.
|
|
23
26
|
*
|
|
24
|
-
* ctx.compact()
|
|
25
|
-
* (agent-session
|
|
26
|
-
* abort path, the compact call is
|
|
27
|
-
*
|
|
27
|
+
* ctx.compact() aborts the current agent operation first and never retries or
|
|
28
|
+
* continues the interrupted turn (pi-core's agent-session compact()). To keep
|
|
29
|
+
* the handler's synchronous part off the abort path, the compact call is
|
|
30
|
+
* deferred via setTimeout(0). Resume after the compaction is
|
|
31
|
+
* register-session-compact's decision, not ours.
|
|
28
32
|
*
|
|
29
33
|
* Discoverability (scratchpad/memory/episodes surfacing) fires from
|
|
30
34
|
* SESSION_START (register-session-start-discoverability.ts), before the
|
|
31
35
|
* first turn.
|
|
32
36
|
*/
|
|
33
37
|
import { SettingsManager, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
34
|
-
import { existsSync, mkdirSync, writeFileSync
|
|
38
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
35
39
|
import * as path from "node:path";
|
|
36
40
|
import { execSync } from "node:child_process";
|
|
37
41
|
import { createLogger } from "../../../lib/core/logger.js";
|
|
38
42
|
import { registerTurnEndHandler } from "../../../lib/events/turn-end-coordinator.js";
|
|
43
|
+
import { turnBoundaryMayAbortRun } from "../../../lib/events/turn-boundary.js";
|
|
39
44
|
import { sendEnforcementWhisper } from "../whisper.js";
|
|
40
45
|
import { getState } from "../state.js";
|
|
41
46
|
import { fileMutationQueue } from "../../../lib/utils/file-mutation-queue.js";
|
|
42
|
-
import { braidDir
|
|
47
|
+
import { braidDir } from "../../../lib/config/braid-paths.js";
|
|
43
48
|
import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
|
|
44
49
|
import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
|
|
50
|
+
import { readResumeScratchpadState } from "../resume-state.js";
|
|
45
51
|
import { isCompactionActive, getCmState } from "../../memory/context-manager/handlers/shared.js";
|
|
46
52
|
import { snapBoundaryOutsideToolBatch } from "../../memory/context-manager/handlers/tool-batch-boundary.js";
|
|
47
|
-
import { USAGE_COMPACT_AGGRESSIVE,
|
|
48
|
-
import {
|
|
53
|
+
import { USAGE_COMPACT_AGGRESSIVE, HYGIENE_AUTO_COMPACT_MIN_TURNS, } from "../../../lib/detection/context-thresholds.js";
|
|
54
|
+
import { resolveContextNudge, findContextNudgeRung, contextNudgeFellBelow, contextNudgeCrossed, } from "../../../lib/detection/context-tiers.js";
|
|
49
55
|
import { measureLiveUsage, tokenArms, formatTokensK, } from "../../../lib/detection/context-usage.js";
|
|
50
56
|
import { recordCompaction, recordHygieneAct, recordHygieneSkip, recordLiveUsageSample, } from "../substate/context-hygiene-state.js";
|
|
51
57
|
const log = createLogger("enforcement:turn-end-hygiene");
|
|
52
58
|
// Pre-save safety: flush scratchpad + write resume.json
|
|
53
|
-
function saveStateBeforeCompact(cwd, ctx) {
|
|
59
|
+
async function saveStateBeforeCompact(cwd, ctx) {
|
|
54
60
|
try {
|
|
55
61
|
// 1. Flush file mutation queue + scratchpad debounced queue
|
|
56
62
|
// Pre-compaction flush is best-effort: a failed flush loses only the
|
|
57
|
-
// newest queued writes; blocking compaction would lose far more.
|
|
63
|
+
// newest queued writes; blocking compaction would lose far more. The
|
|
64
|
+
// scratchpad flush is awaited because the resume read below reads the
|
|
65
|
+
// checkpoint log that flush appends to - unawaited, the pre-save could
|
|
66
|
+
// record the previous turn's pad, or none at all.
|
|
58
67
|
fileMutationQueue.flushAll().catch(() => { });
|
|
59
|
-
flushPendingScratchpadWrites().catch(() => { });
|
|
68
|
+
await flushPendingScratchpadWrites().catch(() => { });
|
|
60
69
|
}
|
|
61
70
|
catch {
|
|
62
71
|
// flush APIs themselves failed — compaction must still proceed
|
|
@@ -69,32 +78,15 @@ function saveStateBeforeCompact(cwd, ctx) {
|
|
|
69
78
|
// No reader consumes either key; the fields both writers carry are the
|
|
70
79
|
// ones the reader reads back.
|
|
71
80
|
const slug = projectSlugFromCwd(cwd);
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
//
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
|
|
82
|
-
if (existsSync(scratchpadFile)) {
|
|
83
|
-
const content = readFileSync(scratchpadFile, "utf-8");
|
|
84
|
-
const parsed = JSON.parse(content);
|
|
85
|
-
goal = parsed.goal ?? null;
|
|
86
|
-
openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
|
|
87
|
-
.filter((p) => !p.done)
|
|
88
|
-
.slice(0, 10)
|
|
89
|
-
.map((p) => ({ id: p.id ?? "", text: p.text ?? "" }));
|
|
90
|
-
recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
|
|
91
|
-
.slice(-5)
|
|
92
|
-
.map((d) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
catch (err) {
|
|
96
|
-
log.debug(`scratchpad prior-state read failed: ${err}`);
|
|
97
|
-
}
|
|
81
|
+
// Prior state is a READ through the scratchpad store's own loader (the
|
|
82
|
+
// checkpoint log, not a hand-built path), so a schema or storage change
|
|
83
|
+
// in the store moves this reader with it. A refused root (no absolute
|
|
84
|
+
// braid home) or a corrupt section degrades to an empty prior-state
|
|
85
|
+
// section instead of failing the resume write below.
|
|
86
|
+
const resumeState = await readResumeScratchpadState(slug);
|
|
87
|
+
const goal = resumeState.goal;
|
|
88
|
+
const openPlans = resumeState.openPlans;
|
|
89
|
+
const recentDecisions = resumeState.recentDecisions;
|
|
98
90
|
let uncommittedFiles = [];
|
|
99
91
|
try {
|
|
100
92
|
// Scope to the project dir only. When ctx.cwd is missing, `cwd` is "" and
|
|
@@ -165,7 +157,7 @@ function compactionEnabledPerCheck(ctx) {
|
|
|
165
157
|
return true;
|
|
166
158
|
}
|
|
167
159
|
}
|
|
168
|
-
function checkContextUsage(pi, ctx, event) {
|
|
160
|
+
async function checkContextUsage(pi, ctx, event) {
|
|
169
161
|
const state = getState(ctx);
|
|
170
162
|
if (!state?.enforcementActive)
|
|
171
163
|
return;
|
|
@@ -196,15 +188,19 @@ function checkContextUsage(pi, ctx, event) {
|
|
|
196
188
|
recordHygieneSkip(state);
|
|
197
189
|
return;
|
|
198
190
|
}
|
|
199
|
-
// The previous usable turn's live sample (the
|
|
200
|
-
//
|
|
191
|
+
// The previous usable turn's live sample (the crossing witness), captured
|
|
192
|
+
// before this turn's sample replaces it.
|
|
201
193
|
const prevLiveTokens = state.liveUsageSamples[state.liveUsageSamples.length - 1];
|
|
202
194
|
recordLiveUsageSample(state, usageTokens);
|
|
203
|
-
// Re-arm the shared context-nudge latch
|
|
204
|
-
//
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
|
|
195
|
+
// Re-arm the shared context-nudge latch in the unit that armed it: a token
|
|
196
|
+
// rung clears on a fall back below that token arm, a percent rung below its
|
|
197
|
+
// own percent. A bar in the other unit clears a token arm on the very next
|
|
198
|
+
// turn whenever the arm sits above the bar (0.45W is 45% of every window,
|
|
199
|
+
// below the 50% bar), which is the repeat loop this latch exists to stop.
|
|
200
|
+
// The rung id stays recorded: it is the floor a weaker rung must cross to be
|
|
201
|
+
// news rather than a descent.
|
|
202
|
+
if (state.contextNudgeSent &&
|
|
203
|
+
contextNudgeFellBelow(state.contextNudgeRung, usagePercent, usageTokens, usageWindow)) {
|
|
208
204
|
state.contextNudgeSent = false;
|
|
209
205
|
}
|
|
210
206
|
// Auto-compact arms (fractions of the resolved window W)
|
|
@@ -225,14 +221,16 @@ function checkContextUsage(pi, ctx, event) {
|
|
|
225
221
|
recordHygieneSkip(state);
|
|
226
222
|
return;
|
|
227
223
|
}
|
|
228
|
-
// Loop-done gate:
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
233
|
-
// overflow (its purpose).
|
|
234
|
-
|
|
235
|
-
|
|
224
|
+
// Loop-done gate: the act runs ctx.compact(), which aborts the running
|
|
225
|
+
// agent operation (manual compaction never retries or continues the
|
|
226
|
+
// interrupted turn), so the boundary decides it. One rule, shared with the
|
|
227
|
+
// context_compress drain: a loop-done stop fires, a live loop parks, an
|
|
228
|
+
// unreadable boundary parks, and the 0.90W backstop below still acts
|
|
229
|
+
// mid-loop to stop a runaway loop before overflow (its purpose).
|
|
230
|
+
if (!turnBoundaryMayAbortRun(event, () => ({
|
|
231
|
+
tokens: usageTokens,
|
|
232
|
+
contextWindow: usageWindow,
|
|
233
|
+
}))) {
|
|
236
234
|
recordHygieneSkip(state);
|
|
237
235
|
return;
|
|
238
236
|
}
|
|
@@ -256,8 +254,14 @@ function checkContextUsage(pi, ctx, event) {
|
|
|
256
254
|
? "token"
|
|
257
255
|
: "percent";
|
|
258
256
|
state.contextNudgeSent = true;
|
|
259
|
-
//
|
|
260
|
-
|
|
257
|
+
// The act is not a nudge rung: leave no rung recorded, so the nudge
|
|
258
|
+
// block stays suppressed behind the act (and the percent reset bar
|
|
259
|
+
// governs this latch) exactly as before.
|
|
260
|
+
state.contextNudgeRung = null;
|
|
261
|
+
// Pre-save safety net before compaction. Awaited: the act arms right
|
|
262
|
+
// after, and the write must land before the compaction it protects
|
|
263
|
+
// against. ctx.compact itself is deferred to a macrotask below.
|
|
264
|
+
await saveStateBeforeCompact(ctx.cwd ?? "", ctx);
|
|
261
265
|
const kind = armHygieneAct(ctx, trigger, plan);
|
|
262
266
|
if (!kind) {
|
|
263
267
|
// The deterministic state could not be armed: stand down instead of
|
|
@@ -273,29 +277,31 @@ function checkContextUsage(pi, ctx, event) {
|
|
|
273
277
|
return;
|
|
274
278
|
}
|
|
275
279
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
//
|
|
279
|
-
//
|
|
280
|
-
//
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
// USAGE_FIRED_RESET_BELOW, a bar above the soft arm, so without this
|
|
290
|
-
// gate the same whisper re-injected every turn from the soft arm up to
|
|
291
|
-
// the reset bar. The higher tiers keep the shared latch untouched.
|
|
292
|
-
if (usageTokens < arms.warning) {
|
|
293
|
-
const crossedSoftArm = prevLiveTokens === undefined || prevLiveTokens < arms.soft;
|
|
294
|
-
if (!crossedSoftArm)
|
|
280
|
+
// Progressive nudge: ONE ladder over both units, ordered by position
|
|
281
|
+
// (percent of the resolved window) — token soft 0.18W, percent soft 30%,
|
|
282
|
+
// token warning 0.45W, advisory 50%, warning 65%, critical 75%, compact
|
|
283
|
+
// 80%. The strongest rung reached wins, so no token arm can shadow a
|
|
284
|
+
// percent tier above it (see lib/detection/context-tiers.ts).
|
|
285
|
+
const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow);
|
|
286
|
+
if (nudge) {
|
|
287
|
+
const lastFired = findContextNudgeRung(state.contextNudgeRung, usageWindow);
|
|
288
|
+
if (state.contextNudgeSent) {
|
|
289
|
+
// The latch holds the rung that fired; a strictly stronger rung is new
|
|
290
|
+
// information and may pass it. Without this the ladder went quiet from
|
|
291
|
+
// the first rung upward and an agent at 95% read the 45% line.
|
|
292
|
+
if (!lastFired || nudge.position <= lastFired.position)
|
|
295
293
|
return;
|
|
296
294
|
}
|
|
295
|
+
else if (lastFired &&
|
|
296
|
+
nudge.position < lastFired.position &&
|
|
297
|
+
!contextNudgeCrossed(nudge, prevLiveTokens, usageWindow)) {
|
|
298
|
+
// A weaker rung that usage merely settled at (a descent, not a
|
|
299
|
+
// crossing) is not news; a rung climbed back past is.
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
297
302
|
state.contextNudgeSent = true;
|
|
298
|
-
|
|
303
|
+
state.contextNudgeRung = nudge.id;
|
|
304
|
+
sendEnforcementWhisper(pi, ctx, nudge.message);
|
|
299
305
|
}
|
|
300
306
|
}
|
|
301
307
|
/**
|
|
@@ -370,7 +376,7 @@ function armHygieneAct(ctx, trigger, plan) {
|
|
|
370
376
|
export function registerTurnEndHygiene(pi) {
|
|
371
377
|
registerTurnEndHandler("turn-end-hygiene", 5, async (event, ctx) => {
|
|
372
378
|
try {
|
|
373
|
-
checkContextUsage(pi, ctx, event);
|
|
379
|
+
await checkContextUsage(pi, ctx, event);
|
|
374
380
|
}
|
|
375
381
|
catch (err) {
|
|
376
382
|
log.error("turn-end-hygiene error:", err);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resume handoff state - the scratchpad program a fresh seat needs after a
|
|
3
|
+
* mastership transfer.
|
|
4
|
+
*
|
|
5
|
+
* The resume file (`<braidDir>/sessions/<slug>/resume.json`) is written by
|
|
6
|
+
* two handlers (the turn-end pre-save, the session shutdown writer) and read
|
|
7
|
+
* by a third (session-start discoverability). All three need the same
|
|
8
|
+
* projection of the scratchpad, so it lives here once.
|
|
9
|
+
*
|
|
10
|
+
* The scratchpad is an append-only checkpoint log (`events.jsonl`, last line
|
|
11
|
+
* wins), not a single JSON snapshot, so this reads through the store's own
|
|
12
|
+
* loader - `loadScratchpadFromDisk` - instead of re-deriving a path and a
|
|
13
|
+
* parse. The loader also runs the store's migrations, which is why a legacy
|
|
14
|
+
* `latest.json` still yields state here.
|
|
15
|
+
*
|
|
16
|
+
* The field names come from `TaskScratchpad`: `plan`, `decisions`,
|
|
17
|
+
* `key_learnings`. Reading `plans`/`learnings` off the persisted state
|
|
18
|
+
* silently yields nothing.
|
|
19
|
+
*/
|
|
20
|
+
import type { TaskScratchpad } from "../memory/scratchpad/types.js";
|
|
21
|
+
/**
|
|
22
|
+
* How many entries of each list the resume file carries. Sized for a
|
|
23
|
+
* transfer, not an audit: the first open plan steps are the program a
|
|
24
|
+
* successor continues (later steps are usually its to rewrite), and five
|
|
25
|
+
* decisions/learnings cover the recent working assumptions. The uncapped
|
|
26
|
+
* counts travel alongside so a reader can report "20 open, 10 shown".
|
|
27
|
+
*/
|
|
28
|
+
export declare const RESUME_OPEN_PLAN_LIMIT = 10;
|
|
29
|
+
export declare const RESUME_RECENT_DECISION_LIMIT = 5;
|
|
30
|
+
export declare const RESUME_RECENT_LEARNING_LIMIT = 5;
|
|
31
|
+
/** A plan step is live once it has been started (see `add_plan`/`mark_done`). */
|
|
32
|
+
export type ResumePlanStatus = "in_progress" | "pending";
|
|
33
|
+
export interface ResumePlanItem {
|
|
34
|
+
id: string;
|
|
35
|
+
text: string;
|
|
36
|
+
status: ResumePlanStatus;
|
|
37
|
+
}
|
|
38
|
+
export interface ResumeDecisionItem {
|
|
39
|
+
id: string;
|
|
40
|
+
text: string;
|
|
41
|
+
reason?: string;
|
|
42
|
+
}
|
|
43
|
+
export interface ResumeLearningItem {
|
|
44
|
+
category: string;
|
|
45
|
+
content: string;
|
|
46
|
+
}
|
|
47
|
+
export interface ResumeScratchpadState {
|
|
48
|
+
goal: string | null;
|
|
49
|
+
/** First RESUME_OPEN_PLAN_LIMIT unfinished steps, in plan order. */
|
|
50
|
+
openPlans: ResumePlanItem[];
|
|
51
|
+
/** Unfinished steps overall, before the display cap. */
|
|
52
|
+
openPlanCount: number;
|
|
53
|
+
recentDecisions: ResumeDecisionItem[];
|
|
54
|
+
recentLearnings: ResumeLearningItem[];
|
|
55
|
+
}
|
|
56
|
+
/** The projection of "no scratchpad": every section empty, never undefined. */
|
|
57
|
+
export declare function emptyResumeScratchpadState(): ResumeScratchpadState;
|
|
58
|
+
/**
|
|
59
|
+
* Project a loaded scratchpad onto the resume fields. Pure: the input pad is
|
|
60
|
+
* never mutated.
|
|
61
|
+
*
|
|
62
|
+
* Plan completion lives in `doneTurn` (mark_done stamps the turn and leaves
|
|
63
|
+
* the step in `plan`), so "open" is `doneTurn === 0` - the step is still in
|
|
64
|
+
* the plan, unfinished. A started-but-unfinished step is the live one.
|
|
65
|
+
*/
|
|
66
|
+
export declare function projectResumeScratchpad(pad: TaskScratchpad | null): ResumeScratchpadState;
|
|
67
|
+
/**
|
|
68
|
+
* Read this project's scratchpad and project it onto the resume fields.
|
|
69
|
+
*
|
|
70
|
+
* Degrades to the empty projection on any read failure: a resume file with no
|
|
71
|
+
* prior-state section is worth less than a program, but far more than a
|
|
72
|
+
* handler that threw during shutdown or before a compaction. The refusal is
|
|
73
|
+
* logged at debug - the empty projection is the visible outcome.
|
|
74
|
+
*/
|
|
75
|
+
export declare function readResumeScratchpadState(projectSlug: string): Promise<ResumeScratchpadState>;
|
|
76
|
+
//# sourceMappingURL=resume-state.d.ts.map
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resume handoff state - the scratchpad program a fresh seat needs after a
|
|
3
|
+
* mastership transfer.
|
|
4
|
+
*
|
|
5
|
+
* The resume file (`<braidDir>/sessions/<slug>/resume.json`) is written by
|
|
6
|
+
* two handlers (the turn-end pre-save, the session shutdown writer) and read
|
|
7
|
+
* by a third (session-start discoverability). All three need the same
|
|
8
|
+
* projection of the scratchpad, so it lives here once.
|
|
9
|
+
*
|
|
10
|
+
* The scratchpad is an append-only checkpoint log (`events.jsonl`, last line
|
|
11
|
+
* wins), not a single JSON snapshot, so this reads through the store's own
|
|
12
|
+
* loader - `loadScratchpadFromDisk` - instead of re-deriving a path and a
|
|
13
|
+
* parse. The loader also runs the store's migrations, which is why a legacy
|
|
14
|
+
* `latest.json` still yields state here.
|
|
15
|
+
*
|
|
16
|
+
* The field names come from `TaskScratchpad`: `plan`, `decisions`,
|
|
17
|
+
* `key_learnings`. Reading `plans`/`learnings` off the persisted state
|
|
18
|
+
* silently yields nothing.
|
|
19
|
+
*/
|
|
20
|
+
import { createLogger } from "../../lib/core/logger.js";
|
|
21
|
+
import { loadScratchpadFromDisk } from "../memory/scratchpad/persistence.js";
|
|
22
|
+
const log = createLogger("enforcement:resume-state");
|
|
23
|
+
/**
|
|
24
|
+
* How many entries of each list the resume file carries. Sized for a
|
|
25
|
+
* transfer, not an audit: the first open plan steps are the program a
|
|
26
|
+
* successor continues (later steps are usually its to rewrite), and five
|
|
27
|
+
* decisions/learnings cover the recent working assumptions. The uncapped
|
|
28
|
+
* counts travel alongside so a reader can report "20 open, 10 shown".
|
|
29
|
+
*/
|
|
30
|
+
export const RESUME_OPEN_PLAN_LIMIT = 10;
|
|
31
|
+
export const RESUME_RECENT_DECISION_LIMIT = 5;
|
|
32
|
+
export const RESUME_RECENT_LEARNING_LIMIT = 5;
|
|
33
|
+
/** The projection of "no scratchpad": every section empty, never undefined. */
|
|
34
|
+
export function emptyResumeScratchpadState() {
|
|
35
|
+
return {
|
|
36
|
+
goal: null,
|
|
37
|
+
openPlans: [],
|
|
38
|
+
openPlanCount: 0,
|
|
39
|
+
recentDecisions: [],
|
|
40
|
+
recentLearnings: [],
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Project a loaded scratchpad onto the resume fields. Pure: the input pad is
|
|
45
|
+
* never mutated.
|
|
46
|
+
*
|
|
47
|
+
* Plan completion lives in `doneTurn` (mark_done stamps the turn and leaves
|
|
48
|
+
* the step in `plan`), so "open" is `doneTurn === 0` - the step is still in
|
|
49
|
+
* the plan, unfinished. A started-but-unfinished step is the live one.
|
|
50
|
+
*/
|
|
51
|
+
export function projectResumeScratchpad(pad) {
|
|
52
|
+
if (!pad)
|
|
53
|
+
return emptyResumeScratchpadState();
|
|
54
|
+
const openSteps = pad.plan.filter((step) => !step.doneTurn);
|
|
55
|
+
return {
|
|
56
|
+
goal: pad.goal && pad.goal.length > 0 ? pad.goal : null,
|
|
57
|
+
openPlans: openSteps.slice(0, RESUME_OPEN_PLAN_LIMIT).map((step) => ({
|
|
58
|
+
id: step.id,
|
|
59
|
+
text: step.text,
|
|
60
|
+
status: step.startTurn > 0 ? "in_progress" : "pending",
|
|
61
|
+
})),
|
|
62
|
+
openPlanCount: openSteps.length,
|
|
63
|
+
recentDecisions: pad.decisions.slice(-RESUME_RECENT_DECISION_LIMIT).map((decision) => ({
|
|
64
|
+
id: decision.id,
|
|
65
|
+
text: decision.text,
|
|
66
|
+
...(decision.reason ? { reason: decision.reason } : {}),
|
|
67
|
+
})),
|
|
68
|
+
recentLearnings: pad.key_learnings
|
|
69
|
+
.slice(-RESUME_RECENT_LEARNING_LIMIT)
|
|
70
|
+
.map((learning) => ({ category: learning.category, content: learning.content })),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Read this project's scratchpad and project it onto the resume fields.
|
|
75
|
+
*
|
|
76
|
+
* Degrades to the empty projection on any read failure: a resume file with no
|
|
77
|
+
* prior-state section is worth less than a program, but far more than a
|
|
78
|
+
* handler that threw during shutdown or before a compaction. The refusal is
|
|
79
|
+
* logged at debug - the empty projection is the visible outcome.
|
|
80
|
+
*/
|
|
81
|
+
export async function readResumeScratchpadState(projectSlug) {
|
|
82
|
+
try {
|
|
83
|
+
return projectResumeScratchpad(await loadScratchpadFromDisk(projectSlug));
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
log.debug(`scratchpad read for resume failed: ${err}`);
|
|
87
|
+
return emptyResumeScratchpadState();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=resume-state.js.map
|
|
@@ -24,6 +24,15 @@ export declare function createScratchpadState(): ScratchpadState;
|
|
|
24
24
|
export declare function resetScratchpadState(s: ScratchpadState): void;
|
|
25
25
|
export interface ContextHygieneState {
|
|
26
26
|
contextNudgeSent: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The nudge-ladder rung that armed `contextNudgeSent` (its id), or null when
|
|
29
|
+
* the latch was armed by something that is not a rung (the hygiene act) or
|
|
30
|
+
* by nothing yet. The latch re-arms in this rung's unit, and the rung is the
|
|
31
|
+
* floor a weaker rung has to cross to be news rather than a descent. Survives
|
|
32
|
+
* the re-arm; cleared when a compaction or a context tool makes a fresh
|
|
33
|
+
* start.
|
|
34
|
+
*/
|
|
35
|
+
contextNudgeRung: string | null;
|
|
27
36
|
lastContextCheckTurn: number;
|
|
28
37
|
lastCompactionTurn: number;
|
|
29
38
|
overflowRecently: number;
|
|
@@ -41,6 +41,7 @@ export function resetScratchpadState(s) {
|
|
|
41
41
|
export function createContextHygieneState() {
|
|
42
42
|
return {
|
|
43
43
|
contextNudgeSent: false,
|
|
44
|
+
contextNudgeRung: null,
|
|
44
45
|
lastContextCheckTurn: 0,
|
|
45
46
|
lastCompactionTurn: 0,
|
|
46
47
|
overflowRecently: 0,
|
|
@@ -56,6 +57,7 @@ export function createContextHygieneState() {
|
|
|
56
57
|
}
|
|
57
58
|
export function resetContextHygieneState(s) {
|
|
58
59
|
s.contextNudgeSent = false;
|
|
60
|
+
s.contextNudgeRung = null;
|
|
59
61
|
s.lastContextCheckTurn = 0;
|
|
60
62
|
s.lastCompactionTurn = 0;
|
|
61
63
|
s.overflowRecently = 0;
|
|
@@ -91,22 +93,28 @@ export function recordLiveUsageSample(s, tokens) {
|
|
|
91
93
|
/** Mark context nudge as sent (system sends nudge to agent). */
|
|
92
94
|
export function markNudgeSent(s, turn) {
|
|
93
95
|
s.contextNudgeSent = true;
|
|
96
|
+
s.contextNudgeRung = null;
|
|
94
97
|
s.lastContextCheckTurn = turn;
|
|
95
98
|
}
|
|
96
99
|
/** Reset context nudge (e.g., after compaction freed space). */
|
|
97
100
|
export function resetNudge(s) {
|
|
98
101
|
s.contextNudgeSent = false;
|
|
102
|
+
s.contextNudgeRung = null;
|
|
99
103
|
}
|
|
100
104
|
/** Record that a context management tool was used. */
|
|
101
105
|
export function recordContextTool(s, turn) {
|
|
102
106
|
s.lastContextCheckTurn = turn;
|
|
103
107
|
s.contextNudgeSent = false;
|
|
108
|
+
s.contextNudgeRung = null;
|
|
104
109
|
}
|
|
105
110
|
/** Record that compaction happened. Also resets scratchpad nudge timer. */
|
|
106
111
|
export function recordCompaction(s, turn) {
|
|
107
112
|
s.lastCompactionTurn = turn;
|
|
108
113
|
s.lastContextCheckTurn = turn;
|
|
109
114
|
s.contextNudgeSent = false;
|
|
115
|
+
// A compaction is a fresh start: usage dropped by construction, so the rung
|
|
116
|
+
// that armed the old latch says nothing about where the next nudge belongs.
|
|
117
|
+
s.contextNudgeRung = null;
|
|
110
118
|
s.overflowRecently = turn;
|
|
111
119
|
if (typeof s.lastScratchpadNudgeTurn === "number") {
|
|
112
120
|
s.lastScratchpadNudgeTurn = turn;
|
|
@@ -35,6 +35,17 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
|
35
35
|
* options.deliverAs - Delivery mode. Defaults to `"steer"` for a
|
|
36
36
|
* non-waking whisper; left undefined when triggerTurn:true so
|
|
37
37
|
* pi-core's wake branch is not shadowed by the nextTurn queue.
|
|
38
|
+
* options.bypassFloodCap - Skip the per-turn/per-source whisper flood cap
|
|
39
|
+
* in the funnel (see `sendTrackedMessage`'s JSDoc). Opt-in
|
|
40
|
+
* per call site, default false, and reserved for a wake
|
|
41
|
+
* whose loss is a correctness bug rather than a lost nudge:
|
|
42
|
+
* the post-compaction resume, which is the only thing that
|
|
43
|
+
* hands the aborted loop back. Every enforcement whisper
|
|
44
|
+
* shares the `enforcement/whisper` bucket, so three ordinary
|
|
45
|
+
* advisories in one turn are enough to spend it - a blanket
|
|
46
|
+
* exemption for `triggerTurn` would instead turn every
|
|
47
|
+
* waking caller into a flood risk, which is why the cap is
|
|
48
|
+
* bypassed here per call rather than in the funnel.
|
|
38
49
|
*
|
|
39
50
|
* Nudges are suppressed when braid.suppressNudges=true in settings.json.
|
|
40
51
|
*/
|
|
@@ -42,5 +53,6 @@ export declare function sendEnforcementWhisper(pi: ExtensionAPI, ctx: ExtensionC
|
|
|
42
53
|
triggerTurn?: boolean;
|
|
43
54
|
deliverAs?: "steer" | "nextTurn";
|
|
44
55
|
delivery?: "live" | "park";
|
|
56
|
+
bypassFloodCap?: boolean;
|
|
45
57
|
}): void;
|
|
46
58
|
//# sourceMappingURL=whisper.d.ts.map
|
|
@@ -39,6 +39,17 @@ const log = createLogger("enforcement");
|
|
|
39
39
|
* options.deliverAs - Delivery mode. Defaults to `"steer"` for a
|
|
40
40
|
* non-waking whisper; left undefined when triggerTurn:true so
|
|
41
41
|
* pi-core's wake branch is not shadowed by the nextTurn queue.
|
|
42
|
+
* options.bypassFloodCap - Skip the per-turn/per-source whisper flood cap
|
|
43
|
+
* in the funnel (see `sendTrackedMessage`'s JSDoc). Opt-in
|
|
44
|
+
* per call site, default false, and reserved for a wake
|
|
45
|
+
* whose loss is a correctness bug rather than a lost nudge:
|
|
46
|
+
* the post-compaction resume, which is the only thing that
|
|
47
|
+
* hands the aborted loop back. Every enforcement whisper
|
|
48
|
+
* shares the `enforcement/whisper` bucket, so three ordinary
|
|
49
|
+
* advisories in one turn are enough to spend it - a blanket
|
|
50
|
+
* exemption for `triggerTurn` would instead turn every
|
|
51
|
+
* waking caller into a flood risk, which is why the cap is
|
|
52
|
+
* bypassed here per call rather than in the funnel.
|
|
42
53
|
*
|
|
43
54
|
* Nudges are suppressed when braid.suppressNudges=true in settings.json.
|
|
44
55
|
*/
|
|
@@ -99,6 +110,10 @@ export function sendEnforcementWhisper(pi, ctx, message, critical = false, optio
|
|
|
99
110
|
customType: "enforcement",
|
|
100
111
|
content: [{ type: "text", text: message }],
|
|
101
112
|
display: true,
|
|
102
|
-
}, { deliverAs, triggerTurn, delivery }, { type: "enforcement", source: "enforcement/whisper" }
|
|
113
|
+
}, { deliverAs, triggerTurn, delivery }, { type: "enforcement", source: "enforcement/whisper" },
|
|
114
|
+
// Forwarded per call, never defaulted on: the funnel's flood cap stays
|
|
115
|
+
// the gate for every enforcement whisper that does not ask for the
|
|
116
|
+
// exemption explicitly.
|
|
117
|
+
{ bypassFloodCap: options?.bypassFloodCap === true });
|
|
103
118
|
}
|
|
104
119
|
//# sourceMappingURL=whisper.js.map
|
|
@@ -75,7 +75,7 @@ function newestUserText(ctx) {
|
|
|
75
75
|
}
|
|
76
76
|
import { DEFAULT_CONFIG, getState, getMemoryState } from "./state.js";
|
|
77
77
|
import { updateMetaLearning, getAdaptiveInterval } from "./meta-learning.js";
|
|
78
|
-
import { createDefaultPolicies,
|
|
78
|
+
import { createDefaultPolicies, isVerificationToolCall, WEB_TOOLS, CODE_TOOLS, } from "./policies.js";
|
|
79
79
|
import { formatPendingCompactionsLine, maybeArmAutoCompaction, } from "../../memory/context-manager/handlers/tools/context-compress.js";
|
|
80
80
|
import { pushBounded } from "../../../lib/utils/bounded.js";
|
|
81
81
|
import { RSS_RING_CAP } from "../../../lib/telemetry/rss-telemetry.js";
|
|
@@ -222,7 +222,7 @@ import { flushWhisperBuffer } from "./whisper-batcher.js";
|
|
|
222
222
|
import { buildSelfStateLine } from "./whisper-batcher.js";
|
|
223
223
|
import { getSelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
|
|
224
224
|
// Tick Engine
|
|
225
|
-
function tick(pi, state, config, ctx) {
|
|
225
|
+
function tick(pi, state, config, ctx, turnEvent) {
|
|
226
226
|
state.stats.totalTicks++;
|
|
227
227
|
// Real telemetry: collect live context/RSS/session metrics, append the
|
|
228
228
|
// JSONL heartbeat line, and feed recordTurnMetrics real values (not
|
|
@@ -296,7 +296,7 @@ function tick(pi, state, config, ctx) {
|
|
|
296
296
|
log.warn(`[heartbeat] pending-compaction advisory failed: ${err}`);
|
|
297
297
|
}
|
|
298
298
|
try {
|
|
299
|
-
maybeArmAutoCompaction(pi, ctx);
|
|
299
|
+
maybeArmAutoCompaction(pi, ctx, turnEvent);
|
|
300
300
|
}
|
|
301
301
|
catch (err) {
|
|
302
302
|
log.warn(`[heartbeat] context auto-arm check failed: ${err}`);
|
|
@@ -483,7 +483,7 @@ export default function heartbeatExtension(pi) {
|
|
|
483
483
|
behavioralDriftModule,
|
|
484
484
|
];
|
|
485
485
|
// Event: turn_end
|
|
486
|
-
pi.on(TURN_END, async (
|
|
486
|
+
pi.on(TURN_END, async (event, ctx) => {
|
|
487
487
|
const state = getState(ctx);
|
|
488
488
|
if (!state.enabled || !config.enabled)
|
|
489
489
|
return;
|
|
@@ -496,7 +496,12 @@ export default function heartbeatExtension(pi) {
|
|
|
496
496
|
const interval = getAdaptiveInterval(state);
|
|
497
497
|
if (state.turnCount % interval !== 0)
|
|
498
498
|
return;
|
|
499
|
-
tick
|
|
499
|
+
// The boundary travels with the tick: the usage-driven auto-arm arms inside
|
|
500
|
+
// this dispatch, and a drain there can only be judged from the event that
|
|
501
|
+
// named the boundary. Dropping this argument is invisible to every other
|
|
502
|
+
// fixture, so one drives the real handler end to end:
|
|
503
|
+
// test/runtime/heartbeat/test-turn-boundary-arm-wiring.mjs.
|
|
504
|
+
tick(pi, state, config, ctx, event);
|
|
500
505
|
});
|
|
501
506
|
// Event: before_agent_start - flush delayed whispers
|
|
502
507
|
// Deliver buffered heartbeat whispers as part of the turn context,
|
|
@@ -539,7 +544,10 @@ export default function heartbeatExtension(pi) {
|
|
|
539
544
|
const toolName = event?.toolName;
|
|
540
545
|
if (!toolName)
|
|
541
546
|
return;
|
|
542
|
-
|
|
547
|
+
// Verification activity is a name set plus bash by its command shape:
|
|
548
|
+
// a search or diff run through bash is the same activity the hint is
|
|
549
|
+
// about, and counting every bash call (edits, builds) would silence it.
|
|
550
|
+
if (isVerificationToolCall(toolName, event?.input)) {
|
|
543
551
|
state.metaLearning.toolTracking.verificationCount++;
|
|
544
552
|
state.metaLearning.toolTracking.lastVerificationTurn = state.policyTurnCount;
|
|
545
553
|
}
|
|
@@ -10,5 +10,12 @@ import type { ToolTracking } from "./types.js";
|
|
|
10
10
|
export declare const VERIFICATION_TOOLS: Set<string>;
|
|
11
11
|
export declare const WEB_TOOLS: Set<string>;
|
|
12
12
|
export declare const CODE_TOOLS: Set<string>;
|
|
13
|
+
/** True when the command is inspection-shaped (see the rule above). */
|
|
14
|
+
export declare function bashCommandIsVerification(command: string): boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Does this tool call count as verification activity? The name set first, then
|
|
17
|
+
* bash by the command's shape. Every other tool is not verification.
|
|
18
|
+
*/
|
|
19
|
+
export declare function isVerificationToolCall(toolName: string, input: unknown): boolean;
|
|
13
20
|
export declare function createDefaultPolicies(getToolTracking: () => ToolTracking, onSignal: (type: string, data: Record<string, unknown>) => void, sendWhisper: (msg: string) => void, sendSteerMessage: (msg: string) => void): Policy[];
|
|
14
21
|
//# sourceMappingURL=policies.d.ts.map
|