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,119 @@
|
|
|
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
|
+
* Characters per token. The same divisor the pre-send guard uses
|
|
51
|
+
* (`packages/providers/presend-guard.ts`, `CHARS_PER_TOKEN`) and the one
|
|
52
|
+
* pi-core's `estimateTokens` applies, so a reach estimate and a payload
|
|
53
|
+
* estimate are comparable numbers rather than two private conventions.
|
|
54
|
+
* Declared here instead of imported: providers is a standalone package with no
|
|
55
|
+
* import path into core.
|
|
56
|
+
*/
|
|
57
|
+
export declare const CHARS_PER_TOKEN = 4;
|
|
58
|
+
/**
|
|
59
|
+
* Headings reported per skill when the caller does not ask for another cap.
|
|
60
|
+
*
|
|
61
|
+
* Six is a prompt-budget number, not a taste one: over the shipped pack the
|
|
62
|
+
* heaviest ten-row page of the pretty-printed catalog measures 11984 bytes at
|
|
63
|
+
* six headings, 304 bytes under the 12KB bound, and 13568 at eight, where it
|
|
64
|
+
* crosses. Callers who want the full contents pass `sectionsMax` (up to
|
|
65
|
+
* SECTIONS_MAX_LIMIT).
|
|
66
|
+
*/
|
|
67
|
+
export declare const DEFAULT_SECTIONS_MAX = 6;
|
|
68
|
+
/**
|
|
69
|
+
* Upper bound on the per-skill heading cap - a request above it is a bug.
|
|
70
|
+
* `list_skills` declares this same value as its schema maximum, so the ceiling
|
|
71
|
+
* a caller meets through the tool and the ceiling `clampSectionsMax` enforces
|
|
72
|
+
* cannot drift into two numbers.
|
|
73
|
+
*/
|
|
74
|
+
export declare const SECTIONS_MAX_LIMIT = 64;
|
|
75
|
+
export interface SkillSection {
|
|
76
|
+
/** 1-indexed line the heading sits on. */
|
|
77
|
+
line: number;
|
|
78
|
+
/** Heading text with its leading `#`s stripped, trimmed, capped. */
|
|
79
|
+
text: string;
|
|
80
|
+
}
|
|
81
|
+
export interface SkillReach {
|
|
82
|
+
reachable: true;
|
|
83
|
+
lines: number;
|
|
84
|
+
bytes: number;
|
|
85
|
+
/** `String.length`: UTF-16 code units, so astral-plane text counts twice. */
|
|
86
|
+
chars: number;
|
|
87
|
+
estTokens: number;
|
|
88
|
+
/** Total headings in the file, independent of the per-call report cap. */
|
|
89
|
+
sectionCount: number;
|
|
90
|
+
/** Omitted when the caller asked for no section list. */
|
|
91
|
+
sections?: SkillSection[];
|
|
92
|
+
}
|
|
93
|
+
export interface UnreachableReach {
|
|
94
|
+
reachable: false;
|
|
95
|
+
/** Stat size when stat() succeeded and the read failed; absent otherwise. */
|
|
96
|
+
bytes?: number;
|
|
97
|
+
}
|
|
98
|
+
export type Reach = SkillReach | UnreachableReach;
|
|
99
|
+
/**
|
|
100
|
+
* Lines in a file's text: a trailing newline ends the last line rather than
|
|
101
|
+
* opening a blank one, an empty file has no lines, and a final line with no
|
|
102
|
+
* terminating newline counts, because the partial line is content the read
|
|
103
|
+
* pays for.
|
|
104
|
+
*/
|
|
105
|
+
export declare function countLines(text: string): number;
|
|
106
|
+
/** Clamp a caller-supplied heading cap into range; 0 means "no list". */
|
|
107
|
+
export declare function clampSectionsMax(value: unknown): number;
|
|
108
|
+
/**
|
|
109
|
+
* Reach for one SKILL.md. A file that cannot be stat'ed or read answers
|
|
110
|
+
* `reachable: false` instead of throwing: the catalog has to render, and one
|
|
111
|
+
* unreadable skill must not take the page down with it.
|
|
112
|
+
*
|
|
113
|
+
* `sectionsMax` caps the returned heading list; the cached parse keeps the
|
|
114
|
+
* whole list, so two callers asking for different caps share one read.
|
|
115
|
+
*/
|
|
116
|
+
export declare function readSkillReach(filePath: string, sectionsMax?: number): Reach;
|
|
117
|
+
/** Test seam: forget every memoized reach measurement. */
|
|
118
|
+
export declare function clearReachCache(): void;
|
|
119
|
+
//# sourceMappingURL=reach.d.ts.map
|
|
@@ -0,0 +1,213 @@
|
|
|
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
|
+
import { readFileSync, statSync } from "node:fs";
|
|
50
|
+
import { resolve } from "node:path";
|
|
51
|
+
/**
|
|
52
|
+
* Characters per token. The same divisor the pre-send guard uses
|
|
53
|
+
* (`packages/providers/presend-guard.ts`, `CHARS_PER_TOKEN`) and the one
|
|
54
|
+
* pi-core's `estimateTokens` applies, so a reach estimate and a payload
|
|
55
|
+
* estimate are comparable numbers rather than two private conventions.
|
|
56
|
+
* Declared here instead of imported: providers is a standalone package with no
|
|
57
|
+
* import path into core.
|
|
58
|
+
*/
|
|
59
|
+
export const CHARS_PER_TOKEN = 4;
|
|
60
|
+
/**
|
|
61
|
+
* Headings reported per skill when the caller does not ask for another cap.
|
|
62
|
+
*
|
|
63
|
+
* Six is a prompt-budget number, not a taste one: over the shipped pack the
|
|
64
|
+
* heaviest ten-row page of the pretty-printed catalog measures 11984 bytes at
|
|
65
|
+
* six headings, 304 bytes under the 12KB bound, and 13568 at eight, where it
|
|
66
|
+
* crosses. Callers who want the full contents pass `sectionsMax` (up to
|
|
67
|
+
* SECTIONS_MAX_LIMIT).
|
|
68
|
+
*/
|
|
69
|
+
export const DEFAULT_SECTIONS_MAX = 6;
|
|
70
|
+
/** A heading is a table-of-contents entry, not a paragraph. */
|
|
71
|
+
const SECTION_TEXT_MAX = 80;
|
|
72
|
+
/**
|
|
73
|
+
* Upper bound on the per-skill heading cap - a request above it is a bug.
|
|
74
|
+
* `list_skills` declares this same value as its schema maximum, so the ceiling
|
|
75
|
+
* a caller meets through the tool and the ceiling `clampSectionsMax` enforces
|
|
76
|
+
* cannot drift into two numbers.
|
|
77
|
+
*/
|
|
78
|
+
export const SECTIONS_MAX_LIMIT = 64;
|
|
79
|
+
/**
|
|
80
|
+
* ATX heading: up to three spaces of indent (four would be an indented code
|
|
81
|
+
* block), one to six `#`, then a space or the end of the line - so `#region`
|
|
82
|
+
* in a TypeScript sample is not a heading.
|
|
83
|
+
*/
|
|
84
|
+
const ATX_HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/;
|
|
85
|
+
/**
|
|
86
|
+
* A heading's optional closing sequence: `## Title ##`, trailing whitespace
|
|
87
|
+
* allowed - `## Title ## ` closes the same way, and the spaces after the run
|
|
88
|
+
* are not part of the text.
|
|
89
|
+
*/
|
|
90
|
+
const CLOSING_HASHES = /[ \t]+#+[ \t]*$/;
|
|
91
|
+
/** A fence line: up to three spaces of indent, then three or more backticks or tildes. */
|
|
92
|
+
const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
93
|
+
const cache = new Map();
|
|
94
|
+
/**
|
|
95
|
+
* Lines in a file's text: a trailing newline ends the last line rather than
|
|
96
|
+
* opening a blank one, an empty file has no lines, and a final line with no
|
|
97
|
+
* terminating newline counts, because the partial line is content the read
|
|
98
|
+
* pays for.
|
|
99
|
+
*/
|
|
100
|
+
export function countLines(text) {
|
|
101
|
+
if (text === "")
|
|
102
|
+
return 0;
|
|
103
|
+
let newlines = 0;
|
|
104
|
+
for (let i = 0; i < text.length; i++)
|
|
105
|
+
if (text[i] === "\n")
|
|
106
|
+
newlines++;
|
|
107
|
+
return text.endsWith("\n") ? newlines : newlines + 1;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Headings in document order, skipping fenced blocks. A fence opens on a run
|
|
111
|
+
* of backticks or tildes (with or without an info string) and closes only on a
|
|
112
|
+
* run of the same character at least as long, so a `~~~` sample inside a
|
|
113
|
+
* backtick fence is content, not a delimiter. A backtick run followed by more
|
|
114
|
+
* backticks (` ```a`` `) is not a fence at all, per CommonMark.
|
|
115
|
+
*/
|
|
116
|
+
function scanHeadings(text) {
|
|
117
|
+
const headings = [];
|
|
118
|
+
let fence = null;
|
|
119
|
+
const lines = text.split("\n");
|
|
120
|
+
for (let i = 0; i < lines.length; i++) {
|
|
121
|
+
const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
|
|
122
|
+
const fenceLine = FENCE.exec(line);
|
|
123
|
+
if (fence) {
|
|
124
|
+
if (fenceLine &&
|
|
125
|
+
fenceLine[1][0] === fence.marker &&
|
|
126
|
+
fenceLine[1].length >= fence.length &&
|
|
127
|
+
fenceLine[2].trim() === "") {
|
|
128
|
+
fence = null;
|
|
129
|
+
}
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (fenceLine && !(fenceLine[1][0] === "`" && fenceLine[2].includes("`"))) {
|
|
133
|
+
fence = { marker: fenceLine[1][0], length: fenceLine[1].length };
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const heading = ATX_HEADING.exec(line);
|
|
137
|
+
if (!heading)
|
|
138
|
+
continue;
|
|
139
|
+
const text = (heading[2] ?? "").replace(CLOSING_HASHES, "").trim();
|
|
140
|
+
headings.push({
|
|
141
|
+
line: i + 1,
|
|
142
|
+
text: text.length > SECTION_TEXT_MAX ? text.slice(0, SECTION_TEXT_MAX) : text,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return headings;
|
|
146
|
+
}
|
|
147
|
+
/** Clamp a caller-supplied heading cap into range; 0 means "no list". */
|
|
148
|
+
export function clampSectionsMax(value) {
|
|
149
|
+
const n = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : NaN;
|
|
150
|
+
if (Number.isNaN(n))
|
|
151
|
+
return DEFAULT_SECTIONS_MAX;
|
|
152
|
+
if (n <= 0)
|
|
153
|
+
return 0;
|
|
154
|
+
return Math.min(n, SECTIONS_MAX_LIMIT);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Reach for one SKILL.md. A file that cannot be stat'ed or read answers
|
|
158
|
+
* `reachable: false` instead of throwing: the catalog has to render, and one
|
|
159
|
+
* unreadable skill must not take the page down with it.
|
|
160
|
+
*
|
|
161
|
+
* `sectionsMax` caps the returned heading list; the cached parse keeps the
|
|
162
|
+
* whole list, so two callers asking for different caps share one read.
|
|
163
|
+
*/
|
|
164
|
+
export function readSkillReach(filePath, sectionsMax = DEFAULT_SECTIONS_MAX) {
|
|
165
|
+
const key = resolve(filePath);
|
|
166
|
+
let size;
|
|
167
|
+
let mtimeMs;
|
|
168
|
+
try {
|
|
169
|
+
const stat = statSync(key);
|
|
170
|
+
size = stat.size;
|
|
171
|
+
mtimeMs = stat.mtimeMs;
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
cache.delete(key);
|
|
175
|
+
return { reachable: false };
|
|
176
|
+
}
|
|
177
|
+
let entry = cache.get(key);
|
|
178
|
+
if (!entry || entry.mtimeMs !== mtimeMs || entry.size !== size) {
|
|
179
|
+
let text;
|
|
180
|
+
try {
|
|
181
|
+
text = readFileSync(key, "utf-8");
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
cache.delete(key);
|
|
185
|
+
return { reachable: false, bytes: size };
|
|
186
|
+
}
|
|
187
|
+
const headings = scanHeadings(text);
|
|
188
|
+
entry = {
|
|
189
|
+
mtimeMs,
|
|
190
|
+
size,
|
|
191
|
+
reach: {
|
|
192
|
+
reachable: true,
|
|
193
|
+
lines: countLines(text),
|
|
194
|
+
bytes: size,
|
|
195
|
+
chars: text.length,
|
|
196
|
+
estTokens: Math.ceil(text.length / CHARS_PER_TOKEN),
|
|
197
|
+
sectionCount: headings.length,
|
|
198
|
+
sections: headings,
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
cache.set(key, entry);
|
|
202
|
+
}
|
|
203
|
+
const { sections: all = [], ...scalars } = entry.reach;
|
|
204
|
+
const cap = clampSectionsMax(sectionsMax);
|
|
205
|
+
if (cap === 0)
|
|
206
|
+
return scalars;
|
|
207
|
+
return { ...scalars, sections: cap >= all.length ? all : all.slice(0, cap) };
|
|
208
|
+
}
|
|
209
|
+
/** Test seam: forget every memoized reach measurement. */
|
|
210
|
+
export function clearReachCache() {
|
|
211
|
+
cache.clear();
|
|
212
|
+
}
|
|
213
|
+
//# sourceMappingURL=reach.js.map
|
|
@@ -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
|
|
@@ -27,13 +31,26 @@
|
|
|
27
31
|
*/
|
|
28
32
|
/**
|
|
29
33
|
* Max trigger phrases read per skill — a longer list is an authoring bug, not a
|
|
30
|
-
* matcher input.
|
|
31
|
-
* pi-reference 15),
|
|
32
|
-
* the
|
|
34
|
+
* matcher input. Three authored lists reach the cap: braid-reference (16
|
|
35
|
+
* phrases), pi-reference (15), and agent-testing, which fills it exactly (7 in
|
|
36
|
+
* the description tail + 5 in the body heading) now that the sources merge.
|
|
37
|
+
* The cap assertion lives in test-skill-triggers-body.mjs; raising the number
|
|
38
|
+
* means changing it there.
|
|
33
39
|
*/
|
|
34
40
|
export declare const MAX_TRIGGERS = 12;
|
|
35
41
|
/** Max characters of one trigger phrase. */
|
|
36
42
|
export declare const MAX_TRIGGER_CHARS = 64;
|
|
43
|
+
/**
|
|
44
|
+
* Where an authored phrase came from. Precedence (frontmatter, heading,
|
|
45
|
+
* description) orders the merged list and decides which source the cap cuts
|
|
46
|
+
* last; the label itself is what a ranking row reports as its evidence.
|
|
47
|
+
*/
|
|
48
|
+
export type TriggerSource = "frontmatter" | "heading" | "description";
|
|
49
|
+
/** One authored phrase and the source that declared it. */
|
|
50
|
+
export interface TriggerEntry {
|
|
51
|
+
phrase: string;
|
|
52
|
+
source: TriggerSource;
|
|
53
|
+
}
|
|
37
54
|
/**
|
|
38
55
|
* Normalize a frontmatter `triggers` value into clean phrases. Accepts a YAML
|
|
39
56
|
* list or a comma-separated string; drops empty, overlong, and surplus
|
|
@@ -41,13 +58,33 @@ export declare const MAX_TRIGGER_CHARS = 64;
|
|
|
41
58
|
*/
|
|
42
59
|
export declare function normalizeTriggers(value: unknown): string[];
|
|
43
60
|
/**
|
|
44
|
-
* Read a skill's trigger phrases
|
|
45
|
-
*
|
|
46
|
-
* "Triggers: …" segment.
|
|
47
|
-
*
|
|
61
|
+
* Read a skill's trigger phrases from every source the file uses, merged in
|
|
62
|
+
* priority order: frontmatter (`trigger` or `triggers`), then a `## trigger:`
|
|
63
|
+
* body heading, then the description's trailing "Triggers: …" segment.
|
|
64
|
+
* Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
|
|
65
|
+
* description tail is still read.
|
|
48
66
|
* Memoized: unchanged files never re-read.
|
|
49
67
|
*/
|
|
50
68
|
export declare function readSkillTriggers(filePath: string, description?: string): string[];
|
|
69
|
+
/**
|
|
70
|
+
* Read a skill's authored phrases WITH their provenance, merged in priority
|
|
71
|
+
* order: frontmatter (`trigger` or `triggers`), then a `## trigger:` body
|
|
72
|
+
* heading, then the description's trailing "Triggers: …" segment.
|
|
73
|
+
* Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
|
|
74
|
+
* description tail is still read.
|
|
75
|
+
* Memoized: unchanged files never re-read (a different description argument is
|
|
76
|
+
* a miss, because the merged list depends on it).
|
|
77
|
+
*/
|
|
78
|
+
export declare function readSkillTriggerEntries(filePath: string, description?: string): TriggerEntry[];
|
|
79
|
+
/**
|
|
80
|
+
* Merge authored phrase sources into one bounded list, in priority order.
|
|
81
|
+
*
|
|
82
|
+
* The cap is a budget spent down the list, so when it binds the LOWEST
|
|
83
|
+
* priority source is the one that loses phrases — a higher-priority source is
|
|
84
|
+
* never cut to make room for a later one. A phrase repeated by two sources
|
|
85
|
+
* keeps its first (highest-priority) source. Pure.
|
|
86
|
+
*/
|
|
87
|
+
export declare function mergeTriggerEntries(sources: TriggerEntry[][]): TriggerEntry[];
|
|
51
88
|
/**
|
|
52
89
|
* Trigger phrases from a body `## trigger: "a, b, c"` heading. The FIRST such
|
|
53
90
|
* heading is the whole input: a body with several is an authoring error, not
|
|
@@ -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
|
|
@@ -29,9 +33,11 @@ import { statSync, readFileSync } from "node:fs";
|
|
|
29
33
|
import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
|
30
34
|
/**
|
|
31
35
|
* Max trigger phrases read per skill — a longer list is an authoring bug, not a
|
|
32
|
-
* matcher input.
|
|
33
|
-
* pi-reference 15),
|
|
34
|
-
* the
|
|
36
|
+
* matcher input. Three authored lists reach the cap: braid-reference (16
|
|
37
|
+
* phrases), pi-reference (15), and agent-testing, which fills it exactly (7 in
|
|
38
|
+
* the description tail + 5 in the body heading) now that the sources merge.
|
|
39
|
+
* The cap assertion lives in test-skill-triggers-body.mjs; raising the number
|
|
40
|
+
* means changing it there.
|
|
35
41
|
*/
|
|
36
42
|
export const MAX_TRIGGERS = 12;
|
|
37
43
|
/** Max characters of one trigger phrase. */
|
|
@@ -60,13 +66,27 @@ export function normalizeTriggers(value) {
|
|
|
60
66
|
return cleaned;
|
|
61
67
|
}
|
|
62
68
|
/**
|
|
63
|
-
* Read a skill's trigger phrases
|
|
64
|
-
*
|
|
65
|
-
* "Triggers: …" segment.
|
|
66
|
-
*
|
|
69
|
+
* Read a skill's trigger phrases from every source the file uses, merged in
|
|
70
|
+
* priority order: frontmatter (`trigger` or `triggers`), then a `## trigger:`
|
|
71
|
+
* body heading, then the description's trailing "Triggers: …" segment.
|
|
72
|
+
* Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
|
|
73
|
+
* description tail is still read.
|
|
67
74
|
* Memoized: unchanged files never re-read.
|
|
68
75
|
*/
|
|
69
76
|
export function readSkillTriggers(filePath, description) {
|
|
77
|
+
return readSkillTriggerEntries(filePath, description).map((entry) => entry.phrase);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Read a skill's authored phrases WITH their provenance, merged in priority
|
|
81
|
+
* order: frontmatter (`trigger` or `triggers`), then a `## trigger:` body
|
|
82
|
+
* heading, then the description's trailing "Triggers: …" segment.
|
|
83
|
+
* Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
|
|
84
|
+
* description tail is still read.
|
|
85
|
+
* Memoized: unchanged files never re-read (a different description argument is
|
|
86
|
+
* a miss, because the merged list depends on it).
|
|
87
|
+
*/
|
|
88
|
+
export function readSkillTriggerEntries(filePath, description) {
|
|
89
|
+
const desc = description ?? "";
|
|
70
90
|
let st;
|
|
71
91
|
try {
|
|
72
92
|
st = statSync(filePath);
|
|
@@ -76,25 +96,48 @@ export function readSkillTriggers(filePath, description) {
|
|
|
76
96
|
return [];
|
|
77
97
|
}
|
|
78
98
|
const cached = cache.get(filePath);
|
|
79
|
-
if (cached &&
|
|
80
|
-
|
|
81
|
-
|
|
99
|
+
if (cached &&
|
|
100
|
+
cached.mtimeMs === st.mtimeMs &&
|
|
101
|
+
cached.size === st.size &&
|
|
102
|
+
cached.description === desc) {
|
|
103
|
+
return cached.entries;
|
|
104
|
+
}
|
|
105
|
+
const sources = [];
|
|
82
106
|
try {
|
|
83
107
|
const { frontmatter, body } = parseFrontmatter(readFileSync(filePath, "utf-8"));
|
|
84
108
|
const fm = frontmatter;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
triggers = normalizeTriggers(fm.triggers);
|
|
88
|
-
if (!triggers.length)
|
|
89
|
-
triggers = parseBodyTriggers(body);
|
|
109
|
+
const label = (source) => (phrase) => ({ phrase, source });
|
|
110
|
+
sources.push(normalizeTriggers(fm.trigger).map(label("frontmatter")), normalizeTriggers(fm.triggers).map(label("frontmatter")), parseBodyTriggers(body).map(label("heading")));
|
|
90
111
|
}
|
|
91
112
|
catch {
|
|
92
|
-
|
|
113
|
+
// Malformed frontmatter: the file sources yield nothing, and the
|
|
114
|
+
// description tail below is still read.
|
|
115
|
+
}
|
|
116
|
+
if (desc)
|
|
117
|
+
sources.push(parseDescriptionTriggers(desc).map((phrase) => ({ phrase, source: "description" })));
|
|
118
|
+
const entries = mergeTriggerEntries(sources);
|
|
119
|
+
cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, description: desc, entries });
|
|
120
|
+
return entries;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Merge authored phrase sources into one bounded list, in priority order.
|
|
124
|
+
*
|
|
125
|
+
* The cap is a budget spent down the list, so when it binds the LOWEST
|
|
126
|
+
* priority source is the one that loses phrases — a higher-priority source is
|
|
127
|
+
* never cut to make room for a later one. A phrase repeated by two sources
|
|
128
|
+
* keeps its first (highest-priority) source. Pure.
|
|
129
|
+
*/
|
|
130
|
+
export function mergeTriggerEntries(sources) {
|
|
131
|
+
const merged = [];
|
|
132
|
+
for (const source of sources) {
|
|
133
|
+
for (const entry of source) {
|
|
134
|
+
if (merged.length >= MAX_TRIGGERS)
|
|
135
|
+
return merged;
|
|
136
|
+
if (!merged.some((kept) => kept.phrase === entry.phrase))
|
|
137
|
+
merged.push(entry);
|
|
138
|
+
}
|
|
93
139
|
}
|
|
94
|
-
|
|
95
|
-
triggers = parseDescriptionTriggers(description);
|
|
96
|
-
cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, triggers });
|
|
97
|
-
return triggers;
|
|
140
|
+
return merged;
|
|
98
141
|
}
|
|
99
142
|
/** First `## trigger:` / `## triggers:` heading; a heading-shaped line cannot come from frontmatter. */
|
|
100
143
|
const BODY_TRIGGER_HEADING = /^##\s*triggers?\s*:\s*(.*)$/i;
|
|
@@ -191,12 +191,23 @@ export function registerSessionCompactHandler(pi) {
|
|
|
191
191
|
// resume-vs-advisory delivery differs. A mid-work turn stays
|
|
192
192
|
// triggerTurn:true (compaction aborted the loop; it must be handed
|
|
193
193
|
// back to the agent).
|
|
194
|
+
//
|
|
195
|
+
// bypassFloodCap: this whisper is the resume. It is the only thing that
|
|
196
|
+
// restarts a turn the context_compress tool aborted, so dropping it
|
|
197
|
+
// halts the session instead of losing a nudge. Every enforcement
|
|
198
|
+
// whisper shares the `enforcement/whisper` per-source bucket (cap 3),
|
|
199
|
+
// so three ordinary advisories earlier in the same turn are enough to
|
|
200
|
+
// spend it and swallow the wake. The exemption is granted here, at the
|
|
201
|
+
// one call site that cannot afford to lose the message - not in the
|
|
202
|
+
// wrapper's default and not in the funnel.
|
|
194
203
|
setTimeout(() => {
|
|
195
204
|
sendEnforcementWhisper(pi, ctx, `Context compacted at turn ${compactTurn}. ` +
|
|
196
205
|
`Re-orient: read scratchpad for goal/plan/learnings, then check next pending task. ` +
|
|
197
206
|
`Note: compaction summaries may lack speaker labels — use the scratchpad ` +
|
|
198
207
|
`(which preserves speaker context) to distinguish who said what. ` +
|
|
199
|
-
`These surfaces survive compaction - continue from there.`, false, naturalStop && !agentRequestedResume
|
|
208
|
+
`These surfaces survive compaction - continue from there.`, false, naturalStop && !agentRequestedResume
|
|
209
|
+
? { delivery: "park", bypassFloodCap: true }
|
|
210
|
+
: { triggerTurn: true, bypassFloodCap: true });
|
|
200
211
|
}, 0);
|
|
201
212
|
}
|
|
202
213
|
finally {
|
|
@@ -13,15 +13,17 @@
|
|
|
13
13
|
*
|
|
14
14
|
* File location: <braidDir()>/sessions/<projectSlug>/resume.json
|
|
15
15
|
*/
|
|
16
|
-
import { existsSync, mkdirSync, writeFileSync
|
|
16
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
17
17
|
import * as path from "node:path";
|
|
18
18
|
import { execSync } from "node:child_process";
|
|
19
19
|
import { createLogger } from "../../../lib/core/logger.js";
|
|
20
20
|
import { onEvent } from "../../../lib/events/event-types.js";
|
|
21
21
|
import { getState } from "../state.js";
|
|
22
|
-
import {
|
|
22
|
+
import { braidDir } from "../../../lib/config/braid-paths.js";
|
|
23
23
|
import { SESSION_SHUTDOWN } from "../../../lib/core/event-names.js";
|
|
24
24
|
import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
|
|
25
|
+
import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
|
|
26
|
+
import { readResumeScratchpadState, } from "../resume-state.js";
|
|
25
27
|
const log = createLogger("enforcement:session-shutdown-resumption");
|
|
26
28
|
/**
|
|
27
29
|
* Register the SESSION_SHUTDOWN resumption writer.
|
|
@@ -31,38 +33,17 @@ export function registerSessionShutdownResumption(pi) {
|
|
|
31
33
|
try {
|
|
32
34
|
const cwd = ctx.cwd ?? "";
|
|
33
35
|
const slug = projectSlugFromCwd(cwd);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
// Prior state is a READ
|
|
39
|
-
//
|
|
40
|
-
//
|
|
41
|
-
//
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const content = readFileSync(scratchpadFile, "utf-8");
|
|
46
|
-
const parsed = JSON.parse(content);
|
|
47
|
-
goal = parsed.goal ?? null;
|
|
48
|
-
openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
|
|
49
|
-
.filter((p) => !p.done)
|
|
50
|
-
.slice(0, 10)
|
|
51
|
-
.map((p) => ({ id: p.id ?? "", text: p.text ?? "" }));
|
|
52
|
-
recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
|
|
53
|
-
.slice(-5)
|
|
54
|
-
.map((d) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
|
|
55
|
-
recentLearnings = (Array.isArray(parsed.learnings) ? parsed.learnings : [])
|
|
56
|
-
.slice(-5)
|
|
57
|
-
.map((l) => ({
|
|
58
|
-
category: l.category ?? "",
|
|
59
|
-
content: l.content ?? l.text ?? "",
|
|
60
|
-
}));
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
catch (err) {
|
|
64
|
-
log.debug(`scratchpad prior-state read failed: ${err}`);
|
|
65
|
-
}
|
|
36
|
+
// Flush the debounced scratchpad write queue first: at shutdown the
|
|
37
|
+
// in-memory pad may hold the session's last mutations and the read
|
|
38
|
+
// below only sees what reached the checkpoint log.
|
|
39
|
+
await flushPendingScratchpadWrites().catch(() => { });
|
|
40
|
+
// Prior state is a READ through the scratchpad store's own loader (the
|
|
41
|
+
// checkpoint log, not a hand-built path), so a schema or storage change
|
|
42
|
+
// in the store moves this reader with it. A refused root (no absolute
|
|
43
|
+
// braid home) degrades to an empty prior-state section instead of
|
|
44
|
+
// failing the resume write below.
|
|
45
|
+
const resumeState = await readResumeScratchpadState(slug);
|
|
46
|
+
const { goal, openPlans, recentDecisions, recentLearnings } = resumeState;
|
|
66
47
|
let uncommittedFiles = [];
|
|
67
48
|
try {
|
|
68
49
|
// Scope to the project dir only. When ctx.cwd is missing, `cwd` is "" and
|
|
@@ -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)
|