@howaboua/pi-notes-compaction 0.0.15 → 0.0.17

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 (86) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +17 -2
  4. package/index.ts +8 -0
  5. package/package.json +16 -13
  6. package/src/board/context-briefing.ts +245 -0
  7. package/src/board/delivery.ts +85 -0
  8. package/src/guidance.ts +121 -0
  9. package/src/notes/AGENTS.md +27 -0
  10. package/src/{activation.ts → notes/activation.ts} +8 -10
  11. package/src/{attachment-sharing.ts → notes/attachment-sharing.ts} +1 -1
  12. package/src/{attachment-snapshot.ts → notes/attachment-snapshot.ts} +33 -20
  13. package/src/{context-sharing.ts → notes/context-sharing.ts} +7 -2
  14. package/src/{extension-hooks.ts → notes/extension-hooks.ts} +1 -12
  15. package/src/{extension-sharing.ts → notes/extension-sharing.ts} +1 -1
  16. package/src/notes/feature.ts +234 -0
  17. package/src/notes/history-search-pruning.mjs +154 -0
  18. package/src/{history-search-worker.mjs → notes/history-search-worker.mjs} +1 -1
  19. package/src/{history-windows.ts → notes/history-windows.ts} +10 -22
  20. package/src/{history.ts → notes/history.ts} +6 -5
  21. package/src/{index.ts → notes/index.ts} +20 -11
  22. package/src/{integrations.ts → notes/integrations.ts} +19 -3
  23. package/src/{lifecycle.ts → notes/lifecycle.ts} +0 -2
  24. package/src/{note-query.ts → notes/note-query.ts} +3 -5
  25. package/src/notes/note-result.ts +119 -0
  26. package/src/{note-save-marker.ts → notes/note-save-marker.ts} +3 -1
  27. package/src/{notes-lookup.ts → notes/notes-lookup.ts} +1 -1
  28. package/src/{query-executor.ts → notes/query-executor.ts} +7 -2
  29. package/src/{query-input.ts → notes/query-input.ts} +1 -0
  30. package/src/{remote.ts → notes/remote.ts} +1 -1
  31. package/src/{saved-session-access.ts → notes/saved-session-access.ts} +14 -10
  32. package/src/{saved-session.ts → notes/saved-session.ts} +31 -15
  33. package/src/notes/saved-sharing-records.ts +170 -0
  34. package/src/notes/session-pruning-cleanup.mjs +163 -0
  35. package/src/notes/session-pruning-exit.mjs +312 -0
  36. package/src/{session-pruning-screen.ts → notes/session-pruning-screen.ts} +1 -1
  37. package/src/notes/session-pruning-sparse.mjs +133 -0
  38. package/src/notes/session-pruning-state.mjs +123 -0
  39. package/src/{session-pruning.ts → notes/session-pruning.ts} +39 -6
  40. package/src/{settings-command.ts → notes/settings-command.ts} +29 -42
  41. package/src/{settings-controls.ts → notes/settings-controls.ts} +61 -75
  42. package/src/{settings-screen.ts → notes/settings-screen.ts} +25 -11
  43. package/src/{settings.ts → notes/settings.ts} +37 -6
  44. package/src/{shared-notes.ts → notes/shared-notes.ts} +21 -13
  45. package/src/{shared-session-reader.ts → notes/shared-session-reader.ts} +8 -11
  46. package/src/{sharing-service.ts → notes/sharing-service.ts} +1 -1
  47. package/src/{tool-contracts.ts → notes/tool-contracts.ts} +71 -44
  48. package/src/{tools.ts → notes/tools.ts} +2 -2
  49. package/src/{tree-handoff-read.ts → notes/tree-handoff-read.ts} +47 -32
  50. package/src/{window-message.ts → notes/window-message.ts} +8 -25
  51. package/src/settings-navigation.ts +11 -0
  52. package/src/timestamps.ts +3 -0
  53. package/tsconfig.json +9 -0
  54. package/src/history-search-pruning.mjs +0 -120
  55. package/src/note-result.ts +0 -70
  56. package/src/saved-sharing-records.ts +0 -135
  57. /package/src/{agent-identity.ts → notes/agent-identity.ts} +0 -0
  58. /package/src/{binding-startup.ts → notes/binding-startup.ts} +0 -0
  59. /package/src/{bridge.ts → notes/bridge.ts} +0 -0
  60. /package/src/{compaction-projection.ts → notes/compaction-projection.ts} +0 -0
  61. /package/src/{context-owner.ts → notes/context-owner.ts} +0 -0
  62. /package/src/{fresh-checkpoint.ts → notes/fresh-checkpoint.ts} +0 -0
  63. /package/src/{fresh-notes.ts → notes/fresh-notes.ts} +0 -0
  64. /package/src/{history-search-protocol.ts → notes/history-search-protocol.ts} +0 -0
  65. /package/src/{history-search.ts → notes/history-search.ts} +0 -0
  66. /package/src/{idle-admission.ts → notes/idle-admission.ts} +0 -0
  67. /package/src/{model-role-config.ts → notes/model-role-config.ts} +0 -0
  68. /package/src/{model-role-screen.ts → notes/model-role-screen.ts} +0 -0
  69. /package/src/{model-roles.ts → notes/model-roles.ts} +0 -0
  70. /package/src/{notes.ts → notes/notes.ts} +0 -0
  71. /package/src/{rollover.ts → notes/rollover.ts} +0 -0
  72. /package/src/{saved-session-index.mjs → notes/saved-session-index.mjs} +0 -0
  73. /package/src/{saved-session.mjs → notes/saved-session.mjs} +0 -0
  74. /package/src/{session-pruning-content.ts → notes/session-pruning-content.ts} +0 -0
  75. /package/src/{session-pruning-plan.ts → notes/session-pruning-plan.ts} +0 -0
  76. /package/src/{session-pruning-policy.ts → notes/session-pruning-policy.ts} +0 -0
  77. /package/src/{session-pruning-source.ts → notes/session-pruning-source.ts} +0 -0
  78. /package/src/{session-pruning-transaction.ts → notes/session-pruning-transaction.ts} +0 -0
  79. /package/src/{sqlite.mjs → notes/sqlite.mjs} +0 -0
  80. /package/src/{store.ts → notes/store.ts} +0 -0
  81. /package/src/{task-boundary.ts → notes/task-boundary.ts} +0 -0
  82. /package/src/{tree-archive-manifest.mjs → notes/tree-archive-manifest.mjs} +0 -0
  83. /package/src/{tree-archive.ts → notes/tree-archive.ts} +0 -0
  84. /package/src/{tree-checkpoint.ts → notes/tree-checkpoint.ts} +0 -0
  85. /package/src/{window-checkpoint.ts → notes/window-checkpoint.ts} +0 -0
  86. /package/src/{windows.ts → notes/windows.ts} +0 -0
@@ -1,7 +1,6 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import type { Static } from "typebox";
4
- import { Check } from "typebox/value";
3
+ import { compile, type Static } from "@earendil-works/pi-schema";
5
4
  import {
6
5
  canonicalAgentName,
7
6
  contextAgentNames,
@@ -28,6 +27,12 @@ import type { NotesStore } from "./store.js";
28
27
 
29
28
  export { savedNotesIdentity } from "./saved-sharing-records.js";
30
29
 
30
+ const detachmentValidator = compile(Detachment);
31
+ const memberValidator = compile(Member);
32
+ const parentValidator = compile(Parent);
33
+ const planValidator = compile(Plan);
34
+ const routeValidator = compile(Route);
35
+
31
36
  function records(session: SavedNotesSession, kind: string): unknown[] {
32
37
  return session.entries.flatMap((entry) =>
33
38
  entry.type === "custom" && entry.customType === kind ? [entry.data] : [],
@@ -193,7 +198,7 @@ async function readSharedSession(
193
198
  const routes = new Map<string, Static<typeof Route>>();
194
199
  for (const value of records(session, "shepherdr-attachment-route"))
195
200
  if (
196
- Check(Route, value) &&
201
+ routeValidator.check(value) &&
197
202
  value.plan.controllerSessionId === identity.threadId
198
203
  )
199
204
  routes.set(`${value.machine}\0${value.sessionFile}`, value);
@@ -232,10 +237,11 @@ async function readSharedSession(
232
237
  }
233
238
  const owner = records(session, "shepherdr-attachment-owner").findLast(
234
239
  (value) =>
235
- Check(Plan, value) && value.targetSessionId === identity.threadId,
240
+ planValidator.check(value) &&
241
+ value.targetSessionId === identity.threadId,
236
242
  );
237
243
  if (
238
- Check(Plan, owner) &&
244
+ planValidator.check(owner) &&
239
245
  owner.context &&
240
246
  (inside(destination, owner.context.controllerAlias) ||
241
247
  destination === canonicalAgentName(owner.context.controller.threadId))
@@ -253,9 +259,10 @@ async function readSharedSession(
253
259
  "shepherdr-attachment-detached",
254
260
  ).findLast(
255
261
  (value) =>
256
- Check(Detachment, value) && isDeepStrictEqual(value.plan, owner),
262
+ detachmentValidator.check(value) &&
263
+ isDeepStrictEqual(value.plan, owner),
257
264
  );
258
- const snapshot = Check(Detachment, detached)
265
+ const snapshot = detachmentValidator.check(detached)
259
266
  ? detached.context
260
267
  : undefined;
261
268
  return reference(
@@ -289,15 +296,16 @@ async function readSharedSession(
289
296
  let result: Record<string, unknown> | undefined;
290
297
  const members = records(session, "herdr-context-child").filter(
291
298
  (value) =>
292
- Check(Member, value) &&
299
+ memberValidator.check(value) &&
293
300
  value.threadId === identity.threadId &&
294
301
  value.sessionId === identity.sessionId,
295
302
  );
296
303
  const direct = members.filter(
297
- (member) => Check(Member, member) && member.agentName === destination,
304
+ (member) =>
305
+ memberValidator.check(member) && member.agentName === destination,
298
306
  );
299
307
  for (const member of direct.length ? direct : members) {
300
- if (!Check(Member, member)) continue;
308
+ if (!memberValidator.check(member)) continue;
301
309
  const location = locator(session, member.machine, member.sessionFile);
302
310
  // Only exploratory edges may be skipped. A recorded target must report its failure.
303
311
  const saved = await (direct.length
@@ -312,7 +320,7 @@ async function readSharedSession(
312
320
  contextStorageAgentName(child) !== member.agentName)
313
321
  )
314
322
  throw new Error(
315
- "Saved shared notes belong to a different agent family",
323
+ "This session cannot access the requested saved context. Request an accessible handoff or note path from its owner.",
316
324
  );
317
325
  const candidate = await resolve(saved, destination, query);
318
326
  if (candidate) {
@@ -326,7 +334,7 @@ async function readSharedSession(
326
334
  if (direct.length) return result;
327
335
  const routing = identity.routing;
328
336
  const suffix = ".jsonl.shepherdr-context.json";
329
- if (Check(Parent, routing)) {
337
+ if (parentValidator.check(routing)) {
330
338
  const parentLocator = routing.savedParent
331
339
  ? locator(
332
340
  session,
@@ -401,7 +409,7 @@ async function readSharedSession(
401
409
  )
402
410
  throw Object.assign(
403
411
  new Error(
404
- `Saved shared ${namespace} are unavailable on this machine. Restore access to the saved Pi JSONL session, then retry.`,
412
+ `Saved ${namespace} could not be read on this machine. Request a handoff from the owner, or ask the user to restore access before retrying.`,
405
413
  { cause: error },
406
414
  ),
407
415
  { code: "SAVED_SESSION_UNAVAILABLE" },
@@ -1,5 +1,6 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { Check } from "typebox/value";
2
+ import { compile } from "@earendil-works/pi-schema";
3
+ import { minuteTimestamp } from "../timestamps.js";
3
4
  import { contextStorageAgentName } from "./agent-identity.js";
4
5
  import type { SavedSessionLocator } from "./context-sharing.js";
5
6
  import { useHistory } from "./history.js";
@@ -15,6 +16,8 @@ import {
15
16
  } from "./saved-sharing-records.js";
16
17
  import type { NotesStore } from "./store.js";
17
18
 
19
+ const snapshotValidator = compile(Snapshot);
20
+
18
21
  export function createSharedSessionReader(
19
22
  store: Pick<NotesStore, "read">,
20
23
  access:
@@ -69,16 +72,9 @@ export function createSharedSessionReader(
69
72
  normalizeNoteParams(query, native),
70
73
  outputAgent,
71
74
  )),
72
- ...(namespace === "notes"
73
- ? {
74
- read_only: true,
75
- warning:
76
- "Only saved notes are included; other notes may be missing",
77
- }
78
- : {}),
79
75
  ...(session.savedAt === undefined
80
76
  ? {}
81
- : { saved_at: new Date(session.savedAt).toISOString() }),
77
+ : { saved_at: minuteTimestamp(session.savedAt) }),
82
78
  };
83
79
  }
84
80
  async function reference(
@@ -114,7 +110,7 @@ export function createSharedSessionReader(
114
110
  namespace === "history" ||
115
111
  (destination !== identity.agentName &&
116
112
  destination !== contextStorageAgentName(identity)) ||
117
- !Check(Snapshot, retained)
113
+ !snapshotValidator.check(retained)
118
114
  )
119
115
  return;
120
116
  const entry: SessionEntry = {
@@ -138,7 +134,8 @@ export function createSharedSessionReader(
138
134
  query,
139
135
  destination,
140
136
  )),
141
- captured_at: new Date(retained.timestamp).toISOString(),
137
+ read_only: true,
138
+ captured_at: minuteTimestamp(retained.timestamp),
142
139
  warning: detached
143
140
  ? "Read-only notes captured when sharing ended; later changes are not included"
144
141
  : "The latest notes are unavailable; this read-only copy may be outdated",
@@ -264,7 +264,7 @@ export function registerContextSharingService(
264
264
  if (!savedSessionLoader)
265
265
  throw Object.assign(
266
266
  new Error(
267
- "Saved shared sessions on that machine are unavailable. Resume the shared agent and reconnect its machine, or make its saved Pi JSONL session available locally.",
267
+ "Saved context on that machine is unavailable. Request a handoff from its owner, or ask the user to reconnect the machine before retrying.",
268
268
  ),
269
269
  { code: "SAVED_SESSION_UNAVAILABLE" },
270
270
  );
@@ -1,7 +1,17 @@
1
- import { StringEnum } from "@earendil-works/pi-ai";
2
1
  import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
3
- import { Type } from "typebox";
4
- import { Check } from "typebox/value";
2
+ import {
3
+ bool,
4
+ compile,
5
+ int,
6
+ nul,
7
+ obj,
8
+ oneOf,
9
+ opt,
10
+ type Schema,
11
+ str,
12
+ union,
13
+ type Validator,
14
+ } from "@earendil-works/pi-schema";
5
15
  import type { LookupQuery } from "./bridge.js";
6
16
  import { noteResult } from "./note-result.js";
7
17
  import { internalQueryArguments, normalizeQueryInput } from "./query-input.js";
@@ -29,14 +39,14 @@ export const NOTES_ROUTING_GUIDELINE =
29
39
  export const NEW_CONTEXT_DESCRIPTION =
30
40
  "Start fresh context window. MUST save notes before calling";
31
41
  export const GPT_NEW_CONTEXT_DESCRIPTION = "Save notes→fresh context";
32
- const STRING = Type.Optional(Type.String());
33
- const INTEGER = Type.Optional(Type.Integer({ minimum: 1 }));
34
- const LINE = Type.Optional(Type.Union([Type.Integer(), Type.Null()]));
35
- export const NOTES_SCHEMA = Type.Object(
42
+ const STRING = opt(str());
43
+ const INTEGER = opt(int({ minimum: 1 }));
44
+ const LINE = opt(union([int(), nul()]));
45
+ export const NOTES_SCHEMA = obj(
36
46
  {
37
- action: Type.Optional(StringEnum(NOTES_ACTIONS)),
38
- path: Type.Optional(
39
- Type.Union([Type.String(), Type.Null()], {
47
+ action: opt({ ...oneOf(NOTES_ACTIONS), type: "string" }),
48
+ path: opt(
49
+ union([str(), nul()], {
40
50
  description:
41
51
  "File for read/write/append; prefix for list/search; virtual filesystem, not files in the project",
42
52
  }),
@@ -47,49 +57,52 @@ export const NOTES_SCHEMA = Type.Object(
47
57
  stop_line: LINE,
48
58
  limit: INTEGER,
49
59
  max_matches_per_file: INTEGER,
50
- file_order: Type.Optional(StringEnum(["ascending", "descending"])),
51
- file_order_by: Type.Optional(
52
- StringEnum(["name", "created_at", "updated_at"]),
53
- ),
54
- recent_file_first: Type.Optional(Type.Boolean()),
60
+ file_order: opt({ ...oneOf(["ascending", "descending"]), type: "string" }),
61
+ file_order_by: opt({
62
+ ...oneOf(["name", "created_at", "updated_at"]),
63
+ type: "string",
64
+ }),
65
+ recent_file_first: opt(bool()),
55
66
  },
56
- { additionalProperties: false },
67
+ { open: false },
57
68
  );
58
- const NEW_CONTEXT_SCHEMA = Type.Object(
69
+ const NEW_CONTEXT_SCHEMA = obj(
59
70
  {
60
- role: Type.Optional(
61
- Type.String({
71
+ role: opt(
72
+ str({
62
73
  minLength: 1,
63
74
  description:
64
75
  "Configured model-role ID, not an agent name or handoff text",
65
76
  }),
66
77
  ),
67
78
  },
68
- { additionalProperties: false },
79
+ { open: false },
69
80
  );
70
81
 
82
+ const newContextSchemaValidator = compile(NEW_CONTEXT_SCHEMA);
83
+
71
84
  export function newContextSchema(roleIds: string[]) {
72
- return Type.Object(
73
- roleIds.length ? { role: Type.Optional(StringEnum(roleIds)) } : {},
74
- { additionalProperties: false },
85
+ return obj(
86
+ roleIds.length ? { role: opt({ ...oneOf(roleIds), type: "string" }) } : {},
87
+ { open: false },
75
88
  );
76
89
  }
77
90
 
78
91
  export function prepareNewContextArguments(input: unknown) {
79
92
  const args = input ?? {};
80
- if (!Check(NEW_CONTEXT_SCHEMA, args))
93
+ if (!newContextSchemaValidator.check(args))
81
94
  throw new Error(
82
95
  'Use {} to keep the current model, or {role: "name"} for a configured role.',
83
96
  );
84
97
  return args;
85
98
  }
86
- export const HISTORY_SCHEMA = Type.Object(
99
+ export const HISTORY_SCHEMA = obj(
87
100
  {
88
- action: Type.Optional(StringEnum(HISTORY_ACTIONS)),
89
- agent_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
90
- item_id: Type.Optional(Type.String()),
91
- window_id: Type.Optional(
92
- Type.Union([Type.String(), Type.Null()], {
101
+ action: opt({ ...oneOf(HISTORY_ACTIONS), type: "string" }),
102
+ agent_name: opt(union([str(), nul()])),
103
+ item_id: opt(str()),
104
+ window_id: opt(
105
+ union([str(), nul()], {
93
106
  description: "Required with item_id for read",
94
107
  }),
95
108
  ),
@@ -97,18 +110,21 @@ export const HISTORY_SCHEMA = Type.Object(
97
110
  limit: INTEGER,
98
111
  limit_chars: INTEGER,
99
112
  max_chars_per_item: INTEGER,
100
- offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
101
- recent_first: Type.Optional(Type.Boolean()),
102
- role: Type.Optional(
103
- Type.Union([
104
- StringEnum(["user", "assistant", "tool", "system", "developer"]),
105
- Type.Null(),
113
+ offset_chars: opt(int({ minimum: 0 })),
114
+ recent_first: opt(bool()),
115
+ role: opt(
116
+ union([
117
+ {
118
+ ...oneOf(["user", "assistant", "tool", "system", "developer"]),
119
+ type: "string",
120
+ },
121
+ nul(),
106
122
  ]),
107
123
  ),
108
- tool_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
109
- tool_namespace: Type.Optional(Type.Union([Type.String(), Type.Null()])),
124
+ tool_name: opt(union([str(), nul()])),
125
+ tool_namespace: opt(union([str(), nul()])),
110
126
  },
111
- { additionalProperties: false },
127
+ { open: false },
112
128
  );
113
129
 
114
130
  const FIELDS: Record<string, readonly string[]> = {
@@ -272,25 +288,36 @@ export function queryHelp(
272
288
 
273
289
  export function prepareNotesArguments(args: unknown) {
274
290
  const params = normalizeQueryInput("notes", args);
275
- validateArguments("notes", params, NOTES_SCHEMA);
291
+ validateArguments("notes", params, NOTES_FIELD_VALIDATORS);
276
292
  return params;
277
293
  }
278
294
 
279
295
  export function prepareHistoryArguments(args: unknown) {
280
296
  const params = normalizeQueryInput("history", args);
281
- validateArguments("history", params, HISTORY_SCHEMA);
297
+ validateArguments("history", params, HISTORY_FIELD_VALIDATORS);
282
298
  return params;
283
299
  }
284
300
 
301
+ const NOTES_FIELD_VALIDATORS = fieldValidators(NOTES_SCHEMA);
302
+ const HISTORY_FIELD_VALIDATORS = fieldValidators(HISTORY_SCHEMA);
303
+
304
+ function fieldValidators(schema: Schema): Record<string, Validator> {
305
+ return Object.fromEntries(
306
+ Object.entries(schema["properties"] as Record<string, Schema>).map(
307
+ ([field, property]) => [field, compile(property)],
308
+ ),
309
+ );
310
+ }
311
+
285
312
  function validateArguments(
286
313
  namespace: LookupQuery["namespace"],
287
314
  params: Record<string, unknown>,
288
- schema: import("typebox").TObject,
315
+ validators: Record<string, Validator>,
289
316
  ) {
290
317
  if (!queryHelp(namespace, params)) queryArguments(namespace, params);
291
318
  for (const [field, value] of Object.entries(params)) {
292
- const property = schema.properties[field];
293
- if (!property || !Check(property, value))
319
+ const validator = validators[field];
320
+ if (!validator || !validator.check(value))
294
321
  throw new Error(
295
322
  `Invalid ${namespace} ${field}; use {} for exact arguments`,
296
323
  );
@@ -4,7 +4,7 @@ import type {
4
4
  ExtensionContext,
5
5
  ToolDefinition,
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { Type } from "typebox";
7
+ import { obj } from "@earendil-works/pi-schema";
8
8
  import type { LookupQuery, SharedNotesDetails } from "./bridge.js";
9
9
  import type { HistorySearch } from "./history-search.js";
10
10
  import type { NotesLifecycle } from "./lifecycle.js";
@@ -123,7 +123,7 @@ export function createTools(
123
123
  name: "get_context_remaining",
124
124
  label: "get_context_remaining",
125
125
  description: "Remaining context tokens",
126
- parameters: Type.Object({}, { additionalProperties: false }),
126
+ parameters: obj({}, { open: false }),
127
127
  async execute(_id, _input, _signal, _update, ctx) {
128
128
  assertActive();
129
129
  const remaining = lifecycle.windows.remaining(ctx);
@@ -4,45 +4,60 @@ import {
4
4
  buildSessionProjection,
5
5
  type SessionEntry,
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { Type } from "typebox";
8
- import { Check } from "typebox/value";
7
+ import {
8
+ arr,
9
+ compile,
10
+ lit,
11
+ num,
12
+ obj,
13
+ opt,
14
+ str,
15
+ union,
16
+ unknown,
17
+ unsafe,
18
+ } from "@earendil-works/pi-schema";
9
19
 
10
20
  const READ_KEY = "codexContextNoteRead";
11
- const READ_SCHEMA = Type.Object(
21
+ const READ_SCHEMA = obj(
12
22
  {
13
- protocol: Type.Literal(1),
14
- origin: Type.Literal("host"),
15
- id: Type.String({ pattern: "^[a-f0-9-]{36}$" }),
16
- path: Type.String({ minLength: 1 }),
17
- namespace: Type.Optional(Type.Literal("notes")),
18
- api: Type.String({ minLength: 1 }),
19
- provider: Type.String({ minLength: 1 }),
20
- model: Type.String({ minLength: 1 }),
21
- timestamp: Type.Number({ minimum: 0 }),
22
- content: Type.Array(
23
- Type.Union([
24
- Type.Object({ type: Type.Literal("text"), text: Type.String() }),
25
- Type.Object({
26
- type: Type.Literal("image"),
27
- data: Type.String(),
28
- mimeType: Type.String(),
29
- detail: Type.Optional(
30
- Type.Union([
31
- Type.Literal("auto"),
32
- Type.Literal("high"),
33
- Type.Literal("original"),
34
- ]),
35
- ),
36
- }),
23
+ protocol: lit(1),
24
+ origin: lit("host"),
25
+ id: str({ pattern: "^[a-f0-9-]{36}$" }),
26
+ path: str({ minLength: 1 }),
27
+ namespace: opt(lit("notes")),
28
+ api: str({ minLength: 1 }),
29
+ provider: str({ minLength: 1 }),
30
+ model: str({ minLength: 1 }),
31
+ timestamp: num({ minimum: 0 }),
32
+ content: arr(
33
+ union([
34
+ obj({ type: lit("text"), text: str() }, { open: true }),
35
+ obj(
36
+ {
37
+ type: lit("image"),
38
+ data: str(),
39
+ mimeType: str(),
40
+ detail: opt(union([lit("auto"), lit("high"), lit("original")])),
41
+ },
42
+ { open: true },
43
+ ),
37
44
  ]),
38
45
  ),
39
- details: Type.Object({
40
- codexHistoryNotes: Type.Record(Type.String(), Type.Unknown()),
41
- }),
46
+ details: obj(
47
+ {
48
+ codexHistoryNotes: unsafe<Record<string, unknown>>({
49
+ type: "object",
50
+ patternProperties: { "^.*$": unknown() },
51
+ }),
52
+ },
53
+ { open: true },
54
+ ),
42
55
  },
43
- { additionalProperties: false },
56
+ { open: false },
44
57
  );
45
58
 
59
+ const readSchemaValidator = compile(READ_SCHEMA);
60
+
46
61
  function callId(id: string): string {
47
62
  const name = "tree_handoff_" + id.replaceAll("-", "");
48
63
  return `${name}|fc_${name}`;
@@ -95,7 +110,7 @@ export function projectTreeHandoffReads(
95
110
  if (!details || typeof details !== "object" || !(READ_KEY in details))
96
111
  return [message];
97
112
  const read = details[READ_KEY];
98
- if (!Check(READ_SCHEMA, read))
113
+ if (!readSchemaValidator.check(read))
99
114
  throw new Error("Invalid persisted tree handoff read");
100
115
  const resultDetails = read.details;
101
116
  if (!isJson(resultDetails))
@@ -15,31 +15,19 @@ export interface WindowDetails {
15
15
  trim: boolean;
16
16
  }
17
17
  const GUIDANCE = `<context_window_guidance>
18
- Notes are recovery state, not diary. They use virtual storage, not disk filesystem. Use relative paths when creating.
18
+ Notes are short virtual resume points, not working memory. Use task notes and/or checkpoints as needed. Reuse existing notes and avoid duplicating state. Use relative paths. Keep only current goal, task-specific constraints or exceptions, decision/status, next action and evidence/history links. Keep reasoning and intermediate results in context. Omit harness instructions, tool usage and skill-read bookkeeping.
19
19
 
20
- MUST maintain one authoritative checkpoint per task/topic with request, constraints, decision, status, next steps and relevant history IDs.
20
+ Write less: consolidate changed recovery state at substantive turn end, before replying. Skip routine turns and unchanged state unless explicit reminders or earlier handoffs require a save. If a no-action report needs recording, add only its run/report ID and "no owned action". Keep current state first; replace superseded status. Append only while existing state remains accurate. Use history on demand for older decisions and evidence instead of copying them into notes.
21
21
 
22
- Use the notes tool write action to create or replace the checkpoint at milestones, task switches and completion. Use action append to add to it.
23
-
24
- Subagents MUST maintain their own notes and return paths. For subagent handoffs, include the checkpoint path.
25
-
26
- Link existing notes instead of duplicating content. Recording does not authorise implementation.
27
-
28
- Before new_context or a handoff, MUST save the checkpoint with notes. For rollover, call new_context.
29
-
30
- After rollover, use notes read action to recover the checkpoint, then read only necessary links. SHOULD NOT reread unchanged notes. Use the history tool for missing details.
31
-
32
- Skill reads do not survive rollover. MUST reread required skills.
22
+ Save relevant notes before handoff and immediately before new_context. On recovery, read relevant notes, necessary links and a few relevant user messages with history, then resume the current task. Past messages are context, not renewed requests; current instructions win. Avoid unchanged rereads. Reread required skills after rollover. Recording does not authorise implementation.
33
23
  </context_window_guidance>`;
34
24
 
35
25
  const GPT_GUIDANCE = `<context_window_guidance>
36
- Notes=recovery stateNOTdiary. Virtual Notes storageNOTfilesystem. Create notes with relative paths. One authoritative checkpoint per task/topic→request/constraints/decision/status/next steps/history IDs. Existing notes→linkNOTduplicate. RecordingNOTimplementation permission.
37
-
38
- MUST maintain task checkpoint→update@ milestones, task switches + completion. Notes tool: write→create/replace stale checkpoint; append→add content. Not every reply/step. Subagents MUST maintain own notes→return paths.
26
+ Notes=short virtual resume points, not working memory. Relative paths; task notes and/or checkpoints as needed. Reuse existing notes; avoid duplicate state. Keep only current goal, task constraints/exceptions, decision/status, next action, evidence/history links. Reasoning/intermediate results stay in context. Omit harness/tool instructions and skill-read state.
39
27
 
40
- Before new_context/handoff: MUST save checkpoint via notes. Rollover→call new_context after save; subagent handoff→include checkpoint path. Post-rollover: notes read→checkpoint→necessary links only. SHOULD NOT reread unchanged notes. Missing details→history tool.
28
+ Fewer writes→consolidate changed recovery at substantive turn end BEFORE reply; skip routine/unchanged turns unless explicit reminders/earlier handoffs require saving. No-action report + save needed→add only run/report ID + "no owned action". Current first; replace superseded status. Append only while prior state stays accurate. History→older decisions/evidence on demand, not copied into notes.
41
29
 
42
- Prior skill reads≠current context. MUST reread required skills after rollover.
30
+ Save relevant notes before handoff/immediately before new_context. Recovery→relevant notes, necessary links, a few relevant user messages via history→resume current task. Past messages≠renewed requests; current instructions win. No unchanged rereads. Reread required skills after rollover. Recording≠implementation permission.
43
31
  </context_window_guidance>`;
44
32
 
45
33
  export function registerWindowRenderer(pi: ExtensionAPI): void {
@@ -167,13 +155,8 @@ export function windowMessage(
167
155
  kind: "window" | "identity" = "window",
168
156
  gpt = false,
169
157
  ): CustomMessageEntryDraft {
170
- const lines = [
171
- `Agent name: ${agent}`,
172
- `First context window id: ${ids.firstWindowId}`,
173
- `Current context window id: ${ids.currentWindowId}`,
174
- ];
175
- if (ids.previousWindowId)
176
- lines.push(`Previous context window id: ${ids.previousWindowId}`);
158
+ // History exposes lookup IDs on demand; rollover must not churn this text just for UUIDs.
159
+ const lines = [`Agent name: ${agent}`];
177
160
  if (hint) lines.push(hint);
178
161
  return {
179
162
  type: "custom_message",
@@ -0,0 +1,11 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export type SettingsTab = "notes" | "board";
4
+ export type OpenSettings = (
5
+ ctx: ExtensionCommandContext,
6
+ tab: SettingsTab,
7
+ ) => Promise<void>;
8
+
9
+ export interface FeatureSettings {
10
+ openSettings(ctx: ExtensionCommandContext): Promise<SettingsTab | undefined>;
11
+ }
@@ -0,0 +1,3 @@
1
+ export function minuteTimestamp(value: string | number = Date.now()): string {
2
+ return new Date(value).toISOString().slice(0, 16) + "Z";
3
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "allowJs": true,
5
+ "checkJs": true,
6
+ "allowImportingTsExtensions": true
7
+ },
8
+ "include": ["*.ts", "src/**/*.ts", "src/**/*.mjs"]
9
+ }