@davidorex/pi-context 0.26.0
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/CHANGELOG.md +23 -0
- package/README.md +195 -0
- package/dist/block-api.d.ts +328 -0
- package/dist/block-api.d.ts.map +1 -0
- package/dist/block-api.js +1167 -0
- package/dist/block-api.js.map +1 -0
- package/dist/block-validation.d.ts +33 -0
- package/dist/block-validation.d.ts.map +1 -0
- package/dist/block-validation.js +213 -0
- package/dist/block-validation.js.map +1 -0
- package/dist/context-dir.d.ts +93 -0
- package/dist/context-dir.d.ts.map +1 -0
- package/dist/context-dir.js +224 -0
- package/dist/context-dir.js.map +1 -0
- package/dist/context-sdk.d.ts +428 -0
- package/dist/context-sdk.d.ts.map +1 -0
- package/dist/context-sdk.js +1327 -0
- package/dist/context-sdk.js.map +1 -0
- package/dist/context.d.ts +497 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +1060 -0
- package/dist/context.js.map +1 -0
- package/dist/dispatch-context.d.ts +112 -0
- package/dist/dispatch-context.d.ts.map +1 -0
- package/dist/dispatch-context.js +119 -0
- package/dist/dispatch-context.js.map +1 -0
- package/dist/execution-context.d.ts +138 -0
- package/dist/execution-context.d.ts.map +1 -0
- package/dist/execution-context.js +151 -0
- package/dist/execution-context.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1655 -0
- package/dist/index.js.map +1 -0
- package/dist/lens-validator.d.ts +50 -0
- package/dist/lens-validator.d.ts.map +1 -0
- package/dist/lens-validator.js +46 -0
- package/dist/lens-validator.js.map +1 -0
- package/dist/lens-view.d.ts +75 -0
- package/dist/lens-view.d.ts.map +1 -0
- package/dist/lens-view.js +253 -0
- package/dist/lens-view.js.map +1 -0
- package/dist/rename-canonical-id.d.ts +64 -0
- package/dist/rename-canonical-id.d.ts.map +1 -0
- package/dist/rename-canonical-id.js +378 -0
- package/dist/rename-canonical-id.js.map +1 -0
- package/dist/roadmap-plan.d.ts +186 -0
- package/dist/roadmap-plan.d.ts.map +1 -0
- package/dist/roadmap-plan.js +534 -0
- package/dist/roadmap-plan.js.map +1 -0
- package/dist/samples-catalog.d.ts +48 -0
- package/dist/samples-catalog.d.ts.map +1 -0
- package/dist/samples-catalog.js +128 -0
- package/dist/samples-catalog.js.map +1 -0
- package/dist/schema-migrations.d.ts +82 -0
- package/dist/schema-migrations.d.ts.map +1 -0
- package/dist/schema-migrations.js +106 -0
- package/dist/schema-migrations.js.map +1 -0
- package/dist/schema-validator.d.ts +76 -0
- package/dist/schema-validator.d.ts.map +1 -0
- package/dist/schema-validator.js +219 -0
- package/dist/schema-validator.js.map +1 -0
- package/dist/schema-write.d.ts +122 -0
- package/dist/schema-write.d.ts.map +1 -0
- package/dist/schema-write.js +210 -0
- package/dist/schema-write.js.map +1 -0
- package/dist/status-vocab.d.ts +60 -0
- package/dist/status-vocab.d.ts.map +1 -0
- package/dist/status-vocab.js +109 -0
- package/dist/status-vocab.js.map +1 -0
- package/dist/test-helpers.d.ts +12 -0
- package/dist/test-helpers.d.ts.map +1 -0
- package/dist/test-helpers.js +28 -0
- package/dist/test-helpers.js.map +1 -0
- package/dist/topo.d.ts +19 -0
- package/dist/topo.d.ts.map +1 -0
- package/dist/topo.js +99 -0
- package/dist/topo.js.map +1 -0
- package/dist/update-check.d.ts +6 -0
- package/dist/update-check.d.ts.map +1 -0
- package/dist/update-check.js +82 -0
- package/dist/update-check.js.map +1 -0
- package/package.json +115 -0
- package/samples/blocks/context-contracts.json +3 -0
- package/samples/blocks/conventions.json +3 -0
- package/samples/blocks/decisions.json +3 -0
- package/samples/blocks/features.json +3 -0
- package/samples/blocks/framework-gaps.json +3 -0
- package/samples/blocks/issues.json +3 -0
- package/samples/blocks/layer-plans.json +3 -0
- package/samples/blocks/phase.json +3 -0
- package/samples/blocks/rationale.json +3 -0
- package/samples/blocks/requirements.json +3 -0
- package/samples/blocks/research.json +3 -0
- package/samples/blocks/spec-reviews.json +3 -0
- package/samples/blocks/story.json +3 -0
- package/samples/blocks/tasks.json +3 -0
- package/samples/blocks/verification.json +3 -0
- package/samples/conception.json +467 -0
- package/samples/schemas/context-contracts.schema.json +89 -0
- package/samples/schemas/conventions.schema.json +34 -0
- package/samples/schemas/decisions.schema.json +87 -0
- package/samples/schemas/features.schema.json +53 -0
- package/samples/schemas/framework-gaps.schema.json +64 -0
- package/samples/schemas/issues.schema.json +39 -0
- package/samples/schemas/layer-plans.schema.json +92 -0
- package/samples/schemas/phase.schema.json +118 -0
- package/samples/schemas/rationale.schema.json +24 -0
- package/samples/schemas/requirements.schema.json +34 -0
- package/samples/schemas/research.schema.json +134 -0
- package/samples/schemas/spec-reviews.schema.json +62 -0
- package/samples/schemas/story.schema.json +73 -0
- package/samples/schemas/tasks.schema.json +34 -0
- package/samples/schemas/verification.schema.json +37 -0
- package/schemas/bootstrap.schema.json +24 -0
- package/schemas/config.schema.json +193 -0
- package/schemas/layer.schema.json +9 -0
- package/schemas/priority.schema.json +9 -0
- package/schemas/relations.schema.json +31 -0
- package/schemas/severity.schema.json +9 -0
- package/schemas/source.schema.json +9 -0
- package/schemas/status.schema.json +9 -0
- package/schemas/verification-method.schema.json +9 -0
- package/skill-narrative.md +130 -0
- package/skills/pi-context/SKILL.md +684 -0
- package/skills/pi-context/references/bundled-resources.md +47 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1655 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extension entry point for pi-context — registers block tools and the
|
|
3
|
+
* /context command for project state management.
|
|
4
|
+
*/
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { truncateHead } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { Type } from "typebox";
|
|
10
|
+
import { appendToBlock, appendToNestedArray, nextId, readBlock, readBlockDir, removeFromBlock, removeFromNestedArray, updateItemInBlock, updateNestedArrayItem, writeBlock, } from "./block-api.js";
|
|
11
|
+
import { adoptConception, amendConfigEntry, appendRelation, installedBlockDestPath, installedSchemaDestPath, loadConfig, loadContext, } from "./context.js";
|
|
12
|
+
import { BootstrapNotFoundError, resolveContextDir, SCHEMAS_DIR, schemaPath, schemasDir, tryResolveContextDir, writeBootstrapPointer, } from "./context-dir.js";
|
|
13
|
+
import { completeTask, contextState, currentState, deriveBootstrapState, filterBlockItems, findAppendableBlocks, joinBlocks, readBlockItem, readBlockPage, resolveItemById, resolveItemsByIds, validateContext, } from "./context-sdk.js";
|
|
14
|
+
import { gatherExecutionContext } from "./execution-context.js";
|
|
15
|
+
import { buildCurationSuggestions, edgesForLensByName, findReferencesInRepo, loadLensView, renderLensView, validateContextRelations, walkAncestorsByLens, walkLensDescendants, } from "./lens-view.js";
|
|
16
|
+
import { renameCanonicalId } from "./rename-canonical-id.js";
|
|
17
|
+
import { listRoadmaps, loadRoadmap, renderRoadmap, validateRoadmaps } from "./roadmap-plan.js";
|
|
18
|
+
import { samplesCatalog } from "./samples-catalog.js";
|
|
19
|
+
import { readSchema, writeSchemaChecked } from "./schema-write.js";
|
|
20
|
+
import { checkForUpdates } from "./update-check.js";
|
|
21
|
+
// ── Command handlers ────────────────────────────────────────────────────────
|
|
22
|
+
/**
|
|
23
|
+
* /context status — derives project state from authoritative sources and
|
|
24
|
+
* sends it as a structured message. Available to human, LLM, and system.
|
|
25
|
+
*/
|
|
26
|
+
function handleStatus(ctx, pi) {
|
|
27
|
+
const state = contextState(ctx.cwd);
|
|
28
|
+
const lines = [];
|
|
29
|
+
lines.push(`## Project Status`);
|
|
30
|
+
lines.push("");
|
|
31
|
+
lines.push(`**Source:** ${state.sourceFiles} files, ${state.sourceLines} lines | **Tests:** ${state.testCount}`);
|
|
32
|
+
lines.push(`**Schemas:** ${state.schemas} | **Blocks:** ${state.blocks}`);
|
|
33
|
+
lines.push(`**Phases:** ${state.phases.total} (current: ${state.phases.current})`);
|
|
34
|
+
lines.push(`**Commit:** ${state.lastCommit} (${state.lastCommitMessage})`);
|
|
35
|
+
// Block summaries
|
|
36
|
+
const summaryEntries = Object.entries(state.blockSummaries);
|
|
37
|
+
if (summaryEntries.length > 0) {
|
|
38
|
+
lines.push("");
|
|
39
|
+
lines.push("**Blocks:**");
|
|
40
|
+
for (const [name, summary] of summaryEntries) {
|
|
41
|
+
const arrayEntries = Object.entries(summary.arrays);
|
|
42
|
+
if (arrayEntries.length === 1) {
|
|
43
|
+
// Single-array block — compact display
|
|
44
|
+
const [, arr] = arrayEntries[0];
|
|
45
|
+
let detail = `${arr.total} items`;
|
|
46
|
+
if (arr.byStatus) {
|
|
47
|
+
detail += ` (${Object.entries(arr.byStatus)
|
|
48
|
+
.map(([s, n]) => `${s}: ${n}`)
|
|
49
|
+
.join(", ")})`;
|
|
50
|
+
}
|
|
51
|
+
lines.push(`- **${name}:** ${detail}`);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
// Multi-array block — show each array
|
|
55
|
+
lines.push(`- **${name}:**`);
|
|
56
|
+
for (const [key, arr] of arrayEntries) {
|
|
57
|
+
lines.push(` ${key}: ${arr.total}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Planning lifecycle
|
|
63
|
+
if (state.requirements) {
|
|
64
|
+
const r = state.requirements;
|
|
65
|
+
const statusParts = Object.entries(r.byStatus)
|
|
66
|
+
.map(([s, n]) => `${s}: ${n}`)
|
|
67
|
+
.join(", ");
|
|
68
|
+
lines.push(`- **Requirements:** ${r.total} (${statusParts})`);
|
|
69
|
+
}
|
|
70
|
+
if (state.tasks) {
|
|
71
|
+
const t = state.tasks;
|
|
72
|
+
const statusParts = Object.entries(t.byStatus)
|
|
73
|
+
.map(([s, n]) => `${s}: ${n}`)
|
|
74
|
+
.join(", ");
|
|
75
|
+
lines.push(`- **Tasks:** ${t.total} (${statusParts})`);
|
|
76
|
+
}
|
|
77
|
+
if (state.domain) {
|
|
78
|
+
lines.push(`- **Domain:** ${state.domain.total} entries`);
|
|
79
|
+
}
|
|
80
|
+
if (state.verifications) {
|
|
81
|
+
const v = state.verifications;
|
|
82
|
+
lines.push(`- **Verifications:** ${v.total} (${v.passed} passed, ${v.failed} failed)`);
|
|
83
|
+
}
|
|
84
|
+
if (state.hasHandoff) {
|
|
85
|
+
lines.push(`- **Handoff:** active (.project/handoff.json)`);
|
|
86
|
+
}
|
|
87
|
+
if (state.recentCommits.length > 0) {
|
|
88
|
+
lines.push("");
|
|
89
|
+
lines.push("**Recent:**");
|
|
90
|
+
for (const c of state.recentCommits)
|
|
91
|
+
lines.push(` ${c}`);
|
|
92
|
+
}
|
|
93
|
+
pi.sendMessage({
|
|
94
|
+
customType: "context-status",
|
|
95
|
+
content: lines.join("\n"),
|
|
96
|
+
display: true,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* /context add-work — discovers appendable blocks from schemas,
|
|
101
|
+
* returns a structured instruction for main context to extract
|
|
102
|
+
* items from the conversation into typed JSON blocks.
|
|
103
|
+
*/
|
|
104
|
+
async function handleAddWork(args, ctx, pi) {
|
|
105
|
+
const workflowDir = tryResolveContextDir(ctx.cwd);
|
|
106
|
+
if (workflowDir === null) {
|
|
107
|
+
ctx.ui.notify("No .pi-context.json bootstrap pointer found. Run /context init first to bootstrap the substrate.", "error");
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const schemasDirPath = schemasDir(ctx.cwd);
|
|
111
|
+
if (!fs.existsSync(schemasDirPath)) {
|
|
112
|
+
// Reachable only when the bootstrap pointer is present but the substrate
|
|
113
|
+
// dir's schemas/ subdirectory is absent (e.g. partial init). Display
|
|
114
|
+
// string references the resolved schemas path rather than the literal
|
|
115
|
+
// `.project/schemas/` so non-default substrate dirs surface accurately.
|
|
116
|
+
ctx.ui.notify(`No schemas directory found at ${schemasDirPath}.`, "warning");
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const appendableBlocks = findAppendableBlocks(ctx.cwd);
|
|
120
|
+
const blockInfo = [];
|
|
121
|
+
for (const { block, arrayKey, schemaPath } of appendableBlocks) {
|
|
122
|
+
const dataPath = path.join(workflowDir, `${block}.json`);
|
|
123
|
+
const schema = fs.readFileSync(schemaPath, "utf8");
|
|
124
|
+
let currentCount = "";
|
|
125
|
+
try {
|
|
126
|
+
const data = readBlock(ctx.cwd, block);
|
|
127
|
+
const arr = data[arrayKey];
|
|
128
|
+
if (Array.isArray(arr))
|
|
129
|
+
currentCount = ` (${arr.length} existing)`;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
/* block file doesn't exist or invalid — skip count */
|
|
133
|
+
}
|
|
134
|
+
blockInfo.push(`### ${block} (array: ${arrayKey})${currentCount}\nSchema: ${schemaPath}\nData: ${dataPath}\n\`\`\`json\n${schema}\n\`\`\``);
|
|
135
|
+
}
|
|
136
|
+
const inputSection = args.trim() ? `**Input:**\n${args.trim()}\n\n` : "";
|
|
137
|
+
const blockNames = appendableBlocks.map((b) => b.block).join(", ");
|
|
138
|
+
const instruction = `## Add Work to Project Blocks
|
|
139
|
+
|
|
140
|
+
${inputSection}Read the recent conversation and extract relevant items into the project's typed JSON blocks. Each block has a schema — conform to it exactly.
|
|
141
|
+
|
|
142
|
+
**Appendable blocks:** ${blockNames}
|
|
143
|
+
|
|
144
|
+
**Blocks to update:**
|
|
145
|
+
|
|
146
|
+
${blockInfo.join("\n\n")}
|
|
147
|
+
|
|
148
|
+
**Process:**
|
|
149
|
+
1. Read the conversation for items that belong in the appendable blocks
|
|
150
|
+
2. Read the current block files to check for duplicates
|
|
151
|
+
3. Append new entries — do NOT replace existing content
|
|
152
|
+
4. Schema validation happens automatically when you use append-block-item
|
|
153
|
+
|
|
154
|
+
**Rules:**
|
|
155
|
+
- IDs must be kebab-case and unique within their block
|
|
156
|
+
- Use \`source: "human"\` for content from this conversation
|
|
157
|
+
- Architecture changes and phase creation are separate processes — do not attempt them here`;
|
|
158
|
+
pi.sendMessage({
|
|
159
|
+
customType: "context-add-work",
|
|
160
|
+
content: instruction,
|
|
161
|
+
display: false,
|
|
162
|
+
}, {
|
|
163
|
+
triggerTurn: true,
|
|
164
|
+
deliverAs: "followUp",
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Initialize the substrate dir: write the bootstrap pointer and scaffold the
|
|
169
|
+
* substrate + schemas directories ONLY. No schema/block assets are copied here
|
|
170
|
+
* (FGAP-067 / DEC-0011: init must not impose a catalog). Run accept-all to adopt
|
|
171
|
+
* a config + install to materialize the declared assets. Idempotent: skips
|
|
172
|
+
* directories that already exist. Shared by the /context init command handler
|
|
173
|
+
* and the context-init tool.
|
|
174
|
+
*/
|
|
175
|
+
function initProject(cwd, contextDir) {
|
|
176
|
+
// FIRST action — write the `.pi-context.json` bootstrap pointer carrying
|
|
177
|
+
// the caller-supplied `contextDir` (required per DEC-0015) so every
|
|
178
|
+
// subsequent path-builder call (projectDir / schemasDir) resolves through
|
|
179
|
+
// the freshly-written pointer rather than throwing BootstrapNotFoundError.
|
|
180
|
+
// writeBootstrapPointer is idempotent (atomic tmp+rename) so re-running
|
|
181
|
+
// initProject after a prior init does not corrupt the pointer.
|
|
182
|
+
if (!fs.existsSync(path.join(cwd, ".pi-context.json")))
|
|
183
|
+
writeBootstrapPointer(cwd, contextDir);
|
|
184
|
+
const projectDirPath = resolveContextDir(cwd);
|
|
185
|
+
const schemasDirPath = schemasDir(cwd);
|
|
186
|
+
const created = [];
|
|
187
|
+
const skipped = [];
|
|
188
|
+
for (const dir of [projectDirPath, schemasDirPath]) {
|
|
189
|
+
if (!fs.existsSync(dir)) {
|
|
190
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
191
|
+
created.push(`${path.relative(cwd, dir)}/`);
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
skipped.push(`${path.relative(cwd, dir)}/`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return { created, skipped };
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* /context install opt-in mechanism (DEC-0011). Reads config.installed_schemas
|
|
201
|
+
* and config.installed_blocks, copies declared assets from the package
|
|
202
|
+
* samples catalog (samples/, keyed by conception.json's block_kinds) into the
|
|
203
|
+
* project's substrate root + schemas dir.
|
|
204
|
+
*
|
|
205
|
+
* - Default behavior is skip-if-exists. With overwrite=true, replaces the
|
|
206
|
+
* destination file and reports as "updated" rather than "installed".
|
|
207
|
+
* - Sources missing from the samples catalog are reported as "notFound".
|
|
208
|
+
* - Empty install lists are not an error — the result is a clean no-op.
|
|
209
|
+
*/
|
|
210
|
+
export function installContext(cwd, options = {}) {
|
|
211
|
+
const result = { installed: [], updated: [], skipped: [], notFound: [] };
|
|
212
|
+
const overwrite = options.overwrite === true;
|
|
213
|
+
const destRoot = tryResolveContextDir(cwd);
|
|
214
|
+
if (destRoot === null) {
|
|
215
|
+
result.error = "No .pi-context.json bootstrap pointer found. Run /context init first to bootstrap the substrate.";
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
const config = loadConfig(cwd);
|
|
219
|
+
if (!config) {
|
|
220
|
+
result.error = "No config.json found in substrate dir — run /context init first.";
|
|
221
|
+
return result;
|
|
222
|
+
}
|
|
223
|
+
// destRoot is resolver-aware via tryResolveContextDir(cwd) — it already
|
|
224
|
+
// cascades through resolveContextDir under the hood (context-dir.ts).
|
|
225
|
+
// SCHEMAS_DIR is composed as a bare segment off that
|
|
226
|
+
// resolver-aware root; this is intentional and DEC-0015-compliant
|
|
227
|
+
// (no hardcoded substrate-dir literal here — `schemas/` is a substrate
|
|
228
|
+
// internal-layout constant, not the substrate-dir name itself).
|
|
229
|
+
const schemasRoot = path.join(destRoot, SCHEMAS_DIR);
|
|
230
|
+
if (!fs.existsSync(schemasRoot))
|
|
231
|
+
fs.mkdirSync(schemasRoot, { recursive: true });
|
|
232
|
+
// lazy fileURLToPath idiom (FGAP-088): import.meta.dirname is undefined under
|
|
233
|
+
// tsx's CJS-interop dist-load; import.meta.url is not. Read the conception once for
|
|
234
|
+
// the canonical_id→paths map so install resolves sources by the same
|
|
235
|
+
// block_kind declarations the accept-all conception ships (DEC-0037/0038).
|
|
236
|
+
const samplesRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "samples");
|
|
237
|
+
const conception = JSON.parse(fs.readFileSync(path.join(samplesRoot, "conception.json"), "utf-8"));
|
|
238
|
+
const byId = new Map();
|
|
239
|
+
for (const bk of conception.block_kinds ?? []) {
|
|
240
|
+
byId.set(bk.canonical_id, { schema_path: bk.schema_path, data_path: bk.data_path });
|
|
241
|
+
}
|
|
242
|
+
for (const name of config.installed_schemas ?? []) {
|
|
243
|
+
const relDest = `${SCHEMAS_DIR}/${name}.schema.json`;
|
|
244
|
+
const kind = byId.get(name);
|
|
245
|
+
if (!kind) {
|
|
246
|
+
result.notFound.push(relDest);
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const sourceFile = path.join(samplesRoot, kind.schema_path);
|
|
250
|
+
// Single source of the dest derivation, shared with findUnmaterializedAssets
|
|
251
|
+
// (installedSchemaDestPath(destRoot, name) === path.join(schemasRoot, name+".schema.json")).
|
|
252
|
+
const destFile = installedSchemaDestPath(destRoot, name);
|
|
253
|
+
if (!fs.existsSync(sourceFile)) {
|
|
254
|
+
result.notFound.push(relDest);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
const destExists = fs.existsSync(destFile);
|
|
258
|
+
if (destExists && !overwrite) {
|
|
259
|
+
result.skipped.push(relDest);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
fs.copyFileSync(sourceFile, destFile);
|
|
263
|
+
(destExists ? result.updated : result.installed).push(relDest);
|
|
264
|
+
}
|
|
265
|
+
for (const name of config.installed_blocks ?? []) {
|
|
266
|
+
const relDest = `${name}.json`;
|
|
267
|
+
const kind = byId.get(name);
|
|
268
|
+
if (!kind) {
|
|
269
|
+
result.notFound.push(relDest);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
const sourceFile = path.join(samplesRoot, "blocks", kind.data_path);
|
|
273
|
+
const destFile = installedBlockDestPath(destRoot, name);
|
|
274
|
+
if (!fs.existsSync(sourceFile)) {
|
|
275
|
+
result.notFound.push(relDest);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
const destExists = fs.existsSync(destFile);
|
|
279
|
+
if (destExists && !overwrite) {
|
|
280
|
+
result.skipped.push(relDest);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
fs.copyFileSync(sourceFile, destFile);
|
|
284
|
+
(destExists ? result.updated : result.installed).push(relDest);
|
|
285
|
+
}
|
|
286
|
+
return result;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* /context init — scaffold the substrate dir (bootstrap pointer + substrate +
|
|
290
|
+
* schemas directories only; no asset copying). Run accept-all + install to
|
|
291
|
+
* populate. Idempotent: skips directories that already exist.
|
|
292
|
+
*/
|
|
293
|
+
function handleInit(args, ctx) {
|
|
294
|
+
const contextDir = args.trim().split(/\s+/)[0];
|
|
295
|
+
if (!contextDir) {
|
|
296
|
+
ctx.ui.notify("/context init requires a substrate dir name (e.g. '/context init .project' or '/context init .context'). Per DEC-0015, no default.", "error");
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const { created, skipped } = initProject(ctx.cwd, contextDir);
|
|
300
|
+
const lines = [];
|
|
301
|
+
lines.push(`Project initialized`);
|
|
302
|
+
lines.push("");
|
|
303
|
+
if (created.length > 0) {
|
|
304
|
+
lines.push(`Created (${created.length}): ${created.join(", ")}`);
|
|
305
|
+
}
|
|
306
|
+
if (skipped.length > 0) {
|
|
307
|
+
lines.push(`Skipped (${skipped.length}, already exist): ${skipped.join(", ")}`);
|
|
308
|
+
}
|
|
309
|
+
if (created.length === 0 && skipped.length > 0) {
|
|
310
|
+
lines.push("Project already initialized — nothing to do.");
|
|
311
|
+
}
|
|
312
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* /context accept-all — adopt the canonical packaged conception
|
|
316
|
+
* (samples/conception.json) as this substrate's config.json. Writes config only
|
|
317
|
+
* (no asset materialization — run /context install after). Idempotent: never
|
|
318
|
+
* overwrites an existing config. Requires the substrate to be initialized first
|
|
319
|
+
* (a bootstrap pointer must exist).
|
|
320
|
+
*/
|
|
321
|
+
function handleAcceptAll(_args, ctx) {
|
|
322
|
+
let r;
|
|
323
|
+
try {
|
|
324
|
+
r = adoptConception(ctx.cwd);
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
if (err instanceof BootstrapNotFoundError) {
|
|
328
|
+
ctx.ui.notify("Run /context init <dir> first", "error");
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
throw err;
|
|
332
|
+
}
|
|
333
|
+
if (!r.adopted) {
|
|
334
|
+
ctx.ui.notify("config.json already present — not overwritten.", "info");
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
ctx.ui.notify(`Adopted canonical config (root: ${r.root}, ${r.schemaCount} schemas / ${r.blockCount} blocks declared). Run /context install to materialize them.`, "info");
|
|
338
|
+
}
|
|
339
|
+
// ── Extension factory ───────────────────────────────────────────────────────
|
|
340
|
+
const extension = (pi) => {
|
|
341
|
+
// ── Update check on session start (non-blocking) ───────────────────
|
|
342
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
343
|
+
checkForUpdates((msg, level) => ctx.ui.notify(msg, level)).catch(() => { });
|
|
344
|
+
});
|
|
345
|
+
// ── Tool: append-block-item ─────────────────────────────────────────
|
|
346
|
+
pi.registerTool({
|
|
347
|
+
name: "append-block-item",
|
|
348
|
+
label: "Append Block Item",
|
|
349
|
+
description: "Append an item to an array in a project block file. Schema validation is automatic. Set autoId:true to allocate the next id from the block's id pattern when the item has no id.",
|
|
350
|
+
promptSnippet: "Append items to project blocks (issues, decisions, or any user-defined block)",
|
|
351
|
+
parameters: Type.Object({
|
|
352
|
+
block: Type.String({ description: "Block name (e.g., 'issues', 'decisions')" }),
|
|
353
|
+
arrayKey: Type.String({ description: "Array key in the block (e.g., 'issues', 'decisions')" }),
|
|
354
|
+
item: Type.Unknown({ description: "Item object to append — must conform to block schema" }),
|
|
355
|
+
autoId: Type.Optional(Type.Boolean({
|
|
356
|
+
description: "When true and the item has no id, allocate the next id from the block's id pattern",
|
|
357
|
+
})),
|
|
358
|
+
}),
|
|
359
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
360
|
+
// Type.Unknown() params may arrive as JSON strings — parse if needed
|
|
361
|
+
if (typeof params.item === "string") {
|
|
362
|
+
try {
|
|
363
|
+
params.item = JSON.parse(params.item);
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
throw new Error(`item parameter must be a JSON object, got unparseable string`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
// Auto-id allocation (FGAP-084 dual-surface twin of file-block-item --auto-id)
|
|
370
|
+
if (params.autoId && params.item && typeof params.item === "object" && !params.item.id) {
|
|
371
|
+
params.item.id = nextId(ctx.cwd, params.block);
|
|
372
|
+
}
|
|
373
|
+
// Duplicate check if item has an id field
|
|
374
|
+
if (params.item && typeof params.item === "object" && "id" in params.item) {
|
|
375
|
+
try {
|
|
376
|
+
const data = readBlock(ctx.cwd, params.block);
|
|
377
|
+
const arr = data[params.arrayKey];
|
|
378
|
+
if (Array.isArray(arr) && arr.some((i) => i.id === params.item.id)) {
|
|
379
|
+
throw new Error(`Item '${params.item.id}' already exists in ${params.block}.${params.arrayKey}`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
catch (e) {
|
|
383
|
+
/* Re-throw duplicate errors; swallow block-not-found */
|
|
384
|
+
if (e instanceof Error && e.message.includes("already exists"))
|
|
385
|
+
throw e;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
appendToBlock(ctx.cwd, params.block, params.arrayKey, params.item);
|
|
389
|
+
const id = params.item?.id ? ` '${params.item.id}'` : "";
|
|
390
|
+
return {
|
|
391
|
+
details: undefined,
|
|
392
|
+
content: [{ type: "text", text: `Appended item${id} to ${params.block}.${params.arrayKey}` }],
|
|
393
|
+
};
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
// ── Tool: update-block-item ───────────────────────────────────────────
|
|
397
|
+
pi.registerTool({
|
|
398
|
+
name: "update-block-item",
|
|
399
|
+
label: "Update Block Item",
|
|
400
|
+
description: "Update fields on an item in a project block array. Finds by predicate field match.",
|
|
401
|
+
promptSnippet: "Update items in project blocks — change status, add details, mark resolved",
|
|
402
|
+
parameters: Type.Object({
|
|
403
|
+
block: Type.String({ description: "Block name (e.g., 'issues', 'decisions')" }),
|
|
404
|
+
arrayKey: Type.String({ description: "Array key in the block" }),
|
|
405
|
+
match: Type.Record(Type.String(), Type.Unknown(), { description: "Fields to match (e.g., { id: 'issue-123' })" }),
|
|
406
|
+
updates: Type.Record(Type.String(), Type.Unknown(), {
|
|
407
|
+
description: "Fields to update (e.g., { status: 'resolved' })",
|
|
408
|
+
}),
|
|
409
|
+
}),
|
|
410
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
411
|
+
if (Object.keys(params.updates).length === 0) {
|
|
412
|
+
throw new Error("No fields to update — updates parameter is empty");
|
|
413
|
+
}
|
|
414
|
+
const matchEntries = Object.entries(params.match);
|
|
415
|
+
updateItemInBlock(ctx.cwd, params.block, params.arrayKey, (item) => matchEntries.every(([k, v]) => item[k] === v), params.updates);
|
|
416
|
+
const matchDesc = matchEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
417
|
+
return {
|
|
418
|
+
details: undefined,
|
|
419
|
+
content: [
|
|
420
|
+
{
|
|
421
|
+
type: "text",
|
|
422
|
+
text: `Updated item (${matchDesc}) in ${params.block}.${params.arrayKey}: ${Object.keys(params.updates).join(", ")}`,
|
|
423
|
+
},
|
|
424
|
+
],
|
|
425
|
+
};
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
// ── Tool: append-relation ─────────────────────────────────────────────
|
|
429
|
+
pi.registerTool({
|
|
430
|
+
name: "append-relation",
|
|
431
|
+
label: "Append Relation",
|
|
432
|
+
description: "Append a closure-table relation (edge: parent, child, relation_type, optional ordinal) to relations.json. " +
|
|
433
|
+
"Shape is AJV-validated; an exact-duplicate edge (same parent+child+relation_type) is a no-op. Reference " +
|
|
434
|
+
"integrity (endpoints resolve, relation_type registered, no cycle) is NOT checked here — run context-validate " +
|
|
435
|
+
"after. Creates relations.json if absent.",
|
|
436
|
+
promptSnippet: "Create a relation/edge between two items (parent→child under a relation_type)",
|
|
437
|
+
parameters: Type.Object({
|
|
438
|
+
parent: Type.String({ description: "Canonical id (or lens bin name) of the parent endpoint" }),
|
|
439
|
+
child: Type.String({ description: "Canonical id of the child endpoint" }),
|
|
440
|
+
relation_type: Type.String({
|
|
441
|
+
description: "Registered relation_type canonical_id / hierarchy edge type / lens id",
|
|
442
|
+
}),
|
|
443
|
+
ordinal: Type.Optional(Type.Integer({ description: "Optional sibling-ordering within (parent, relation_type)" })),
|
|
444
|
+
}),
|
|
445
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
446
|
+
const edge = {
|
|
447
|
+
parent: params.parent,
|
|
448
|
+
child: params.child,
|
|
449
|
+
relation_type: params.relation_type,
|
|
450
|
+
...(params.ordinal !== undefined ? { ordinal: params.ordinal } : {}),
|
|
451
|
+
};
|
|
452
|
+
const { appended } = appendRelation(ctx.cwd, edge);
|
|
453
|
+
const ordinalNote = params.ordinal !== undefined ? ` (ordinal ${params.ordinal})` : "";
|
|
454
|
+
const text = appended
|
|
455
|
+
? `Appended relation ${edge.parent} -[${edge.relation_type}]-> ${edge.child}${ordinalNote}`
|
|
456
|
+
: `Relation ${edge.parent} -[${edge.relation_type}]-> ${edge.child} already exists — no-op`;
|
|
457
|
+
return {
|
|
458
|
+
details: undefined,
|
|
459
|
+
content: [{ type: "text", text }],
|
|
460
|
+
};
|
|
461
|
+
},
|
|
462
|
+
});
|
|
463
|
+
// ── Tool: append-block-nested-item ────────────────────────────────────
|
|
464
|
+
pi.registerTool({
|
|
465
|
+
name: "append-block-nested-item",
|
|
466
|
+
label: "Append Block Nested Item",
|
|
467
|
+
description: "Append an item to a nested array on a parent-array item in a project block. Schema validation is automatic.",
|
|
468
|
+
promptSnippet: "Append items to nested arrays inside parent items (e.g., findings inside a review)",
|
|
469
|
+
parameters: Type.Object({
|
|
470
|
+
block: Type.String({ description: "Block name (e.g., 'spec-reviews')" }),
|
|
471
|
+
arrayKey: Type.String({ description: "Parent array key (e.g., 'reviews')" }),
|
|
472
|
+
match: Type.Record(Type.String(), Type.Unknown(), {
|
|
473
|
+
description: "Fields to match the parent item (e.g., { id: 'REVIEW-001' })",
|
|
474
|
+
}),
|
|
475
|
+
nestedKey: Type.String({ description: "Nested array key on the matched parent (e.g., 'findings')" }),
|
|
476
|
+
item: Type.Unknown({ description: "Item object to append to the nested array — must conform to schema" }),
|
|
477
|
+
}),
|
|
478
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
479
|
+
if (typeof params.item === "string") {
|
|
480
|
+
try {
|
|
481
|
+
params.item = JSON.parse(params.item);
|
|
482
|
+
}
|
|
483
|
+
catch {
|
|
484
|
+
throw new Error(`item parameter must be a JSON object, got unparseable string`);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const matchEntries = Object.entries(params.match);
|
|
488
|
+
const predicate = (i) => matchEntries.every(([k, v]) => i[k] === v);
|
|
489
|
+
appendToNestedArray(ctx.cwd, params.block, params.arrayKey, predicate, params.nestedKey, params.item);
|
|
490
|
+
const matchDesc = matchEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
491
|
+
const id = params.item?.id ? ` '${params.item.id}'` : "";
|
|
492
|
+
return {
|
|
493
|
+
details: undefined,
|
|
494
|
+
content: [
|
|
495
|
+
{
|
|
496
|
+
type: "text",
|
|
497
|
+
text: `Appended item${id} to ${params.block}.${params.arrayKey}[${matchDesc}].${params.nestedKey}`,
|
|
498
|
+
},
|
|
499
|
+
],
|
|
500
|
+
};
|
|
501
|
+
},
|
|
502
|
+
});
|
|
503
|
+
// ── Tool: update-block-nested-item ────────────────────────────────────
|
|
504
|
+
pi.registerTool({
|
|
505
|
+
name: "update-block-nested-item",
|
|
506
|
+
label: "Update Block Nested Item",
|
|
507
|
+
description: "Update fields on a nested-array item inside a parent-array item in a project block. Finds parent and nested by predicate field match. Throws on parent or nested miss (mirrors update-block-item semantics).",
|
|
508
|
+
promptSnippet: "Update items inside nested arrays — change finding state, mark resolved",
|
|
509
|
+
parameters: Type.Object({
|
|
510
|
+
block: Type.String({ description: "Block name (e.g., 'spec-reviews')" }),
|
|
511
|
+
arrayKey: Type.String({ description: "Parent array key (e.g., 'reviews')" }),
|
|
512
|
+
match: Type.Record(Type.String(), Type.Unknown(), {
|
|
513
|
+
description: "Fields to match the parent item (e.g., { id: 'REVIEW-001' })",
|
|
514
|
+
}),
|
|
515
|
+
nestedKey: Type.String({ description: "Nested array key on the matched parent (e.g., 'findings')" }),
|
|
516
|
+
nestedMatch: Type.Record(Type.String(), Type.Unknown(), {
|
|
517
|
+
description: "Fields to match the nested item (e.g., { id: 'F-001' })",
|
|
518
|
+
}),
|
|
519
|
+
updates: Type.Record(Type.String(), Type.Unknown(), {
|
|
520
|
+
description: "Fields to update on the nested item (e.g., { state: 'resolved' })",
|
|
521
|
+
}),
|
|
522
|
+
}),
|
|
523
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
524
|
+
if (Object.keys(params.updates).length === 0) {
|
|
525
|
+
throw new Error("No fields to update — updates parameter is empty");
|
|
526
|
+
}
|
|
527
|
+
const parentEntries = Object.entries(params.match);
|
|
528
|
+
const nestedEntries = Object.entries(params.nestedMatch);
|
|
529
|
+
const parentPred = (i) => parentEntries.every(([k, v]) => i[k] === v);
|
|
530
|
+
const nestedPred = (i) => nestedEntries.every(([k, v]) => i[k] === v);
|
|
531
|
+
updateNestedArrayItem(ctx.cwd, params.block, params.arrayKey, parentPred, params.nestedKey, nestedPred, params.updates);
|
|
532
|
+
const parentDesc = parentEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
533
|
+
const nestedDesc = nestedEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
534
|
+
return {
|
|
535
|
+
details: undefined,
|
|
536
|
+
content: [
|
|
537
|
+
{
|
|
538
|
+
type: "text",
|
|
539
|
+
text: `Updated nested item (${nestedDesc}) in ${params.block}.${params.arrayKey}[${parentDesc}].${params.nestedKey}: ${Object.keys(params.updates).join(", ")}`,
|
|
540
|
+
},
|
|
541
|
+
],
|
|
542
|
+
};
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
// ── Tool: remove-block-item ───────────────────────────────────────────
|
|
546
|
+
pi.registerTool({
|
|
547
|
+
name: "remove-block-item",
|
|
548
|
+
label: "Remove Block Item",
|
|
549
|
+
description: "Remove items matching a predicate from a top-level array in a project block. Idempotent — returns { removed: 0 } on no match without throwing. Schema validation runs after removal.",
|
|
550
|
+
promptSnippet: "Remove items from project blocks — prune retracted issues, dedupe entries",
|
|
551
|
+
parameters: Type.Object({
|
|
552
|
+
block: Type.String({ description: "Block name (e.g., 'issues')" }),
|
|
553
|
+
arrayKey: Type.String({ description: "Top-level array key (e.g., 'issues')" }),
|
|
554
|
+
match: Type.Record(Type.String(), Type.Unknown(), { description: "Fields to match (e.g., { id: 'issue-123' })" }),
|
|
555
|
+
}),
|
|
556
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
557
|
+
const matchEntries = Object.entries(params.match);
|
|
558
|
+
const predicate = (i) => matchEntries.every(([k, v]) => i[k] === v);
|
|
559
|
+
const result = removeFromBlock(ctx.cwd, params.block, params.arrayKey, predicate);
|
|
560
|
+
const matchDesc = matchEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
561
|
+
return {
|
|
562
|
+
details: undefined,
|
|
563
|
+
content: [
|
|
564
|
+
{
|
|
565
|
+
type: "text",
|
|
566
|
+
text: `Removed ${result.removed} item(s) matching (${matchDesc}) from ${params.block}.${params.arrayKey}`,
|
|
567
|
+
},
|
|
568
|
+
],
|
|
569
|
+
};
|
|
570
|
+
},
|
|
571
|
+
});
|
|
572
|
+
// ── Tool: remove-block-nested-item ────────────────────────────────────
|
|
573
|
+
pi.registerTool({
|
|
574
|
+
name: "remove-block-nested-item",
|
|
575
|
+
label: "Remove Block Nested Item",
|
|
576
|
+
description: "Remove items matching a predicate from a nested array on a parent-array item in a project block. Throws on parent miss; returns { removed: 0 } on nested miss without throwing.",
|
|
577
|
+
promptSnippet: "Remove nested items — drop rejected findings, retract nested references",
|
|
578
|
+
parameters: Type.Object({
|
|
579
|
+
block: Type.String({ description: "Block name (e.g., 'spec-reviews')" }),
|
|
580
|
+
arrayKey: Type.String({ description: "Parent array key (e.g., 'reviews')" }),
|
|
581
|
+
match: Type.Record(Type.String(), Type.Unknown(), {
|
|
582
|
+
description: "Fields to match the parent item (e.g., { id: 'REVIEW-001' })",
|
|
583
|
+
}),
|
|
584
|
+
nestedKey: Type.String({ description: "Nested array key on the matched parent (e.g., 'findings')" }),
|
|
585
|
+
nestedMatch: Type.Record(Type.String(), Type.Unknown(), {
|
|
586
|
+
description: "Fields to match the nested items to remove (e.g., { id: 'F-001' })",
|
|
587
|
+
}),
|
|
588
|
+
}),
|
|
589
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
590
|
+
const parentEntries = Object.entries(params.match);
|
|
591
|
+
const nestedEntries = Object.entries(params.nestedMatch);
|
|
592
|
+
const parentPred = (i) => parentEntries.every(([k, v]) => i[k] === v);
|
|
593
|
+
const nestedPred = (i) => nestedEntries.every(([k, v]) => i[k] === v);
|
|
594
|
+
const result = removeFromNestedArray(ctx.cwd, params.block, params.arrayKey, parentPred, params.nestedKey, nestedPred);
|
|
595
|
+
const parentDesc = parentEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
596
|
+
const nestedDesc = nestedEntries.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
597
|
+
return {
|
|
598
|
+
details: undefined,
|
|
599
|
+
content: [
|
|
600
|
+
{
|
|
601
|
+
type: "text",
|
|
602
|
+
text: `Removed ${result.removed} nested item(s) matching (${nestedDesc}) from ${params.block}.${params.arrayKey}[${parentDesc}].${params.nestedKey}`,
|
|
603
|
+
},
|
|
604
|
+
],
|
|
605
|
+
};
|
|
606
|
+
},
|
|
607
|
+
});
|
|
608
|
+
// ── Tool: read-block-dir ──────────────────────────────────────────────
|
|
609
|
+
pi.registerTool({
|
|
610
|
+
name: "read-block-dir",
|
|
611
|
+
label: "Read Block Dir",
|
|
612
|
+
description: "Enumerate and parse all .json files in a .project/<subdir>/ directory, returned as a sorted array. Missing directories return [].",
|
|
613
|
+
promptSnippet: "Enumerate project block subdirectories (phases, schemas, etc.) as parsed JSON",
|
|
614
|
+
parameters: Type.Object({
|
|
615
|
+
subdir: Type.String({ description: "Subdirectory under .project/ (e.g., 'phases', 'schemas')" }),
|
|
616
|
+
}),
|
|
617
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
618
|
+
const result = readBlockDir(ctx.cwd, params.subdir);
|
|
619
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
620
|
+
const truncated = truncateHead(jsonStr);
|
|
621
|
+
let text = truncated.content;
|
|
622
|
+
if (truncated.truncated) {
|
|
623
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit. Full content: .project/${params.subdir}/]`;
|
|
624
|
+
}
|
|
625
|
+
return {
|
|
626
|
+
details: undefined,
|
|
627
|
+
content: [{ type: "text", text }],
|
|
628
|
+
};
|
|
629
|
+
},
|
|
630
|
+
});
|
|
631
|
+
// ── Tool: read-block ────────────────────────────────────────────────────
|
|
632
|
+
pi.registerTool({
|
|
633
|
+
name: "read-block",
|
|
634
|
+
label: "Read Block",
|
|
635
|
+
description: "Read a project block file as structured JSON.",
|
|
636
|
+
promptSnippet: "Read a project block as structured JSON",
|
|
637
|
+
parameters: Type.Object({
|
|
638
|
+
block: Type.String({ description: "Block name (e.g., 'issues', 'tasks', 'requirements')" }),
|
|
639
|
+
}),
|
|
640
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
641
|
+
const result = readBlock(ctx.cwd, params.block);
|
|
642
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
643
|
+
const truncated = truncateHead(jsonStr);
|
|
644
|
+
let text = truncated.content;
|
|
645
|
+
if (truncated.truncated) {
|
|
646
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit. Full content: .project/${params.block}.json]`;
|
|
647
|
+
}
|
|
648
|
+
return {
|
|
649
|
+
details: undefined,
|
|
650
|
+
content: [{ type: "text", text }],
|
|
651
|
+
};
|
|
652
|
+
},
|
|
653
|
+
});
|
|
654
|
+
// ── Tool: write-block ───────────────────────────────────────────────────
|
|
655
|
+
pi.registerTool({
|
|
656
|
+
name: "write-block",
|
|
657
|
+
label: "Write Block",
|
|
658
|
+
description: "Write or replace an entire project block with schema validation.",
|
|
659
|
+
promptSnippet: "Write or replace a project block with schema validation",
|
|
660
|
+
parameters: Type.Object({
|
|
661
|
+
block: Type.String({ description: "Block name (e.g., 'project', 'architecture')" }),
|
|
662
|
+
data: Type.Unknown({ description: "Complete block data — must conform to block schema" }),
|
|
663
|
+
}),
|
|
664
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
665
|
+
const data = typeof params.data === "string" ? JSON.parse(params.data) : params.data;
|
|
666
|
+
writeBlock(ctx.cwd, params.block, data);
|
|
667
|
+
return {
|
|
668
|
+
details: undefined,
|
|
669
|
+
content: [{ type: "text", text: `Wrote block '${params.block}' successfully` }],
|
|
670
|
+
};
|
|
671
|
+
},
|
|
672
|
+
});
|
|
673
|
+
// ── Tool: context-status ────────────────────────────────────────────────
|
|
674
|
+
pi.registerTool({
|
|
675
|
+
name: "context-status",
|
|
676
|
+
label: "Context Status",
|
|
677
|
+
description: "Get derived context state — source metrics, block summaries, planning lifecycle status.",
|
|
678
|
+
promptSnippet: "Get context state — source metrics, block summaries, planning lifecycle status",
|
|
679
|
+
parameters: Type.Object({}),
|
|
680
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
681
|
+
const result = contextState(ctx.cwd);
|
|
682
|
+
return {
|
|
683
|
+
details: undefined,
|
|
684
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
685
|
+
};
|
|
686
|
+
},
|
|
687
|
+
});
|
|
688
|
+
// ── Tool: context-validate ──────────────────────────────────────────────
|
|
689
|
+
pi.registerTool({
|
|
690
|
+
name: "context-validate",
|
|
691
|
+
label: "Context Validate",
|
|
692
|
+
description: "Validate cross-block referential integrity — check that IDs referenced across blocks exist.",
|
|
693
|
+
promptSnippet: "Validate cross-block referential integrity",
|
|
694
|
+
parameters: Type.Object({}),
|
|
695
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
696
|
+
const result = validateContext(ctx.cwd);
|
|
697
|
+
return {
|
|
698
|
+
details: undefined,
|
|
699
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
700
|
+
};
|
|
701
|
+
},
|
|
702
|
+
});
|
|
703
|
+
// ── Tool: read-config ───────────────────────────────────────────────────
|
|
704
|
+
pi.registerTool({
|
|
705
|
+
name: "read-config",
|
|
706
|
+
label: "Read Config",
|
|
707
|
+
description: "Read the substrate config.json as structured JSON — vocabulary, lenses, relation_types, status_buckets, display_strings, layers, block_kinds, installed_schemas, installed_blocks.",
|
|
708
|
+
promptSnippet: "Read project config — vocabulary, lenses, relation_types, status_buckets",
|
|
709
|
+
parameters: Type.Object({}),
|
|
710
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
711
|
+
const config = loadConfig(ctx.cwd);
|
|
712
|
+
const root = tryResolveContextDir(ctx.cwd);
|
|
713
|
+
const configPath = root === null ? null : path.join(root, "config.json");
|
|
714
|
+
const result = { config, configPath };
|
|
715
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
716
|
+
const truncated = truncateHead(jsonStr);
|
|
717
|
+
let text = truncated.content;
|
|
718
|
+
if (truncated.truncated) {
|
|
719
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit. Full content: ${configPath}]`;
|
|
720
|
+
}
|
|
721
|
+
return {
|
|
722
|
+
details: undefined,
|
|
723
|
+
content: [{ type: "text", text }],
|
|
724
|
+
};
|
|
725
|
+
},
|
|
726
|
+
});
|
|
727
|
+
// ── Tool: list-tools ──────────────────────────────────────────────────────
|
|
728
|
+
pi.registerTool({
|
|
729
|
+
name: "list-tools",
|
|
730
|
+
label: "List Tools",
|
|
731
|
+
description: "List every tool bound into the current Pi session — name, description, parameter JSON-schema, and source extension — plus which tools are currently active. Self-introspection of the agent's own tool surface (all loaded extensions + builtins).",
|
|
732
|
+
promptSnippet: "Discover available tools — names, params, descriptions, active set",
|
|
733
|
+
parameters: Type.Object({}),
|
|
734
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
|
|
735
|
+
// Closes over the factory `pi` (the introspection surface lives on
|
|
736
|
+
// ExtensionAPI, not ExtensionContext) — `_ctx` is unused.
|
|
737
|
+
const all = pi.getAllTools();
|
|
738
|
+
const active = pi.getActiveTools();
|
|
739
|
+
const result = { tools: all, active, total: all.length, activeCount: active.length };
|
|
740
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
741
|
+
const truncated = truncateHead(jsonStr);
|
|
742
|
+
let text = truncated.content;
|
|
743
|
+
if (truncated.truncated) {
|
|
744
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
745
|
+
}
|
|
746
|
+
return {
|
|
747
|
+
details: undefined,
|
|
748
|
+
content: [{ type: "text", text }],
|
|
749
|
+
};
|
|
750
|
+
},
|
|
751
|
+
});
|
|
752
|
+
// ── Tool: read-samples-catalog ────────────────────────────────────────────
|
|
753
|
+
pi.registerTool({
|
|
754
|
+
name: "read-samples-catalog",
|
|
755
|
+
label: "Read Samples Catalog",
|
|
756
|
+
description: "Enumerate installable sample block kinds (DEC-0037 packaged view): per kind — title, description, item shape, applicable relation_types (as source/target), invariants, lenses — plus top-level relation_type/lens/invariant/layer/status_bucket registries. Package-intrinsic: reads the extension's bundled samples catalog, independent of any project. Optional `kind` returns one packaged kind.",
|
|
757
|
+
promptSnippet: "Discover installable sample block kinds — title, shape, relation_types, invariants, lenses",
|
|
758
|
+
parameters: Type.Object({
|
|
759
|
+
kind: Type.Optional(Type.String({ description: "Filter to one block_kind canonical_id (e.g. 'tasks')" })),
|
|
760
|
+
}),
|
|
761
|
+
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
762
|
+
// Package-intrinsic: the catalog reads the extension's bundled samples
|
|
763
|
+
// directory, not the project substrate — `_ctx` (and its cwd) is unused.
|
|
764
|
+
const catalog = samplesCatalog(params.kind ? { kind: params.kind } : undefined);
|
|
765
|
+
const jsonStr = JSON.stringify(catalog, null, 2);
|
|
766
|
+
const truncated = truncateHead(jsonStr);
|
|
767
|
+
let text = truncated.content;
|
|
768
|
+
if (truncated.truncated) {
|
|
769
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
770
|
+
}
|
|
771
|
+
return {
|
|
772
|
+
details: undefined,
|
|
773
|
+
content: [{ type: "text", text }],
|
|
774
|
+
};
|
|
775
|
+
},
|
|
776
|
+
});
|
|
777
|
+
// ── Tool: context-current-state ───────────────────────────────────────────
|
|
778
|
+
pi.registerTool({
|
|
779
|
+
name: "context-current-state",
|
|
780
|
+
label: "Context Current State",
|
|
781
|
+
description: "Derive 'where are we + what's next' purely from .project substrate — focus, in-flight tasks, ranked atomic-next actions (open framework-gaps then unblocked planned tasks), and blocked tasks. No writes; nothing hand-stored.",
|
|
782
|
+
promptSnippet: "Derive current project state — focus, in-flight, next actions, blocked",
|
|
783
|
+
parameters: Type.Object({}),
|
|
784
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
785
|
+
const state = currentState(ctx.cwd);
|
|
786
|
+
return {
|
|
787
|
+
details: undefined,
|
|
788
|
+
content: [{ type: "text", text: JSON.stringify(state, null, 2) }],
|
|
789
|
+
};
|
|
790
|
+
},
|
|
791
|
+
});
|
|
792
|
+
// ── Tool: context-bootstrap-state ─────────────────────────────────────────
|
|
793
|
+
pi.registerTool({
|
|
794
|
+
name: "context-bootstrap-state",
|
|
795
|
+
label: "Context Bootstrap State",
|
|
796
|
+
description: "Derive the substrate bootstrap state for the cwd, purely from the filesystem (DEC-0040): 'no-pointer' | 'no-config' | 'not-installed' | 'ready', plus the resolved contextDir and any declared-but-unmaterialized installed assets. Unlike every other tool, this NEVER throws on an un-bootstrapped substrate — it returns 'no-pointer' so you can detect a fresh substrate and tell the human to run /context start (bootstrap is human-only). No writes.",
|
|
797
|
+
promptSnippet: "Derive substrate bootstrap state — no-pointer | no-config | not-installed | ready (never throws pre-bootstrap)",
|
|
798
|
+
parameters: Type.Object({}),
|
|
799
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
800
|
+
const status = deriveBootstrapState(ctx.cwd);
|
|
801
|
+
return {
|
|
802
|
+
details: undefined,
|
|
803
|
+
content: [{ type: "text", text: JSON.stringify(status, null, 2) }],
|
|
804
|
+
};
|
|
805
|
+
},
|
|
806
|
+
});
|
|
807
|
+
// ── Tool: rename-canonical-id ─────────────────────────────────────────────
|
|
808
|
+
pi.registerTool({
|
|
809
|
+
name: "rename-canonical-id",
|
|
810
|
+
label: "Rename Canonical Id",
|
|
811
|
+
description: "Rename a canonical_id (kind: item | relation_type | lens | layer) from oldId to newId across all substrate surfaces that carry it as DATA — item home block + relations.json edges, or the relevant config registries. Out-of-substrate occurrences (analysis MDs, git history) are REPORTED, never rewritten. block_kind renames are unsupported (filesystem cascade). Use dryRun to preview the would-change counts without writing.",
|
|
812
|
+
promptSnippet: "Rename a canonical_id (item/relation_type/lens/layer) across substrate; dryRun to preview",
|
|
813
|
+
parameters: Type.Object({
|
|
814
|
+
kind: Type.String({ description: "One of: item | relation_type | lens | layer" }),
|
|
815
|
+
oldId: Type.String({ description: "Current canonical_id to rename from" }),
|
|
816
|
+
newId: Type.String({ description: "New canonical_id to rename to" }),
|
|
817
|
+
dryRun: Type.Optional(Type.Boolean({ description: "Compute would-change counts without writing" })),
|
|
818
|
+
}),
|
|
819
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
820
|
+
const report = renameCanonicalId(ctx.cwd, params.kind, params.oldId, params.newId, { dryRun: params.dryRun });
|
|
821
|
+
return {
|
|
822
|
+
details: undefined,
|
|
823
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }],
|
|
824
|
+
};
|
|
825
|
+
},
|
|
826
|
+
});
|
|
827
|
+
// ── Tool: amend-config ────────────────────────────────────────────────────
|
|
828
|
+
pi.registerTool({
|
|
829
|
+
name: "amend-config",
|
|
830
|
+
label: "Amend Config",
|
|
831
|
+
description: "Scoped add / replace / remove of ONE entry in ONE config.json registry (block_kinds, relation_types, lenses, " +
|
|
832
|
+
"layers, invariants, status_buckets, display_strings, naming, installed_schemas, installed_blocks, hierarchy). " +
|
|
833
|
+
"The whole resulting config is AJV-validated (SHAPE) and op-correctness is enforced (add ⇒ key absent, " +
|
|
834
|
+
"replace/remove ⇒ key present). Cross-registry referential integrity (removing a still-referenced " +
|
|
835
|
+
"relation_type / lens / layer / block_kind) is NOT checked here — run context-validate after. dryRun previews " +
|
|
836
|
+
"without writing.",
|
|
837
|
+
promptSnippet: "Add/replace/remove one entry in a config.json registry (vocabulary, lenses, invariants, status_buckets)",
|
|
838
|
+
parameters: Type.Object({
|
|
839
|
+
registry: Type.String({
|
|
840
|
+
description: "One of: block_kinds | relation_types | lenses | layers | invariants | status_buckets | display_strings | naming | installed_schemas | installed_blocks | hierarchy",
|
|
841
|
+
}),
|
|
842
|
+
operation: Type.String({ description: "add | replace | remove" }),
|
|
843
|
+
key: Type.String({
|
|
844
|
+
description: "Entry key: id for keyed-array (block_kinds/relation_types/lenses/layers/invariants), map key for " +
|
|
845
|
+
"map (status_buckets/display_strings/naming), the string value for string-array " +
|
|
846
|
+
"(installed_schemas/installed_blocks), or a JSON {parent_block, child_block, relation_type} for hierarchy",
|
|
847
|
+
}),
|
|
848
|
+
entry: Type.Optional(Type.Unknown({
|
|
849
|
+
description: "Entry payload: object for keyed-array/hierarchy, string for map value; omit for remove. For keyed-array its id field must equal key; for string-array (when given) it must equal key",
|
|
850
|
+
})),
|
|
851
|
+
dryRun: Type.Optional(Type.Boolean({ description: "Preview the op without writing config.json" })),
|
|
852
|
+
}),
|
|
853
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
854
|
+
// Type.Unknown() params may arrive as JSON strings. Parse if possible; on
|
|
855
|
+
// failure KEEP the raw string (valid for map-value registries whose value
|
|
856
|
+
// is a bare string, e.g. naming/display_strings/status_buckets).
|
|
857
|
+
let entry = params.entry;
|
|
858
|
+
if (typeof entry === "string") {
|
|
859
|
+
try {
|
|
860
|
+
entry = JSON.parse(entry);
|
|
861
|
+
}
|
|
862
|
+
catch {
|
|
863
|
+
/* keep raw string — valid for map-value registries */
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
const result = amendConfigEntry(ctx.cwd, params.registry, params.operation, params.key, entry, undefined, {
|
|
867
|
+
dryRun: params.dryRun,
|
|
868
|
+
});
|
|
869
|
+
const verb = result.modified ? (params.dryRun ? `would ${result.operation}` : `${result.operation}d`) : "no-op";
|
|
870
|
+
return {
|
|
871
|
+
details: undefined,
|
|
872
|
+
content: [{ type: "text", text: `amend-config: ${verb} ${result.registry}[${result.key}]` }],
|
|
873
|
+
};
|
|
874
|
+
},
|
|
875
|
+
});
|
|
876
|
+
// ── Tool: read-schema ───────────────────────────────────────────────────
|
|
877
|
+
pi.registerTool({
|
|
878
|
+
name: "read-schema",
|
|
879
|
+
label: "Read Schema",
|
|
880
|
+
description: "Read a substrate schema by name as parsed JSON. Returns null when the schema file is absent.",
|
|
881
|
+
promptSnippet: "Read a block schema as structured JSON",
|
|
882
|
+
parameters: Type.Object({
|
|
883
|
+
schemaName: Type.String({
|
|
884
|
+
description: "Schema name without extension (e.g., 'tasks', 'decisions', 'issues')",
|
|
885
|
+
}),
|
|
886
|
+
}),
|
|
887
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
888
|
+
const schema = readSchema(ctx.cwd, params.schemaName);
|
|
889
|
+
const schemaPathStr = schemaPath(ctx.cwd, params.schemaName);
|
|
890
|
+
const result = { schema, schemaPath: schemaPathStr };
|
|
891
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
892
|
+
const truncated = truncateHead(jsonStr);
|
|
893
|
+
let text = truncated.content;
|
|
894
|
+
if (truncated.truncated) {
|
|
895
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit. Full content: ${schemaPathStr}]`;
|
|
896
|
+
}
|
|
897
|
+
return {
|
|
898
|
+
details: undefined,
|
|
899
|
+
content: [{ type: "text", text }],
|
|
900
|
+
};
|
|
901
|
+
},
|
|
902
|
+
});
|
|
903
|
+
// ── Tool: write-schema ──────────────────────────────────────────────────
|
|
904
|
+
pi.registerTool({
|
|
905
|
+
name: "write-schema",
|
|
906
|
+
label: "Write Schema",
|
|
907
|
+
description: "Create or replace a substrate block-kind JSON Schema. operation 'create' requires the schema absent; " +
|
|
908
|
+
"'replace' requires it present. The body is AJV draft-07 meta-validated before an atomic write. CAVEAT: a " +
|
|
909
|
+
"'replace' that changes the schema's version does NOT migrate existing block items — read-time " +
|
|
910
|
+
"validateBlockWithMigration throws a version mismatch until a code-level MigrationFn is registered (no tool " +
|
|
911
|
+
"surface for that). Registering the block_kind that points at this schema is a separate step (amend-config " +
|
|
912
|
+
"block_kinds).",
|
|
913
|
+
promptSnippet: "Create or replace a block-kind JSON Schema (meta-validated, atomic)",
|
|
914
|
+
parameters: Type.Object({
|
|
915
|
+
operation: Type.String({ description: "create | replace" }),
|
|
916
|
+
schemaName: Type.String({ description: "Schema name without extension (e.g., 'tasks')" }),
|
|
917
|
+
schema: Type.Unknown({
|
|
918
|
+
description: "The whole JSON Schema object (draft-07). Accepts a JSON string.",
|
|
919
|
+
}),
|
|
920
|
+
dryRun: Type.Optional(Type.Boolean({ description: "Meta-validate without writing" })),
|
|
921
|
+
}),
|
|
922
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
923
|
+
// Type.Unknown() params may arrive as JSON strings. Parse if possible; on
|
|
924
|
+
// failure KEEP the raw value (meta-validation rejects a non-object body).
|
|
925
|
+
let schema = params.schema;
|
|
926
|
+
if (typeof schema === "string") {
|
|
927
|
+
try {
|
|
928
|
+
schema = JSON.parse(schema);
|
|
929
|
+
}
|
|
930
|
+
catch {
|
|
931
|
+
/* keep raw string — meta-validation will reject a non-object */
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const result = writeSchemaChecked(ctx.cwd, params.schemaName, schema, params.operation, undefined, { dryRun: params.dryRun });
|
|
935
|
+
const verb = result.written ? `${result.operation}d` : `would ${result.operation}`;
|
|
936
|
+
return {
|
|
937
|
+
details: undefined,
|
|
938
|
+
content: [
|
|
939
|
+
{ type: "text", text: `write-schema: ${verb} schema '${params.schemaName}' at ${result.schemaPath}` },
|
|
940
|
+
],
|
|
941
|
+
};
|
|
942
|
+
},
|
|
943
|
+
});
|
|
944
|
+
// ── Tool: context-init ──────────────────────────────────────────────────
|
|
945
|
+
pi.registerTool({
|
|
946
|
+
name: "context-init",
|
|
947
|
+
label: "Context Init",
|
|
948
|
+
description: "Initialize the substrate dir (bootstrap pointer + dirs only; run accept-all + install to populate).",
|
|
949
|
+
promptSnippet: "Initialize the substrate dir (bootstrap pointer + dirs only; run accept-all + install to populate)",
|
|
950
|
+
parameters: Type.Object({
|
|
951
|
+
contextDir: Type.String({
|
|
952
|
+
description: "Substrate dir name (e.g. .project). Required per DEC-0015 — no default.",
|
|
953
|
+
}),
|
|
954
|
+
}),
|
|
955
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
956
|
+
const result = initProject(ctx.cwd, params.contextDir);
|
|
957
|
+
return {
|
|
958
|
+
details: undefined,
|
|
959
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
960
|
+
};
|
|
961
|
+
},
|
|
962
|
+
});
|
|
963
|
+
// ── Tool: context-accept-all ──────────────────────────────────────────────
|
|
964
|
+
pi.registerTool({
|
|
965
|
+
name: "context-accept-all",
|
|
966
|
+
label: "Accept-All Conception",
|
|
967
|
+
description: "Adopt the canonical packaged conception (samples/conception.json) as this substrate's config.json (accept-all). Writes config only — run install after. Idempotent: never overwrites an existing config.",
|
|
968
|
+
promptSnippet: "Adopt the canonical conception as config (accept-all)",
|
|
969
|
+
parameters: Type.Object({}),
|
|
970
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
971
|
+
let result;
|
|
972
|
+
try {
|
|
973
|
+
result = adoptConception(ctx.cwd);
|
|
974
|
+
}
|
|
975
|
+
catch (err) {
|
|
976
|
+
if (err instanceof BootstrapNotFoundError) {
|
|
977
|
+
return {
|
|
978
|
+
details: undefined,
|
|
979
|
+
content: [{ type: "text", text: "substrate not initialized — run context-init first" }],
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
throw err;
|
|
983
|
+
}
|
|
984
|
+
return {
|
|
985
|
+
details: undefined,
|
|
986
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
987
|
+
};
|
|
988
|
+
},
|
|
989
|
+
});
|
|
990
|
+
// ── Tool: filter-block-items ──────────────────────────────────────────
|
|
991
|
+
pi.registerTool({
|
|
992
|
+
name: "filter-block-items",
|
|
993
|
+
label: "Filter Block Items",
|
|
994
|
+
description: "Filter the array items of a block by a single-field predicate (eq / neq / in / matches). Discovers the single top-level array property in the block; items missing the predicate field are never matched. Wraps the canonical readBlock + caller-side filter into one queryable surface; never mutates the block.",
|
|
995
|
+
promptSnippet: "Filter a block's items by a predicate — eq / neq / in / matches against a single field",
|
|
996
|
+
parameters: Type.Object({
|
|
997
|
+
block: Type.String({
|
|
998
|
+
description: "Block name (e.g., 'tasks', 'decisions', 'framework-gaps', 'context-contracts')",
|
|
999
|
+
}),
|
|
1000
|
+
field: Type.String({ description: "Item field to test (e.g., 'status', 'priority', 'id')" }),
|
|
1001
|
+
op: Type.Union([Type.Literal("eq"), Type.Literal("neq"), Type.Literal("in"), Type.Literal("matches")], {
|
|
1002
|
+
description: "Comparison operator: eq (===), neq (!==), in (value is array, item[field] in it), matches (regexp test on string)",
|
|
1003
|
+
}),
|
|
1004
|
+
value: Type.Unknown({
|
|
1005
|
+
description: "Comparison value — scalar for eq/neq, array for in, regexp pattern string for matches",
|
|
1006
|
+
}),
|
|
1007
|
+
}),
|
|
1008
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1009
|
+
const result = filterBlockItems(ctx.cwd, params.block, {
|
|
1010
|
+
field: params.field,
|
|
1011
|
+
op: params.op,
|
|
1012
|
+
value: params.value,
|
|
1013
|
+
});
|
|
1014
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1015
|
+
const truncated = truncateHead(jsonStr);
|
|
1016
|
+
let text = truncated.content;
|
|
1017
|
+
if (truncated.truncated) {
|
|
1018
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1019
|
+
}
|
|
1020
|
+
return {
|
|
1021
|
+
details: undefined,
|
|
1022
|
+
content: [{ type: "text", text }],
|
|
1023
|
+
};
|
|
1024
|
+
},
|
|
1025
|
+
});
|
|
1026
|
+
// ── Tool: resolve-item-by-id ──────────────────────────────────────────
|
|
1027
|
+
pi.registerTool({
|
|
1028
|
+
name: "resolve-item-by-id",
|
|
1029
|
+
label: "Resolve Item By Id",
|
|
1030
|
+
description: "Look up the block, array key, and item payload for a given ID across all .project/ blocks. Returns null when no item matches. Mirrors the resolveItemById SDK function and shares its prefix-vs-block invariant — IDs whose prefix maps to a known block but live elsewhere throw at index-build time.",
|
|
1031
|
+
promptSnippet: "Resolve a kind-prefixed ID (DEC-/FEAT-/FGAP-/issue-/REQ-/TASK-/etc.) to its owning block and item",
|
|
1032
|
+
parameters: Type.Object({
|
|
1033
|
+
id: Type.String({ description: "Kind-prefixed ID, e.g., DEC-0001 / FEAT-001 / FGAP-003 / issue-064" }),
|
|
1034
|
+
}),
|
|
1035
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1036
|
+
const result = resolveItemById(ctx.cwd, params.id);
|
|
1037
|
+
return {
|
|
1038
|
+
details: undefined,
|
|
1039
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
1040
|
+
};
|
|
1041
|
+
},
|
|
1042
|
+
});
|
|
1043
|
+
// ── Tool: read-block-item ─────────────────────────────────────────────
|
|
1044
|
+
pi.registerTool({
|
|
1045
|
+
name: "read-block-item",
|
|
1046
|
+
label: "Read Block Item",
|
|
1047
|
+
description: "Read a single item from a named block by its id — returns the item or null. Block-scoped (unlike resolve-item-by-id, which searches all blocks by kind-prefixed id). Avoids fetching a whole large block to get one item.",
|
|
1048
|
+
promptSnippet: "Read one item from a block by id (block-scoped; null if absent)",
|
|
1049
|
+
parameters: Type.Object({
|
|
1050
|
+
block: Type.String({ description: "Block name (e.g., 'tasks', 'decisions', 'framework-gaps')" }),
|
|
1051
|
+
id: Type.String({ description: "Item id within the block (e.g., 'TASK-001')" }),
|
|
1052
|
+
}),
|
|
1053
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1054
|
+
const result = readBlockItem(ctx.cwd, params.block, params.id);
|
|
1055
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1056
|
+
const truncated = truncateHead(jsonStr);
|
|
1057
|
+
let text = truncated.content;
|
|
1058
|
+
if (truncated.truncated) {
|
|
1059
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1060
|
+
}
|
|
1061
|
+
return {
|
|
1062
|
+
details: undefined,
|
|
1063
|
+
content: [{ type: "text", text }],
|
|
1064
|
+
};
|
|
1065
|
+
},
|
|
1066
|
+
});
|
|
1067
|
+
// ── Tool: read-block-page ─────────────────────────────────────────────
|
|
1068
|
+
pi.registerTool({
|
|
1069
|
+
name: "read-block-page",
|
|
1070
|
+
label: "Read Block Page",
|
|
1071
|
+
description: "Paginate a block's items: returns { items, total, hasMore }. offset default 0, limit default 50. Use for blocks too large to fetch whole (past the 50KB read-block cap). total is the full item count; hasMore signals another page.",
|
|
1072
|
+
promptSnippet: "Paginate a block's items — offset + limit; returns {items,total,hasMore}",
|
|
1073
|
+
parameters: Type.Object({
|
|
1074
|
+
block: Type.String({ description: "Block name (e.g., 'framework-gaps', 'decisions', 'issues')" }),
|
|
1075
|
+
offset: Type.Optional(Type.Integer({ minimum: 0, description: "Start index (default 0)" })),
|
|
1076
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, description: "Max items to return (default 50)" })),
|
|
1077
|
+
}),
|
|
1078
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1079
|
+
const result = readBlockPage(ctx.cwd, params.block, { offset: params.offset, limit: params.limit });
|
|
1080
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1081
|
+
const truncated = truncateHead(jsonStr);
|
|
1082
|
+
let text = truncated.content;
|
|
1083
|
+
if (truncated.truncated) {
|
|
1084
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1085
|
+
}
|
|
1086
|
+
return {
|
|
1087
|
+
details: undefined,
|
|
1088
|
+
content: [{ type: "text", text }],
|
|
1089
|
+
};
|
|
1090
|
+
},
|
|
1091
|
+
});
|
|
1092
|
+
// ── Tool: join-blocks ─────────────────────────────────────────────────
|
|
1093
|
+
pi.registerTool({
|
|
1094
|
+
name: "join-blocks",
|
|
1095
|
+
label: "Join Blocks",
|
|
1096
|
+
description: "Join two blocks in one call (FGAP-043). EDGE mode: pass `relationType` — pairs left items with right-block items connected by that relations.json edge (`leftEndpoint` parent|child, default parent). FIELD mode: pass `leftField`+`rightField` — pairs where left[leftField] === right[rightField]. Optional left pre-filter via where{Field,Op,Value}. Returns [{left, right:[]}] (right always an array; one-to-many). Use instead of N+1 read-block + resolve calls.",
|
|
1097
|
+
promptSnippet: "Join two blocks in one call — by relation edge or shared field; returns {left,right[]} pairs",
|
|
1098
|
+
parameters: Type.Object({
|
|
1099
|
+
leftBlock: Type.String({ description: "Left block name (e.g., 'tasks')" }),
|
|
1100
|
+
rightBlock: Type.String({ description: "Right block name (e.g., 'verification')" }),
|
|
1101
|
+
relationType: Type.Optional(Type.String({ description: "Edge mode: relations.json relation_type" })),
|
|
1102
|
+
leftField: Type.Optional(Type.String({ description: "Field mode: left item field" })),
|
|
1103
|
+
rightField: Type.Optional(Type.String({ description: "Field mode: right item field" })),
|
|
1104
|
+
leftEndpoint: Type.Optional(Type.Union([Type.Literal("parent"), Type.Literal("child")], {
|
|
1105
|
+
description: "Edge mode: is the left item the edge parent (default) or child",
|
|
1106
|
+
})),
|
|
1107
|
+
whereField: Type.Optional(Type.String({ description: "Optional left pre-filter field" })),
|
|
1108
|
+
whereOp: Type.Optional(Type.Union([Type.Literal("eq"), Type.Literal("neq"), Type.Literal("in"), Type.Literal("matches")])),
|
|
1109
|
+
whereValue: Type.Optional(Type.Unknown({ description: "Optional left pre-filter value" })),
|
|
1110
|
+
}),
|
|
1111
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1112
|
+
const leftPredicate = params.whereField !== undefined
|
|
1113
|
+
? { field: params.whereField, op: params.whereOp ?? "eq", value: params.whereValue }
|
|
1114
|
+
: undefined;
|
|
1115
|
+
const result = joinBlocks(ctx.cwd, {
|
|
1116
|
+
leftBlock: params.leftBlock,
|
|
1117
|
+
rightBlock: params.rightBlock,
|
|
1118
|
+
relationType: params.relationType,
|
|
1119
|
+
leftField: params.leftField,
|
|
1120
|
+
rightField: params.rightField,
|
|
1121
|
+
leftEndpoint: params.leftEndpoint,
|
|
1122
|
+
leftPredicate,
|
|
1123
|
+
});
|
|
1124
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1125
|
+
const truncated = truncateHead(jsonStr);
|
|
1126
|
+
let text = truncated.content;
|
|
1127
|
+
if (truncated.truncated) {
|
|
1128
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1129
|
+
}
|
|
1130
|
+
return {
|
|
1131
|
+
details: undefined,
|
|
1132
|
+
content: [{ type: "text", text }],
|
|
1133
|
+
};
|
|
1134
|
+
},
|
|
1135
|
+
});
|
|
1136
|
+
// ── Tool: resolve-items-by-id (bulk) ──────────────────────────────────
|
|
1137
|
+
pi.registerTool({
|
|
1138
|
+
name: "resolve-items-by-id",
|
|
1139
|
+
label: "Resolve Items By Id (Bulk)",
|
|
1140
|
+
description: "Bulk variant of resolve-item-by-id — resolve N kind-prefixed ids against a single buildIdIndex traversal. Returns an object mapping each input id to its ItemLocation (block / arrayKey / item) or null when not found. Coexists with the singular resolve-item-by-id tool; bulk collapses the N×singular-call pattern for callers resolving multiple ids in one render pass.",
|
|
1141
|
+
promptSnippet: "Resolve a batch of kind-prefixed ids (DEC-/FGAP-/TASK-/issue-/REQ-/...) in one call",
|
|
1142
|
+
parameters: Type.Object({
|
|
1143
|
+
ids: Type.Array(Type.String(), {
|
|
1144
|
+
description: "Array of kind-prefixed ids (DEC-/FGAP-/TASK-/issue-/REQ-/...) to resolve in one call",
|
|
1145
|
+
}),
|
|
1146
|
+
}),
|
|
1147
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1148
|
+
const resultMap = resolveItemsByIds(ctx.cwd, params.ids);
|
|
1149
|
+
const obj = {};
|
|
1150
|
+
for (const [id, loc] of resultMap)
|
|
1151
|
+
obj[id] = loc;
|
|
1152
|
+
const jsonStr = JSON.stringify(obj, null, 2);
|
|
1153
|
+
const truncated = truncateHead(jsonStr);
|
|
1154
|
+
let text = truncated.content;
|
|
1155
|
+
if (truncated.truncated) {
|
|
1156
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1157
|
+
}
|
|
1158
|
+
return {
|
|
1159
|
+
details: undefined,
|
|
1160
|
+
content: [{ type: "text", text }],
|
|
1161
|
+
};
|
|
1162
|
+
},
|
|
1163
|
+
});
|
|
1164
|
+
// ── Tool: complete-task ────────────────────────────────────────────────
|
|
1165
|
+
pi.registerTool({
|
|
1166
|
+
name: "complete-task",
|
|
1167
|
+
label: "Complete Task",
|
|
1168
|
+
description: "Complete a task with verification gate — requires a passing verification entry targeting the task.",
|
|
1169
|
+
promptSnippet: "Complete a task — gates on passing verification before updating status",
|
|
1170
|
+
parameters: Type.Object({
|
|
1171
|
+
taskId: Type.String({ description: "Task ID to complete" }),
|
|
1172
|
+
verificationId: Type.String({
|
|
1173
|
+
description: "Verification entry ID (must target this task with status 'passed')",
|
|
1174
|
+
}),
|
|
1175
|
+
}),
|
|
1176
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1177
|
+
const result = completeTask(ctx.cwd, params.taskId, params.verificationId);
|
|
1178
|
+
return {
|
|
1179
|
+
details: undefined,
|
|
1180
|
+
content: [
|
|
1181
|
+
{
|
|
1182
|
+
type: "text",
|
|
1183
|
+
text: `Task '${result.taskId}' completed (was '${result.previousStatus}'). Verification: ${result.verificationId} (${result.verificationStatus})`,
|
|
1184
|
+
},
|
|
1185
|
+
],
|
|
1186
|
+
};
|
|
1187
|
+
},
|
|
1188
|
+
});
|
|
1189
|
+
// ── Tool: context-validate-relations ──────────────────────────────────
|
|
1190
|
+
pi.registerTool({
|
|
1191
|
+
name: "context-validate-relations",
|
|
1192
|
+
label: "Context Validate Relations",
|
|
1193
|
+
description: "Validate substrate relations.json edges against config-declared lenses + hierarchy + relation_types and the cross-block id index. Returns SubstrateValidationResult with status (clean/warnings/invalid) and per-issue diagnostics.",
|
|
1194
|
+
promptSnippet: "Validate substrate relations against config + items",
|
|
1195
|
+
parameters: Type.Object({}),
|
|
1196
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
1197
|
+
const result = validateContextRelations(ctx.cwd);
|
|
1198
|
+
return {
|
|
1199
|
+
details: undefined,
|
|
1200
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
1201
|
+
};
|
|
1202
|
+
},
|
|
1203
|
+
});
|
|
1204
|
+
// ── Tool: context-edges-for-lens ──────────────────────────────────────
|
|
1205
|
+
pi.registerTool({
|
|
1206
|
+
name: "context-edges-for-lens",
|
|
1207
|
+
label: "Context Edges For Lens",
|
|
1208
|
+
description: "Materialize the Edge[] for a named lens — synthetic edges from derived_from_field for auto-derived lenses; authored edges filtered by relation_type for hand-curated lenses; unioned items from composition members for kind=composition lenses.",
|
|
1209
|
+
promptSnippet: "Materialize edges for a named lens (auto-derived or hand-curated)",
|
|
1210
|
+
parameters: Type.Object({
|
|
1211
|
+
lensId: Type.String({ description: "Lens id from config.lenses[].id" }),
|
|
1212
|
+
}),
|
|
1213
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1214
|
+
const result = edgesForLensByName(ctx.cwd, params.lensId);
|
|
1215
|
+
return {
|
|
1216
|
+
details: undefined,
|
|
1217
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
1218
|
+
};
|
|
1219
|
+
},
|
|
1220
|
+
});
|
|
1221
|
+
// ── Tool: context-walk-descendants ────────────────────────────────────
|
|
1222
|
+
pi.registerTool({
|
|
1223
|
+
name: "context-walk-descendants",
|
|
1224
|
+
label: "Context Walk Descendants",
|
|
1225
|
+
description: "Walk closure-table descendants of a parent id under a given relation_type. Returns string[] of descendant ids (may be empty if no children or relations.json absent).",
|
|
1226
|
+
promptSnippet: "Walk closure-table descendants under a relation_type",
|
|
1227
|
+
parameters: Type.Object({
|
|
1228
|
+
parentId: Type.String({ description: "Parent id (canonical id or lens bin name)" }),
|
|
1229
|
+
relationType: Type.String({ description: "Relation type from config.relation_types[].canonical_id" }),
|
|
1230
|
+
}),
|
|
1231
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1232
|
+
const result = walkLensDescendants(ctx.cwd, params.parentId, params.relationType);
|
|
1233
|
+
return {
|
|
1234
|
+
details: undefined,
|
|
1235
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
1236
|
+
};
|
|
1237
|
+
},
|
|
1238
|
+
});
|
|
1239
|
+
// ── Tool: walk-ancestors ─────────────────────────────────────────────
|
|
1240
|
+
// Reverse-direction counterpart to context-walk-descendants. Coexists
|
|
1241
|
+
// with the descendants tool — this tool is the parent-direction
|
|
1242
|
+
// traversal; FGAP-029 partial closure (TASK-036 / sub-phase 2.3).
|
|
1243
|
+
pi.registerTool({
|
|
1244
|
+
name: "walk-ancestors",
|
|
1245
|
+
label: "Walk Ancestors",
|
|
1246
|
+
description: "Walk closure-table ancestors of an item id under a given relation_type — reverse-direction counterpart to context-walk-descendants. Returns string[] of ancestor ids (may be empty if no parents or relations.json absent).",
|
|
1247
|
+
promptSnippet: "Walk closure-table ancestors under a relation_type",
|
|
1248
|
+
parameters: Type.Object({
|
|
1249
|
+
itemId: Type.String({ description: "Child item id whose ancestors are sought" }),
|
|
1250
|
+
relationType: Type.String({ description: "Relation type from config.relation_types[].canonical_id" }),
|
|
1251
|
+
}),
|
|
1252
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1253
|
+
const result = walkAncestorsByLens(ctx.cwd, params.itemId, params.relationType);
|
|
1254
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1255
|
+
const truncated = truncateHead(jsonStr);
|
|
1256
|
+
let text = truncated.content;
|
|
1257
|
+
if (truncated.truncated) {
|
|
1258
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1259
|
+
}
|
|
1260
|
+
return {
|
|
1261
|
+
details: undefined,
|
|
1262
|
+
content: [{ type: "text", text }],
|
|
1263
|
+
};
|
|
1264
|
+
},
|
|
1265
|
+
});
|
|
1266
|
+
// ── Tool: find-references ────────────────────────────────────────────
|
|
1267
|
+
// Edge-level inspection of closure-table references incident on an item.
|
|
1268
|
+
// Returns Edge[] (NOT string[]) — distinguishing semantic vs the id-chain
|
|
1269
|
+
// walk-ancestors / context-walk-descendants tools. Coexists with both:
|
|
1270
|
+
// walk-* surfaces serve id-chain traversal; find-references serves
|
|
1271
|
+
// relation-typed edge inspection. TASK-037 / Phase 2 sub-phase 2.4 —
|
|
1272
|
+
// final Phase 2 atomic unit.
|
|
1273
|
+
pi.registerTool({
|
|
1274
|
+
name: "find-references",
|
|
1275
|
+
label: "Find References",
|
|
1276
|
+
description: "Find all closure-table edges incident on an item id (inbound, outbound, or both). Returns Edge[] preserving relation_type + ordinal per record — edge-level view, not the id-chain projection that walk-ancestors / context-walk-descendants emit.",
|
|
1277
|
+
promptSnippet: "Find closure-table edges incident on an item id",
|
|
1278
|
+
parameters: Type.Object({
|
|
1279
|
+
itemId: Type.String({ description: "Item id whose incident edges are sought" }),
|
|
1280
|
+
direction: Type.Optional(Type.Union([Type.Literal("inbound"), Type.Literal("outbound"), Type.Literal("both")], {
|
|
1281
|
+
description: "inbound: edges where child === itemId; outbound: edges where parent === itemId; both: union (default).",
|
|
1282
|
+
})),
|
|
1283
|
+
}),
|
|
1284
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1285
|
+
const result = findReferencesInRepo(ctx.cwd, params.itemId, params.direction);
|
|
1286
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1287
|
+
const truncated = truncateHead(jsonStr);
|
|
1288
|
+
let text = truncated.content;
|
|
1289
|
+
if (truncated.truncated) {
|
|
1290
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1291
|
+
}
|
|
1292
|
+
return {
|
|
1293
|
+
details: undefined,
|
|
1294
|
+
content: [{ type: "text", text }],
|
|
1295
|
+
};
|
|
1296
|
+
},
|
|
1297
|
+
});
|
|
1298
|
+
// ── Tool: gather-execution-context ───────────────────────────────────
|
|
1299
|
+
// Work-unit-driven context bundling per DEC-0017: read unit + read its
|
|
1300
|
+
// context-contract (by unit_kind) + walk each declared relation_type
|
|
1301
|
+
// bidirectionally per direction semantic + resolve reached ids to full
|
|
1302
|
+
// item payloads via the bulk resolver. Returns ContextBundle as one
|
|
1303
|
+
// structured payload, removing the N+1-read pattern that orchestrators
|
|
1304
|
+
// had to hand-roll before this primitive. Closes FGAP-031.
|
|
1305
|
+
// TASK-039 / Phase 3 sub-phase 3.2.
|
|
1306
|
+
pi.registerTool({
|
|
1307
|
+
name: "gather-execution-context",
|
|
1308
|
+
label: "Gather Execution Context",
|
|
1309
|
+
description: "Compose a ContextBundle for a work-unit by reading its context-contract (by unit_kind) and walking declared relation_types bidirectionally per direction semantic. Returns unit + perRelationType buckets of resolved items + traversal_depth + scoped_at. Per DEC-0017 substrate primitive serving harness-confined dispatch.",
|
|
1310
|
+
promptSnippet: "Compose ContextBundle for unit + context-contract-declared bundle_relation_types",
|
|
1311
|
+
parameters: Type.Object({
|
|
1312
|
+
unitId: Type.String({ description: "Work-unit id (e.g. TASK-NNN / DEC-NNNN / FGAP-NNN)" }),
|
|
1313
|
+
kind: Type.String({
|
|
1314
|
+
description: "Unit-kind type tag (e.g. 'task', 'decision', 'verification') matching a context-contract entry's unit_kind",
|
|
1315
|
+
}),
|
|
1316
|
+
maxDepth: Type.Optional(Type.Integer({
|
|
1317
|
+
minimum: 1,
|
|
1318
|
+
description: "Override per-relation-type max_depth via Math.min against each spec.max_depth",
|
|
1319
|
+
})),
|
|
1320
|
+
}),
|
|
1321
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1322
|
+
const result = gatherExecutionContext(ctx.cwd, params);
|
|
1323
|
+
const jsonStr = JSON.stringify(result, null, 2);
|
|
1324
|
+
const truncated = truncateHead(jsonStr);
|
|
1325
|
+
let text = truncated.content;
|
|
1326
|
+
if (truncated.truncated) {
|
|
1327
|
+
text += `\n\n[Truncated: ${truncated.totalBytes} bytes exceeds 50KB limit.]`;
|
|
1328
|
+
}
|
|
1329
|
+
return {
|
|
1330
|
+
details: undefined,
|
|
1331
|
+
content: [{ type: "text", text }],
|
|
1332
|
+
};
|
|
1333
|
+
},
|
|
1334
|
+
});
|
|
1335
|
+
// ── Roadmap tools (Step 7 / pi-context PM-lens) ─────────────────────────
|
|
1336
|
+
// Strip non-serializable fields (suggestionTemplate fn, grouped Map) from
|
|
1337
|
+
// the embedded LoadedLensView records before tool serialization. Mirrors
|
|
1338
|
+
// the Map → object precedent used elsewhere for tool boundary shapes.
|
|
1339
|
+
const serializeRoadmapView = (view) => ({
|
|
1340
|
+
roadmap: view.roadmap,
|
|
1341
|
+
phases: view.phases.map((pv) => ({
|
|
1342
|
+
phase: pv.phase,
|
|
1343
|
+
lensView: "error" in pv.lensView
|
|
1344
|
+
? pv.lensView
|
|
1345
|
+
: {
|
|
1346
|
+
lens: pv.lensView.lens,
|
|
1347
|
+
items: pv.lensView.items,
|
|
1348
|
+
edges: pv.lensView.edges,
|
|
1349
|
+
grouped: Object.fromEntries(pv.lensView.grouped),
|
|
1350
|
+
uncategorized: pv.lensView.uncategorized,
|
|
1351
|
+
},
|
|
1352
|
+
status: pv.status,
|
|
1353
|
+
...(pv.milestone ? { milestone: pv.milestone } : {}),
|
|
1354
|
+
...(pv.milestoneSatisfied !== undefined ? { milestoneSatisfied: pv.milestoneSatisfied } : {}),
|
|
1355
|
+
})),
|
|
1356
|
+
phaseOrder: view.phaseOrder,
|
|
1357
|
+
cycles: view.cycles,
|
|
1358
|
+
edges: view.edges,
|
|
1359
|
+
});
|
|
1360
|
+
pi.registerTool({
|
|
1361
|
+
name: "context-roadmap-load",
|
|
1362
|
+
label: "Context: load roadmap",
|
|
1363
|
+
description: "Load a roadmap by id and return the materialized RoadmapView (phases, lens-views, status rollup, milestone resolution, scoped phase_depends_on edges, topo-ordered phaseOrder + cycles). Per DEC-0012 phase ordering lives in relations.json with relation_type='phase_depends_on'.",
|
|
1364
|
+
promptSnippet: "Load a roadmap by id",
|
|
1365
|
+
parameters: Type.Object({
|
|
1366
|
+
roadmapId: Type.String({ description: "ROADMAP-NNN id from <config.root>/roadmap.json" }),
|
|
1367
|
+
}),
|
|
1368
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1369
|
+
const view = loadRoadmap(ctx.cwd, params.roadmapId);
|
|
1370
|
+
if ("error" in view) {
|
|
1371
|
+
return {
|
|
1372
|
+
details: undefined,
|
|
1373
|
+
content: [{ type: "text", text: JSON.stringify(view, null, 2) }],
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
details: undefined,
|
|
1378
|
+
content: [{ type: "text", text: JSON.stringify(serializeRoadmapView(view), null, 2) }],
|
|
1379
|
+
};
|
|
1380
|
+
},
|
|
1381
|
+
});
|
|
1382
|
+
pi.registerTool({
|
|
1383
|
+
name: "context-roadmap-render",
|
|
1384
|
+
label: "Context: render roadmap",
|
|
1385
|
+
description: "Render a roadmap by id as pure-textual markdown — phase order list, per-phase adjacency lines (sourced from view.edges, alphabetically sorted), status rollup counts, milestone resolution, exit criteria. NO mermaid / graph syntax: per-phase **Depends on:** lines come strictly from authored phase_depends_on edges scoped to in-roadmap phases.",
|
|
1386
|
+
promptSnippet: "Render a roadmap as markdown",
|
|
1387
|
+
parameters: Type.Object({
|
|
1388
|
+
roadmapId: Type.String({ description: "ROADMAP-NNN id from <config.root>/roadmap.json" }),
|
|
1389
|
+
}),
|
|
1390
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1391
|
+
const view = loadRoadmap(ctx.cwd, params.roadmapId);
|
|
1392
|
+
if ("error" in view) {
|
|
1393
|
+
return {
|
|
1394
|
+
details: undefined,
|
|
1395
|
+
content: [{ type: "text", text: JSON.stringify(view, null, 2) }],
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
const naming = loadContext(ctx.cwd).config?.naming;
|
|
1399
|
+
return {
|
|
1400
|
+
details: undefined,
|
|
1401
|
+
content: [{ type: "text", text: renderRoadmap(view, naming) }],
|
|
1402
|
+
};
|
|
1403
|
+
},
|
|
1404
|
+
});
|
|
1405
|
+
pi.registerTool({
|
|
1406
|
+
name: "context-roadmap-validate",
|
|
1407
|
+
label: "Context: validate roadmap(s)",
|
|
1408
|
+
description: "Validate every roadmap × phase × milestone in <config.root>/roadmap.json. Codes: roadmap_lens_missing, roadmap_phase_dep_missing, roadmap_phase_cycle, roadmap_composition_cycle, roadmap_milestone_evidence_block_missing, roadmap_milestone_query_invalid, roadmap_status_unknown_value. Display strings flow through config.display_strings (pi-context divergence). Optional roadmapId filter restricts issue list to a single roadmap.",
|
|
1409
|
+
promptSnippet: "Validate roadmaps",
|
|
1410
|
+
parameters: Type.Object({
|
|
1411
|
+
roadmapId: Type.Optional(Type.String({ description: "Filter to issues matching this roadmap_id (omit for full-project validation)" })),
|
|
1412
|
+
}),
|
|
1413
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1414
|
+
const result = validateRoadmaps(ctx.cwd);
|
|
1415
|
+
const filtered = params.roadmapId
|
|
1416
|
+
? result.issues.filter((i) => !i.roadmap_id || i.roadmap_id === params.roadmapId)
|
|
1417
|
+
: result.issues;
|
|
1418
|
+
return {
|
|
1419
|
+
details: undefined,
|
|
1420
|
+
content: [{ type: "text", text: JSON.stringify({ status: result.status, issues: filtered }, null, 2) }],
|
|
1421
|
+
};
|
|
1422
|
+
},
|
|
1423
|
+
});
|
|
1424
|
+
pi.registerTool({
|
|
1425
|
+
name: "context-roadmap-list",
|
|
1426
|
+
label: "Context: list roadmaps",
|
|
1427
|
+
description: "List every roadmap in <config.root>/roadmap.json with id, title, optional status, and phase count. Returns [] when roadmap.json absent (opt-in block; absence is the truthful answer).",
|
|
1428
|
+
promptSnippet: "List roadmaps",
|
|
1429
|
+
parameters: Type.Object({}),
|
|
1430
|
+
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
|
|
1431
|
+
return {
|
|
1432
|
+
details: undefined,
|
|
1433
|
+
content: [{ type: "text", text: JSON.stringify(listRoadmaps(ctx.cwd), null, 2) }],
|
|
1434
|
+
};
|
|
1435
|
+
},
|
|
1436
|
+
});
|
|
1437
|
+
const CONTEXT_SUBCOMMANDS = {
|
|
1438
|
+
init: {
|
|
1439
|
+
description: "Initialize the substrate dir (bootstrap pointer + dirs only; run accept-all + install to populate)",
|
|
1440
|
+
handler: (args, ctx) => handleInit(args, ctx),
|
|
1441
|
+
},
|
|
1442
|
+
install: {
|
|
1443
|
+
description: "Copy schemas and starter blocks declared in .project/config.json from the package samples catalog",
|
|
1444
|
+
handler: (args, ctx) => {
|
|
1445
|
+
const overwrite = /(^|\s)--update(\s|$)/.test(args);
|
|
1446
|
+
const result = installContext(ctx.cwd, { overwrite });
|
|
1447
|
+
if (result.error) {
|
|
1448
|
+
ctx.ui.notify(result.error, "error");
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
const lines = [];
|
|
1452
|
+
if (result.installed.length > 0) {
|
|
1453
|
+
lines.push(`Installed (${result.installed.length}): ${result.installed.join(", ")}`);
|
|
1454
|
+
}
|
|
1455
|
+
if (result.updated.length > 0) {
|
|
1456
|
+
lines.push(`Updated (${result.updated.length}): ${result.updated.join(", ")}`);
|
|
1457
|
+
}
|
|
1458
|
+
if (result.skipped.length > 0) {
|
|
1459
|
+
lines.push(`Skipped (${result.skipped.length}, exists — pass --update to overwrite): ${result.skipped.join(", ")}`);
|
|
1460
|
+
}
|
|
1461
|
+
if (result.notFound.length > 0) {
|
|
1462
|
+
lines.push(`Not found in samples catalog (${result.notFound.length}): ${result.notFound.join(", ")}`);
|
|
1463
|
+
}
|
|
1464
|
+
if (lines.length === 0) {
|
|
1465
|
+
lines.push("Nothing declared in installed_schemas / installed_blocks — edit .project/config.json to add entries.");
|
|
1466
|
+
}
|
|
1467
|
+
const level = result.notFound.length > 0 ? "warning" : "info";
|
|
1468
|
+
ctx.ui.notify(lines.join("\n"), level);
|
|
1469
|
+
},
|
|
1470
|
+
},
|
|
1471
|
+
"accept-all": {
|
|
1472
|
+
description: "Adopt the canonical packaged conception as config.json (writes config only; run install after)",
|
|
1473
|
+
handler: (args, ctx) => handleAcceptAll(args, ctx),
|
|
1474
|
+
},
|
|
1475
|
+
view: {
|
|
1476
|
+
description: "Render a configured lens view (groupByLens projection) into the conversation",
|
|
1477
|
+
handler: (args, ctx) => {
|
|
1478
|
+
const lensId = args.trim().split(/\s+/)[0];
|
|
1479
|
+
if (!lensId) {
|
|
1480
|
+
ctx.ui.notify("Usage: /context view <lensId>", "error");
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
const result = loadLensView(ctx.cwd, lensId);
|
|
1484
|
+
if ("error" in result) {
|
|
1485
|
+
ctx.ui.notify(result.error, "error");
|
|
1486
|
+
return;
|
|
1487
|
+
}
|
|
1488
|
+
const config = loadContext(ctx.cwd).config;
|
|
1489
|
+
ctx.ui.notify(renderLensView(result, config?.naming), "info");
|
|
1490
|
+
},
|
|
1491
|
+
},
|
|
1492
|
+
"lens-curate": {
|
|
1493
|
+
description: "Walk uncategorized items in a lens and surface bin-assignment suggestions for the LLM to act on",
|
|
1494
|
+
handler: (args, ctx) => {
|
|
1495
|
+
const lensId = args.trim().split(/\s+/)[0];
|
|
1496
|
+
if (!lensId) {
|
|
1497
|
+
ctx.ui.notify("Usage: /context lens-curate <lensId>", "error");
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
const result = loadLensView(ctx.cwd, lensId);
|
|
1501
|
+
if ("error" in result) {
|
|
1502
|
+
ctx.ui.notify(result.error, "error");
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
if (result.uncategorized.length === 0) {
|
|
1506
|
+
ctx.ui.notify(`Lens '${lensId}' has no uncategorized items — nothing to curate.`, "info");
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
pi.sendMessage({
|
|
1510
|
+
customType: "context-lens-curate",
|
|
1511
|
+
content: buildCurationSuggestions(result),
|
|
1512
|
+
display: false,
|
|
1513
|
+
}, {
|
|
1514
|
+
triggerTurn: true,
|
|
1515
|
+
deliverAs: "followUp",
|
|
1516
|
+
});
|
|
1517
|
+
},
|
|
1518
|
+
},
|
|
1519
|
+
"roadmap-list": {
|
|
1520
|
+
description: "List every roadmap in <config.root>/roadmap.json with id, title, status, and phase count",
|
|
1521
|
+
handler: (_args, ctx) => {
|
|
1522
|
+
const list = listRoadmaps(ctx.cwd);
|
|
1523
|
+
if (list.length === 0) {
|
|
1524
|
+
ctx.ui.notify("No roadmaps found. Install the roadmap block via .project/config.json's installed_blocks, then author roadmap.json.", "info");
|
|
1525
|
+
return;
|
|
1526
|
+
}
|
|
1527
|
+
const lines = list.map((r) => `${r.id} [${r.status ?? "(unspecified)"}] ${r.title} (${r.phaseCount} phase${r.phaseCount === 1 ? "" : "s"})`);
|
|
1528
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
1529
|
+
},
|
|
1530
|
+
},
|
|
1531
|
+
"roadmap-view": {
|
|
1532
|
+
description: "Render a roadmap as pure-textual markdown (phase order, per-phase adjacency from authored phase_depends_on edges, status rollup, milestone resolution). NO mermaid.",
|
|
1533
|
+
handler: (args, ctx) => {
|
|
1534
|
+
const roadmapId = args.trim().split(/\s+/)[0];
|
|
1535
|
+
if (!roadmapId) {
|
|
1536
|
+
ctx.ui.notify("Usage: /context roadmap-view <ROADMAP-id>", "error");
|
|
1537
|
+
return;
|
|
1538
|
+
}
|
|
1539
|
+
const view = loadRoadmap(ctx.cwd, roadmapId);
|
|
1540
|
+
if ("error" in view) {
|
|
1541
|
+
ctx.ui.notify(view.error, "error");
|
|
1542
|
+
return;
|
|
1543
|
+
}
|
|
1544
|
+
const naming = loadContext(ctx.cwd).config?.naming;
|
|
1545
|
+
ctx.ui.notify(renderRoadmap(view, naming), "info");
|
|
1546
|
+
},
|
|
1547
|
+
},
|
|
1548
|
+
"roadmap-validate": {
|
|
1549
|
+
description: "Validate every roadmap (or a single one when ROADMAP-id supplied) — surfaces structured issues",
|
|
1550
|
+
handler: (args, ctx) => {
|
|
1551
|
+
const roadmapId = args.trim().split(/\s+/)[0] || undefined;
|
|
1552
|
+
const result = validateRoadmaps(ctx.cwd);
|
|
1553
|
+
const filtered = roadmapId
|
|
1554
|
+
? result.issues.filter((i) => !i.roadmap_id || i.roadmap_id === roadmapId)
|
|
1555
|
+
: result.issues;
|
|
1556
|
+
if (filtered.length === 0) {
|
|
1557
|
+
ctx.ui.notify(`✓ Roadmap validation passed${roadmapId ? ` for ${roadmapId}` : ""}.`, "info");
|
|
1558
|
+
return;
|
|
1559
|
+
}
|
|
1560
|
+
const lines = filtered.map((i) => `✗ [${i.code}] ${i.roadmap_id ?? ""}/${i.phase_id ?? ""}: ${i.message}`);
|
|
1561
|
+
const level = result.status === "invalid" ? "error" : "warning";
|
|
1562
|
+
ctx.ui.notify(lines.join("\n"), level);
|
|
1563
|
+
},
|
|
1564
|
+
},
|
|
1565
|
+
status: {
|
|
1566
|
+
description: "Show derived project state",
|
|
1567
|
+
handler: (_args, ctx) => handleStatus(ctx, pi),
|
|
1568
|
+
},
|
|
1569
|
+
"add-work": {
|
|
1570
|
+
description: "Extract conversation items into project blocks",
|
|
1571
|
+
handler: (args, ctx) => handleAddWork(args, ctx, pi),
|
|
1572
|
+
getCompletions: (argPrefix) => {
|
|
1573
|
+
const blocks = findAppendableBlocks(process.cwd());
|
|
1574
|
+
return blocks
|
|
1575
|
+
.filter((b) => b.block.startsWith(argPrefix))
|
|
1576
|
+
.map((b) => ({ value: b.block, label: b.block, description: `array: ${b.arrayKey}` }));
|
|
1577
|
+
},
|
|
1578
|
+
},
|
|
1579
|
+
validate: {
|
|
1580
|
+
description: "Check cross-block referential integrity",
|
|
1581
|
+
handler: (_args, ctx) => {
|
|
1582
|
+
const result = validateContext(ctx.cwd);
|
|
1583
|
+
const errors = result.issues.filter((i) => i.severity === "error").length;
|
|
1584
|
+
const warnings = result.issues.filter((i) => i.severity === "warning").length;
|
|
1585
|
+
const statusIcon = result.status === "clean" ? "\u2713" : result.status === "warnings" ? "\u26a0" : "\u2717";
|
|
1586
|
+
const lines = [];
|
|
1587
|
+
if (result.status === "clean") {
|
|
1588
|
+
lines.push(`${statusIcon} Project validation passed — no cross-block reference issues.`);
|
|
1589
|
+
}
|
|
1590
|
+
else {
|
|
1591
|
+
for (const issue of result.issues) {
|
|
1592
|
+
const icon = issue.severity === "error" ? "\u2717" : "\u26a0";
|
|
1593
|
+
const locator = issue.field ?? issue.code ?? "(no locator)";
|
|
1594
|
+
lines.push(`${icon} [${issue.block}] ${locator}: ${issue.message}`);
|
|
1595
|
+
}
|
|
1596
|
+
lines.push("");
|
|
1597
|
+
lines.push(`${statusIcon} ${errors} error(s), ${warnings} warning(s)`);
|
|
1598
|
+
}
|
|
1599
|
+
const level = result.status === "invalid" ? "error" : result.status === "warnings" ? "warning" : "info";
|
|
1600
|
+
ctx.ui.notify(lines.join("\n"), level);
|
|
1601
|
+
},
|
|
1602
|
+
},
|
|
1603
|
+
help: {
|
|
1604
|
+
description: "Show available subcommands",
|
|
1605
|
+
handler: (_args, ctx) => {
|
|
1606
|
+
const lines = ["Usage: /context <subcommand> [args]", ""];
|
|
1607
|
+
for (const [name, entry] of Object.entries(CONTEXT_SUBCOMMANDS)) {
|
|
1608
|
+
lines.push(` ${name.padEnd(12)} ${entry.description}`);
|
|
1609
|
+
}
|
|
1610
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
1611
|
+
},
|
|
1612
|
+
},
|
|
1613
|
+
};
|
|
1614
|
+
pi.registerCommand("context", {
|
|
1615
|
+
description: "Context state management",
|
|
1616
|
+
getArgumentCompletions: (prefix) => {
|
|
1617
|
+
const tokens = prefix.split(/\s+/);
|
|
1618
|
+
const partial = tokens[tokens.length - 1];
|
|
1619
|
+
if (tokens.length <= 1) {
|
|
1620
|
+
return Object.entries(CONTEXT_SUBCOMMANDS)
|
|
1621
|
+
.filter(([name]) => name.startsWith(partial))
|
|
1622
|
+
.map(([name, entry]) => ({ value: name, label: name, description: entry.description }));
|
|
1623
|
+
}
|
|
1624
|
+
const subName = tokens[0];
|
|
1625
|
+
const sub = CONTEXT_SUBCOMMANDS[subName];
|
|
1626
|
+
if (sub?.getCompletions) {
|
|
1627
|
+
const argPrefix = tokens.slice(1).join(" ");
|
|
1628
|
+
const items = sub.getCompletions(argPrefix);
|
|
1629
|
+
if (items) {
|
|
1630
|
+
return items.map((item) => ({ ...item, value: `${subName} ${item.value}` }));
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
return null;
|
|
1634
|
+
},
|
|
1635
|
+
async handler(args, ctx) {
|
|
1636
|
+
const trimmed = args.trim();
|
|
1637
|
+
const spaceIdx = trimmed.indexOf(" ");
|
|
1638
|
+
const subcommand = spaceIdx === -1 ? trimmed || "status" : trimmed.slice(0, spaceIdx);
|
|
1639
|
+
const rest = spaceIdx === -1 ? "" : trimmed.slice(spaceIdx + 1);
|
|
1640
|
+
const entry = CONTEXT_SUBCOMMANDS[subcommand];
|
|
1641
|
+
if (!entry) {
|
|
1642
|
+
const names = Object.keys(CONTEXT_SUBCOMMANDS).join(", ");
|
|
1643
|
+
ctx.ui.notify(`Unknown subcommand: ${subcommand}. Available: ${names}`, "warning");
|
|
1644
|
+
return;
|
|
1645
|
+
}
|
|
1646
|
+
await entry.handler(rest, ctx);
|
|
1647
|
+
},
|
|
1648
|
+
});
|
|
1649
|
+
};
|
|
1650
|
+
export default extension;
|
|
1651
|
+
// Re-export for consumers
|
|
1652
|
+
export { blockStructure, buildIdIndex, CONTEXT_BLOCK_TYPES, completeTask, findAppendableBlocks, resolveItemById, schemaInfo, schemaVocabulary, } from "./context-sdk.js";
|
|
1653
|
+
export { renameCanonicalId } from "./rename-canonical-id.js";
|
|
1654
|
+
export { listRoadmaps, loadRoadmap, renderRoadmap, resolveStatusVocabulary, rollupPhaseStatus, topoSort, validateRoadmaps, } from "./roadmap-plan.js";
|
|
1655
|
+
//# sourceMappingURL=index.js.map
|