pi-braid 0.40.5 → 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 +89 -10
- package/dist/extensions/core/skills-tool/auto-inject.js +150 -21
- 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 +47 -10
- package/dist/extensions/core/skills-tool/skill-triggers.js +66 -23
- 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 +1 -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 +196 -24
- 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 +90 -20
- 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
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a SKILL.md costs before it is read.
|
|
3
|
+
*
|
|
4
|
+
* `list_skills` is a choice between reads, and a row that names a path but
|
|
5
|
+
* prices nothing leaves that choice blind: a 650-byte pointer and a 25KB
|
|
6
|
+
* reference look identical until one of them is already in context. The fields
|
|
7
|
+
* here are the price - line count, byte count, character count, a token
|
|
8
|
+
* estimate, and the file's ATX headings with line numbers, which is the
|
|
9
|
+
* cheapest useful table of contents for "read section 88 and stop".
|
|
10
|
+
*
|
|
11
|
+
* Counts are the whole file, frontmatter included: the question a reader is
|
|
12
|
+
* asking is what the `read` call will cost, not what the body costs. `chars`
|
|
13
|
+
* is `String.length`, so it counts UTF-16 code units and not code points: text
|
|
14
|
+
* outside the BMP counts twice, and `estTokens` inherits that over-count. A
|
|
15
|
+
* byte-priced budget is what this row feeds, `chars` is the name callers
|
|
16
|
+
* already read, and the doc block is where the difference is stated.
|
|
17
|
+
* Lines end at a newline; a last line without a terminating newline still
|
|
18
|
+
* counts, because the read pays for it.
|
|
19
|
+
*
|
|
20
|
+
* One read per change. The cache is keyed on mtime + size, the same
|
|
21
|
+
* invalidation `skill-triggers.ts` uses: a page render stats every row, and
|
|
22
|
+
* only a first-seen or changed file is opened and parsed. Failures are not
|
|
23
|
+
* cached, because a chmod that took away read access leaves mtime untouched -
|
|
24
|
+
* a cached failure would outlive the repair.
|
|
25
|
+
*
|
|
26
|
+
* Headings are parsed fence-aware. Skill files carry long fenced blocks of
|
|
27
|
+
* shell, TypeScript and markdown samples whose comment lines start with `#`.
|
|
28
|
+
* Over the 22 skills of the shipped pack, 293 lines are shaped like headings
|
|
29
|
+
* and 248 are headings: 45 phantom entries, 1.18x. The ratio is not the
|
|
30
|
+
* argument, the entries are. Those 45 lines are shell and TypeScript
|
|
31
|
+
* commentary, and a fence-blind parse advertises them as document structure,
|
|
32
|
+
* sending a reader to a line that holds no section.
|
|
33
|
+
*
|
|
34
|
+
* Two fence edges are known limits, not open bugs. A fence opener indented
|
|
35
|
+
* four spaces is not a fence - the fence and ATX rules both stop at three
|
|
36
|
+
* spaces - so `#` lines inside such a block are reported as headings. An
|
|
37
|
+
* unclosed fence swallows every later heading, which is CommonMark's rule too
|
|
38
|
+
* and costs a truncated file its table of contents. Neither occurs in the
|
|
39
|
+
* shipped pack. Fixing either is a behaviour change with its own evidence, so
|
|
40
|
+
* this block is where they are recorded rather than where they are repaired.
|
|
41
|
+
*
|
|
42
|
+
* The default page is a budget, not a ceiling. A row carries at most
|
|
43
|
+
* SECTIONS_MAX_LIMIT headings and `list_skills` serves at most 50 rows per
|
|
44
|
+
* page, so one call can ask for tens of kilobytes: `pageSize: 50` with
|
|
45
|
+
* `sectionsMax: 64` over the shipped pack is 35852 bytes, nearly three times
|
|
46
|
+
* the 12KB default page. That is the caller's choice, priced here so it is not
|
|
47
|
+
* a surprise; the budget below binds on the default arguments only.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
import { readFileSync, statSync } from "node:fs";
|
|
51
|
+
import { resolve } from "node:path";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Characters per token. The same divisor the pre-send guard uses
|
|
55
|
+
* (`packages/providers/presend-guard.ts`, `CHARS_PER_TOKEN`) and the one
|
|
56
|
+
* pi-core's `estimateTokens` applies, so a reach estimate and a payload
|
|
57
|
+
* estimate are comparable numbers rather than two private conventions.
|
|
58
|
+
* Declared here instead of imported: providers is a standalone package with no
|
|
59
|
+
* import path into core.
|
|
60
|
+
*/
|
|
61
|
+
export const CHARS_PER_TOKEN = 4;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Headings reported per skill when the caller does not ask for another cap.
|
|
65
|
+
*
|
|
66
|
+
* Six is a prompt-budget number, not a taste one: over the shipped pack the
|
|
67
|
+
* heaviest ten-row page of the pretty-printed catalog measures 11984 bytes at
|
|
68
|
+
* six headings, 304 bytes under the 12KB bound, and 13568 at eight, where it
|
|
69
|
+
* crosses. Callers who want the full contents pass `sectionsMax` (up to
|
|
70
|
+
* SECTIONS_MAX_LIMIT).
|
|
71
|
+
*/
|
|
72
|
+
export const DEFAULT_SECTIONS_MAX = 6;
|
|
73
|
+
|
|
74
|
+
/** A heading is a table-of-contents entry, not a paragraph. */
|
|
75
|
+
const SECTION_TEXT_MAX = 80;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Upper bound on the per-skill heading cap - a request above it is a bug.
|
|
79
|
+
* `list_skills` declares this same value as its schema maximum, so the ceiling
|
|
80
|
+
* a caller meets through the tool and the ceiling `clampSectionsMax` enforces
|
|
81
|
+
* cannot drift into two numbers.
|
|
82
|
+
*/
|
|
83
|
+
export const SECTIONS_MAX_LIMIT = 64;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* ATX heading: up to three spaces of indent (four would be an indented code
|
|
87
|
+
* block), one to six `#`, then a space or the end of the line - so `#region`
|
|
88
|
+
* in a TypeScript sample is not a heading.
|
|
89
|
+
*/
|
|
90
|
+
const ATX_HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A heading's optional closing sequence: `## Title ##`, trailing whitespace
|
|
94
|
+
* allowed - `## Title ## ` closes the same way, and the spaces after the run
|
|
95
|
+
* are not part of the text.
|
|
96
|
+
*/
|
|
97
|
+
const CLOSING_HASHES = /[ \t]+#+[ \t]*$/;
|
|
98
|
+
|
|
99
|
+
/** A fence line: up to three spaces of indent, then three or more backticks or tildes. */
|
|
100
|
+
const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
101
|
+
|
|
102
|
+
export interface SkillSection {
|
|
103
|
+
/** 1-indexed line the heading sits on. */
|
|
104
|
+
line: number;
|
|
105
|
+
/** Heading text with its leading `#`s stripped, trimmed, capped. */
|
|
106
|
+
text: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface SkillReach {
|
|
110
|
+
reachable: true;
|
|
111
|
+
lines: number;
|
|
112
|
+
bytes: number;
|
|
113
|
+
/** `String.length`: UTF-16 code units, so astral-plane text counts twice. */
|
|
114
|
+
chars: number;
|
|
115
|
+
estTokens: number;
|
|
116
|
+
/** Total headings in the file, independent of the per-call report cap. */
|
|
117
|
+
sectionCount: number;
|
|
118
|
+
/** Omitted when the caller asked for no section list. */
|
|
119
|
+
sections?: SkillSection[];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface UnreachableReach {
|
|
123
|
+
reachable: false;
|
|
124
|
+
/** Stat size when stat() succeeded and the read failed; absent otherwise. */
|
|
125
|
+
bytes?: number;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type Reach = SkillReach | UnreachableReach;
|
|
129
|
+
|
|
130
|
+
interface ReachCacheEntry {
|
|
131
|
+
mtimeMs: number;
|
|
132
|
+
size: number;
|
|
133
|
+
reach: SkillReach;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const cache = new Map<string, ReachCacheEntry>();
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Lines in a file's text: a trailing newline ends the last line rather than
|
|
140
|
+
* opening a blank one, an empty file has no lines, and a final line with no
|
|
141
|
+
* terminating newline counts, because the partial line is content the read
|
|
142
|
+
* pays for.
|
|
143
|
+
*/
|
|
144
|
+
export function countLines(text: string): number {
|
|
145
|
+
if (text === "") return 0;
|
|
146
|
+
let newlines = 0;
|
|
147
|
+
for (let i = 0; i < text.length; i++) if (text[i] === "\n") newlines++;
|
|
148
|
+
return text.endsWith("\n") ? newlines : newlines + 1;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Headings in document order, skipping fenced blocks. A fence opens on a run
|
|
153
|
+
* of backticks or tildes (with or without an info string) and closes only on a
|
|
154
|
+
* run of the same character at least as long, so a `~~~` sample inside a
|
|
155
|
+
* backtick fence is content, not a delimiter. A backtick run followed by more
|
|
156
|
+
* backticks (` ```a`` `) is not a fence at all, per CommonMark.
|
|
157
|
+
*/
|
|
158
|
+
function scanHeadings(text: string): SkillSection[] {
|
|
159
|
+
const headings: SkillSection[] = [];
|
|
160
|
+
let fence: { marker: string; length: number } | null = null;
|
|
161
|
+
const lines = text.split("\n");
|
|
162
|
+
for (let i = 0; i < lines.length; i++) {
|
|
163
|
+
const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
|
|
164
|
+
const fenceLine = FENCE.exec(line);
|
|
165
|
+
if (fence) {
|
|
166
|
+
if (
|
|
167
|
+
fenceLine &&
|
|
168
|
+
fenceLine[1][0] === fence.marker &&
|
|
169
|
+
fenceLine[1].length >= fence.length &&
|
|
170
|
+
fenceLine[2].trim() === ""
|
|
171
|
+
) {
|
|
172
|
+
fence = null;
|
|
173
|
+
}
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (fenceLine && !(fenceLine[1][0] === "`" && fenceLine[2].includes("`"))) {
|
|
177
|
+
fence = { marker: fenceLine[1][0], length: fenceLine[1].length };
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const heading = ATX_HEADING.exec(line);
|
|
181
|
+
if (!heading) continue;
|
|
182
|
+
const text = (heading[2] ?? "").replace(CLOSING_HASHES, "").trim();
|
|
183
|
+
headings.push({
|
|
184
|
+
line: i + 1,
|
|
185
|
+
text: text.length > SECTION_TEXT_MAX ? text.slice(0, SECTION_TEXT_MAX) : text,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return headings;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Clamp a caller-supplied heading cap into range; 0 means "no list". */
|
|
192
|
+
export function clampSectionsMax(value: unknown): number {
|
|
193
|
+
const n = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : NaN;
|
|
194
|
+
if (Number.isNaN(n)) return DEFAULT_SECTIONS_MAX;
|
|
195
|
+
if (n <= 0) return 0;
|
|
196
|
+
return Math.min(n, SECTIONS_MAX_LIMIT);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Reach for one SKILL.md. A file that cannot be stat'ed or read answers
|
|
201
|
+
* `reachable: false` instead of throwing: the catalog has to render, and one
|
|
202
|
+
* unreadable skill must not take the page down with it.
|
|
203
|
+
*
|
|
204
|
+
* `sectionsMax` caps the returned heading list; the cached parse keeps the
|
|
205
|
+
* whole list, so two callers asking for different caps share one read.
|
|
206
|
+
*/
|
|
207
|
+
export function readSkillReach(
|
|
208
|
+
filePath: string,
|
|
209
|
+
sectionsMax: number = DEFAULT_SECTIONS_MAX,
|
|
210
|
+
): Reach {
|
|
211
|
+
const key = resolve(filePath);
|
|
212
|
+
let size: number;
|
|
213
|
+
let mtimeMs: number;
|
|
214
|
+
try {
|
|
215
|
+
const stat = statSync(key);
|
|
216
|
+
size = stat.size;
|
|
217
|
+
mtimeMs = stat.mtimeMs;
|
|
218
|
+
} catch {
|
|
219
|
+
cache.delete(key);
|
|
220
|
+
return { reachable: false };
|
|
221
|
+
}
|
|
222
|
+
let entry = cache.get(key);
|
|
223
|
+
if (!entry || entry.mtimeMs !== mtimeMs || entry.size !== size) {
|
|
224
|
+
let text: string;
|
|
225
|
+
try {
|
|
226
|
+
text = readFileSync(key, "utf-8");
|
|
227
|
+
} catch {
|
|
228
|
+
cache.delete(key);
|
|
229
|
+
return { reachable: false, bytes: size };
|
|
230
|
+
}
|
|
231
|
+
const headings = scanHeadings(text);
|
|
232
|
+
entry = {
|
|
233
|
+
mtimeMs,
|
|
234
|
+
size,
|
|
235
|
+
reach: {
|
|
236
|
+
reachable: true,
|
|
237
|
+
lines: countLines(text),
|
|
238
|
+
bytes: size,
|
|
239
|
+
chars: text.length,
|
|
240
|
+
estTokens: Math.ceil(text.length / CHARS_PER_TOKEN),
|
|
241
|
+
sectionCount: headings.length,
|
|
242
|
+
sections: headings,
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
cache.set(key, entry);
|
|
246
|
+
}
|
|
247
|
+
const { sections: all = [], ...scalars } = entry.reach;
|
|
248
|
+
const cap = clampSectionsMax(sectionsMax);
|
|
249
|
+
if (cap === 0) return scalars;
|
|
250
|
+
return { ...scalars, sections: cap >= all.length ? all : all.slice(0, cap) };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Test seam: forget every memoized reach measurement. */
|
|
254
|
+
export function clearReachCache(): void {
|
|
255
|
+
cache.clear();
|
|
256
|
+
}
|
|
@@ -13,9 +13,13 @@
|
|
|
13
13
|
* carry the phrases here and nowhere else);
|
|
14
14
|
* 3. the description's trailing "Triggers: …" segment, the pack's older
|
|
15
15
|
* convention.
|
|
16
|
-
* A file may use any of them
|
|
17
|
-
* the
|
|
18
|
-
*
|
|
16
|
+
* A file may use any of them, and every source that yields phrases is read:
|
|
17
|
+
* the lists are MERGED in that order, so a phrase an author put in the body
|
|
18
|
+
* heading survives when frontmatter also declares some, and the frontmatter
|
|
19
|
+
* still outranks the rest. First-wins was the defect: agent-testing declares
|
|
20
|
+
* seven phrases in its description tail and five in its body heading, and
|
|
21
|
+
* precedence let the tail replace the heading, so the five never reached the
|
|
22
|
+
* matcher while the file said they had.
|
|
19
23
|
*
|
|
20
24
|
* A trigger hit scores like a name hit and qualifies a skill whose
|
|
21
25
|
* description alone would stay under the qualification bar — the phrase is
|
|
@@ -31,19 +35,36 @@ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
|
|
31
35
|
|
|
32
36
|
/**
|
|
33
37
|
* Max trigger phrases read per skill — a longer list is an authoring bug, not a
|
|
34
|
-
* matcher input.
|
|
35
|
-
* pi-reference 15),
|
|
36
|
-
* the
|
|
38
|
+
* matcher input. Three authored lists reach the cap: braid-reference (16
|
|
39
|
+
* phrases), pi-reference (15), and agent-testing, which fills it exactly (7 in
|
|
40
|
+
* the description tail + 5 in the body heading) now that the sources merge.
|
|
41
|
+
* The cap assertion lives in test-skill-triggers-body.mjs; raising the number
|
|
42
|
+
* means changing it there.
|
|
37
43
|
*/
|
|
38
44
|
export const MAX_TRIGGERS = 12;
|
|
39
45
|
|
|
40
46
|
/** Max characters of one trigger phrase. */
|
|
41
47
|
export const MAX_TRIGGER_CHARS = 64;
|
|
42
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Where an authored phrase came from. Precedence (frontmatter, heading,
|
|
51
|
+
* description) orders the merged list and decides which source the cap cuts
|
|
52
|
+
* last; the label itself is what a ranking row reports as its evidence.
|
|
53
|
+
*/
|
|
54
|
+
export type TriggerSource = "frontmatter" | "heading" | "description";
|
|
55
|
+
|
|
56
|
+
/** One authored phrase and the source that declared it. */
|
|
57
|
+
export interface TriggerEntry {
|
|
58
|
+
phrase: string;
|
|
59
|
+
source: TriggerSource;
|
|
60
|
+
}
|
|
61
|
+
|
|
43
62
|
interface TriggerCacheEntry {
|
|
44
63
|
mtimeMs: number;
|
|
45
64
|
size: number;
|
|
46
|
-
|
|
65
|
+
/** The description the entries were merged with: a different one is a miss. */
|
|
66
|
+
description: string;
|
|
67
|
+
entries: TriggerEntry[];
|
|
47
68
|
}
|
|
48
69
|
|
|
49
70
|
const cache = new Map<string, TriggerCacheEntry>();
|
|
@@ -70,13 +91,28 @@ export function normalizeTriggers(value: unknown): string[] {
|
|
|
70
91
|
}
|
|
71
92
|
|
|
72
93
|
/**
|
|
73
|
-
* Read a skill's trigger phrases
|
|
74
|
-
*
|
|
75
|
-
* "Triggers: …" segment.
|
|
76
|
-
*
|
|
94
|
+
* Read a skill's trigger phrases from every source the file uses, merged in
|
|
95
|
+
* priority order: frontmatter (`trigger` or `triggers`), then a `## trigger:`
|
|
96
|
+
* body heading, then the description's trailing "Triggers: …" segment.
|
|
97
|
+
* Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
|
|
98
|
+
* description tail is still read.
|
|
77
99
|
* Memoized: unchanged files never re-read.
|
|
78
100
|
*/
|
|
79
101
|
export function readSkillTriggers(filePath: string, description?: string): string[] {
|
|
102
|
+
return readSkillTriggerEntries(filePath, description).map((entry) => entry.phrase);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Read a skill's authored phrases WITH their provenance, merged in priority
|
|
107
|
+
* order: frontmatter (`trigger` or `triggers`), then a `## trigger:` body
|
|
108
|
+
* heading, then the description's trailing "Triggers: …" segment.
|
|
109
|
+
* Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
|
|
110
|
+
* description tail is still read.
|
|
111
|
+
* Memoized: unchanged files never re-read (a different description argument is
|
|
112
|
+
* a miss, because the merged list depends on it).
|
|
113
|
+
*/
|
|
114
|
+
export function readSkillTriggerEntries(filePath: string, description?: string): TriggerEntry[] {
|
|
115
|
+
const desc = description ?? "";
|
|
80
116
|
let st;
|
|
81
117
|
try {
|
|
82
118
|
st = statSync(filePath);
|
|
@@ -85,20 +121,54 @@ export function readSkillTriggers(filePath: string, description?: string): strin
|
|
|
85
121
|
return [];
|
|
86
122
|
}
|
|
87
123
|
const cached = cache.get(filePath);
|
|
88
|
-
if (
|
|
89
|
-
|
|
124
|
+
if (
|
|
125
|
+
cached &&
|
|
126
|
+
cached.mtimeMs === st.mtimeMs &&
|
|
127
|
+
cached.size === st.size &&
|
|
128
|
+
cached.description === desc
|
|
129
|
+
) {
|
|
130
|
+
return cached.entries;
|
|
131
|
+
}
|
|
132
|
+
const sources: TriggerEntry[][] = [];
|
|
90
133
|
try {
|
|
91
134
|
const { frontmatter, body } = parseFrontmatter(readFileSync(filePath, "utf-8"));
|
|
92
135
|
const fm = frontmatter as Record<string, unknown>;
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
136
|
+
const label = (source: TriggerSource) => (phrase: string) => ({ phrase, source });
|
|
137
|
+
sources.push(
|
|
138
|
+
normalizeTriggers(fm.trigger).map(label("frontmatter")),
|
|
139
|
+
normalizeTriggers(fm.triggers).map(label("frontmatter")),
|
|
140
|
+
parseBodyTriggers(body).map(label("heading")),
|
|
141
|
+
);
|
|
96
142
|
} catch {
|
|
97
|
-
|
|
143
|
+
// Malformed frontmatter: the file sources yield nothing, and the
|
|
144
|
+
// description tail below is still read.
|
|
145
|
+
}
|
|
146
|
+
if (desc)
|
|
147
|
+
sources.push(
|
|
148
|
+
parseDescriptionTriggers(desc).map((phrase) => ({ phrase, source: "description" })),
|
|
149
|
+
);
|
|
150
|
+
const entries = mergeTriggerEntries(sources);
|
|
151
|
+
cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, description: desc, entries });
|
|
152
|
+
return entries;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Merge authored phrase sources into one bounded list, in priority order.
|
|
157
|
+
*
|
|
158
|
+
* The cap is a budget spent down the list, so when it binds the LOWEST
|
|
159
|
+
* priority source is the one that loses phrases — a higher-priority source is
|
|
160
|
+
* never cut to make room for a later one. A phrase repeated by two sources
|
|
161
|
+
* keeps its first (highest-priority) source. Pure.
|
|
162
|
+
*/
|
|
163
|
+
export function mergeTriggerEntries(sources: TriggerEntry[][]): TriggerEntry[] {
|
|
164
|
+
const merged: TriggerEntry[] = [];
|
|
165
|
+
for (const source of sources) {
|
|
166
|
+
for (const entry of source) {
|
|
167
|
+
if (merged.length >= MAX_TRIGGERS) return merged;
|
|
168
|
+
if (!merged.some((kept) => kept.phrase === entry.phrase)) merged.push(entry);
|
|
169
|
+
}
|
|
98
170
|
}
|
|
99
|
-
|
|
100
|
-
cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, triggers });
|
|
101
|
-
return triggers;
|
|
171
|
+
return merged;
|
|
102
172
|
}
|
|
103
173
|
|
|
104
174
|
/** First `## trigger:` / `## triggers:` heading; a heading-shaped line cannot come from frontmatter. */
|
|
@@ -228,6 +228,15 @@ export function registerSessionCompactHandler(pi: ExtensionAPI): void {
|
|
|
228
228
|
// resume-vs-advisory delivery differs. A mid-work turn stays
|
|
229
229
|
// triggerTurn:true (compaction aborted the loop; it must be handed
|
|
230
230
|
// back to the agent).
|
|
231
|
+
//
|
|
232
|
+
// bypassFloodCap: this whisper is the resume. It is the only thing that
|
|
233
|
+
// restarts a turn the context_compress tool aborted, so dropping it
|
|
234
|
+
// halts the session instead of losing a nudge. Every enforcement
|
|
235
|
+
// whisper shares the `enforcement/whisper` per-source bucket (cap 3),
|
|
236
|
+
// so three ordinary advisories earlier in the same turn are enough to
|
|
237
|
+
// spend it and swallow the wake. The exemption is granted here, at the
|
|
238
|
+
// one call site that cannot afford to lose the message - not in the
|
|
239
|
+
// wrapper's default and not in the funnel.
|
|
231
240
|
setTimeout(() => {
|
|
232
241
|
sendEnforcementWhisper(
|
|
233
242
|
pi,
|
|
@@ -238,7 +247,9 @@ export function registerSessionCompactHandler(pi: ExtensionAPI): void {
|
|
|
238
247
|
`(which preserves speaker context) to distinguish who said what. ` +
|
|
239
248
|
`These surfaces survive compaction - continue from there.`,
|
|
240
249
|
false,
|
|
241
|
-
naturalStop && !agentRequestedResume
|
|
250
|
+
naturalStop && !agentRequestedResume
|
|
251
|
+
? { delivery: "park", bypassFloodCap: true }
|
|
252
|
+
: { triggerTurn: true, bypassFloodCap: true },
|
|
242
253
|
);
|
|
243
254
|
}, 0);
|
|
244
255
|
} finally {
|
|
@@ -15,15 +15,22 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
18
|
-
import { existsSync, mkdirSync, writeFileSync
|
|
18
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
19
19
|
import * as path from "node:path";
|
|
20
20
|
import { execSync } from "node:child_process";
|
|
21
21
|
import { createLogger } from "../../../lib/core/logger.js";
|
|
22
22
|
import { onEvent } from "../../../lib/events/event-types.js";
|
|
23
23
|
import { getState } from "../state.js";
|
|
24
|
-
import {
|
|
24
|
+
import { braidDir } from "../../../lib/config/braid-paths.js";
|
|
25
25
|
import { SESSION_SHUTDOWN } from "../../../lib/core/event-names.js";
|
|
26
26
|
import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
|
|
27
|
+
import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
|
|
28
|
+
import {
|
|
29
|
+
readResumeScratchpadState,
|
|
30
|
+
type ResumeDecisionItem,
|
|
31
|
+
type ResumeLearningItem,
|
|
32
|
+
type ResumePlanItem,
|
|
33
|
+
} from "../resume-state.js";
|
|
27
34
|
|
|
28
35
|
const log = createLogger("enforcement:session-shutdown-resumption");
|
|
29
36
|
|
|
@@ -31,9 +38,9 @@ interface ResumptionFile {
|
|
|
31
38
|
writtenAt: string;
|
|
32
39
|
cwd: string;
|
|
33
40
|
goal: string | null;
|
|
34
|
-
openPlans:
|
|
35
|
-
recentDecisions:
|
|
36
|
-
recentLearnings:
|
|
41
|
+
openPlans: ResumePlanItem[];
|
|
42
|
+
recentDecisions: ResumeDecisionItem[];
|
|
43
|
+
recentLearnings: ResumeLearningItem[];
|
|
37
44
|
uncommittedFiles: string[];
|
|
38
45
|
toolCallCount: number;
|
|
39
46
|
verificationCount: number;
|
|
@@ -48,38 +55,18 @@ export function registerSessionShutdownResumption(pi: ExtensionAPI): void {
|
|
|
48
55
|
const cwd = (ctx as { cwd?: string }).cwd ?? "";
|
|
49
56
|
const slug = projectSlugFromCwd(cwd);
|
|
50
57
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
58
|
+
// Flush the debounced scratchpad write queue first: at shutdown the
|
|
59
|
+
// in-memory pad may hold the session's last mutations and the read
|
|
60
|
+
// below only sees what reached the checkpoint log.
|
|
61
|
+
await flushPendingScratchpadWrites().catch(() => {});
|
|
55
62
|
|
|
56
|
-
// Prior state is a READ
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
//
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const content = readFileSync(scratchpadFile, "utf-8");
|
|
64
|
-
const parsed = JSON.parse(content);
|
|
65
|
-
goal = parsed.goal ?? null;
|
|
66
|
-
openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
|
|
67
|
-
.filter((p: any) => !p.done)
|
|
68
|
-
.slice(0, 10)
|
|
69
|
-
.map((p: any) => ({ id: p.id ?? "", text: p.text ?? "" }));
|
|
70
|
-
recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
|
|
71
|
-
.slice(-5)
|
|
72
|
-
.map((d: any) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
|
|
73
|
-
recentLearnings = (Array.isArray(parsed.learnings) ? parsed.learnings : [])
|
|
74
|
-
.slice(-5)
|
|
75
|
-
.map((l: any) => ({
|
|
76
|
-
category: l.category ?? "",
|
|
77
|
-
content: l.content ?? l.text ?? "",
|
|
78
|
-
}));
|
|
79
|
-
}
|
|
80
|
-
} catch (err) {
|
|
81
|
-
log.debug(`scratchpad prior-state read failed: ${err}`);
|
|
82
|
-
}
|
|
63
|
+
// Prior state is a READ through the scratchpad store's own loader (the
|
|
64
|
+
// checkpoint log, not a hand-built path), so a schema or storage change
|
|
65
|
+
// in the store moves this reader with it. A refused root (no absolute
|
|
66
|
+
// braid home) degrades to an empty prior-state section instead of
|
|
67
|
+
// failing the resume write below.
|
|
68
|
+
const resumeState = await readResumeScratchpadState(slug);
|
|
69
|
+
const { goal, openPlans, recentDecisions, recentLearnings } = resumeState;
|
|
83
70
|
|
|
84
71
|
let uncommittedFiles: string[] = [];
|
|
85
72
|
try {
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
*
|
|
9
9
|
* This handler runs in SessionPhase.Background (fire-and-forget, non-blocking)
|
|
10
10
|
* so it doesn't delay agent startup. It checks for:
|
|
11
|
-
* 1. Scratchpad
|
|
11
|
+
* 1. Scratchpad checkpoint log for this project (`events.jsonl`, last
|
|
12
|
+
* checkpoint)
|
|
12
13
|
* 2. Episodes file with content
|
|
13
14
|
* 3. Semantic memory file with content
|
|
14
15
|
* 4. Prior session .jsonl files (session-recall)
|
|
@@ -43,14 +44,15 @@ import {
|
|
|
43
44
|
type DiscoverySignalType,
|
|
44
45
|
} from "../../../lib/state/global-state.js";
|
|
45
46
|
import {
|
|
46
|
-
scratchpadDir,
|
|
47
47
|
episodesFilePath,
|
|
48
48
|
semanticMemoryFilePath,
|
|
49
49
|
AGENT,
|
|
50
50
|
braidDir,
|
|
51
|
+
journalFilePath,
|
|
51
52
|
tagsSlugFromCwd,
|
|
52
53
|
} from "../../../lib/config/braid-paths.js";
|
|
53
54
|
import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
|
|
55
|
+
import { readResumeScratchpadState } from "../resume-state.js";
|
|
54
56
|
|
|
55
57
|
const log = createLogger("enforcement:session-start-discoverability");
|
|
56
58
|
|
|
@@ -91,30 +93,23 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
|
|
|
91
93
|
delete (enforcementSignals as Record<string, EnforcementSignalEntry>)[key];
|
|
92
94
|
}
|
|
93
95
|
|
|
94
|
-
// 1. Scratchpad.
|
|
95
|
-
//
|
|
96
|
-
//
|
|
96
|
+
// 1. Scratchpad. Read through the store's own loader (the checkpoint
|
|
97
|
+
// log), never a hand-built snapshot path: the snapshot file this
|
|
98
|
+
// branch used to open has not been written for years, so the signal
|
|
99
|
+
// was armed against a file that never existed. The store root is
|
|
100
|
+
// resolved on every call, never a module-load constant, so a pinned
|
|
101
|
+
// run reads the tree the writers wrote to.
|
|
97
102
|
try {
|
|
98
103
|
const slug = projectSlugFromCwd(cwd);
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
: 0;
|
|
109
|
-
if (hasGoal || openPlans > 0) {
|
|
110
|
-
signals.push({
|
|
111
|
-
type: "scratchpad_prior",
|
|
112
|
-
text:
|
|
113
|
-
`Prior scratchpad data exists for this project (${openPlans} open plan items). ` +
|
|
114
|
-
`Use \`scratchpad action=continue\` to resume -- it returns goal + open plan + recent context in one call.`,
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
}
|
|
104
|
+
const prior = await readResumeScratchpadState(slug);
|
|
105
|
+
const openPlans = prior.openPlanCount;
|
|
106
|
+
if (prior.goal || openPlans > 0) {
|
|
107
|
+
signals.push({
|
|
108
|
+
type: "scratchpad_prior",
|
|
109
|
+
text:
|
|
110
|
+
`Prior scratchpad data exists for this project (${openPlans} open plan items). ` +
|
|
111
|
+
`Use \`scratchpad action=continue\` to resume -- it returns goal + open plan + recent context in one call.`,
|
|
112
|
+
});
|
|
118
113
|
}
|
|
119
114
|
} catch (err) {
|
|
120
115
|
log.debug(`scratchpad discoverability check failed: ${err}`);
|
|
@@ -227,7 +222,33 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
|
|
|
227
222
|
// ignore
|
|
228
223
|
}
|
|
229
224
|
|
|
230
|
-
// 7.
|
|
225
|
+
// 7. The owner-input journal. The path comes from the constant the
|
|
226
|
+
// writer appends through, never a hand-built shape: two spellings for
|
|
227
|
+
// one file is how the scratchpad pointer armed itself against a file
|
|
228
|
+
// nothing writes (see step 1).
|
|
229
|
+
try {
|
|
230
|
+
const slug = projectSlugFromCwd(cwd);
|
|
231
|
+
const journalFile = journalFilePath(slug);
|
|
232
|
+
if (existsSync(journalFile)) {
|
|
233
|
+
const count = readFileSync(journalFile, "utf-8")
|
|
234
|
+
.split("\n")
|
|
235
|
+
.filter((line) => line.trim()).length;
|
|
236
|
+
if (count > 0) {
|
|
237
|
+
signals.push({
|
|
238
|
+
type: "journal_prior",
|
|
239
|
+
text:
|
|
240
|
+
`The project journal holds ${count} entr${count === 1 ? "y" : "ies"} at ${journalFile} -- ` +
|
|
241
|
+
`what earlier seats decided and why, readable without their sessions. ` +
|
|
242
|
+
`Read the open program before acting (digest printer: packages/core/scripts/check-journal.mjs --digest), ` +
|
|
243
|
+
`so a decision gets superseded, not rediscovered.`,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
} catch {
|
|
248
|
+
// ignore
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 8. Context hygiene & state preservation tip: forward-looking
|
|
231
252
|
// guidance — when prior state exists, remind the agent how to manage
|
|
232
253
|
// context and preserve state against crashes.
|
|
233
254
|
// Shown only when there's prior state to manage (other signals exist).
|
|
@@ -246,14 +267,23 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
|
|
|
246
267
|
// persistence (via `projectSlugFromCwd`) lets `pi --session <id>` (a new
|
|
247
268
|
// process) read previously shown signals from disk and skip them, so the
|
|
248
269
|
// discoverability bundle doesn't re-fire on session resume.
|
|
270
|
+
// Signal types that must reach every seat, not only the first. The
|
|
271
|
+
// dedupe below -- and the branch entries it writes -- exists so a
|
|
272
|
+
// resumed session is not told what it already saw. A journal pointer is
|
|
273
|
+
// aimed at a seat that has never seen this project, so a mark left by an
|
|
274
|
+
// earlier seat is exactly the one-shot failure it exists to repair.
|
|
275
|
+
const alwaysShown: ReadonlySet<DiscoverySignalType> = new Set(["journal_prior"]);
|
|
276
|
+
|
|
249
277
|
const slug = signals.length > 0 && (cwd ? projectSlugFromCwd(cwd) : "");
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
278
|
+
const projectKey = slug || "default";
|
|
279
|
+
const unseenSignals = signals.filter(
|
|
280
|
+
(s) => alwaysShown.has(s.type) || !isProjectSignalShown(projectKey, s.type),
|
|
281
|
+
);
|
|
253
282
|
if (unseenSignals.length > 0) {
|
|
254
283
|
const bundled = unseenSignals.map((s) => s.text).join("\n");
|
|
255
284
|
for (const s of unseenSignals) {
|
|
256
|
-
|
|
285
|
+
if (alwaysShown.has(s.type)) continue;
|
|
286
|
+
markProjectSignalShown(projectKey, s.type, pi);
|
|
257
287
|
}
|
|
258
288
|
// Informational pointers to prior state: park (no forced turn).
|
|
259
289
|
sendEnforcementWhisper(pi, ctx, bundled, false, { delivery: "park" });
|