foretext 0.0.0-stage → 0.8.0-bootstrap.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.
@@ -0,0 +1,853 @@
1
+ import { Ct as ENGRAM_TYPES, Nt as splitAliasList, St as ENGRAM_STATUSES, Tt as SOURCE_TYPES, s as evaluateCapture, u as MainLiveAt } from "./src-CRnWgfbx.js";
2
+ import { A as runOpAtDirectory, b as compactAutomaticContext, c as initOp, d as searchOp, f as showOp, g as recordAutomaticContextUsage, i as addOp, k as runOp, l as linksOp, m as elapsedUsageMs, n as contextualRecallOp, o as contextDigest, s as editOp, t as CONTEXTUAL_RECALL_LIMITS, u as relatedOp, x as reportAutomaticContext } from "./contextual-recall-AR3ign-H.js";
3
+ import { t as stageCapture } from "./capture-admission-Dnu2eW39.js";
4
+ import { Effect } from "effect";
5
+ import { Type } from "typebox";
6
+ import { StringEnum } from "@earendil-works/pi-ai";
7
+ //#region ../harnesses/src/pi/capture-hook.ts
8
+ const MAX_STATEMENT_CHARS = 1e3;
9
+ const MAX_MESSAGES = 64;
10
+ const MAX_PROPOSALS = 8;
11
+ const CAPTURE_BUDGET_MS = 200;
12
+ function registerCapture(pi, onWriteSuccess) {
13
+ let active;
14
+ pi.on("session_start", () => {
15
+ active = void 0;
16
+ });
17
+ pi.on("input", (event, ctx) => {
18
+ if (ctx.mode !== "tui") return;
19
+ const sessionId = ctx.sessionManager.getSessionId();
20
+ if (active?.sessionId !== sessionId || active.cwd !== ctx.cwd) active = {
21
+ sessionId,
22
+ cwd: ctx.cwd,
23
+ ordinal: 0,
24
+ messages: []
25
+ };
26
+ active.input = event.source === "interactive" && !event.streamingBehavior && !event.images?.length && event.text.length <= MAX_STATEMENT_CHARS && !event.text.trimStart().startsWith("/") ? event.text : void 0;
27
+ });
28
+ pi.on("message_end", ({ message }, ctx) => {
29
+ if (!active || ctx.mode !== "tui" || active.sessionId !== ctx.sessionManager.getSessionId() || active.cwd !== ctx.cwd) return;
30
+ const content = message.role === "user" ? message.content : void 0;
31
+ const text = typeof content === "string" ? content : content?.length === 1 && content[0].type === "text" ? content[0].text : void 0;
32
+ const direct = active.input !== void 0 && text === active.input;
33
+ if (message.role === "user") active.input = void 0;
34
+ const origin = direct ? "user" : message.role === "assistant" ? "assistant" : message.role === "toolResult" ? "tool" : "system";
35
+ if (!direct && active.messages.at(-1)?.origin !== "user") return;
36
+ active.messages.push({
37
+ id: `message-${message.timestamp}-${++active.ordinal}`,
38
+ origin,
39
+ text: direct ? text : ""
40
+ });
41
+ if (active.messages.length > MAX_MESSAGES) active.messages.shift();
42
+ });
43
+ const flush = async (event, ctx, signal) => {
44
+ if (!active?.messages.length || ctx.mode !== "tui" || active.sessionId !== ctx.sessionManager.getSessionId() || active.cwd !== ctx.cwd || signal?.aborted) return;
45
+ const { sessionId, cwd, messages } = active;
46
+ active.messages = [];
47
+ const proposals = evaluateCapture({ messages }).slice(0, MAX_PROPOSALS);
48
+ if (!proposals.length) return;
49
+ const timeout = new AbortController();
50
+ const captureSignal = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal;
51
+ let timer;
52
+ let staged = 0;
53
+ let recorded = 0;
54
+ const stage = async () => {
55
+ for (const { evidence } of proposals) {
56
+ if (captureSignal.aborted) break;
57
+ const result = await Effect.runPromise(stageCapture({
58
+ messages,
59
+ selectedEvidence: evidence.map(({ messageId }) => messageId)
60
+ }, cwd, {
61
+ harness: "pi",
62
+ sessionKind: "tui",
63
+ sessionId,
64
+ event
65
+ }, captureSignal).pipe(Effect.provide(MainLiveAt(cwd))), { signal: captureSignal });
66
+ if (result.status === "pending") staged++;
67
+ if (result.status === "recorded") {
68
+ recorded++;
69
+ onWriteSuccess?.();
70
+ }
71
+ }
72
+ };
73
+ try {
74
+ const deadline = new Promise((resolve) => {
75
+ timer = setTimeout(() => {
76
+ resolve();
77
+ timeout.abort();
78
+ }, CAPTURE_BUDGET_MS);
79
+ });
80
+ await Promise.race([stage(), deadline]);
81
+ } catch {} finally {
82
+ clearTimeout(timer);
83
+ }
84
+ if (recorded > 0 && ctx.hasUI) ctx.ui.notify(`Engram automatically recorded ${recorded} ${recorded === 1 ? "memory" : "memories"}.`, "info");
85
+ if (staged > 0 && ctx.hasUI) ctx.ui.notify(`Engram staged ${staged} ${staged === 1 ? "candidate" : "candidates"} for review. Run engram pending list --scope all.`, "info");
86
+ };
87
+ pi.on("agent_settled", (event, ctx) => flush(event.type, ctx));
88
+ pi.on("session_before_compact", (event, ctx) => flush(event.type, ctx, event.signal));
89
+ pi.on("session_shutdown", (event, ctx) => flush(event.type, ctx));
90
+ }
91
+ //#endregion
92
+ //#region ../harnesses/src/pi/context-hook.ts
93
+ const defaultLoader = (directory, prompt) => runOpAtDirectory(directory, contextualRecallOp({
94
+ prompt,
95
+ intent: "task"
96
+ }, true));
97
+ const LOAD_FAILED_WARNING = "Engram automatic context could not be loaded for this session; call engram_context to load memory manually if needed.";
98
+ function registerAutoContext(pi, opts = {}) {
99
+ const load = opts.load ?? defaultLoader;
100
+ const onDiagnostics = opts.onDiagnostics ?? reportAutomaticContext;
101
+ let pending;
102
+ let generation = 0;
103
+ let warned = false;
104
+ const invalidate = () => {
105
+ generation++;
106
+ pending = void 0;
107
+ };
108
+ const read = async (directory, prompt) => {
109
+ try {
110
+ return await load(directory, prompt);
111
+ } catch {
112
+ return {
113
+ text: "",
114
+ isError: true,
115
+ details: { reason: "unavailable" }
116
+ };
117
+ }
118
+ };
119
+ pi.on("session_start", () => {
120
+ invalidate();
121
+ warned = false;
122
+ });
123
+ pi.on("before_agent_start", async (event, ctx) => {
124
+ const started = performance.now();
125
+ const { prompt } = event;
126
+ const directory = ctx.cwd;
127
+ if (prompt.length > CONTEXTUAL_RECALL_LIMITS.promptChars) {
128
+ invalidate();
129
+ return;
130
+ }
131
+ if (pending?.directory !== directory || pending.prompt !== prompt) {
132
+ generation++;
133
+ pending = {
134
+ directory,
135
+ prompt,
136
+ result: read(directory, prompt)
137
+ };
138
+ }
139
+ const requestGeneration = generation;
140
+ const result = await pending.result;
141
+ if (requestGeneration !== generation) return;
142
+ pending = void 0;
143
+ const recordDelivery = (text, diagnostics) => {
144
+ Effect.runFork(recordAutomaticContextUsage("recall", elapsedUsageMs(started), result, text, diagnostics));
145
+ };
146
+ if (result.isError || result.details.reason === "unavailable" || result.details.reason === "timeout") {
147
+ recordDelivery();
148
+ if (!warned && ctx.hasUI) {
149
+ warned = true;
150
+ ctx.ui.notify(LOAD_FAILED_WARNING, "warning");
151
+ }
152
+ return;
153
+ }
154
+ if (!result.automatic) {
155
+ recordDelivery();
156
+ return;
157
+ }
158
+ try {
159
+ const { text, diagnostics } = compactAutomaticContext(result.automatic, {
160
+ harness: "pi",
161
+ system: [event.systemPrompt],
162
+ prompt,
163
+ contextWindow: ctx.model?.contextWindow,
164
+ output: ctx.model?.maxTokens,
165
+ priorUsage: ctx.getContextUsage?.()?.tokens
166
+ });
167
+ onDiagnostics(diagnostics);
168
+ recordDelivery(text, diagnostics);
169
+ if (text) return { systemPrompt: `${event.systemPrompt}\n\n${text}` };
170
+ } catch {}
171
+ });
172
+ return { invalidate };
173
+ }
174
+ //#endregion
175
+ //#region ../harnesses/src/pi/run.ts
176
+ /** Map an OpResult to a pi tool result (D16: isError for genuine failures). */
177
+ const toToolResult = (r) => ({
178
+ content: [{
179
+ type: "text",
180
+ text: r.text
181
+ }],
182
+ isError: r.isError,
183
+ details: r.details
184
+ });
185
+ //#endregion
186
+ //#region ../harnesses/src/pi/commands.ts
187
+ const HELP = [
188
+ "engram - git-native memory for you and your team",
189
+ "",
190
+ " /engram show the context digest (decisions & pinned first)",
191
+ " /engram context [scope] digest for scope: project | personal | both",
192
+ " /engram search <query> keyword search across recorded engrams",
193
+ " /engram show <id> read one full entry (unique prefixes work)",
194
+ " /engram related <id> lifecycle lineage + explicit links (exact id)",
195
+ " /engram links <id> link graph: outgoing related + incoming backlinks (exact id)",
196
+ " flags: --scope project|personal --offset n --limit n (max 100)",
197
+ " /engram add [--confirm-write] <title> -- <body> record an entry",
198
+ " flags: --type decision|fact|preference|note|issue|context",
199
+ " --scope project|personal --tags a,b --aliases a,b --pinned",
200
+ " --status active|superseded|archived --supersedes <id>",
201
+ " --review-after <ts> --expires <ts>",
202
+ " --source-type conversation|file|url|command|other",
203
+ " --source-ref <ref> quote it if it contains spaces",
204
+ " /engram edit <id> [flags] [-- <body>] edit an entry (unique prefixes work)",
205
+ " flags: --title <title> --type decision|fact|preference|note|issue|context",
206
+ " --tags a,b --aliases a,b --scope project|personal --pinned | --no-pinned",
207
+ " --author <name> --confirm-write",
208
+ " --status active|superseded|archived --supersedes <id>",
209
+ " --review-after <ts> --expires <ts>",
210
+ " --source-type conversation|file|url|command|other",
211
+ " --source-ref <ref> quote multiword values: --title \"Two words\"",
212
+ " clear a field: --clear-status --clear-supersedes",
213
+ " --clear-review-after --clear-expires --clear-source-type",
214
+ " --clear-source-ref --clear-aliases",
215
+ " /engram init [tracked|untracked] initialize .engram/ here",
216
+ "",
217
+ "Agents: prefer the engram_context / engram_search / engram_show / engram_add / engram_edit tools."
218
+ ].join("\n");
219
+ const parseAddError = (error) => ({
220
+ ok: false,
221
+ error
222
+ });
223
+ function parseAdd(rest) {
224
+ const parsed = {
225
+ title: "",
226
+ body: ""
227
+ };
228
+ const confirmation = /^--confirm-write\s+/.exec(rest);
229
+ parsed.confirmWrite = confirmation !== null;
230
+ let work = ` ${confirmation === null ? rest : rest.slice(confirmation[0].length)} `;
231
+ const flag = (name) => {
232
+ const m = work.match(new RegExp(`\\s${name}\\s+([^\\s]+)`));
233
+ if (!m) return null;
234
+ work = work.replace(m[0], " ");
235
+ return m[1];
236
+ };
237
+ const type = flag("--type");
238
+ if (type !== null) {
239
+ if (!ENGRAM_TYPES.includes(type)) return parseAddError(`Invalid --type "${type}". Valid: ${ENGRAM_TYPES.join(" | ")}`);
240
+ parsed.type = type;
241
+ }
242
+ const scope = flag("--scope");
243
+ if (scope !== null) {
244
+ if (scope !== "project" && scope !== "personal") return parseAddError(`Invalid --scope "${scope}". Valid: project | personal`);
245
+ parsed.scope = scope;
246
+ }
247
+ const status = flag("--status");
248
+ if (status !== null) {
249
+ if (!ENGRAM_STATUSES.includes(status)) return parseAddError(`Invalid --status "${status}". Valid: ${ENGRAM_STATUSES.join(" | ")}`);
250
+ parsed.status = status;
251
+ }
252
+ const sourceType = flag("--source-type");
253
+ if (sourceType !== null) {
254
+ if (!SOURCE_TYPES.includes(sourceType)) return parseAddError(`Invalid --source-type "${sourceType}". Valid: ${SOURCE_TYPES.join(" | ")}`);
255
+ parsed.sourceType = sourceType;
256
+ }
257
+ const supersedes = flag("--supersedes");
258
+ if (supersedes !== null) parsed.supersedes = supersedes;
259
+ const reviewAfter = flag("--review-after");
260
+ if (reviewAfter !== null) parsed.reviewAfter = reviewAfter;
261
+ const expires = flag("--expires");
262
+ if (expires !== null) parsed.expires = expires;
263
+ const sourceRef = work.match(/\s--source-ref\s+(?:"([^"]*)"|'([^']*)'|([^\s]+))/);
264
+ if (sourceRef) {
265
+ work = work.replace(sourceRef[0], " ");
266
+ parsed.sourceRef = sourceRef[1] ?? sourceRef[2] ?? sourceRef[3];
267
+ }
268
+ const tags = flag("--tags");
269
+ if (tags) parsed.tags = tags.split(",").map((t) => t.trim()).filter(Boolean);
270
+ if (/\s--aliases(\s|$)/.test(work)) {
271
+ const aliasesMatch = work.match(/\s--aliases\s+(?:"([^"]*)"|'([^']*)'|([^\s]+))/);
272
+ if (aliasesMatch === null) return parseAddError("Missing value for --aliases.");
273
+ work = work.replace(aliasesMatch[0], " ");
274
+ const raw = aliasesMatch[1] ?? aliasesMatch[2] ?? aliasesMatch[3];
275
+ if (aliasesMatch[3] !== void 0 && raw.startsWith("--")) return parseAddError("Missing value for --aliases.");
276
+ parsed.aliases = splitAliasList(raw);
277
+ }
278
+ if (/\s--pinned\b/.test(work)) {
279
+ parsed.pinned = true;
280
+ work = work.replace(/\s--pinned\b/, " ");
281
+ }
282
+ const [title, ...bodyParts] = work.trim().split(/\s+--\s+/);
283
+ parsed.title = (title ?? "").trim();
284
+ parsed.body = bodyParts.join(" -- ").trim();
285
+ return parsed;
286
+ }
287
+ const parseEditError = (error) => ({
288
+ ok: false,
289
+ error
290
+ });
291
+ /** Split a raw command tail into whitespace-separated tokens, treating
292
+ * single- and double-quoted spans as literal content (quotes stripped,
293
+ * usable anywhere inside a token). Unclosed quotes are an error: they would
294
+ * silently mis-parse everything after them. Scoped to slash commands; the
295
+ * parseAdd grammar above keeps its own long-standing behavior. */
296
+ const tokenizeCommand = (input) => {
297
+ const tokens = [];
298
+ let i = 0;
299
+ while (i < input.length) {
300
+ while (i < input.length && /\s/.test(input[i])) i += 1;
301
+ if (i >= input.length) break;
302
+ const start = i;
303
+ let value = "";
304
+ while (i < input.length && !/\s/.test(input[i])) {
305
+ const ch = input[i];
306
+ if (ch === "\"" || ch === "'") {
307
+ const close = input.indexOf(ch, i + 1);
308
+ if (close === -1) return { error: "Unmatched quote. Quote multiword values like --title \"Two words\"." };
309
+ value += input.slice(i + 1, close);
310
+ i = close + 1;
311
+ } else {
312
+ value += ch;
313
+ i += 1;
314
+ }
315
+ }
316
+ tokens.push({
317
+ value,
318
+ raw: input.slice(start, i),
319
+ end: i
320
+ });
321
+ }
322
+ return tokens;
323
+ };
324
+ /** Lifecycle flags: the value flag and its paired clear flag. */
325
+ const LIFECYCLE_FLAG_PAIRS = [
326
+ {
327
+ value: "--status",
328
+ clear: "--clear-status",
329
+ field: "status"
330
+ },
331
+ {
332
+ value: "--supersedes",
333
+ clear: "--clear-supersedes",
334
+ field: "supersedes"
335
+ },
336
+ {
337
+ value: "--review-after",
338
+ clear: "--clear-review-after",
339
+ field: "reviewAfter"
340
+ },
341
+ {
342
+ value: "--expires",
343
+ clear: "--clear-expires",
344
+ field: "expires"
345
+ },
346
+ {
347
+ value: "--source-type",
348
+ clear: "--clear-source-type",
349
+ field: "sourceType"
350
+ },
351
+ {
352
+ value: "--source-ref",
353
+ clear: "--clear-source-ref",
354
+ field: "sourceRef"
355
+ }
356
+ ];
357
+ const EDIT_USAGE = "Usage: /engram edit <id> [flags] [-- <body>]";
358
+ /** Every recognized flag spelling. A bare token with one of these raw forms
359
+ * can never be a flag's value: the value is simply missing. Quoting is the
360
+ * way to pass flag-looking text — the tokenizer keeps the quote characters
361
+ * in a quoted token's `raw`, so a quoted "--clear-status" is still accepted
362
+ * as a value while a bare one is rejected. The body delimiter (`--`) never
363
+ * enters the flag walk at all: everything from the first bare `--` token on
364
+ * is the body, taken verbatim. */
365
+ const FLAG_SPELLINGS = /* @__PURE__ */ new Set([
366
+ "--title",
367
+ "--type",
368
+ "--tags",
369
+ "--aliases",
370
+ "--clear-aliases",
371
+ "--scope",
372
+ "--pinned",
373
+ "--no-pinned",
374
+ "--author",
375
+ "--confirm-write",
376
+ ...LIFECYCLE_FLAG_PAIRS.flatMap((p) => [p.value, p.clear])
377
+ ]);
378
+ /** Parse `/engram edit` arguments: the first token is the id (or unique
379
+ * prefix), then field flags, then an optional ` -- <body>` delimiter. The
380
+ * body is everything after the first bare `--` token, verbatim, so
381
+ * flag-looking text inside it is never parsed as flags. All conflicts and
382
+ * unknown values are rejected here, before anything runs. */
383
+ function parseEdit(rest) {
384
+ const tokens = tokenizeCommand(rest);
385
+ if ("error" in tokens) return parseEditError(tokens.error);
386
+ if (tokens.length === 0) return parseEditError(EDIT_USAGE);
387
+ const head = tokens[0];
388
+ if (head.raw.startsWith("--")) return parseEditError(`Missing id. ${EDIT_USAGE}`);
389
+ const dashIndex = tokens.findIndex((t) => t.raw === "--");
390
+ const flagTokens = tokens.slice(1, dashIndex === -1 ? tokens.length : dashIndex);
391
+ const parsed = { id: head.value };
392
+ const bodyPresent = dashIndex !== -1;
393
+ if (bodyPresent) parsed.body = rest.slice(tokens[dashIndex].end).trim();
394
+ const setFlags = /* @__PURE__ */ new Set();
395
+ const clearFlags = /* @__PURE__ */ new Set();
396
+ let aliasesFlag;
397
+ let fieldCount = 0;
398
+ const nextValue = () => {
399
+ const t = flagTokens[k + 1];
400
+ if (t !== void 0 && FLAG_SPELLINGS.has(t.raw)) return null;
401
+ k += 1;
402
+ return t?.value ?? null;
403
+ };
404
+ const assignLifecycle = (field, value) => {
405
+ parsed[field] = value;
406
+ };
407
+ let k = 0;
408
+ for (k = 0; k < flagTokens.length; k += 1) {
409
+ const t = flagTokens[k];
410
+ const lifecycle = LIFECYCLE_FLAG_PAIRS.find((p) => p.value === t.raw || p.clear === t.raw);
411
+ if (lifecycle !== void 0) {
412
+ if (t.raw === lifecycle.clear) {
413
+ assignLifecycle(lifecycle.field, null);
414
+ clearFlags.add(lifecycle.field);
415
+ } else {
416
+ const v = nextValue();
417
+ if (v === null) return parseEditError(`Missing value for ${t.raw}.`);
418
+ assignLifecycle(lifecycle.field, v);
419
+ setFlags.add(lifecycle.field);
420
+ }
421
+ fieldCount += 1;
422
+ continue;
423
+ }
424
+ switch (t.raw) {
425
+ case "--confirm-write":
426
+ parsed.confirmWrite = true;
427
+ continue;
428
+ case "--title": {
429
+ const v = nextValue();
430
+ if (v === null) return parseEditError("Missing value for --title.");
431
+ parsed.title = v;
432
+ break;
433
+ }
434
+ case "--type": {
435
+ const v = nextValue();
436
+ if (v === null) return parseEditError("Missing value for --type.");
437
+ if (!ENGRAM_TYPES.includes(v)) return parseEditError(`Invalid --type "${v}". Valid: ${ENGRAM_TYPES.join(" | ")}`);
438
+ parsed.type = v;
439
+ break;
440
+ }
441
+ case "--tags": {
442
+ const v = nextValue();
443
+ if (v === null) return parseEditError("Missing value for --tags.");
444
+ parsed.tags = v.split(",").map((tag) => tag.trim()).filter(Boolean);
445
+ break;
446
+ }
447
+ case "--aliases": {
448
+ if (aliasesFlag === "clear") return parseEditError("Use either --aliases or --clear-aliases, not both.");
449
+ aliasesFlag = "set";
450
+ const v = nextValue();
451
+ if (v === null) return parseEditError("Missing value for --aliases.");
452
+ parsed.aliases = splitAliasList(v);
453
+ break;
454
+ }
455
+ case "--clear-aliases":
456
+ if (aliasesFlag === "set") return parseEditError("Use either --aliases or --clear-aliases, not both.");
457
+ aliasesFlag = "clear";
458
+ parsed.aliases = null;
459
+ break;
460
+ case "--scope": {
461
+ const v = nextValue();
462
+ if (v === null) return parseEditError("Missing value for --scope.");
463
+ if (v !== "project" && v !== "personal") return parseEditError(`Invalid --scope "${v}". Valid: project | personal`);
464
+ parsed.scope = v;
465
+ break;
466
+ }
467
+ case "--pinned":
468
+ case "--no-pinned": {
469
+ const pin = t.raw === "--pinned";
470
+ if (parsed.pinned !== void 0 && parsed.pinned !== pin) return parseEditError("Use either --pinned or --no-pinned, not both.");
471
+ parsed.pinned = pin;
472
+ break;
473
+ }
474
+ case "--author": {
475
+ const v = nextValue();
476
+ if (v === null) return parseEditError("Missing value for --author.");
477
+ parsed.author = v;
478
+ break;
479
+ }
480
+ default: return parseEditError(`Unknown flag "${t.raw}". ${EDIT_USAGE}`);
481
+ }
482
+ fieldCount += 1;
483
+ }
484
+ for (const pair of LIFECYCLE_FLAG_PAIRS) if (setFlags.has(pair.field) && clearFlags.has(pair.field)) return parseEditError(`Use either ${pair.value} or ${pair.clear}, not both.`);
485
+ if (fieldCount === 0 && !bodyPresent) return parseEditError(`Nothing to edit. Pass a field flag or a " -- " body. ${EDIT_USAGE}`);
486
+ return parsed;
487
+ }
488
+ const LINKS_USAGE = "Usage: /engram links <id> [--scope project|personal] [--offset n] [--limit n]";
489
+ /** Recognized links flags: a bare one is a missing value, never a literal. */
490
+ const LINKS_FLAGS = /* @__PURE__ */ new Set([
491
+ "--scope",
492
+ "--offset",
493
+ "--limit"
494
+ ]);
495
+ const parseLinksError = (error) => ({
496
+ ok: false,
497
+ error
498
+ });
499
+ const isNonNegativeInteger = (v) => /^\d+$/.test(v) && Number.isSafeInteger(Number(v));
500
+ /** Parse `/engram links` arguments: exact id first, then value flags. Rejects
501
+ * missing ids, unknown flags, repeated value flags, non-integers, negative
502
+ * offsets, zero or excessive limits, and trailing positional arguments —
503
+ * all before the operation runs. Exact ids only: graph semantics, no
504
+ * prefix resolution. */
505
+ function parseLinks(rest) {
506
+ const tokens = tokenizeCommand(rest);
507
+ if ("error" in tokens) return parseLinksError(tokens.error);
508
+ if (tokens.length === 0) return parseLinksError(LINKS_USAGE);
509
+ const head = tokens[0];
510
+ if (head.raw.startsWith("--")) return parseLinksError(`Missing id. ${LINKS_USAGE}`);
511
+ const parsed = { id: head.value };
512
+ const seen = /* @__PURE__ */ new Set();
513
+ for (let k = 1; k < tokens.length; k += 1) {
514
+ const t = tokens[k];
515
+ if (!t.raw.startsWith("--")) return parseLinksError(`Unexpected argument "${t.raw}". ${LINKS_USAGE}`);
516
+ if (!LINKS_FLAGS.has(t.raw)) return parseLinksError(`Unknown flag "${t.raw}". ${LINKS_USAGE}`);
517
+ if (seen.has(t.raw)) return parseLinksError(`Repeated flag ${t.raw}. ${LINKS_USAGE}`);
518
+ seen.add(t.raw);
519
+ const value = tokens[k + 1];
520
+ if (value === void 0 || LINKS_FLAGS.has(value.raw)) return parseLinksError(`Missing value for ${t.raw}. ${LINKS_USAGE}`);
521
+ k += 1;
522
+ if (t.raw === "--scope") {
523
+ if (value.value !== "project" && value.value !== "personal") return parseLinksError(`Invalid --scope "${value.value}". Valid: project | personal`);
524
+ parsed.scope = value.value;
525
+ } else if (t.raw === "--offset") {
526
+ if (!isNonNegativeInteger(value.value)) return parseLinksError("offset must be a nonnegative safe integer");
527
+ parsed.offset = Number(value.value);
528
+ } else {
529
+ if (!isNonNegativeInteger(value.value) || Number(value.value) < 1) return parseLinksError("limit must be a positive safe integer");
530
+ if (Number(value.value) > 100) return parseLinksError(`limit must be at most 100`);
531
+ parsed.limit = Number(value.value);
532
+ }
533
+ }
534
+ return parsed;
535
+ }
536
+ async function dispatch(args, ctx, onWriteSuccess) {
537
+ const rest = args.trim();
538
+ const sub = rest.split(/\s+/)[0] ?? "";
539
+ const remainder = sub ? rest.slice(sub.length).trim() : rest;
540
+ const notify = (text, level = "info") => {
541
+ if (ctx.hasUI) ctx.ui.notify(text, level);
542
+ };
543
+ if (sub === "help" || sub === "?") {
544
+ notify(HELP);
545
+ return;
546
+ }
547
+ if (sub === "init") {
548
+ let tracked = true;
549
+ if (remainder === "untracked") tracked = false;
550
+ else if (remainder === "tracked") tracked = true;
551
+ else if (ctx.hasUI) tracked = await ctx.ui.confirm("engram init", "Track the team engram in git? (shared with your team; answer No to gitignore it)");
552
+ const r = await runOp(initOp({ tracked }));
553
+ notify(r.text, r.isError ? "error" : "info");
554
+ return;
555
+ }
556
+ if (sub === "search") {
557
+ if (!remainder) {
558
+ notify("Usage: /engram search <query>", "error");
559
+ return;
560
+ }
561
+ const r = await runOp(searchOp({ query: remainder }));
562
+ notify(r.text, r.isError ? "error" : "info");
563
+ return;
564
+ }
565
+ if (sub === "show") {
566
+ if (!remainder) {
567
+ notify("Usage: /engram show <id>", "error");
568
+ return;
569
+ }
570
+ const r = await runOp(showOp({ id: remainder }));
571
+ notify(r.text, r.isError ? "error" : "info");
572
+ return;
573
+ }
574
+ if (sub === "links" || sub === "related") {
575
+ if (!remainder) {
576
+ notify(LINKS_USAGE.replace("links", sub), "error");
577
+ return;
578
+ }
579
+ const parsed = parseLinks(remainder);
580
+ if ("error" in parsed) {
581
+ notify(parsed.error.replace("/engram links", `/engram ${sub}`), "error");
582
+ return;
583
+ }
584
+ const r = await runOp(sub === "related" ? relatedOp(parsed) : linksOp(parsed));
585
+ notify(r.text, r.isError ? "error" : "info");
586
+ return;
587
+ }
588
+ if (sub === "add") {
589
+ const parsed = parseAdd(remainder);
590
+ if ("error" in parsed) {
591
+ notify(parsed.error, "error");
592
+ return;
593
+ }
594
+ if (!parsed.title) {
595
+ notify("Usage: /engram add [--confirm-write] <title> -- <body> [--type X] [--scope Y] [--tags a,b]", "error");
596
+ return;
597
+ }
598
+ const r = await runOp(addOp(parsed, "--confirm-write before the title"));
599
+ notify(r.text, r.isError ? "error" : "info");
600
+ if (!r.isError) onWriteSuccess?.();
601
+ return;
602
+ }
603
+ if (sub === "edit") {
604
+ if (!remainder) {
605
+ notify(EDIT_USAGE, "error");
606
+ return;
607
+ }
608
+ const parsed = parseEdit(remainder);
609
+ if ("error" in parsed) {
610
+ notify(parsed.error, "error");
611
+ return;
612
+ }
613
+ const r = await runOp(editOp(parsed, "--confirm-write"));
614
+ notify(r.text, r.isError ? "error" : "info");
615
+ if (!r.isError) onWriteSuccess?.();
616
+ return;
617
+ }
618
+ const r = await runOp(contextDigest({ scope: remainder === "project" || remainder === "personal" || remainder === "both" ? remainder : void 0 }));
619
+ notify(r.text, r.isError ? "error" : "info");
620
+ }
621
+ function registerEngramCommand(pi, opts = {}) {
622
+ pi.registerCommand("engram", {
623
+ description: "engram memory: context | search | show | links | related | add | edit | init | help",
624
+ handler: async (args, ctx) => {
625
+ await dispatch(args, ctx, opts.onWriteSuccess);
626
+ }
627
+ });
628
+ }
629
+ //#endregion
630
+ //#region ../harnesses/src/pi/tools.ts
631
+ /**
632
+ * engram_* tool definitions for the Pi coding agent.
633
+ *
634
+ * Thin adapters over @engram/harnesses/shared ops: typebox schemas with
635
+ * per-field descriptions and bounds, rich descriptions + promptSnippets.
636
+ */
637
+ const scopeFilter = (description) => Type.Optional(StringEnum([
638
+ "project",
639
+ "personal",
640
+ "both"
641
+ ], { description }));
642
+ const engramContextTool = {
643
+ name: "engram_context",
644
+ label: "Engram Context",
645
+ description: "Refresh the recorded memory digest for this workspace: decisions, pinned notes, gotchas, conventions. Pi recalls confident matches for the current prompt automatically. Use this tool to browse the workspace digest, page deeper, or recover when automatic recall failed or is unavailable. Returns compact one-line entries (id, type, title, tags) with decisions and pinned entries first; read a full entry with engram_show. Results are paginated - when truncated, the footer names the exact next call.",
646
+ promptSnippet: "Relevant memory is recalled automatically; use this to browse the digest, page deeper, or recover when recall is unavailable.",
647
+ parameters: Type.Object({
648
+ scope: scopeFilter(`Which memory scope to read. Default "both" (falls back to personal-only with a note outside a project).`),
649
+ limit: Type.Optional(Type.Integer({
650
+ minimum: 1,
651
+ maximum: 100,
652
+ description: `Max entries per page. Default 25.`
653
+ })),
654
+ offset: Type.Optional(Type.Integer({
655
+ minimum: 0,
656
+ description: "0-based page offset for pagination."
657
+ })),
658
+ tokens: Type.Optional(Type.Integer({
659
+ minimum: 512,
660
+ maximum: Number.MAX_SAFE_INTEGER,
661
+ description: "Budget the digest text using Engram's versioned token accounting."
662
+ }))
663
+ }),
664
+ async execute(_id, params) {
665
+ return toToolResult(await runOp(contextDigest({
666
+ scope: params.scope,
667
+ limit: params.limit,
668
+ offset: params.offset,
669
+ tokens: params.tokens
670
+ })));
671
+ }
672
+ };
673
+ const engramSearchTool = {
674
+ name: "engram_search",
675
+ label: "Engram Search",
676
+ description: "Keyword-search recorded engrams (tags score highest, then aliases, titles, types, bodies). Use when you need specifics beyond the digest - \"auth\", \"migrations\", the name of a library. Returns bounded matching snippets and relevance reasons framed as untrusted memory data, plus structured score summaries; read one with engram_show. Results are paginated. Set explain to include matched fields and score contributions in metadata.",
677
+ promptSnippet: "Use to pull specific recorded knowledge by keyword instead of re-deriving it.",
678
+ parameters: Type.Object({
679
+ query: Type.String({ description: "Search keywords (matched against tags, aliases, titles, types, and bodies)." }),
680
+ explain: Type.Optional(Type.Boolean({ description: "Include matched fields, normalized query tokens, and score contributions in metadata. Default false." })),
681
+ scope: scopeFilter("Which memory scope to search. Default \"both\"."),
682
+ limit: Type.Optional(Type.Integer({
683
+ minimum: 1,
684
+ maximum: 50,
685
+ description: `Max matches per page. Default 10.`
686
+ })),
687
+ offset: Type.Optional(Type.Integer({
688
+ minimum: 0,
689
+ description: "0-based page offset for pagination."
690
+ }))
691
+ }),
692
+ async execute(_id, params) {
693
+ return toToolResult(await runOp(searchOp({
694
+ query: params.query,
695
+ explain: params.explain,
696
+ scope: params.scope,
697
+ limit: params.limit,
698
+ offset: params.offset
699
+ })));
700
+ }
701
+ };
702
+ const engramShowTool = {
703
+ name: "engram_show",
704
+ label: "Engram Show",
705
+ description: "Read one full engram by id (unique prefixes work, e.g. \"12\" for \"0012\"): frontmatter (type, tags, dates, author, scope) plus the complete body. Use after engram_context or engram_search picked an entry worth reading. Very long bodies are sliced - the footer names the exact next call.",
706
+ promptSnippet: "Read full recorded entries by id after spotting them in context or search.",
707
+ parameters: Type.Object({
708
+ id: Type.String({ description: "Engram id or unique prefix, e.g. \"0012\" or \"12\"." }),
709
+ scope: Type.Optional(StringEnum(["project", "personal"], { description: "Where to look. Default: project inside a project, personal otherwise." })),
710
+ offset: Type.Optional(Type.Integer({
711
+ minimum: 0,
712
+ description: "0-based char offset into the body."
713
+ })),
714
+ limit: Type.Optional(Type.Integer({
715
+ minimum: 1,
716
+ description: "Max body chars to return."
717
+ }))
718
+ }),
719
+ async execute(_id, params) {
720
+ return toToolResult(await runOp(showOp({
721
+ id: params.id,
722
+ scope: params.scope,
723
+ offset: params.offset,
724
+ limit: params.limit
725
+ })));
726
+ }
727
+ };
728
+ const engramAddTool = {
729
+ name: "engram_add",
730
+ label: "Engram Add",
731
+ description: `Record a durable fact, decision, gotcha, or convention to shared memory. Use type "decision" for important choices (state the rationale and alternatives in the body), and record gotchas that cost debugging time. Do not record transient state, secrets, or anything the user says not to store. Project scope is committed to git and shared with the team; pass scope "personal" only for notes that must stay on this machine. Optional lifecycle/provenance metadata (status, supersedes, reviewAfter, expires, sourceType, sourceRef) is an unauthenticated claim, not a verified truth. Optional related links exact same-scope entry ids as directional metadata: the whole list is stored as given, and missing targets only dangle as a warning. Optional aliases are alternate names for the entry (max 20, 80 characters each); the store trims, lowercases, and deduplicates them.`,
732
+ promptSnippet: "Record durable decisions (with rationale), gotchas, and conventions as you discover them; ask scope personal only for machine-private notes.",
733
+ parameters: Type.Object({
734
+ title: Type.String({ description: "Short, descriptive title (one line)." }),
735
+ body: Type.String({ description: "Full content: rationale, context, details." }),
736
+ type: Type.Optional(StringEnum([...ENGRAM_TYPES], { description: `Entry kind. Default: the project config defaultType ("note" unless configured).` })),
737
+ scope: Type.Optional(StringEnum(["project", "personal"], { description: "Default \"project\" (team-shared, git-committed)." })),
738
+ tags: Type.Optional(Type.Array(Type.String(), { description: "Searchable tags, e.g. [\"auth\", \"deps\"]." })),
739
+ pinned: Type.Optional(Type.Boolean({ description: "Pin to the top of the digest for high-value entries." })),
740
+ status: Type.Optional(StringEnum([...ENGRAM_STATUSES], { description: "Lifecycle status: active | superseded | archived. Optional; not set unless passed." })),
741
+ supersedes: Type.Optional(Type.String({ description: "Id of the older entry this one replaces. Optional; validated when saved." })),
742
+ reviewAfter: Type.Optional(Type.String({ description: "ISO 8601 timestamp with an explicit zone, e.g. 2026-01-01T00:00:00.000Z. Optional; validated when saved." })),
743
+ expires: Type.Optional(Type.String({ description: "ISO 8601 timestamp with an explicit zone, e.g. 2026-06-01T00:00:00.000Z. Optional; validated when saved." })),
744
+ sourceType: Type.Optional(StringEnum([...SOURCE_TYPES], { description: "Provenance shape: conversation | file | url | command | other. Optional." })),
745
+ sourceRef: Type.Optional(Type.String({ description: "Source reference: path, URL, command, or conversation note. Optional; validated when saved." })),
746
+ related: Type.Optional(Type.Array(Type.String(), { description: "Exact engram ids in the same scope, e.g. [\"0002\"]. Replaces the whole list in this order; duplicates are rejected. Missing targets are advisory (a warning on check, not an error). Optional." })),
747
+ aliases: Type.Optional(Type.Array(Type.String({ maxLength: 80 }), {
748
+ maxItems: 20,
749
+ description: "Alternate names for this entry, e.g. [\"pg\", \"postgres row level security\"]. The store trims, lowercases, and deduplicates them (first occurrence wins); the whole set is replaced. Optional."
750
+ })),
751
+ confirmWrite: Type.Optional(Type.Boolean({ description: "Proceed after the user reviews and accepts a write advisory." })),
752
+ allowSecrets: Type.Optional(Type.Boolean({ description: "Write even if the secret scanner flags this content (project writes block by default). Optional." }))
753
+ }),
754
+ async execute(_id, params) {
755
+ return toToolResult(await runOp(addOp({
756
+ title: params.title,
757
+ body: params.body,
758
+ type: params.type,
759
+ scope: params.scope,
760
+ tags: params.tags,
761
+ pinned: params.pinned,
762
+ status: params.status,
763
+ supersedes: params.supersedes,
764
+ reviewAfter: params.reviewAfter,
765
+ expires: params.expires,
766
+ sourceType: params.sourceType,
767
+ sourceRef: params.sourceRef,
768
+ related: params.related,
769
+ aliases: params.aliases,
770
+ allowSecrets: params.allowSecrets,
771
+ confirmWrite: params.confirmWrite
772
+ })));
773
+ }
774
+ };
775
+ const engramEditTool = {
776
+ name: "engram_edit",
777
+ label: "Engram Edit",
778
+ description: "Update an existing engram by id (unique prefixes work). Ordinary fields (title, type, tags, body, pinned, author) are replaced when passed and preserved when omitted. The six lifecycle fields (status, supersedes, reviewAfter, expires, sourceType, sourceRef) are three-state: a concrete value replaces, null clears, omission preserves. related is three-state the same way: an array replaces the whole list with exact same-scope ids, null clears it, omission preserves; links are directional and may dangle with a warning. aliases is three-state too: an array replaces the whole set, null clears it, omission preserves. Use this to correct a title or tags, change a type, pin or unpin, or clear a lifecycle field after acting on it. Scope defaults to project inside a project and personal outside one.",
779
+ promptSnippet: "Update an existing entry: ordinary fields replace when passed, lifecycle fields are three-state (null clears, omission preserves).",
780
+ parameters: Type.Object({
781
+ id: Type.String({ description: "Engram id or unique prefix, e.g. \"0012\" or \"12\". Required." }),
782
+ scope: Type.Optional(StringEnum(["project", "personal"], { description: "Where to edit. Default: project inside a project, personal otherwise." })),
783
+ title: Type.Optional(Type.String({ description: "New title. Omit to preserve." })),
784
+ type: Type.Optional(StringEnum([...ENGRAM_TYPES], { description: "Replace entry kind. Omit to preserve." })),
785
+ tags: Type.Optional(Type.Array(Type.String(), { description: "Replace the whole tag set, e.g. [\"auth\", \"deps\"]. Omit to preserve." })),
786
+ body: Type.Optional(Type.String({ description: "New body content. Omit to preserve." })),
787
+ pinned: Type.Optional(Type.Boolean({ description: "True pins, false unpins. Omit to preserve." })),
788
+ author: Type.Optional(Type.String({ description: "Replace author. Omit to preserve." })),
789
+ status: Type.Optional(Type.Union([StringEnum([...ENGRAM_STATUSES]), Type.Null()], { description: "Lifecycle status: active | superseded | archived. Null clears; omit to preserve." })),
790
+ supersedes: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "Id of the older entry this one replaces. Null clears; omit to preserve. Validated when saved." })),
791
+ reviewAfter: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "ISO 8601 timestamp with an explicit zone, e.g. 2027-01-01T00:00:00.000Z. Null clears; omit to preserve. Validated when saved." })),
792
+ expires: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "ISO 8601 timestamp with an explicit zone, e.g. 2027-06-01T00:00:00.000Z. Null clears; omit to preserve. Validated when saved." })),
793
+ sourceType: Type.Optional(Type.Union([StringEnum([...SOURCE_TYPES]), Type.Null()], { description: "Provenance shape: conversation | file | url | command | other. Null clears; omit to preserve." })),
794
+ sourceRef: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "Source reference: path, URL, command, or conversation note. Null clears; omit to preserve. Validated when saved." })),
795
+ related: Type.Optional(Type.Union([Type.Array(Type.String()), Type.Null()], { description: "Replace the whole related list with exact same-scope ids in this order. Null clears; omit to preserve. Missing targets are advisory (a warning on check, not an error)." })),
796
+ aliases: Type.Optional(Type.Union([Type.Array(Type.String({ maxLength: 80 }), { maxItems: 20 }), Type.Null()], { description: "Replace the whole alias set with these alternate names. The store trims, lowercases, and deduplicates them. Null clears; omit to preserve." })),
797
+ confirmWrite: Type.Optional(Type.Boolean({ description: "Proceed after the user reviews and accepts a write advisory." })),
798
+ allowSecrets: Type.Optional(Type.Boolean({ description: "Write even if the secret scanner flags the resulting entry (project writes block by default). Optional." }))
799
+ }),
800
+ async execute(_id, params) {
801
+ return toToolResult(await runOp(editOp({
802
+ id: params.id,
803
+ scope: params.scope,
804
+ title: params.title,
805
+ type: params.type,
806
+ tags: params.tags,
807
+ body: params.body,
808
+ pinned: params.pinned,
809
+ author: params.author,
810
+ status: params.status,
811
+ supersedes: params.supersedes,
812
+ reviewAfter: params.reviewAfter,
813
+ expires: params.expires,
814
+ sourceType: params.sourceType,
815
+ sourceRef: params.sourceRef,
816
+ related: params.related,
817
+ aliases: params.aliases,
818
+ allowSecrets: params.allowSecrets,
819
+ confirmWrite: params.confirmWrite
820
+ })));
821
+ }
822
+ };
823
+ /** Wrap a write tool so `onWriteSuccess` fires only on non-error results.
824
+ * Keeps the base tool's shape; the 2-arg execute satisfies Pi's
825
+ * ToolDefinition contract (fewer parameters than the declared 5-arg
826
+ * signature is fine, and the base tool registers the same way), so no casts
827
+ * are needed anywhere. */
828
+ const toolWithRefresh = (base, onWriteSuccess) => ({
829
+ ...base,
830
+ async execute(id, params) {
831
+ const result = await base.execute(id, params);
832
+ if (!result.isError) onWriteSuccess();
833
+ return result;
834
+ }
835
+ });
836
+ function registerEngramTools(pi, opts = {}) {
837
+ pi.registerTool(engramContextTool);
838
+ pi.registerTool(engramSearchTool);
839
+ pi.registerTool(engramShowTool);
840
+ const notify = opts.onWriteSuccess;
841
+ pi.registerTool(notify ? toolWithRefresh(engramAddTool, notify) : engramAddTool);
842
+ pi.registerTool(notify ? toolWithRefresh(engramEditTool, notify) : engramEditTool);
843
+ }
844
+ //#endregion
845
+ //#region ../harnesses/src/pi/index.ts
846
+ function engramExtension(pi) {
847
+ const autoContext = registerAutoContext(pi);
848
+ registerCapture(pi, autoContext.invalidate);
849
+ registerEngramTools(pi, { onWriteSuccess: autoContext.invalidate });
850
+ registerEngramCommand(pi, { onWriteSuccess: autoContext.invalidate });
851
+ }
852
+ //#endregion
853
+ export { engramExtension as default };