notesoup 0.45.0 → 0.45.2

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.
Files changed (72) hide show
  1. package/dist/src/boot/text.d.ts +7 -0
  2. package/dist/src/boot/text.js +7 -0
  3. package/dist/src/budget/text.d.ts +4 -2
  4. package/dist/src/budget/text.js +4 -2
  5. package/dist/src/claude/helper.js +3 -8
  6. package/dist/src/dsh/engine.d.ts +6 -0
  7. package/dist/src/dsh/engine.js +34 -1
  8. package/dist/src/dsh/index.js +1 -1
  9. package/dist/src/dsh/tools.d.ts +1 -1
  10. package/dist/src/dsh/tools.js +2 -2
  11. package/dist/src/dsh/window.d.ts +1 -1
  12. package/dist/src/dsh/window.js +4 -6
  13. package/dist/src/notes/index.d.ts +4 -2
  14. package/dist/src/notes/index.js +4 -1
  15. package/dist/src/notes/paths.d.ts +0 -1
  16. package/dist/src/notes/paths.js +0 -1
  17. package/dist/src/pi/boot.d.ts +0 -5
  18. package/dist/src/pi/boot.js +4 -30
  19. package/dist/src/pi/budget.js +3 -3
  20. package/dist/src/pi/entries.d.ts +1 -0
  21. package/dist/src/pi/entries.js +1 -0
  22. package/dist/src/pi/notes/adapter.d.ts +1 -1
  23. package/dist/src/pi/notes/adapter.js +1 -1
  24. package/dist/src/pi/reset/artifacts.d.ts +6 -2
  25. package/dist/src/pi/reset/artifacts.js +14 -3
  26. package/dist/src/pi/reset/lifecycle.d.ts +6 -2
  27. package/dist/src/pi/reset/lifecycle.js +28 -18
  28. package/dist/src/pi/runtime.js +33 -8
  29. package/dist/src/pi/tool-result.d.ts +9 -0
  30. package/dist/src/pi/tool-result.js +4 -0
  31. package/dist/src/tools/notes.d.ts +1 -1
  32. package/dist/src/tools/notes.js +1 -1
  33. package/dist/src/tools/output.d.ts +1 -14
  34. package/dist/src/tools/output.js +1 -9
  35. package/dist/test/dependencies.test.js +53 -17
  36. package/dist/test/dsh.test.js +1 -1
  37. package/dist/test/helpers/dependency-graph.d.ts +3 -3
  38. package/dist/test/helpers/dependency-graph.js +64 -14
  39. package/dist/test/helpers/extension.js +2 -2
  40. package/dist/test/host-neutral.test.js +5 -0
  41. package/dist/test/notes.integration.test.js +4 -4
  42. package/dist/test/notes.test.js +1 -1
  43. package/dist/test/reset-lifecycle.test.js +47 -3
  44. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  45. package/mods/notesoup/dist/claude/helper.js +166 -166
  46. package/package.json +1 -1
  47. package/src/boot/text.ts +8 -0
  48. package/src/budget/text.ts +5 -2
  49. package/src/claude/helper.ts +3 -10
  50. package/src/dsh/engine.ts +27 -1
  51. package/src/dsh/index.ts +1 -1
  52. package/src/dsh/tools.ts +2 -3
  53. package/src/dsh/window.ts +4 -6
  54. package/src/notes/index.ts +4 -2
  55. package/src/notes/paths.ts +0 -1
  56. package/src/pi/boot.ts +4 -33
  57. package/src/pi/budget.ts +3 -3
  58. package/src/pi/entries.ts +1 -0
  59. package/src/pi/notes/adapter.ts +1 -2
  60. package/src/pi/notes/tools.ts +1 -1
  61. package/src/pi/reset/artifacts.ts +15 -2
  62. package/src/pi/reset/lifecycle.ts +34 -21
  63. package/src/pi/runtime.ts +36 -8
  64. package/src/pi/tool-result.ts +5 -0
  65. package/src/tools/notes.ts +1 -1
  66. package/src/tools/output.ts +1 -10
  67. package/dist/src/dsh/preflight.d.ts +0 -8
  68. package/dist/src/dsh/preflight.js +0 -35
  69. package/dist/src/pi/tool-names.d.ts +0 -7
  70. package/dist/src/pi/tool-names.js +0 -7
  71. package/src/dsh/preflight.ts +0 -29
  72. package/src/pi/tool-names.ts +0 -9
@@ -18,10 +18,15 @@ export function initialResetControl() {
18
18
  function requestForWindow(request, windowId) {
19
19
  return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
20
20
  }
21
- function manualCommit(prompt) {
21
+ function manualCommit(prompt, lastWord) {
22
+ const parting = lastWord ? { lastWord } : {};
22
23
  return prompt
23
- ? { state: initialResetControl(), effect: "commit-boundary", prompt }
24
- : { state: initialResetControl(), effect: "commit-boundary-stop" };
24
+ ? { state: initialResetControl(), effect: "commit-boundary", prompt, ...parting }
25
+ : { state: initialResetControl(), effect: "commit-boundary-stop", ...parting };
26
+ }
27
+ /** The parting line rides either committing phase; other phases never carry one. */
28
+ function requestLastWord(request) {
29
+ return request.phase === "close-out" || request.phase === "tool-requested" ? request.lastWord : undefined;
25
30
  }
26
31
  /** Pure reset-control transitions: request phases own close-out, tool commit, and fallback. */
27
32
  export function reduceResetControl(state, event) {
@@ -52,16 +57,20 @@ export function reduceResetControl(state, event) {
52
57
  if (request.phase === "tool-requested" && request.windowId === event.windowId) {
53
58
  return { state, effect: "already-pending" };
54
59
  }
60
+ const parting = event.lastWord ? { lastWord: event.lastWord } : {};
55
61
  // A manual close-out must settle so the stop actually lands; the agent's own wipe
56
62
  // call during one is only an acknowledgement, never a conversion to a turn-end
57
63
  // commit that pi's tool-batch continuation can overrun. A budget close-out still
58
64
  // upgrades: context pressure cannot wait for settlement.
59
65
  if (request.phase === "close-out" && request.windowId === event.windowId) {
60
- if (request.source === "manual")
61
- return { state, effect: "already-pending" };
62
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic" } }, effect: "close-out-armed" };
66
+ // The acknowledging call still contributes its last word; the manual commit keeps the wheel.
67
+ if (request.source === "manual") {
68
+ const lastWord = request.lastWord ?? event.lastWord;
69
+ return { state: { ...state, request: { ...request, ...(lastWord ? { lastWord } : {}) } }, effect: "already-pending" };
70
+ }
71
+ return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic", ...parting } }, effect: "close-out-armed" };
63
72
  }
64
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool" } }, effect: "close-out-armed" };
73
+ return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool", ...parting } }, effect: "close-out-armed" };
65
74
  }
66
75
  case "turn_end": {
67
76
  const facts = event.facts;
@@ -87,11 +96,12 @@ export function reduceResetControl(state, event) {
87
96
  // A direct tool request commits after the whole tool batch. The budget cutoff is
88
97
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
89
98
  if (request.phase === "tool-requested" || facts.hardReserveDue) {
99
+ const lastWord = requestLastWord(request);
90
100
  if (manual && request.prompt)
91
- return manualCommit(request.prompt);
101
+ return manualCommit(request.prompt, lastWord);
92
102
  if (manual)
93
- return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop" };
94
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary" };
103
+ return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop", ...(lastWord ? { lastWord } : {}) };
104
+ return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...(lastWord ? { lastWord } : {}) };
95
105
  }
96
106
  return { state: { request, overflow: "idle" }, effect: "none" };
97
107
  }
@@ -117,7 +127,7 @@ export function reduceResetControl(state, event) {
117
127
  // An explicit manual wipe is not an automatic recovery/retry. It must still
118
128
  // clear on overflow, including when automatic reset is disabled.
119
129
  if (manual && facts.enabled)
120
- return manualCommit(request.prompt);
130
+ return manualCommit(request.prompt, requestLastWord(request));
121
131
  const spent = state.overflow === "pending-spent";
122
132
  if (!facts.enabled || !facts.automaticResetEnabled) {
123
133
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
@@ -129,7 +139,7 @@ export function reduceResetControl(state, event) {
129
139
  }
130
140
  if (facts.queued)
131
141
  return { state: { ...state, request }, effect: "none" };
132
- return manualCommit(request.prompt);
142
+ return manualCommit(request.prompt, requestLastWord(request));
133
143
  }
134
144
  case "settled":
135
145
  return { state: initialResetControl(), effect: "none" };
@@ -152,7 +162,7 @@ export function registerResetLifecycle(pi, options) {
152
162
  let lifecycleGeneration = 0;
153
163
  let control = initialResetControl();
154
164
  const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
155
- const resetBoundaryResult = async (entries, ctx, continueAfterReset, prompt) => {
165
+ const resetBoundaryResult = async (entries, ctx, continueAfterReset, prompt, lastWord) => {
156
166
  const generation = lifecycleGeneration;
157
167
  const outerGeneration = options.getLifecycleGeneration?.();
158
168
  const sessionId = ctx.sessionManager.getSessionId();
@@ -162,7 +172,7 @@ export function registerResetLifecycle(pi, options) {
162
172
  ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
163
173
  let resetDrafts;
164
174
  try {
165
- resetDrafts = await options.buildReset(ctx, isCurrent, prompt);
175
+ resetDrafts = await options.buildReset(ctx, isCurrent, prompt, lastWord);
166
176
  }
167
177
  catch (error) {
168
178
  if (isCurrent())
@@ -214,7 +224,7 @@ export function registerResetLifecycle(pi, options) {
214
224
  });
215
225
  control = decision.state;
216
226
  if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop")
217
- return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt);
227
+ return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt, decision.lastWord);
218
228
  return entries.length > 0 ? { entries } : undefined;
219
229
  });
220
230
  pi.on("agent_before_settle", async (event, ctx) => {
@@ -236,7 +246,7 @@ export function registerResetLifecycle(pi, options) {
236
246
  return { entries: event.entries, continue: false };
237
247
  if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow")
238
248
  return undefined;
239
- return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt);
249
+ return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt, decision.lastWord);
240
250
  });
241
251
  pi.on("session_before_compact", (event, ctx) => {
242
252
  if (!sessionActive)
@@ -268,8 +278,8 @@ export function registerResetLifecycle(pi, options) {
268
278
  control = decision.state;
269
279
  return decision.effect;
270
280
  },
271
- request(windowId) {
272
- const decision = reduceResetControl(control, { type: "tool_request", windowId });
281
+ request(windowId, lastWord) {
282
+ const decision = reduceResetControl(control, { type: "tool_request", windowId, ...(lastWord ? { lastWord } : {}) });
273
283
  control = decision.state;
274
284
  return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
275
285
  },
@@ -3,13 +3,13 @@ import { resetBoundaryCommitted } from "./reset/committed.js";
3
3
  import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
- import { output } from "../tools/output.js";
6
+ import { output } from "./tool-result.js";
7
7
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
- import { buildResetDrafts } from "./reset/artifacts.js";
9
+ import { buildResetDrafts, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
11
  import { WARNING_CONTENT } from "../budget/text.js";
12
- import { ensureBoot } from "./boot.js";
12
+ import { buildBootMessage, sendBoot } from "./boot.js";
13
13
  import { errorMessage } from "../error-message.js";
14
14
  function readPackageVersion() {
15
15
  for (const up of ["../../package.json", "../../../package.json"]) {
@@ -26,6 +26,31 @@ const buildLabel = `v${readPackageVersion()}`;
26
26
  function branchHasWindowMarker(ctx, fromId) {
27
27
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
28
28
  }
29
+ /**
30
+ * Boot entry point for `session_start` / `session_tree`. Ordinary startup ensures one root
31
+ * boot; a reset marker instead asks reset-artifact repair to complete its persisted tail.
32
+ */
33
+ async function ensureBoot(pi, ctx, notifyIncompleteNotes, isCurrent = () => true) {
34
+ const sessionId = ctx.sessionManager.getSessionId();
35
+ const reset = currentReset(ctx);
36
+ const windowId = reset?.data.windowId ?? rootWindowId(sessionId);
37
+ const stillCurrent = () => isCurrent() &&
38
+ ctx.signal?.aborted !== true &&
39
+ ctx.sessionManager.getSessionId() === sessionId &&
40
+ currentWindowId(ctx) === windowId;
41
+ if (reset) {
42
+ await repairResetTail(pi, ctx, reset, notifyIncompleteNotes, stillCurrent);
43
+ return;
44
+ }
45
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
46
+ return;
47
+ const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
48
+ if (!stillCurrent())
49
+ return;
50
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
51
+ return;
52
+ sendBoot(pi, boot);
53
+ }
29
54
  /** Register the context-window runtime and its context-owned commands/tools. */
30
55
  export function registerContext(pi, settingsManager) {
31
56
  let enabled = true;
@@ -180,17 +205,17 @@ export function registerContext(pi, settingsManager) {
180
205
  pi.registerTool(defineTool({
181
206
  name: "clear_memory",
182
207
  label: "Clear memory",
183
- description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive.",
184
- parameters: Type.Object({}, { additionalProperties: false }),
185
- async execute(_id, _params, _signal, _update, ctx) {
208
+ description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to leave one short visible line where this window closes.",
209
+ parameters: Type.Object({ last_word: Type.Optional(Type.String({ description: "A parting line shown where this window closes; the next window can read it too." })) }, { additionalProperties: false }),
210
+ async execute(_id, params, _signal, _update, ctx) {
186
211
  if (!enabled)
187
212
  return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
188
- return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
213
+ return output({ status: resets.request(currentWindowId(ctx), sanitizeLastWord(params.last_word)) }, undefined, true);
189
214
  },
190
215
  }));
191
216
  const resets = registerResetLifecycle(pi, {
192
217
  isEnabled: () => enabled,
193
- buildReset: (ctx, isCurrent, prompt) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt),
218
+ buildReset: (ctx, isCurrent, prompt, lastWord) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt, lastWord),
194
219
  getLifecycleGeneration: () => lifecycleGeneration,
195
220
  onResetReady: (_ctx, drafts) => {
196
221
  const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
@@ -2,6 +2,15 @@
2
2
  import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  import { type Operation, type Outcome } from "../tools/result.js";
5
+ /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
6
+ export declare function output(value: unknown, details?: unknown, terminate?: boolean): {
7
+ content: {
8
+ type: "text";
9
+ text: string;
10
+ }[];
11
+ details: unknown;
12
+ terminate: boolean;
13
+ };
5
14
  export type ToolNamespace = {
6
15
  name: string;
7
16
  description: string;
@@ -1,6 +1,10 @@
1
1
  /** Pi transport for host-neutral operations. */
2
2
  import { defineTool } from "@earendil-works/pi-coding-agent";
3
3
  import { wireResult } from "../tools/result.js";
4
+ /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
5
+ export function output(value, details, terminate = false) {
6
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
7
+ }
4
8
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
5
9
  function piOperationResult(render, outcome) {
6
10
  return {
@@ -149,7 +149,7 @@ export declare const notesUpdate: {
149
149
  code: Type.TString;
150
150
  }>]>;
151
151
  readonly executionMode: "sequential";
152
- readonly execute: (params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string) => Promise<Outcome<NotesUpdateData>>;
152
+ readonly execute: (params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff?: (change: NoteChange) => string) => Promise<Outcome<NotesUpdateData>>;
153
153
  readonly render: typeof renderUpdate;
154
154
  };
155
155
  export declare const notesReadParameters: Type.TObject<{
@@ -230,7 +230,7 @@ export const notesUpdate = {
230
230
  name: "notes_update", label: "Notes update",
231
231
  description: `Edit a note, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
232
232
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
233
- async execute(params, identity, renderDiff) {
233
+ async execute(params, identity, renderDiff = (change) => change.kind === "none" ? "" : `note ${change.kind}`) {
234
234
  try {
235
235
  const store = createNotesStore(identity);
236
236
  // Empty filler is not a request: models that pass every parameter get the edit path.
@@ -1,4 +1,4 @@
1
- /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
1
+ /** Shared output budget primitives. */
2
2
  export declare const TOOL_OUTPUT_MAX_BYTES: number;
3
3
  /** The per-call limit as the model reads it in refusals. */
4
4
  export declare const TOOL_OUTPUT_LIMIT = "32 KB";
@@ -7,16 +7,3 @@ export declare const MAX_READ_WINDOW_CHARS = 50000;
7
7
  export declare const HISTORY_PREVIEW_CHARS = 1200;
8
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
9
9
  export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
10
- /**
11
- * Encode a structured result through the common tool result boundary. `details` is slim
12
- * metadata for logs/UI (pi convention: never a second copy of the payload) and stays
13
- * undefined unless the tool has metadata worth persisting.
14
- */
15
- export declare function output(value: unknown, details?: unknown, terminate?: boolean): {
16
- content: {
17
- type: "text";
18
- text: string;
19
- }[];
20
- details: unknown;
21
- terminate: boolean;
22
- };
@@ -1,4 +1,4 @@
1
- /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
1
+ /** Shared output budget primitives. */
2
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
3
3
  /** The per-call limit as the model reads it in refusals. */
4
4
  export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
@@ -23,11 +23,3 @@ export function prefixFit(text, fits) {
23
23
  }
24
24
  return chars.slice(0, low).join("");
25
25
  }
26
- /**
27
- * Encode a structured result through the common tool result boundary. `details` is slim
28
- * metadata for logs/UI (pi convention: never a second copy of the payload) and stays
29
- * undefined unless the tool has metadata worth persisting.
30
- */
31
- export function output(value, details, terminate = false) {
32
- return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
33
- }
@@ -35,24 +35,14 @@ test("all shared domains resolve without any direct or transitive SDK, Pi adapte
35
35
  assert.equal(manifest.peerDependencies[name], "*", `${name} follows Pi's host dependency contract`);
36
36
  }
37
37
  });
38
- test("dsh resolves into shared domains without Pi, Claude, dream or the root entry", () => {
38
+ test("each adapter resolves only its own host, shared domains and the public notes entry", () => {
39
39
  const root = repository();
40
- const seen = new Set();
41
- const inspect = (file) => {
42
- if (seen.has(file))
43
- return;
44
- seen.add(file);
45
- assert.ok(!["pi", "claude", "dream"].some((adapter) => file.startsWith(join(root, "src", adapter) + "/")) && file !== join(root, "src/index.ts"), file);
46
- const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
47
- for (const reference of moduleReferences(source)) {
48
- assert.ok(!/^@(?:earendil-works|mariozechner)\/pi-/.test(reference), reference);
49
- const resolved = ts.resolveModuleName(reference, file, options, ts.sys).resolvedModule;
50
- if (resolved && resolved.resolvedFileName.startsWith(join(root, "src") + "/"))
51
- inspect(resolved.resolvedFileName);
52
- }
53
- };
54
- for (const file of sources(join(root, "src/dsh")))
55
- inspect(file);
40
+ for (const adapter of ["pi", "claude", "dsh"]) {
41
+ const entries = sources(join(root, "src", adapter));
42
+ if (adapter === "claude")
43
+ entries.push(...sources(join(root, "mods/notesoup/hooks")));
44
+ assert.deepEqual(dependencyViolations(root, entries, options, new Set(["typebox"])), [], adapter);
45
+ }
56
46
  });
57
47
  test("dependency guard follows indirect types, re-exports, dynamic imports and import-type edges through resolved aliases", (t) => {
58
48
  const root = mkdtempSync(join(tmpdir(), "context-dependencies-"));
@@ -86,6 +76,52 @@ test("dependency guard follows indirect types, re-exports, dynamic imports and i
86
76
  put("src/notes/safe.ts", "export type Value = string;");
87
77
  assert.deepEqual(dependencyViolations(root, ["src/notes/identity.ts"], fixtureOptions, new Set()), [], "a host-neutral type/re-export chain is allowed");
88
78
  });
79
+ test("adapter policies reject foreign hosts and notes internals, including reachable Claude hooks", (t) => {
80
+ const root = mkdtempSync(join(tmpdir(), "context-adapters-"));
81
+ t.after(() => rmSync(root, { recursive: true, force: true }));
82
+ const put = (path, text) => { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), text); };
83
+ put("package.json", '{"type":"module"}');
84
+ put("src/notes/index.ts", 'export type { Note } from "./store.js";');
85
+ put("src/notes/store.ts", "export type Note = string;");
86
+ const hosts = ["pi", "claude", "dsh"];
87
+ const sdks = ["@earendil-works/pi-coding-agent", "claude-code", "@deepseek-ai/cordis"];
88
+ for (const host of hosts)
89
+ put(`src/${host}/native.ts`, "export const value = 1;");
90
+ for (const [index, host] of hosts.entries()) {
91
+ const entry = `src/${host}/entry.ts`;
92
+ const check = () => dependencyViolations(root, [entry], options, new Set());
93
+ put(entry, `export type { Note } from "../notes/index.js"; import type { Native } from "${sdks[index]}";`);
94
+ assert.deepEqual(check(), [], `${host} may use its SDK and the notes entry`);
95
+ put(entry, 'export type { Note } from "../notes/store.js";');
96
+ assert.deepEqual(check(), [`${entry} -> src/notes/store.ts`]);
97
+ const other = (index + 1) % hosts.length;
98
+ put(entry, `export { value } from "../${hosts[other]}/native.js";`);
99
+ assert.deepEqual(check(), [`${entry} -> src/${hosts[other]}/native.ts`]);
100
+ put(entry, `export type { Native } from "${sdks[other]}";`);
101
+ assert.deepEqual(check(), [`${entry} -> ${sdks[other]}`]);
102
+ }
103
+ put("src/claude/entry.ts", 'export { value } from "../../mods/notesoup/hooks/register.js";');
104
+ put("mods/notesoup/hooks/register.ts", 'export { value } from "../../../src/pi/native.js";');
105
+ assert.deepEqual(dependencyViolations(root, ["src/claude/entry.ts"], options, new Set()), ["src/claude/entry.ts -> mods/notesoup/hooks/register.ts -> src/pi/native.ts"]);
106
+ put("mods/notesoup/hooks/register.ts", 'export type { Note } from "../../../src/notes/index.js";');
107
+ assert.deepEqual(dependencyViolations(root, ["src/claude/entry.ts"], options, new Set()), []);
108
+ put("src/pi/entry.ts", 'export type { Note } from "@notes-internal";');
109
+ assert.deepEqual(dependencyViolations(root, ["src/pi/entry.ts"], { ...options, baseUrl: root, paths: { "@notes-internal": ["src/notes/store.ts"] } }, new Set()), ["src/pi/entry.ts -> src/notes/store.ts"]);
110
+ });
111
+ test("runtime cycles are rejected but explicit and implicitly erased type edges are allowed", (t) => {
112
+ const root = mkdtempSync(join(tmpdir(), "context-cycles-"));
113
+ t.after(() => rmSync(root, { recursive: true, force: true }));
114
+ mkdirSync(join(root, "src/boot"), { recursive: true });
115
+ writeFileSync(join(root, "package.json"), '{"type":"module"}');
116
+ writeFileSync(join(root, "src/boot/a.ts"), 'import { b } from "./b.js"; export const a = () => b; export type A = string;');
117
+ const check = () => dependencyViolations(root, ["src/boot/a.ts"], options, new Set());
118
+ writeFileSync(join(root, "src/boot/b.ts"), 'export { a as b } from "./a.js";');
119
+ assert.deepEqual(check(), ["runtime cycle: src/boot/a.ts -> src/boot/b.ts -> src/boot/a.ts"]);
120
+ writeFileSync(join(root, "src/boot/b.ts"), 'export type B = import("./a.js").A; export const b = 1;');
121
+ assert.deepEqual(check(), []);
122
+ writeFileSync(join(root, "src/boot/b.ts"), 'import { A } from "./a.js"; export type B = A; export const b = 1;');
123
+ assert.deepEqual(check(), []);
124
+ });
89
125
  test("AST guard sees every literal module edge, not import-like prose or comments", () => {
90
126
  const source = ts.createSourceFile("edges.ts", `
91
127
  // import("not-an-edge")
@@ -16,7 +16,7 @@ import { dshFixture } from "./helpers/dsh.js";
16
16
  import { decodeHistory } from "../src/dsh/history.js";
17
17
  import { checkpointSnapshot, notesIdentity, recoverSnapshot, WINDOW_RECORD } from "../src/dsh/window.js";
18
18
  import { measureBudget } from "../src/dsh/budget.js";
19
- import { preflight } from "../src/dsh/preflight.js";
19
+ import { preflight } from "../src/dsh/engine.js";
20
20
  import { BasicCompactionEngine } from "@deepseek-ai/dsh-compaction-basic";
21
21
  function prompt(text) { return createUserMessage({ content: [{ type: "text", text }], source: { kind: "user" } }); }
22
22
  async function run(agent, text) { agent.followup(prompt(text)); await agent.whenIdle(); }
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- /** AST edges include erased types and re-exports, not merely emitted runtime imports. */
3
- export declare function moduleReferences(source: ts.SourceFile): string[];
4
- /** Resolve every reachable edge with TypeScript, including local aliases and external declarations. */
2
+ /** All AST edges enforce boundaries; emitted edges alone determine runtime cycles. */
3
+ export declare function moduleReferences(source: ts.SourceFile, runtimeOnly?: boolean): string[];
4
+ /** Resolve reachable edges, preserving each importing module's core/adapter ownership. */
5
5
  export declare function dependencyViolations(root: string, entries: string[], options: ts.CompilerOptions, runtimeDependencies: Set<string>): string[];
@@ -3,9 +3,23 @@ import { readFileSync, realpathSync } from "node:fs";
3
3
  import { relative, resolve, sep } from "node:path";
4
4
  import ts from "typescript";
5
5
  const builtins = new Set(builtinModules.map((name) => name.replace(/^node:/, "")));
6
- const hostPackage = /^(?:(?:@earendil-works|@mariozechner)\/pi-(?:ai|agent-core|coding-agent)|@deepseek-ai\/(?:dsh(?:-[^/]+)?|cordis(?:-[^/]+)?))(?:\/|$)/;
7
- /** AST edges include erased types and re-exports, not merely emitted runtime imports. */
8
- export function moduleReferences(source) {
6
+ function packageAdapter(specifier) {
7
+ if (/^@(?:earendil-works|mariozechner)\//.test(specifier))
8
+ return "pi";
9
+ if (/^@deepseek-ai\//.test(specifier))
10
+ return "dsh";
11
+ if (/^(?:claude-code|@anthropic-ai\/[^/]+)(?:\/|$)/.test(specifier))
12
+ return "claude";
13
+ return undefined;
14
+ }
15
+ /** All AST edges enforce boundaries; emitted edges alone determine runtime cycles. */
16
+ export function moduleReferences(source, runtimeOnly = false) {
17
+ if (runtimeOnly) {
18
+ if (source.isDeclarationFile)
19
+ return [];
20
+ const emitted = ts.transpileModule(source.text, { fileName: source.fileName, compilerOptions: { module: ts.ModuleKind.Preserve, target: ts.ScriptTarget.ES2022 } }).outputText;
21
+ source = ts.createSourceFile(source.fileName + ".js", emitted, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
22
+ }
9
23
  const references = new Set();
10
24
  const add = (node) => {
11
25
  if (node && ts.isStringLiteralLike(node))
@@ -28,31 +42,41 @@ export function moduleReferences(source) {
28
42
  function packageName(specifier) {
29
43
  return specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
30
44
  }
31
- /** Resolve every reachable edge with TypeScript, including local aliases and external declarations. */
45
+ /** Resolve reachable edges, preserving each importing module's core/adapter ownership. */
32
46
  export function dependencyViolations(root, entries, options, runtimeDependencies) {
33
47
  root = realpathSync(root);
34
48
  const violations = [];
35
49
  const visited = new Set();
50
+ const runtime = new Map();
36
51
  const cache = ts.createModuleResolutionCache(root, (path) => path, options);
37
52
  const sourceRoot = resolve(root, "src");
53
+ const rootEntry = resolve(sourceRoot, "index.ts");
54
+ const notesEntry = resolve(sourceRoot, "notes/index.ts");
38
55
  const display = (path) => relative(root, path).split(sep).join("/");
39
- const native = (path) => path === resolve(sourceRoot, "index.ts") || ["pi", "claude", "dsh"].some((adapter) => path.startsWith(resolve(sourceRoot, adapter) + sep)) || /node_modules\/(?:(?:@earendil-works|@mariozechner)\/pi-(?:ai|agent-core|coding-agent)|@deepseek-ai\/(?:dsh(?:-[^/]+)?|cordis(?:-[^/]+)?))(?:\/|$)/.test(path.split(sep).join("/"));
56
+ const local = (file) => file.startsWith(sourceRoot + sep) || file.startsWith(resolve(root, "mods/notesoup") + sep);
57
+ const adapter = (file) => {
58
+ const path = display(file);
59
+ return file === rootEntry ? "pi" : /^src\/(pi|claude|dsh)\//.exec(path)?.[1]
60
+ ?? (path.startsWith("mods/notesoup/") ? "claude" : packageAdapter(file.split(sep).join("/").split("/node_modules/").at(-1)));
61
+ };
40
62
  const walk = (file, chain) => {
41
63
  file = realpathSync(file);
42
- if (native(file)) {
43
- violations.push([...chain, display(file)].join(" -> "));
44
- return;
45
- }
46
64
  if (visited.has(file))
47
65
  return;
48
66
  visited.add(file);
49
67
  const here = [...chain, display(file)];
68
+ const owner = adapter(file);
50
69
  const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
70
+ const emitted = new Set(local(file) ? moduleReferences(source, true) : []);
71
+ if (local(file))
72
+ runtime.set(file, []);
51
73
  for (const specifier of moduleReferences(source)) {
52
74
  if (specifier.startsWith("node:") || builtins.has(specifier))
53
75
  continue;
54
- if (hostPackage.test(specifier)) {
55
- violations.push([...here, specifier].join(" -> "));
76
+ const sdk = packageAdapter(specifier);
77
+ if (sdk) {
78
+ if (owner !== sdk)
79
+ violations.push([...here, specifier].join(" -> "));
56
80
  continue;
57
81
  }
58
82
  const resolution = ts.resolveModuleName(specifier, file, options, ts.sys, cache).resolvedModule;
@@ -60,14 +84,40 @@ export function dependencyViolations(root, entries, options, runtimeDependencies
60
84
  violations.push([...here, `unresolved ${specifier}`].join(" -> "));
61
85
  continue;
62
86
  }
63
- // A shared dependency must be intentional, not accidentally supplied by a Pi peer/dev dependency.
64
- if (file.startsWith(sourceRoot + sep) && resolution.isExternalLibraryImport && !runtimeDependencies.has(packageName(specifier))) {
87
+ const target = realpathSync(resolution.resolvedFileName);
88
+ const targetOwner = adapter(target);
89
+ if (target === rootEntry || (targetOwner && targetOwner !== owner) ||
90
+ (owner && target.startsWith(resolve(sourceRoot, "notes") + sep) && target !== notesEntry) ||
91
+ (owner === "dsh" && target.startsWith(resolve(sourceRoot, "dream") + sep))) {
92
+ violations.push([...here, display(target)].join(" -> "));
93
+ continue;
94
+ }
95
+ // Core dependencies must be intentional, not accidentally supplied by a host.
96
+ if (!owner && file.startsWith(sourceRoot + sep) && resolution.isExternalLibraryImport && !runtimeDependencies.has(packageName(specifier))) {
65
97
  violations.push([...here, `undeclared runtime dependency ${specifier}`].join(" -> "));
66
98
  }
67
- walk(resolution.resolvedFileName, here);
99
+ if (emitted.has(specifier) && local(target))
100
+ runtime.get(file).push(target);
101
+ if (!targetOwner || local(target))
102
+ walk(target, here);
68
103
  }
69
104
  };
70
105
  for (const entry of entries)
71
106
  walk(resolve(root, entry), []);
107
+ const checked = new Set();
108
+ const cycles = (file, path) => {
109
+ const start = path.indexOf(file);
110
+ if (start >= 0) {
111
+ violations.push(`runtime cycle: ${[...path.slice(start), file].map(display).join(" -> ")}`);
112
+ return;
113
+ }
114
+ if (checked.has(file))
115
+ return;
116
+ checked.add(file);
117
+ for (const target of runtime.get(file) ?? [])
118
+ cycles(target, [...path, file]);
119
+ };
120
+ for (const file of runtime.keys())
121
+ cycles(file, []);
72
122
  return violations;
73
123
  }
@@ -1,5 +1,5 @@
1
1
  import { notesIdentityFromPi } from "../../src/pi/notes/adapter.js";
2
- import { PI_TOOL_NAMES } from "../../src/pi/tool-names.js";
2
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../../src/boot/text.js";
3
3
  import assert from "node:assert/strict";
4
4
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
@@ -135,7 +135,7 @@ export function makeExtension(sessionManager, settingsManager) {
135
135
  }
136
136
  export async function explicitBoot(ctx, currentWindowId, previousWindowId) {
137
137
  return renderBootBlock({
138
- tools: PI_TOOL_NAMES,
138
+ tools: DEFAULT_BOOT_TOOL_NAMES,
139
139
  agentName: agentSlug(),
140
140
  modelName: modelSlug(ctx),
141
141
  firstWindowId: rootWindowId(ctx.sessionManager.getSessionId()),
@@ -191,6 +191,11 @@ test("shared note operations return canonical outcomes with a body-only read win
191
191
  }));
192
192
  assert.equal(updated.change_kind, "body");
193
193
  assert.equal(updated.diff, "caller-rendered-diff");
194
+ const defaultReceipt = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "gamma", newText: "delta" }] }, notesIdentity));
195
+ assert.equal(defaultReceipt.diff, "note body");
196
+ const unchanged = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "delta", newText: "delta" }] }, notesIdentity));
197
+ assert.equal(unchanged.change_kind, "none");
198
+ assert.equal(unchanged.diff, "");
194
199
  // Frontmatter is metadata, not body: the window addresses the body and counts only the body.
195
200
  const stored = await createNotesStore(notesIdentity).read("@project/test.md");
196
201
  assert.ok(stored, "the note is on disk");
@@ -1,5 +1,5 @@
1
1
  import { notesIdentityFromPi } from "../src/pi/notes/adapter.js";
2
- import { PI_TOOL_NAMES } from "../src/pi/tool-names.js";
2
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
3
3
  import assert from "node:assert/strict";
4
4
  import { mkdirSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { dirname } from "node:path";
@@ -179,7 +179,7 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
179
179
  });
180
180
  assert.deepEqual([...calls.entries()], [["session", 1], ["project", 1], ["human", 1], ["agent", 1], ["model", 1]], "each selected home is loaded exactly once");
181
181
  const renderData = {
182
- tools: PI_TOOL_NAMES,
182
+ tools: DEFAULT_BOOT_TOOL_NAMES,
183
183
  agentName: "root",
184
184
  modelName: "default",
185
185
  firstWindowId: "pcw:test:root",
@@ -237,7 +237,7 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
237
237
  });
238
238
  assert.deepEqual(oneFailed.unavailable.map((home) => home.label), ["@human"]);
239
239
  const oneFailedText = renderBootBlock({
240
- tools: PI_TOOL_NAMES,
240
+ tools: DEFAULT_BOOT_TOOL_NAMES,
241
241
  agentName: "root",
242
242
  modelName: "default",
243
243
  firstWindowId: "pcw:test:root",
@@ -252,7 +252,7 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
252
252
  });
253
253
  assert.equal(allFailed.unavailable.length, 5);
254
254
  const allFailedText = renderBootBlock({
255
- tools: PI_TOOL_NAMES,
255
+ tools: DEFAULT_BOOT_TOOL_NAMES,
256
256
  agentName: "root",
257
257
  modelName: "default",
258
258
  firstWindowId: "pcw:test:root",
@@ -13,7 +13,7 @@ import { join } from "node:path";
13
13
  import test from "node:test";
14
14
  import { Check } from "typebox/value";
15
15
  import { parseNote } from "../src/notes/frontmatter.js";
16
- import { projectKey } from "../src/notes/paths.js";
16
+ import { projectKey } from "../src/notes/index.js";
17
17
  import { globToRegExp } from "../src/notes/address.js";
18
18
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
19
19
  import { notesList, notesSearch } from "../src/tools/notes.js";