pi-ext
bugabingas pi extensions
owned by admin
perf(the-system): defer operational runtime loading
0fdd32728fc009e5873316099832924ec3b71ffc
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
Browse filesCompare with HEAD
Changed files (17)
extensions/the-system/__e2e__/renderer.spec.ts
Modified186 186 const root
= systemFixture();
187 187 const runtime
= createBoardRuntime();
189 - runtime.
beginProposal(
root);
189 + await runtime.
beginProposal(
root);
190 190 await runtime.tool.
execute(
extensions/the-system/__tests__/harness.test.ts
Modified30 30 const sendUserMessage
= vi
31 31 .
spyOn(t.session,
"sendUserMessage")
32 32 .
mockResolvedValue();
33 - expect(extension.tools.
has(
"system_bundle_slot")).
toBe(
true);
33 + expect(extension.tools.
has(
"system_bundle_slot")).
toBe(
false);
34 34 expect(t.session.
getActiveToolNames()).not.
toContain(
"system_bundle_slot");
35 35 await extension.commands
39 39 t.session.extensionRunner.
createCommandContext(),
41 41 expect(sendUserMessage).
toHaveBeenCalledOnce();
42 + expect(extension.tools.
has(
"system_bundle_slot")).
toBe(
true);
42 43 expect(t.session.
getActiveToolNames()).
toContain(
"system_bundle_slot");
43 44 expect(t.session.systemPrompt).
toContain(
44 45 "- system_bundle_slot: Reserve an ID and path for a System bundle",
extensions/the-system/__tests__/startup.test.ts
Addednew file mode 100644 1 +import assert
from "node:assert/strict";
2 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync }
from "node:fs";
3 +import { tmpdir }
from "node:os";
4 +import path
from "node:path";
5 +import { afterEach, beforeEach, describe, it, vi }
from "vitest";
7 +const markdown
= vi.
hoisted(()
=> ({ loaded:
false }));
9 +vi.
mock(
"../markdown.ts",
async (importOriginal)
=> {
10 + markdown.loaded
= true;
11 + return importOriginal();
14 +const roots
: string[]
= [];
16 +function validSystem()
: string {
17 + const root
= mkdtempSync(path.
join(
tmpdir(),
"the-system-startup-"));
19 + mkdirSync(path.
join(
root,
".git"));
20 + mkdirSync(path.
join(
root,
".system"));
21 + for (
const directory
of [
"specs",
"phases",
"plans",
"issues",
"research"])
22 + mkdirSync(path.
join(
root,
".system", directory));
23 + for (
const name
of [
"SYSTEM.md",
"MISSION.md",
"RULES.md"])
24 + writeFileSync(path.
join(
root,
".system", name),
`# ${name}\n`,
"utf8");
26 + path.
join(
root,
".system",
"config.json"),
27 + '{"prefix":"PX","schemaVersion":0}\n',
31 + path.
join(
root,
".system",
"board.json"),
32 + '{"schemaVersion":0,"items":{}}\n',
39 + markdown.loaded
= false;
44 + for (
const root
of roots.
splice(
0))
rmSync(
root, { recursive:
true });
47 +describe(
"The System startup", ()
=> {
48 + it(
"does not load the Markdown parser for a project without a current phase",
async ()
=> {
49 + const handlers
= new Map< 51 + ((event
: { cwd
: string })
=> Promise<unknown
>)[]
53 + const { default: registerTheSystem }
= await import(
"../index.ts");
55 + events: {
emit() {} },
56 + getActiveTools: ()
=> [],
59 + handler: (event
: { cwd
: string })
=> Promise<
unknown>,
61 + handlers.
set(
event, [
...(handlers.
get(
event)
?? []), handler]);
63 + registerCommand() {},
65 + setActiveTools() {},
68 + const discover
= handlers.
get(
"resources_discover")?.[
0];
69 + assert.
ok(discover);
70 + await discover({ cwd:
validSystem() });
71 + assert.
equal(markdown.loaded,
false);
extensions/the-system/__tests__/system.test.ts
Modified104 104 describe(
"runtime core injection", ()
=> {
105 - it(
"injects the current phase after MISSION without mutating it", ()
=> {
105 + it(
"injects the current phase after MISSION without mutating it",
async ()
=> {
106 106 const project
= root();
107 107 const phase
= ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md";
135 135 phaseLabel:
"pre-v1",
137 + assert.
deepEqual(
await startupRuntimeState(project), {
140 + phaseLabel:
"pre-v1",
137 142 rmSync(path.
join(project, path.
dirname(phase)), {
extensions/the-system/__tests__/the-system.test.ts
Modified 183 183 assert.
match(prompt,
/Terse governs prose, not models/);
186 - it(
"registers /system and scoped extension tools", ()
=> {
186 + it(
"registers /system and defers scoped extension tools", ()
=> {
187 187 const commands
: string[]
= [];
188 188 const tools
: string[]
= [];
189 189 registerTheSystem({
194 194 assert.
deepEqual(commands, [
"system"]);
195 - assert.
deepEqual(tools, [
196 - "system_bundle_slot",
197 - "system_board_propose",
198 - "system_board_update",
195 + assert.
deepEqual(tools, []);
202 198 it(
"keeps scoped tools through clarification until their existing completion signal",
async ()
=> {
725 721 assert.
doesNotMatch(notices[
0]
?? "",
/\/reload/);
724 + it(
"waits for board activation before sending lifecycle prompts",
async ()
=> {
725 + const project
= temp();
726 + validSystem(project);
727 + const sent
: string[]
= [];
728 + let release
: (()
=> void)
| undefined;
729 + const activated
= new Promise<
void>((resolve)
=> {
732 + const command
= createSystemCommand(
734 + sendUserMessage: (message
: string)
=> sent.
push(message),
736 + {
activateBoardProposal: ()
=> activated },
739 + const pending
= command.
handler(
"assess", {
741 + ui: {
notify() {} },
743 + await Promise.
resolve();
744 + assert.
deepEqual(sent, []);
747 + assert.
equal(sent.
length,
1);
728 750 it(
"injects lifecycle prompts and activates bundle allocation",
async ()
=> {
729 751 const project
= temp();
730 752 validSystem(project);
extensions/the-system/board-constants.ts
Addednew file mode 100644 1 +export const BOARD_NOTE_LIMIT
= 200;
extensions/the-system/board-runtime.ts
Modified 2 2 import { StringEnum }
from "@earendil-works/pi-ai";
3 3 import { defineTool, keyHint }
from "@earendil-works/pi-coding-agent";
4 4 import { Text }
from "@earendil-works/pi-tui";
5 5 import { Type }
from "typebox";
6 +import { BOARD_NOTE_LIMIT }
from "./board-constants.ts";
6 7 import type { BoardServer }
from "./board-server.ts";
13 -}
from "./board-state.ts";
14 -import { discoverProjectRoot }
from "./documents.ts";
8 +import type { BoardProposal }
from "./board-state.ts";
18 14 loadSystemRenderer,
19 15 }
from "./loaders.js";
20 -import { loadProjectIndex }
from "./project-index.ts";
16 +import { discoverProjectRoot }
from "./project-root.ts";
21 17 import { expandableFallback }
from "./tool-rendering.ts";
23 19 const STATES
= [
"todo",
"done",
"open"]
as const;
91 87 let updateFinished
= false;
92 88 const proposals
= new Map<
string,
Map<
string,
BoardProposal>>();
93 89 const servers
= new Set<
BoardServer>();
90 + const loadBoard = async (cwd
: string)
=> {
91 + const root
= discoverProjectRoot(cwd);
92 + const [projectIndex, boardState]
= await Promise.
all([
96 + const index
= projectIndex.
loadProjectIndex(
root);
97 + const state
= boardState.
readBoardState(
root, index.
prefix);
98 + return { boardState, index, root, state };
94 100 const tool
= defineTool({
95 101 name:
"system_board_propose",
96 102 label:
"system_board_propose",
138 144 "system_board_propose is only available during /system assess or /system exec",
140 - const index
= loadProjectIndex(
root);
146 + const { index }
= await loadBoard(
root);
147 + if (
root !== proposalRoot)
149 + "system_board_propose is only available during /system assess or /system exec",
141 151 const byId
= new Map(
142 152 index.documents.
map((document)
=> [
document.metadata.
id,
document]),
225 235 "system_board_update is only available during /system exec",
227 - const index
= loadProjectIndex(
root);
228 - let state
= readBoardState(
root, index.
prefix);
237 + const loaded
= await loadBoard(
root);
238 + if (
root !== updateRoot)
240 + "system_board_update is only available during /system exec",
242 + let state
= loaded.state;
229 243 const updatedAt
= new Date().
toISOString();
230 244 const applied
: BoardProposal[]
= [];
231 245 for (
const raw
of params.items) {
232 - state
= updateBoardState(
246 + state
= loaded.boardState.
updateBoardState(
248 + loaded.
index.documents,
244 258 rationale: raw.note.
trim(),
247 - if (applied.
length > 0)
writeBoardState(
root, state);
261 + if (applied.
length > 0) loaded.boardState.
writeBoardState(
root, state);
248 262 updateFinished
= true;
249 263 const items
= [
...applied].
sort((left, right)
=> 250 264 left.
id.
localeCompare(right.
id),
270 - beginUpdate(cwd
: string) {
271 - const root
= discoverProjectRoot(cwd);
272 - const index
= loadProjectIndex(
root);
273 - readBoardState(
root, index.
prefix);
284 + async beginUpdate(cwd
: string) {
285 + const { root }
= await loadBoard(cwd);
274 286 updateRoot
= root;
275 287 updateFinished
= false;
281 293 updateRoot
= undefined;
282 294 updateFinished
= false;
284 - beginProposal(cwd: string) {
285 - const root
= discoverProjectRoot(cwd);
286 - const index
= loadProjectIndex(
root);
287 - readBoardState(
root, index.
prefix);
296 + async
beginProposal(cwd: string) {
297 + const { root }
= await loadBoard(cwd);
288 298 proposalRoot
= root;
289 299 proposalFinished
= false;
290 300 proposals.
set(
root,
new Map());
297 307 proposalFinished
= false;
299 309 async
open(cwd: string):
Promise<string
> {
300 - const index
= loadProjectIndex(cwd);
301 - readBoardState(index.root, index.prefix);
310 + const { index }
= await loadBoard(cwd);
302 311 const [{ renderSystemBoardSite }, { startBoardServer }, { openUrl }]
= 303 312 await Promise.
all([
304 313 loadSystemRenderer(),
extensions/the-system/board-state.ts
Modified 1 1 import { readFileSync, renameSync, rmSync, writeFileSync }
from "node:fs";
2 2 import path
from "node:path";
4 - type BundleDocumentRecord,
5 - type DocumentMetadata,
9 -}
from "./documents.ts";
3 +import { BOARD_NOTE_LIMIT }
from "./board-constants.ts";
4 +import type { BundleDocumentRecord, DocumentMetadata }
from "./documents.ts";
5 +import { resolveGovernedPath, SystemDocumentError }
from "./project-root.ts";
6 +import { parseDocumentId }
from "./system-config.ts";
11 8 export const BOARD_SCHEMA_VERSION
= 0;
12 9 export const BOARD_PATH
= ".system/board.json";
14 -export const BOARD_NOTE_LIMIT
= 200;
11 +export { BOARD_NOTE_LIMIT }
from "./board-constants.ts";
15 12 export type BoardItemState = "todo" | "done" | "open";
16 13 export type BoardItemSource = "manual" | "assess" | "agent";
17 14 export type BoardEntry = Readonly<{
extensions/the-system/documents.ts
Modified 7 7 } from
"./markdown.ts";
8 8 import { SystemDocumentError }
from "./project-root.ts";
13 +}
from "./system-config.ts";
10 -export { discoverProjectRoot, SystemDocumentError }
from "./project-root.ts";
16 + discoverProjectRoot,
17 + resolveGovernedPath,
18 + SystemDocumentError,
19 +}
from "./project-root.ts";
20 +export * from "./system-config.ts";
12 -export const SCHEMA_VERSION
= 0;
13 22 export const PHASE_BYTE_LIMIT
= 32 * 1024;
15 -export function resolveGovernedPath(root
: string, candidate
: string)
: string {
16 - const normalizedRoot
= path.
resolve(
root);
17 - const target
= path.
resolve(normalizedRoot, candidate);
18 - const relative
= path.
relative(normalizedRoot, target);
20 - relative
=== ".." || 21 - relative.
startsWith(
`..${path.sep}`)
|| 22 - path.
isAbsolute(relative)
24 - throw new SystemDocumentError(
25 - "path.outside-root",
26 - `Path is outside project root: ${candidate}`,
31 -export const DOCUMENT_TYPES
= [
38 -export type DocumentType = (
typeof DOCUMENT_TYPES)[
number];
39 -export type SystemConfig = Readonly<{
41 - schemaVersion
: number;
43 - currentPhase
?: string;
45 -export type InitializationSystemConfig = Readonly<{
46 - config
: SystemConfig;
47 - sourceSchemaVersion
?: number;
49 -export type ParsedDocumentId = Readonly<{
55 23 export type ResearchMetadata = Readonly<{
113 81 diagnostics: readonly Diagnostic[];
116 -const PREFIX
= /^[A-Z][A-Z0-9]{1,7}$/;
117 84 const SLUG
= "[a-z0-9]+(?:-[a-z0-9]+)*";
118 -const ID_CHARS
= "[A-Z0-9_-]{8}";
119 -const TYPE_BY_TOKEN
= new Map(
120 - DOCUMENT_TYPES.
map((type)
=> [type.
toUpperCase(), type]),
122 85 const DIRECTORY_BY_TYPE
: Readonly<
Record<
DocumentType,
string>>
= {
131 94 return DIRECTORY_BY_TYPE[type];
134 -const objectValue = (
137 -)
: Record<
string,
unknown>
=> {
138 - if (
typeof value
!== "object" || value
=== null || Array.
isArray(value))
139 - throw new SystemDocumentError(
141 - `${label} must be a JSON object`,
143 - return value
as Record<
string,
unknown>;
145 -const duplicateTopLevelKeys = (source
: string)
: string[]
=> {
146 - const keys
: string[]
= [];
147 - const duplicates
= new Set<
string>();
150 - while (index
< source.
length) {
151 - const character
= source[index];
152 - if (character
=== "{") {
157 - if (character
=== "}") {
162 - if (character
!== '"') {
166 - const start
= index
++;
167 - let escaped
= false;
168 - while (index
< source.
length) {
169 - const current
= source[index
++];
170 - if (
!escaped
&& current
=== '"')
break;
171 - escaped
= !escaped
&& current
=== "\\";
172 - if (current
!== "\\") escaped
= false;
174 - if (depth
!== 1)
continue;
175 - let cursor
= index;
176 - while (
/\s/.
test(source[cursor]
?? "")) cursor
+= 1;
177 - if (source[cursor]
!== ":")
continue;
178 - const key
= JSON.
parse(source.
slice(start, index))
as string;
179 - if (keys.
includes(key)) duplicates.
add(key);
182 - return [
...duplicates].
sort();
185 -export function parseSystemConfig(source
: string)
: SystemConfig {
186 - let parsed
: unknown;
188 - parsed
= JSON.
parse(source);
190 - throw new SystemDocumentError(
"config.invalid-json",
"Invalid config JSON");
192 - const duplicates
= duplicateTopLevelKeys(source);
193 - if (duplicates.
length)
194 - throw new SystemDocumentError(
195 - "config.duplicate-key",
196 - `Duplicate config keys: ${duplicates.join(", ")}`,
198 - const value
= objectValue(parsed,
"Config");
199 - if (value.schemaVersion
!== SCHEMA_VERSION)
200 - throw new SystemDocumentError(
202 - `Schema version ${String(value.schemaVersion)} does not match ${SCHEMA_VERSION}; run /system init`,
204 - const keys
= Object.
keys(value).
sort();
205 - const validKeys
= [
"currentPhase",
"prefix",
"schemaVersion",
"title"];
207 - !(
"prefix" in value)
|| 208 - !(
"schemaVersion" in value)
|| 209 - keys.
some((key)
=> !validKeys.
includes(key))
211 - throw new SystemDocumentError(
213 - `Expected keys prefix, schemaVersion[, title, currentPhase]; received ${keys.join(", ")}`,
215 - if (
typeof value.
prefix !== "string" || !PREFIX.
test(value.
prefix))
216 - throw new SystemDocumentError(
"config.prefix",
"Invalid project prefix");
218 - "title" in value
&& 219 - (
typeof value.
title !== "string" || value.
title.
trim()
=== "")
221 - throw new SystemDocumentError(
"config.title",
"Invalid project title");
222 - if (
"currentPhase" in value) {
223 - if (
typeof value.currentPhase
!== "string")
224 - throw new SystemDocumentError(
225 - "config.current-phase",
226 - "Current phase must be a phase ID",
228 - const current
= parseDocumentId(value.currentPhase, value.
prefix);
229 - if (current.
type !== "phase")
230 - throw new SystemDocumentError(
231 - "config.current-phase",
232 - "Current phase must be a phase ID",
236 - prefix: value.
prefix,
237 - schemaVersion: value.schemaVersion
as number,
238 - ...(
typeof value.
title === "string" ? { title: value.
title }
: {}),
239 - ...(
typeof value.currentPhase
=== "string" 240 - ? { currentPhase: value.currentPhase }
245 -export function systemConfigForInitialization(
247 -)
: InitializationSystemConfig {
249 - return { config:
parseSystemConfig(source) };
252 - !(error
instanceof SystemDocumentError)
|| 253 - error.
code !== "config.version" 256 - const parsed
= objectValue(
JSON.
parse(source),
"Config");
258 - duplicateTopLevelKeys(source).
length > 0 || 259 - typeof parsed.schemaVersion
!== "number" || 260 - !Number.
isInteger(parsed.schemaVersion)
263 - const config
= parseSystemConfig(
265 - prefix: parsed.
prefix,
266 - schemaVersion: SCHEMA_VERSION,
267 - ...(
"title" in parsed
? { title: parsed.
title }
: {}),
268 - ...(
"currentPhase" in parsed
269 - ? { currentPhase: parsed.currentPhase }
273 - return { config, sourceSchemaVersion: parsed.schemaVersion };
277 -export function parseDocumentId(
279 - expectedPrefix
?: string,
280 -)
: ParsedDocumentId {
281 - const match
= new RegExp(
282 - `^([A-Z][A-Z0-9]{1,7})-(SPEC|PHASE|PLAN|ISSUE|RESEARCH)-(${ID_CHARS})$`,
285 - throw new SystemDocumentError(
287 - `Invalid document ID: ${source}`,
289 - if (expectedPrefix
&& match[
1]
!== expectedPrefix)
290 - throw new SystemDocumentError(
292 - `Document ID must use prefix ${expectedPrefix}: ${source}`,
296 - prefix: match[
1]
as string,
297 - type: TYPE_BY_TOKEN.
get(match[
2])
as DocumentType,
298 - token: match[
3]
as string,
302 97 export function validateDocumentPath(
303 98 documentPath
: string,
304 99 metadata
: DocumentMetadata,
extensions/the-system/index.ts
Modified 4 4 import path
from "node:path";
7 7 type ExtensionContext,
9 9 }
from "@earendil-works/pi-coding-agent";
10 -import { createBoardRuntime }
from "./board-runtime.js";
11 -import { createBundleSlotTool }
from "./bundle-slot-tool.js";
12 10 import { loadStartupNotice, loadSystem, loadSystemCommand }
from "./loaders.js";
13 11 import { systemArgumentCompletions }
from "./system-command-meta.js";
13 +type BoardRuntime = ReturnType<
14 + typeof import(
"./board-runtime.js")[
"createBoardRuntime"]
16 +type BundleSlotTool = ReturnType<
17 + typeof import(
"./bundle-slot-tool.js")[
"createBundleSlotTool"]
20 +interface OperationalRuntime {
21 + board
: BoardRuntime;
22 + bundleSlot
: BundleSlotTool;
25 +const OPERATIONAL_TOOL_NAMES
= new Set([
26 + "system_bundle_slot",
27 + "system_board_propose",
28 + "system_board_update",
15 31 function isStaleContextError(error
: unknown)
: boolean {
17 33 error
instanceof Error && 24 40 let boardProposalRunActive
= false;
25 41 let boardUpdateRunActive
= false;
26 42 let bundleMigrationRunActive
= false;
27 - const bundleSlot
= createBundleSlotTool(()
=> {
28 - bundleSlotUsed
= true;
30 - const board
= createBoardRuntime();
45 + let operational
: OperationalRuntime | undefined;
46 + let operationalPromise
: Promise<
OperationalRuntime>
| undefined;
47 + const loadOperationalRuntime = ()
: Promise<
OperationalRuntime>
=> {
48 + if (operational)
return Promise.
resolve(operational);
49 + if (operationalPromise)
return operationalPromise;
50 + operationalPromise
= Promise.
all([
51 + import(
"./board-runtime.js"),
52 + import(
"./bundle-slot-tool.js"),
53 + ]).
then(([{ createBoardRuntime }, { createBundleSlotTool }])
=> {
55 + board:
createBoardRuntime(),
56 + bundleSlot:
createBundleSlotTool(()
=> {
57 + bundleSlotUsed
= true;
60 + pi.
registerTool(runtime.bundleSlot);
61 + pi.
registerTool(runtime.board.tool);
62 + pi.
registerTool(runtime.board.updateTool);
64 + pi.
getActiveTools().
filter((name)
=> !OPERATIONAL_TOOL_NAMES.
has(name)),
66 + operational
= runtime;
69 + return operationalPromise;
31 71 const activateBundleSlot = ()
=> {
72 + const bundleSlot
= operational?.bundleSlot;
73 + if (
!bundleSlot)
throw new Error(
"The System tools are not loaded");
32 74 const active
= pi.
getActiveTools();
33 75 if (
!active.
includes(bundleSlot.
name))
34 76 pi.
setActiveTools([
...active, bundleSlot.
name]);
36 78 bundleSlotUsed
= false;
38 80 const deactivateBundleSlot = ()
=> {
81 + const bundleSlot
= operational?.bundleSlot;
39 82 const active
= pi.
getActiveTools();
40 - if (active.
includes(bundleSlot.
name))
83 + if (bundleSlot
&& active.
includes(bundleSlot.
name))
41 84 pi.
setActiveTools(active.
filter((name)
=> name
!== bundleSlot.
name));
42 85 bundleSlotRunActive
= false;
43 86 bundleSlotUsed
= false;
45 - const activateBoardProposal = (cwd
: string)
=> {
46 - board.
beginProposal(cwd);
88 + const activateBoardProposal = async (cwd
: string)
=> {
89 + const board
= operational?.board;
90 + if (
!board)
throw new Error(
"The System tools are not loaded");
91 + await board.
beginProposal(cwd);
47 92 const active
= pi.
getActiveTools();
48 93 if (
!active.
includes(board.tool.
name))
49 94 pi.
setActiveTools([
...active, board.tool.
name]);
50 95 boardProposalRunActive
= true;
52 97 const deactivateBoardProposal = ()
=> {
98 + const board
= operational?.board;
53 99 const active
= pi.
getActiveTools();
54 - if (active.
includes(board.tool.
name))
100 + if (board
&& active.
includes(board.tool.
name))
55 101 pi.
setActiveTools(active.
filter((name)
=> name
!== board.tool.
name));
56 - board.
endProposal();
102 + board?.
endProposal();
57 103 boardProposalRunActive
= false;
59 - const activateBoardUpdate = (cwd
: string)
=> {
60 - board.
beginUpdate(cwd);
105 + const activateBoardUpdate = async (cwd
: string)
=> {
106 + const board
= operational?.board;
107 + if (
!board)
throw new Error(
"The System tools are not loaded");
108 + await board.
beginUpdate(cwd);
61 109 const active
= pi.
getActiveTools();
62 110 if (
!active.
includes(board.updateTool.
name))
63 111 pi.
setActiveTools([
...active, board.updateTool.
name]);
64 112 boardUpdateRunActive
= true;
66 114 const deactivateBoardUpdate = ()
=> {
115 + const board
= operational?.board;
67 116 const active
= pi.
getActiveTools();
68 - if (active.
includes(board.updateTool.
name))
117 + if (board
&& active.
includes(board.updateTool.
name))
69 118 pi.
setActiveTools(
70 119 active.
filter((name)
=> name
!== board.updateTool.
name),
121 + board?.
endUpdate();
73 122 boardUpdateRunActive
= false;
75 124 const activateBundleMigration = ()
=> {
158 207 boardProposalRunActive
= false;
159 208 boardUpdateRunActive
= false;
160 209 bundleMigrationRunActive
= false;
210 + operational?.board.
shutdown();
163 212 pi.
on(
"before_agent_start",
async (event, ctx)
=> {
164 213 void syncRuntimeIndicator(ctx, generation).
catch((error)
=> 173 222 notifyFailure(ctx,
"The System status refresh failed", error),
175 224 if (bundleSlotRunActive
&& bundleSlotUsed)
deactivateBundleSlot();
176 - if (boardProposalRunActive
&& board.
proposalComplete())
225 + if (boardProposalRunActive
&& operational?.board.
proposalComplete())
177 226 deactivateBoardProposal();
178 - if (boardUpdateRunActive
&& board.
updateComplete())
deactivateBoardUpdate();
227 + if (boardUpdateRunActive
&& operational?.board.
updateComplete())
228 + deactivateBoardUpdate();
179 229 bundleMigrationRunActive
= false;
181 231 pi.
on(
"tool_call",
async (event, ctx)
=> {
196 246 return result
? { block:
true, reason: result.reason }
: undefined;
199 - pi.
registerTool(bundleSlot);
200 - pi.
registerTool(board.tool);
201 - pi.
registerTool(board.updateTool);
202 249 pi.
registerCommand(
"system", {
203 250 description:
"The System project governance",
204 251 getArgumentCompletions: systemArgumentCompletions,
205 252 handler:
async (args, ctx)
=> {
206 - const { createSystemCommand }
= await loadSystemCommand();
253 + const [{ createSystemCommand }, runtime]
= await Promise.
all([
254 + loadSystemCommand(),
255 + loadOperationalRuntime(),
207 257 await createSystemCommand(pi, {
209 259 activateBundleTool: activateBundleSlot,
210 260 activateBoardProposal,
211 261 activateBoardUpdate,
212 262 activateBundleMigration,
213 - openBoard: board.open,
263 + openBoard: runtime.board.open,
214 264 }).
handler(args, ctx);
extensions/the-system/init.ts
Modified 9 9 } from
"./board-state.ts";
11 11 discoverProjectRoot,
13 12 resolveGovernedPath,
15 13 SystemDocumentError,
14 +}
from "./project-root.ts";
16 18 systemConfigForInitialization,
17 -}
from "./documents.ts";
19 +}
from "./system-config.ts";
19 21 export type InitializationInspection = Readonly<{
extensions/the-system/loaders.ts
Modified14 14 export const loadBoardServer
= lazy(()
=> import(
"./board-server.ts"));
15 15 export const loadOpenBrowser
= lazy(()
=> import(
"./open-browser.ts"));
16 16 export const loadBundleSlot
= lazy(()
=> import(
"./bundle-slot.js"));
17 +export const loadBoardState
= lazy(()
=> import(
"./board-state.ts"));
18 +export const loadProjectIndex
= lazy(()
=> import(
"./project-index.ts"));
extensions/the-system/project-root.ts
Modified 28 +export function resolveGovernedPath(root
: string, candidate
: string)
: string {
29 + const normalizedRoot
= path.
resolve(
root);
30 + const target
= path.
resolve(normalizedRoot, candidate);
31 + const relative
= path.
relative(normalizedRoot, target);
33 + relative
=== ".." || 34 + relative.
startsWith(
`..${path.sep}`)
|| 35 + path.
isAbsolute(relative)
37 + throw new SystemDocumentError(
38 + "path.outside-root",
39 + `Path is outside project root: ${candidate}`,
28 44 export function discoverProjectRoot(
30 46 markerExists
= existsSync,
extensions/the-system/startup-notice.ts
Modified 1 -import { existsSync }
from "node:fs";
2 -import path
from "node:path";
3 -import { loadSystem }
from "./loaders.js";
4 -import { discoverProjectRoot }
from "./project-root.ts";
5 -import type { SystemRuntimeState }
from "./system.ts";
2 + readStartupRuntimeState,
3 + type StartupRuntimeState,
4 +}
from "./startup-state.ts";
7 6 export async function startupRuntimeState(
9 -)
: Promise<
SystemRuntimeState> {
12 - root = discoverProjectRoot(cwd);
14 - return { active:
false };
16 - if (
!existsSync(path.
join(
root,
".system")))
return { active:
false };
17 - const { runtimeState }
= await loadSystem();
18 - return runtimeState(cwd);
8 +)
: Promise<
StartupRuntimeState> {
9 + return readStartupRuntimeState(cwd);
21 12 export async function startupRuntimeNotice(
extensions/the-system/startup-state.ts
Addednew file mode 100644 1 +import { existsSync }
from "node:fs";
2 +import path
from "node:path";
3 +import { inspectInitialization }
from "./init.ts";
4 +import { loadSystem }
from "./loaders.js";
5 +import { discoverProjectRoot }
from "./project-root.ts";
6 +import { SCHEMA_VERSION }
from "./system-config.ts";
8 +export type StartupRuntimeState = Readonly<{
11 + phaseLabel
?: string;
15 +const INCOMPLETE_NOTICE
= 16 + "The System is incomplete or invalid; run /system init before governed work.";
17 +const SCHEMA_NOTICE
= `The System schema does not match ${SCHEMA_VERSION}; run /system init to update it.`;
22 +export async function readStartupRuntimeState(
24 +)
: Promise<
StartupRuntimeState> {
27 + root = discoverProjectRoot(cwd);
29 + return { active:
false };
31 + if (
!existsSync(path.
join(
root,
".system")))
return { active:
false };
33 + const inspection
= inspectInitialization(
root);
34 + if (inspection.rewrites.
length > 0)
35 + return { active:
true, notice: SCHEMA_NOTICE };
36 + if (inspection.currentPhase) {
37 + const { runtimeState }
= await loadSystem();
38 + return runtimeState(cwd);
41 + inspection.creates.
length > 0 || 42 + inspection.cores.
some(({ state })
=> state
=== "missing");
45 + ...(inspection.
prefix ? { prefix: inspection.
prefix }
: {}),
46 + ...(incomplete
? { notice: INCOMPLETE_NOTICE }
: {}),
49 + return { active:
true, notice: INCOMPLETE_NOTICE };
extensions/the-system/system-command.ts
Modified 44 44 type SystemCommandHooks = Readonly<{
45 45 beginLifecycle?: ()
=> void;
46 46 activateBundleTool?: ()
=> void;
47 - activateBoardProposal?: (cwd
: string)
=> void;
48 - activateBoardUpdate?: (cwd
: string)
=> void;
47 + activateBoardProposal?: (cwd
: string)
=> void | Promise<
void>;
48 + activateBoardUpdate?: (cwd
: string)
=> void | Promise<
void>;
49 49 activateBundleMigration?: ()
=> void;
50 50 openBoard?: (cwd
: string)
=> Promise<
string>;
126 126 if (BUNDLE_SUBCOMMANDS.
has(parsed.subcommand))
127 127 hooks.
activateBundleTool?.();
128 128 if (parsed.subcommand
=== "assess")
129 - hooks.
activateBoardProposal?.(ctx.cwd);
130 - if (parsed.subcommand
=== "exec") hooks.
activateBoardUpdate?.(ctx.cwd);
129 + await hooks.
activateBoardProposal?.(ctx.cwd);
130 + if (parsed.subcommand
=== "exec")
131 + await hooks.
activateBoardUpdate?.(ctx.cwd);
131 132 pi.
sendUserMessage(
133 134 parsed.subcommand,
extensions/the-system/system-config.ts
Addednew file mode 100644 1 +import { SystemDocumentError }
from "./project-root.ts";
3 +export const SCHEMA_VERSION
= 0;
5 +export const DOCUMENT_TYPES
= [
12 +export type DocumentType = (
typeof DOCUMENT_TYPES)[
number];
13 +export type SystemConfig = Readonly<{
15 + schemaVersion
: number;
17 + currentPhase
?: string;
19 +export type InitializationSystemConfig = Readonly<{
20 + config
: SystemConfig;
21 + sourceSchemaVersion
?: number;
23 +export type ParsedDocumentId = Readonly<{
30 +const PREFIX
= /^[A-Z][A-Z0-9]{1,7}$/;
31 +const ID_CHARS
= "[A-Z0-9_-]{8}";
32 +const TYPE_BY_TOKEN
= new Map(
33 + DOCUMENT_TYPES.
map((type)
=> [type.
toUpperCase(), type]),
36 +const objectValue = (
39 +)
: Record<
string,
unknown>
=> {
40 + if (
typeof value
!== "object" || value
=== null || Array.
isArray(value))
41 + throw new SystemDocumentError(
43 + `${label} must be a JSON object`,
45 + return value
as Record<
string,
unknown>;
48 +const duplicateTopLevelKeys = (source
: string)
: string[]
=> {
49 + const keys
: string[]
= [];
50 + const duplicates
= new Set<
string>();
53 + while (index
< source.
length) {
54 + const character
= source[index];
55 + if (character
=== "{") {
60 + if (character
=== "}") {
65 + if (character
!== '"') {
69 + const start
= index
++;
70 + let escaped
= false;
71 + while (index
< source.
length) {
72 + const current
= source[index
++];
73 + if (
!escaped
&& current
=== '"')
break;
74 + escaped
= !escaped
&& current
=== "\\";
75 + if (current
!== "\\") escaped
= false;
77 + if (depth
!== 1)
continue;
79 + while (
/\s/.
test(source[cursor]
?? "")) cursor
+= 1;
80 + if (source[cursor]
!== ":")
continue;
81 + const key
= JSON.
parse(source.
slice(start, index))
as string;
82 + if (keys.
includes(key)) duplicates.
add(key);
85 + return [
...duplicates].
sort();
88 +export function parseSystemConfig(source
: string)
: SystemConfig {
89 + let parsed
: unknown;
91 + parsed
= JSON.
parse(source);
93 + throw new SystemDocumentError(
"config.invalid-json",
"Invalid config JSON");
95 + const duplicates
= duplicateTopLevelKeys(source);
96 + if (duplicates.
length)
97 + throw new SystemDocumentError(
98 + "config.duplicate-key",
99 + `Duplicate config keys: ${duplicates.join(", ")}`,
101 + const value
= objectValue(parsed,
"Config");
102 + if (value.schemaVersion
!== SCHEMA_VERSION)
103 + throw new SystemDocumentError(
105 + `Schema version ${String(value.schemaVersion)} does not match ${SCHEMA_VERSION}; run /system init`,
107 + const keys
= Object.
keys(value).
sort();
108 + const validKeys
= [
"currentPhase",
"prefix",
"schemaVersion",
"title"];
110 + !(
"prefix" in value)
|| 111 + !(
"schemaVersion" in value)
|| 112 + keys.
some((key)
=> !validKeys.
includes(key))
114 + throw new SystemDocumentError(
116 + `Expected keys prefix, schemaVersion[, title, currentPhase]; received ${keys.join(", ")}`,
118 + if (
typeof value.
prefix !== "string" || !PREFIX.
test(value.
prefix))
119 + throw new SystemDocumentError(
"config.prefix",
"Invalid project prefix");
121 + "title" in value
&& 122 + (
typeof value.
title !== "string" || value.
title.
trim()
=== "")
124 + throw new SystemDocumentError(
"config.title",
"Invalid project title");
125 + if (
"currentPhase" in value) {
126 + if (
typeof value.currentPhase
!== "string")
127 + throw new SystemDocumentError(
128 + "config.current-phase",
129 + "Current phase must be a phase ID",
131 + const current
= parseDocumentId(value.currentPhase, value.
prefix);
132 + if (current.
type !== "phase")
133 + throw new SystemDocumentError(
134 + "config.current-phase",
135 + "Current phase must be a phase ID",
139 + prefix: value.
prefix,
140 + schemaVersion: value.schemaVersion
as number,
141 + ...(
typeof value.
title === "string" ? { title: value.
title }
: {}),
142 + ...(
typeof value.currentPhase
=== "string" 143 + ? { currentPhase: value.currentPhase }
148 +export function systemConfigForInitialization(
150 +)
: InitializationSystemConfig {
152 + return { config:
parseSystemConfig(source) };
155 + !(error
instanceof SystemDocumentError)
|| 156 + error.
code !== "config.version" 159 + const parsed
= objectValue(
JSON.
parse(source),
"Config");
161 + duplicateTopLevelKeys(source).
length > 0 || 162 + typeof parsed.schemaVersion
!== "number" || 163 + !Number.
isInteger(parsed.schemaVersion)
166 + const config
= parseSystemConfig(
168 + prefix: parsed.
prefix,
169 + schemaVersion: SCHEMA_VERSION,
170 + ...(
"title" in parsed
? { title: parsed.
title }
: {}),
171 + ...(
"currentPhase" in parsed
172 + ? { currentPhase: parsed.currentPhase }
176 + return { config, sourceSchemaVersion: parsed.schemaVersion };
180 +export function parseDocumentId(
182 + expectedPrefix
?: string,
183 +)
: ParsedDocumentId {
184 + const match
= new RegExp(
185 + `^([A-Z][A-Z0-9]{1,7})-(SPEC|PHASE|PLAN|ISSUE|RESEARCH)-(${ID_CHARS})$`,
188 + throw new SystemDocumentError(
190 + `Invalid document ID: ${source}`,
192 + if (expectedPrefix
&& match[
1]
!== expectedPrefix)
193 + throw new SystemDocumentError(
195 + `Document ID must use prefix ${expectedPrefix}: ${source}`,
199 + prefix: match[
1]
as string,
200 + type: TYPE_BY_TOKEN.
get(match[
2])
as DocumentType,
201 + token: match[
3]
as string,