@howaboua/pi-notes-compaction 0.0.12 → 0.0.14

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 (42) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/PCC-INTEGRATION.md +3 -1
  3. package/README.md +36 -22
  4. package/package.json +4 -6
  5. package/src/agent-identity.ts +112 -10
  6. package/src/attachment-sharing.ts +37 -6
  7. package/src/attachment-snapshot.ts +16 -6
  8. package/src/context-sharing.ts +15 -1
  9. package/src/extension-hooks.ts +15 -2
  10. package/src/extension-sharing.ts +25 -11
  11. package/src/fresh-checkpoint.ts +30 -4
  12. package/src/fresh-notes.ts +44 -33
  13. package/src/history-search.ts +1 -1
  14. package/src/history-windows.ts +12 -2
  15. package/src/history.ts +7 -1
  16. package/src/index.ts +5 -19
  17. package/src/integrations.ts +26 -26
  18. package/src/lifecycle.ts +26 -10
  19. package/src/model-role-config.ts +10 -30
  20. package/src/model-role-screen.ts +48 -32
  21. package/src/model-roles.ts +177 -315
  22. package/src/note-result.ts +70 -0
  23. package/src/note-save-marker.ts +23 -9
  24. package/src/notes-lookup.ts +5 -2
  25. package/src/notes.ts +8 -3
  26. package/src/query-executor.ts +34 -15
  27. package/src/query-input.ts +12 -1
  28. package/src/remote.ts +26 -7
  29. package/src/rollover.ts +17 -5
  30. package/src/saved-session.ts +1 -0
  31. package/src/saved-sharing-records.ts +18 -9
  32. package/src/settings-command.ts +1 -1
  33. package/src/shared-notes.ts +49 -20
  34. package/src/shared-session-reader.ts +8 -4
  35. package/src/sharing-service.ts +25 -8
  36. package/src/task-boundary.ts +1 -1
  37. package/src/tool-contracts.ts +50 -58
  38. package/src/tools.ts +34 -50
  39. package/src/window-message.ts +19 -8
  40. package/src/windows.ts +2 -2
  41. package/changelog.ts +0 -337
  42. package/src/model-role-editor.ts +0 -40
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ CustomMessageEntryDraft,
2
3
  ExtensionAPI,
3
4
  ExtensionCommandContext,
4
5
  ExtensionContext,
@@ -6,358 +7,219 @@ import type {
6
7
  import type { NotesActivation } from "./activation.js";
7
8
  import type { NotesLifecycle } from "./lifecycle.js";
8
9
  import {
9
- type ModelRole,
10
10
  type RoleConfig,
11
11
  readRoleConfig,
12
- writeRoleConfig,
12
+ roleConfigPath,
13
13
  } from "./model-role-config.js";
14
- import { editModelRole } from "./model-role-editor.js";
15
14
  import { openModelRoleScreen } from "./model-role-screen.js";
16
15
  import { modelIsActive } from "./settings.js";
16
+ import { windowDetails } from "./windows.js";
17
+
18
+ const GUIDANCE_TYPE = "notes-compaction:roles";
19
+
20
+ export interface ModelRoleHandoff {
21
+ id: string;
22
+ activate(ctx: ExtensionContext): Promise<void>;
23
+ }
17
24
 
18
25
  export function createModelRoles(
19
26
  pi: ExtensionAPI,
20
27
  activation: NotesActivation,
21
28
  lifecycle: NotesLifecycle,
22
- refresh: () => void,
23
29
  ) {
24
- let config: RoleConfig = { enabled: false, roles: [] };
30
+ let config: RoleConfig = { roles: [] };
25
31
  let configError: string | undefined;
26
- try {
27
- config = readRoleConfig();
28
- } catch (error) {
29
- configError = String(error);
30
- }
31
- type Recommendation = {
32
- role: ModelRole;
33
- reason: string;
34
- continuity: string;
35
- session: string;
36
- provider: string | undefined;
37
- model: string | undefined;
38
- reasoning: string;
39
- settled: boolean;
40
- };
41
- let pending: Recommendation | undefined;
42
- let selectedRole: string | undefined;
43
- let completed = false;
44
- let generation = 0;
45
- const enabled = () => lifecycle.active && config.enabled;
46
- const reset = () => {
47
- generation++;
48
- pending = undefined;
49
- completed = false;
50
- };
51
- const save = (value: RoleConfig) => {
52
- writeRoleConfig(value);
53
- config = value;
54
- selectedRole = undefined;
55
- configError = undefined;
56
- reset();
57
- refresh();
58
- pi.sendMessage(
59
- {
60
- customType: "model-role-update",
61
- display: false,
62
- content: config.enabled
63
- ? "Role preferences updated. Discover current preferences with notes action=roles before recommending a handoff"
64
- : "Role recommendations disabled. Keep the current model unless the user directs a switch",
65
- },
66
- { deliverAs: "nextTurn" },
67
- );
68
- };
69
- const query = async (
70
- args: { role?: string; reason?: string; continuity?: string },
71
- ctx: ExtensionContext,
72
- ) => {
73
- if (!enabled())
74
- throw new Error(
75
- "Role recommendations are off. The user can enable them with /roles",
76
- );
77
- let result: unknown;
78
- if (!args.role) {
79
- if (args.reason || args.continuity)
80
- throw new Error(
81
- "Supply role, reason and continuity together, or use notes action=roles to discover preferences",
82
- );
83
- result = {
84
- current: {
85
- provider: ctx.model?.provider,
86
- model: ctx.model?.id,
87
- reasoning: pi.getThinkingLevel(),
88
- selectedRole: selectedRole ?? null,
89
- matchingRoles: config.roles
90
- .filter(
91
- (role) =>
92
- role.provider === ctx.model?.provider &&
93
- role.model === ctx.model?.id,
94
- )
95
- .map((role) => role.id),
96
- },
97
- roles: config.roles,
98
- pending,
99
- };
100
- } else {
101
- const role = config.roles.find((role) => role.id === args.role);
102
- if (!role)
103
- throw new Error(
104
- "Unknown role. Use notes action=roles for configured roles",
105
- );
106
- if (!args.reason?.trim() || !args.continuity?.trim())
107
- throw new Error("A recommendation needs reason and continuity");
108
- if (
109
- selectedRole === role.id &&
110
- role.provider === ctx.model?.provider &&
111
- role.model === ctx.model.id
112
- )
113
- throw new Error(
114
- "Already using this role's model and reasoning; continue here",
115
- );
116
- pending = {
117
- role: { ...role },
118
- reason: args.reason.trim(),
119
- continuity: args.continuity.trim(),
120
- session: ctx.sessionManager.getSessionId(),
121
- provider: ctx.model?.provider,
122
- model: ctx.model?.id,
123
- reasoning: pi.getThinkingLevel(),
124
- settled: false,
125
- };
126
- result = {
127
- recommendation: role.id,
128
- reason: pending.reason,
129
- continuity: pending.continuity,
130
- status:
131
- "Awaiting run settlement and user action: /roles accept. Continue here unless accepted",
132
- };
32
+ let roleIdsChanged: ((ids: string[]) => void) | undefined;
33
+ const load = () => {
34
+ try {
35
+ config = readRoleConfig();
36
+ configError = undefined;
37
+ } catch (error) {
38
+ config = { roles: [] };
39
+ configError = error instanceof Error ? error.message : String(error);
133
40
  }
134
- return {
135
- content: [{ type: "text" as const, text: JSON.stringify(result) }],
136
- details: {},
137
- };
41
+ roleIdsChanged?.(config.roles.map((role) => role.id).sort());
138
42
  };
139
- pi.on("before_agent_start", (_event, ctx) => {
43
+ pi.on("before_agent_start", (event, ctx) => {
140
44
  activation.refreshActivation(ctx);
141
- refresh();
142
- reset();
143
- if (!enabled()) return;
144
- const content =
145
- "Model role preferences are enabled. Discover current model and configured preferences with notes action=roles. Use notes action=recommend_handoff with role, evidence in reason, and continuity when accumulated conversation favours a different role, never after fixed turns. Keep the current model until the user accepts.";
146
- const present = ctx.sessionManager
147
- .buildContextEntries()
148
- .some(
45
+ if (!lifecycle.active) return;
46
+ const previousError = configError;
47
+ load();
48
+ if (configError && configError !== previousError)
49
+ ctx.ui.notify(`Model roles unavailable: ${configError}`, "error");
50
+ const startingWindow =
51
+ event.messageType === "custom"
52
+ ? windowDetails({ ...event.message, type: "custom_message" })
53
+ : undefined;
54
+ const previous = lifecycle.windows
55
+ .projectBranch(ctx.sessionManager.buildContextEntries())
56
+ .findLast(
149
57
  (entry) =>
150
- entry.type === "message" &&
151
- entry.message.role === "custom" &&
152
- entry.message.customType === "model-role-guidance" &&
153
- entry.message.content === content,
58
+ entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE,
154
59
  );
155
- if (!present)
156
- return {
157
- message: { customType: "model-role-guidance", content, display: false },
158
- };
159
- });
160
- pi.on("model_select", () => {
161
- reset();
162
- selectedRole = undefined;
163
- });
164
- pi.on("thinking_level_select", () => {
165
- reset();
166
- selectedRole = undefined;
167
- });
168
- const navigation = () => {
169
- selectedRole = undefined;
170
- reset();
171
- };
172
- pi.on("session_before_switch", navigation);
173
- pi.on("session_before_fork", navigation);
174
- pi.on("session_before_tree", navigation);
175
- pi.on("session_tree", reset);
176
- pi.on("agent_before_settle", (event) => {
177
- completed = event.outcome === "completed";
178
- });
179
- pi.on("agent_settled", (_event, ctx) => {
180
- if (!pending) {
181
- completed = false;
60
+ if (!config.roles.length && !previous) return;
61
+ const reasoning = pi.getThinkingLevel();
62
+ const matching = config.roles
63
+ .filter(
64
+ (role) =>
65
+ role.provider === ctx.model?.provider &&
66
+ role.model === ctx.model?.id &&
67
+ role.reasoning === reasoning,
68
+ )
69
+ .map((role) => role.id);
70
+ const currentRole =
71
+ matching.length === 0
72
+ ? "none (no matching preset)"
73
+ : matching.length === 1
74
+ ? matching.join(", ")
75
+ : `ambiguous (${matching.join(", ")})`;
76
+ const content = config.roles.length
77
+ ? [
78
+ `Current role: ${currentRole}`,
79
+ lifecycle.gptPromptMode()
80
+ ? 'Roles=user preferences, not capability limits. Switch for clear, sustained task/scope change, not one specialised prompt. Any role can do general work. Bounded specialist detour→consider subagent. Save notes→new_context({role: "name"}); omit role→keep role.'
81
+ : 'Roles are user preferences, not capability limits. Switch for clear, sustained change of task or scope, not single specialised prompt. Any role can do general work. Consider subagents for a bounded specialist detour. Save notes, then call new_context({role: "name"}); omit role to keep the current role.',
82
+ ...config.roles.map((role) => `- ${role.id}: ${role.description}`),
83
+ ].join("\n")
84
+ : "No model roles available. Call new_context without role.";
85
+ if (
86
+ startingWindow?.kind !== "window" &&
87
+ previous?.type === "custom_message" &&
88
+ previous.content === content
89
+ )
182
90
  return;
183
- }
184
- if (!enabled() || pending.settled || _event.aborted || !completed) {
185
- reset();
91
+ const message: CustomMessageEntryDraft = {
92
+ type: "custom_message",
93
+ customType: GUIDANCE_TYPE,
94
+ content,
95
+ display: false,
96
+ details: {},
97
+ };
98
+ return { message: lifecycle.prepareReminder?.(message) ?? message };
99
+ });
100
+ pi.on("context", (event, ctx) => {
101
+ if (
102
+ !lifecycle.active ||
103
+ event.messages.some(
104
+ (message) =>
105
+ message.role === "custom" && message.customType === GUIDANCE_TYPE,
106
+ )
107
+ )
186
108
  return;
187
- }
188
- pending.settled = true;
189
- ctx.ui.notify(
190
- `Recommended role: ${pending.role.id} (${pending.role.provider}/${pending.role.model})\n${pending.reason}\n/roles accept to switch in this conversation; /roles dismiss to keep the current model`,
191
- "info",
109
+ const summary = event.messages.findIndex(
110
+ (message) => message.role === "compactionSummary",
192
111
  );
193
- });
194
- pi.on("session_start", (_event, ctx) => {
195
- reset();
196
- selectedRole = undefined;
197
- if (configError)
198
- ctx.ui.notify(`Role recommendations are off: ${configError}`, "error");
112
+ if (summary < 0) return;
113
+ const previous = ctx.sessionManager
114
+ .getBranch()
115
+ .findLast(
116
+ (entry) =>
117
+ entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE,
118
+ );
119
+ if (previous?.type !== "custom_message") return;
120
+ // In-run compaction has no new kickoff. Restore the owned entry before its summary.
121
+ return {
122
+ messages: [
123
+ ...event.messages.slice(0, summary),
124
+ {
125
+ role: "custom" as const,
126
+ customType: previous.customType,
127
+ content: previous.content,
128
+ display: false,
129
+ details: previous.details,
130
+ timestamp: Date.parse(previous.timestamp),
131
+ },
132
+ ...event.messages.slice(summary),
133
+ ],
134
+ };
199
135
  });
200
136
 
201
- async function switchRole(
202
- role: ModelRole,
203
- ctx: ExtensionCommandContext,
204
- recommendation?: Recommendation,
205
- ) {
206
- const session = ctx.sessionManager.getSessionId();
207
- const provider = ctx.model?.provider;
208
- const modelId = ctx.model?.id;
209
- const reasoning = pi.getThinkingLevel();
210
- const version = generation;
211
- await ctx.waitForIdle();
212
- if (
213
- !ctx.isIdle() ||
214
- generation !== version ||
215
- ctx.sessionManager.getSessionId() !== session ||
216
- ctx.model?.provider !== provider ||
217
- ctx.model?.id !== modelId ||
218
- pi.getThinkingLevel() !== reasoning ||
219
- (recommendation &&
220
- (pending !== recommendation ||
221
- !recommendation.settled ||
222
- recommendation.session !== session ||
223
- recommendation.provider !== provider ||
224
- recommendation.model !== modelId ||
225
- recommendation.reasoning !== reasoning))
226
- ) {
227
- ctx.ui.notify(
228
- "The conversation or model changed. Keep the current model; request a new recommendation or choose a role with /roles",
229
- "warning",
137
+ async function prepare(
138
+ id: string,
139
+ ctx: ExtensionContext,
140
+ ): Promise<ModelRoleHandoff> {
141
+ load();
142
+ if (configError)
143
+ throw new Error(
144
+ "Model roles are unavailable. Continue here and ask the user to check /roles.",
145
+ );
146
+ const role = config.roles.find((candidate) => candidate.id === id);
147
+ if (!role)
148
+ throw new Error(
149
+ `Unknown role ${JSON.stringify(id)}. Use a configured role or omit role to keep the current model.`,
230
150
  );
231
- return;
232
- }
233
151
  const model = ctx.modelRegistry.find(role.provider, role.model);
234
152
  if (!model)
235
153
  throw new Error(
236
- `Model unavailable: ${role.provider}/${role.model}. Choose another model with /roles`,
154
+ `Role ${id} is unavailable. Continue here and ask the user to check its model in /roles.`,
237
155
  );
238
156
  if (!lifecycle.active || !modelIsActive(activation.settings, model))
239
157
  throw new Error(
240
- "Notes must be active for both models. Check Active and model whitelist in /notes before switching",
158
+ `Notes must be active for this session and role ${id}. Ask the user to check /notes before switching.`,
241
159
  );
242
- // Use Pi's existing session and replay projection; never recreate messages or tool pairs.
243
- if (provider !== model.provider || modelId !== model.id) {
244
- if (!(await pi.setModel(model)))
245
- throw new Error(
246
- `Could not select ${role.provider}/${role.model}; check provider authentication or choose another role with /roles`,
247
- );
248
- }
249
- pi.setThinkingLevel(role.reasoning);
250
- selectedRole = role.id;
251
- reset();
252
- pi.sendMessage(
253
- {
254
- customType: "model-role-handoff",
255
- display: true,
256
- content: `Using role ${role.id}: ${role.description}\nModel: ${role.provider}/${role.model}; reasoning: ${pi.getThinkingLevel()}. Conversation retained.${recommendation ? `\nReason: ${recommendation.reason}\nContinuity: ${recommendation.continuity}` : ""}`,
160
+ const session = ctx.sessionManager.getSessionId();
161
+ const source = ctx.model;
162
+ const reasoning = pi.getThinkingLevel();
163
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
164
+ if (!auth.ok)
165
+ throw new Error(
166
+ `Role ${id} has no usable provider access. Continue here and ask the user to check its login or API configuration.`,
167
+ );
168
+ return {
169
+ id,
170
+ async activate(current) {
171
+ if (
172
+ current.sessionManager.getSessionId() !== session ||
173
+ current.model?.provider !== source?.provider ||
174
+ current.model?.id !== source?.id ||
175
+ pi.getThinkingLevel() !== reasoning ||
176
+ !lifecycle.active ||
177
+ !modelIsActive(activation.settings, model)
178
+ )
179
+ throw new Error(
180
+ "The session or model settings changed. Continue here and request a new role handoff if still needed.",
181
+ );
182
+ if (source?.provider !== model.provider || source?.id !== model.id) {
183
+ if (!(await pi.setModel(model)))
184
+ throw new Error(
185
+ `Could not start role ${id}. Check provider access in /roles and retry.`,
186
+ );
187
+ }
188
+ pi.setThinkingLevel(role.reasoning);
257
189
  },
258
- { deliverAs: "nextTurn" },
259
- );
260
- ctx.ui.notify(
261
- `Using ${role.id}: ${role.provider}/${role.model} (${pi.getThinkingLevel()}). Conversation retained`,
262
- "info",
263
- );
190
+ };
264
191
  }
265
192
 
266
- const command = async (args: string, ctx: ExtensionCommandContext) => {
267
- try {
268
- const input = args.trim();
269
- if (input === "dismiss") {
270
- reset();
271
- ctx.ui.notify(
272
- "Recommendation dismissed; current model retained",
273
- "info",
274
- );
275
- return;
276
- }
277
- if (input === "accept") {
278
- if (!pending) {
279
- ctx.ui.notify(
280
- "No current recommendation. Use /roles to choose a role",
281
- "info",
282
- );
283
- return;
284
- }
285
- await switchRole(pending.role, ctx, pending);
286
- return;
287
- }
288
- if (input) {
289
- ctx.ui.notify("Usage: /roles [accept|dismiss]", "error");
290
- return;
291
- }
292
- if (!ctx.hasUI)
293
- throw new Error(
294
- "Role configuration needs interactive Pi. /roles accept and /roles dismiss remain available",
295
- );
296
- while (true) {
297
- const choice = await openModelRoleScreen(
298
- ctx,
299
- [
300
- ...(pending
301
- ? ["Accept recommendation", "Dismiss recommendation"]
302
- : []),
303
- "Switch role",
304
- "Add or replace role",
305
- "Remove role",
306
- config.enabled
307
- ? "Disable recommendations"
308
- : "Enable recommendations",
309
- ],
310
- config.roles,
311
- );
312
- if (!choice) return;
313
- if (choice === "notes-tab") return "notes" as const;
314
- if (choice === "Accept recommendation" && pending)
315
- await switchRole(pending.role, ctx, pending);
316
- else if (choice === "Dismiss recommendation") reset();
317
- else if (choice === "Switch role") {
318
- const id = await ctx.ui.select(
319
- "Switch role (conversation retained)",
320
- config.roles.map((role) => role.id),
321
- );
322
- const role = config.roles.find((role) => role.id === id);
323
- if (role) await switchRole(role, ctx);
324
- } else if (choice === "Add or replace role") {
325
- const role = await editModelRole(ctx);
326
- if (role)
327
- save({
328
- ...config,
329
- roles: [
330
- ...config.roles.filter((existing) => existing.id !== role.id),
331
- role,
332
- ],
333
- });
334
- } else if (choice === "Remove role") {
335
- const id = await ctx.ui.select(
336
- "Remove role",
337
- config.roles.map((role) => role.id),
338
- );
339
- if (!id) return;
340
- save({
341
- ...config,
342
- roles: config.roles.filter((role) => role.id !== id),
343
- });
344
- } else if (
345
- choice === "Enable recommendations" ||
346
- choice === "Disable recommendations"
347
- ) {
348
- save({ ...config, enabled: choice === "Enable recommendations" });
349
- }
350
- }
351
- } catch (error) {
193
+ async function command(args: string, ctx: ExtensionCommandContext) {
194
+ if (args.trim()) {
352
195
  ctx.ui.notify(
353
- error instanceof Error ? error.message : String(error),
354
- "error",
196
+ "Use /roles to view roles and JSON configuration guidance.",
197
+ "info",
355
198
  );
199
+ return;
356
200
  }
357
- };
201
+ if (!ctx.hasUI) {
202
+ ctx.ui.notify(
203
+ `Configure model roles in ${roleConfigPath()}. Open /roles in interactive Pi for guidance.`,
204
+ "info",
205
+ );
206
+ return;
207
+ }
208
+ load();
209
+ return (await openModelRoleScreen(
210
+ ctx,
211
+ config.roles,
212
+ roleConfigPath(),
213
+ configError,
214
+ )) === "notes-tab"
215
+ ? ("notes" as const)
216
+ : undefined;
217
+ }
358
218
  return {
359
- enabled,
219
+ prepare,
360
220
  command,
361
- query,
221
+ onRoleIdsChanged(listener: (ids: string[]) => void) {
222
+ roleIdsChanged = listener;
223
+ },
362
224
  };
363
225
  }
@@ -0,0 +1,70 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { Check } from "typebox/value";
4
+
5
+ const OPTIONAL_STRING = Type.Optional(Type.String());
6
+ const OPTIONAL_BOOLEAN = Type.Optional(Type.Boolean());
7
+ const MATCH = Type.Object({ line_number: Type.Integer(), line: Type.String() });
8
+
9
+ // Pi codemode needs this declaration to return structuredContent rather than text.
10
+ export const NOTES_OUTPUT_SCHEMA = Type.Object(
11
+ {},
12
+ { additionalProperties: true },
13
+ );
14
+
15
+ const NOTES_RESULT_SCHEMA = Type.Object(
16
+ {
17
+ file: Type.Optional(
18
+ Type.Union([
19
+ Type.Object({
20
+ path: Type.String(),
21
+ content: OPTIONAL_STRING,
22
+ start_line: Type.Optional(Type.Integer()),
23
+ stop_line: Type.Optional(Type.Integer()),
24
+ total_lines: Type.Optional(Type.Integer()),
25
+ append_only: OPTIONAL_BOOLEAN,
26
+ }),
27
+ Type.Null(),
28
+ ]),
29
+ ),
30
+ files: Type.Optional(
31
+ Type.Array(
32
+ Type.Object({
33
+ path: Type.String(),
34
+ updated_at: OPTIONAL_STRING,
35
+ created_at: OPTIONAL_STRING,
36
+ matches: Type.Optional(Type.Array(MATCH)),
37
+ truncated: OPTIONAL_BOOLEAN,
38
+ append_only: OPTIONAL_BOOLEAN,
39
+ }),
40
+ ),
41
+ ),
42
+ usage: OPTIONAL_STRING,
43
+ warnings: Type.Optional(Type.Array(Type.String())),
44
+ warning: OPTIONAL_STRING,
45
+ truncated: OPTIONAL_BOOLEAN,
46
+ read_only: OPTIONAL_BOOLEAN,
47
+ saved_at: OPTIONAL_STRING,
48
+ captured_at: OPTIONAL_STRING,
49
+ results: OPTIONAL_STRING,
50
+ actions: Type.Optional(Type.Record(Type.String(), Type.String())),
51
+ writes: OPTIONAL_STRING,
52
+ paths: OPTIONAL_STRING,
53
+ ranges: OPTIONAL_STRING,
54
+ defaults: OPTIONAL_STRING,
55
+ },
56
+ { additionalProperties: false },
57
+ );
58
+
59
+ /** One canonical payload for native text and every programmatic caller. */
60
+ export function noteResult(payload: unknown): AgentToolResult<unknown> {
61
+ if (!Check(NOTES_RESULT_SCHEMA, payload))
62
+ throw new Error(
63
+ "Notes returned invalid data. Read the note before retrying a write.",
64
+ );
65
+ return {
66
+ content: [{ type: "text", text: JSON.stringify(payload) }],
67
+ structuredContent: payload,
68
+ details: {},
69
+ };
70
+ }
@@ -11,9 +11,16 @@ const NOTE_SAVE_MARKER = "codex-note-save-marker";
11
11
  export function registerNoteSaveMarkers(
12
12
  pi: ExtensionAPI,
13
13
  enabled: () => boolean,
14
+ currentWindowId: () => string | undefined,
14
15
  ) {
15
16
  let manager: ExtensionContext["sessionManager"] | undefined;
16
- let cached: { leaf: string | null; id: string | undefined } | undefined;
17
+ let cached:
18
+ | {
19
+ leaf: string | null;
20
+ windowId: string | undefined;
21
+ id: string | undefined;
22
+ }
23
+ | undefined;
17
24
  const restore = (_event: unknown, ctx: ExtensionContext) => {
18
25
  manager = ctx.sessionManager;
19
26
  cached = undefined;
@@ -31,17 +38,24 @@ export function registerNoteSaveMarkers(
31
38
  return new (class extends Text {
32
39
  override render(width: number): string[] {
33
40
  const leaf = manager?.getLeafId();
34
- if (manager && (!cached || cached.leaf !== leaf))
41
+ const windowId = currentWindowId();
42
+ if (
43
+ manager &&
44
+ (!cached || cached.leaf !== leaf || cached.windowId !== windowId)
45
+ ) {
46
+ const branch = manager.getBranch();
35
47
  cached = {
36
48
  leaf: manager.getLeafId(),
37
- id: manager
38
- .getBranch()
39
- .findLast(
40
- (item) =>
41
- item.type === "custom" &&
42
- item.customType === NOTE_SAVE_MARKER,
43
- )?.id,
49
+ windowId,
50
+ id: hasFreshNotes(branch, windowId)
51
+ ? branch.findLast(
52
+ (item) =>
53
+ item.type === "custom" &&
54
+ item.customType === NOTE_SAVE_MARKER,
55
+ )?.id
56
+ : undefined,
44
57
  };
58
+ }
45
59
  const visible = manager && enabled() && cached?.id === entry.id;
46
60
  this.setText(visible ? content : "");
47
61
  return visible ? super.render(width) : [];
@@ -10,9 +10,9 @@ import type {
10
10
  } from "./bridge.js";
11
11
  import { queryKey } from "./bridge.js";
12
12
  import type { NotesLifecycle } from "./lifecycle.js";
13
+ import { noteResult } from "./note-result.js";
13
14
  import { CACHE_RECEIPT, sessionRef, sourceSessionIds } from "./notes.js";
14
15
  import type { NotesStore } from "./store.js";
15
- import { result } from "./tool-contracts.js";
16
16
 
17
17
  export async function lookupNotes(
18
18
  pi: ExtensionAPI,
@@ -85,7 +85,10 @@ export async function lookupNotes(
85
85
  warnings.push(
86
86
  "Older matches may refer to replaced notes. Read a note before relying on its excerpt; read returns the current saved version.",
87
87
  );
88
- const output = result({ ...local, ...(warnings.length ? { warnings } : {}) });
88
+ const output = noteResult({
89
+ ...local,
90
+ ...(warnings.length ? { warnings } : {}),
91
+ });
89
92
  if (shared)
90
93
  return {
91
94
  ...output,