@howaboua/pi-notes-compaction 0.0.14 → 0.0.16

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 (83) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/LICENSE +21 -0
  3. package/README.md +8 -3
  4. package/index.ts +8 -0
  5. package/package.json +16 -11
  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/{bridge.ts → notes/bridge.ts} +1 -0
  14. package/src/{context-sharing.ts → notes/context-sharing.ts} +22 -2
  15. package/src/{extension-hooks.ts → notes/extension-hooks.ts} +1 -12
  16. package/src/{extension-sharing.ts → notes/extension-sharing.ts} +2 -1
  17. package/src/notes/feature.ts +168 -0
  18. package/src/{history-windows.ts → notes/history-windows.ts} +10 -22
  19. package/src/{history.ts → notes/history.ts} +6 -5
  20. package/src/{index.ts → notes/index.ts} +20 -11
  21. package/src/{integrations.ts → notes/integrations.ts} +19 -3
  22. package/src/{lifecycle.ts → notes/lifecycle.ts} +0 -2
  23. package/src/{note-query.ts → notes/note-query.ts} +3 -5
  24. package/src/notes/note-result.ts +119 -0
  25. package/src/{note-save-marker.ts → notes/note-save-marker.ts} +3 -1
  26. package/src/{query-executor.ts → notes/query-executor.ts} +34 -9
  27. package/src/{query-input.ts → notes/query-input.ts} +1 -0
  28. package/src/{remote.ts → notes/remote.ts} +1 -1
  29. package/src/notes/saved-session-access.ts +121 -0
  30. package/src/notes/saved-session-index.mjs +83 -0
  31. package/src/notes/saved-session.mjs +241 -0
  32. package/src/notes/saved-session.ts +67 -0
  33. package/src/notes/saved-sharing-records.ts +170 -0
  34. package/src/{session-pruning.ts → notes/session-pruning.ts} +5 -5
  35. package/src/{settings-command.ts → notes/settings-command.ts} +29 -42
  36. package/src/{settings-controls.ts → notes/settings-controls.ts} +62 -72
  37. package/src/{settings-screen.ts → notes/settings-screen.ts} +25 -7
  38. package/src/{settings.ts → notes/settings.ts} +37 -6
  39. package/src/notes/shared-notes.ts +419 -0
  40. package/src/{shared-session-reader.ts → notes/shared-session-reader.ts} +35 -26
  41. package/src/{sharing-service.ts → notes/sharing-service.ts} +32 -1
  42. package/src/{store.ts → notes/store.ts} +10 -0
  43. package/src/{tool-contracts.ts → notes/tool-contracts.ts} +71 -44
  44. package/src/{tools.ts → notes/tools.ts} +2 -2
  45. package/src/notes/tree-archive-manifest.mjs +27 -0
  46. package/src/{tree-archive.ts → notes/tree-archive.ts} +6 -26
  47. package/src/{tree-handoff-read.ts → notes/tree-handoff-read.ts} +47 -32
  48. package/src/{window-message.ts → notes/window-message.ts} +15 -20
  49. package/src/settings-navigation.ts +11 -0
  50. package/src/timestamps.ts +3 -0
  51. package/tsconfig.json +9 -0
  52. package/src/note-result.ts +0 -70
  53. package/src/saved-session.ts +0 -169
  54. package/src/saved-sharing-records.ts +0 -112
  55. package/src/shared-notes.ts +0 -290
  56. /package/src/{agent-identity.ts → notes/agent-identity.ts} +0 -0
  57. /package/src/{binding-startup.ts → notes/binding-startup.ts} +0 -0
  58. /package/src/{compaction-projection.ts → notes/compaction-projection.ts} +0 -0
  59. /package/src/{context-owner.ts → notes/context-owner.ts} +0 -0
  60. /package/src/{fresh-checkpoint.ts → notes/fresh-checkpoint.ts} +0 -0
  61. /package/src/{fresh-notes.ts → notes/fresh-notes.ts} +0 -0
  62. /package/src/{history-search-protocol.ts → notes/history-search-protocol.ts} +0 -0
  63. /package/src/{history-search-pruning.mjs → notes/history-search-pruning.mjs} +0 -0
  64. /package/src/{history-search-worker.mjs → notes/history-search-worker.mjs} +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-lookup.ts → notes/notes-lookup.ts} +0 -0
  71. /package/src/{notes.ts → notes/notes.ts} +0 -0
  72. /package/src/{rollover.ts → notes/rollover.ts} +0 -0
  73. /package/src/{session-pruning-content.ts → notes/session-pruning-content.ts} +0 -0
  74. /package/src/{session-pruning-plan.ts → notes/session-pruning-plan.ts} +0 -0
  75. /package/src/{session-pruning-policy.ts → notes/session-pruning-policy.ts} +0 -0
  76. /package/src/{session-pruning-screen.ts → notes/session-pruning-screen.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/{task-boundary.ts → notes/task-boundary.ts} +0 -0
  81. /package/src/{tree-checkpoint.ts → notes/tree-checkpoint.ts} +0 -0
  82. /package/src/{window-checkpoint.ts → notes/window-checkpoint.ts} +0 -0
  83. /package/src/{windows.ts → notes/windows.ts} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,11 +1,31 @@
1
1
  # @howaboua/pi-notes-compaction
2
2
 
3
+ ## 0.0.16
4
+
5
+ - Requires Node.js 22.19 or newer.
6
+ - Notes now offers Off and defers inactive initialisation without deleting saved data or retired context boundaries.
7
+ - Notes now accepts `content` as a body alias for `text` in typed tool calls.
8
+ - Notes reads now accept `end_line` as an alias for `stop_line`.
9
+ - Notes results now omit routine bookkeeping while retaining paths, content, search matches and truncation.
10
+ - Context recovery now checks selected past user messages for intent and communication preferences, with current instructions taking precedence.
11
+ - Context window openings now omit UUIDs; history still exposes window references.
12
+ - Notes guidance now consolidates changed checkpoints near the end of substantive turns.
13
+ - Shared notes and history now report recovery options when saved context cannot be accessed.
14
+ - History searches no longer retain full rendered copies of tool arguments and messages for the session lifetime.
15
+ - Notes now uses minute precision in displayed dates, preserving existing records.
16
+ - Replaced the TypeBox dependency with Pi's native schema validation.
17
+
18
+ ## 0.0.15
19
+
20
+ - Shared local checkpoints remain readable after workers close. Saved family lookup no longer depends on a live parent when the saved session is accessible locally.
21
+ - Saved Notes and History reads are faster in sessions with large messages or tool results.
22
+ - Shared saved-session reads no longer fail when the active session appends new entries.
23
+
3
24
  ## 0.0.14
4
25
 
5
26
  - Requires Pi 1.5 or newer.
6
27
 
7
28
  Older checkpoints may require a fresh note save before rollover.
8
-
9
29
  - Notes results in Pi's built-in codemode are now objects, matching Code and Notebook. Remove `JSON.parse` around those results.
10
30
  - Agent references now derive from Pi session IDs, with existing shared-note paths retained.
11
31
  - Fixed rollover rejecting successful large saves and saves in parallel tool groups. The saved-notes indicator uses the same readiness check.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Igor Warzocha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -2,9 +2,11 @@
2
2
 
3
3
  Keep working across fresh context windows with local checkpoint notes, searchable session history and optional remote notes lookup. Works with any Pi model.
4
4
 
5
+ This standalone package remains maintained alongside [Agent Comms](../pi-agent-comms), with the same Notes improvements. It is not deprecated. Choose one or the other; do not load both in the same Pi session.
6
+
5
7
  ## Install
6
8
 
7
- Requires Pi 1.2.0 or newer and Node.js 22.18 or newer.
9
+ Requires Pi 1.5.0 or newer and Node.js 22.19 or newer.
8
10
 
9
11
  ```sh
10
12
  pi install npm:@howaboua/pi-notes-compaction
@@ -24,7 +26,9 @@ Ranked search is off by default. It indexes user messages and visible assistant
24
26
 
25
27
  Explicit searches of tool history, a window containing live context or another agent's history use literal substring matching. Search results identify the matching mode. Listing and reading history still includes the full transcript, including ongoing context and tool activity.
26
28
 
27
- Previously shared local notes and history remain readable after the other agent closes or Shepherdr is removed. Notes follows the saved family relationships and attachment aliases without requiring PCC. Reads use the other session's saved branch and preserve its history IDs. When only a retained attachment snapshot is available, notes identify it as detached or potentially stale. Snapshots do not contain history. Cross-agent writes still require their live routing service. History reads Pi JSONL sessions locally or through a live shared agent, including agents on another machine. Without live access, make the saved session available locally.
29
+ Previously shared local notes and history remain readable from accessible saved sessions after the other agent closes or Shepherdr is removed. Notes follows saved family relationships and attachment aliases without requiring PCC or a live parent. Reads use the other session's selected branch and preserve its history IDs. When only a retained attachment snapshot is available, notes identify it as detached or potentially stale. Snapshots do not contain history. Cross-agent writes still require live routing.
30
+
31
+ Shepherdr 0.2.27 remains supported for live sharing, including across connected machines. Reading a closed agent's saved session on another machine requires a saved-session transport that this Shepherdr version does not provide. Resume the shared agent and reconnect its machine, or make its saved Pi JSONL session available locally. Saved reads do not replace hybrid lookup or its encrypted cache with local-only results. History uses Pi JSONL, never remote notes or cached responses.
28
32
 
29
33
  In Code Mode and Notebook, plaintext notes and history return ordinary JavaScript values. Encrypted notes return delivery receipts instead of exposing their contents to JavaScript.
30
34
 
@@ -83,7 +87,8 @@ recovery keep their existing Notes settings.
83
87
  ### Notes settings
84
88
 
85
89
  `/notes` opens the settings panel in interactive Pi. It shows continuity status, storage counts and remote capabilities. Changes save immediately.
86
- - **Active** selects **All models** (the default) or **Whitelist**. Whitelist enables the extension only for exact model IDs in the global settings file, regardless of provider. Switching models applies the choice immediately; other models keep their installed compaction behaviour.
90
+
91
+ - **Active** selects **All models** (the default), **Whitelist** or **Off**. Whitelist enables the extension only for exact model IDs in the global settings file, regardless of provider. Switching models applies the choice immediately; other models keep their installed compaction behaviour. Off disables Notes without deleting saved data.
87
92
  - **Normal compaction** uses the installed Pi or PCC compaction flow for `/compact` and `new_context`. Off keeps notes-only rollover, the default.
88
93
  - **New window requests** controls the agent's `new_context` tool independently of the compaction method. **off** disables the tool. **pi-limits** uses Pi's eligibility check and continues in the current window when there is too little history. **unrestricted**, the default, accepts requests at any size. With normal compaction on and nothing to summarise, unrestricted requests open a new window identity without discarding the existing context. Manual `/compact` and idle rollover retain their separate policies.
89
94
  - **Idle rollover** selects the interval or disables it.
package/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { registerCommunicationGuidance } from "./src/guidance.js";
3
+ import { createNotesFeature } from "./src/notes/feature.js";
4
+
5
+ export default function notesCompaction(pi: ExtensionAPI): void {
6
+ const notes = createNotesFeature(pi);
7
+ registerCommunicationGuidance(pi, notes);
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-notes-compaction",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -10,23 +10,26 @@
10
10
  "directory": "packages/pi-notes-compaction"
11
11
  },
12
12
  "files": [
13
+ "index.ts",
13
14
  "src",
14
15
  "README.md",
15
- "PCC-INTEGRATION.md",
16
- "CHANGELOG.md"
16
+ "CHANGELOG.md",
17
+ "LICENSE",
18
+ "tsconfig.json",
19
+ "PCC-INTEGRATION.md"
17
20
  ],
18
21
  "engines": {
19
- "node": ">=22.18.0"
22
+ "node": ">=22.19.0"
20
23
  },
21
24
  "type": "module",
22
25
  "description": "Provider-neutral session notes and notes-guided context windows for Pi",
23
26
  "license": "MIT",
24
27
  "pi": {
25
28
  "extensions": [
26
- "./src/index.ts"
29
+ "./index.ts"
27
30
  ]
28
31
  },
29
- "main": "src/index.ts",
32
+ "main": "index.ts",
30
33
  "scripts": {
31
34
  "check": "bun run lint && bun run typecheck",
32
35
  "lint": "biome check .",
@@ -34,10 +37,11 @@
34
37
  "typecheck": "tsgo --noEmit"
35
38
  },
36
39
  "dependencies": {
40
+ "@earendil-works/pi-schema": "1.5.2",
37
41
  "better-sqlite3": "13.0.3"
38
42
  },
39
43
  "devDependencies": {
40
- "@howaboua/pi-codex-conversion": "4.0.8",
44
+ "@howaboua/pi-codex-conversion": "4.0.10",
41
45
  "@types/better-sqlite3": "9.6.0"
42
46
  },
43
47
  "peerDependencies": {
@@ -45,8 +49,7 @@
45
49
  "@earendil-works/pi-agent-core": ">=1.0.4",
46
50
  "@earendil-works/pi-ai": ">=1.0.4",
47
51
  "@earendil-works/pi-tui": ">=1.0.4",
48
- "@howaboua/pi-codex-conversion": ">=4.0.8",
49
- "typebox": "*"
52
+ "@howaboua/pi-codex-conversion": ">=4.0.10"
50
53
  },
51
54
  "peerDependenciesMeta": {
52
55
  "@howaboua/pi-codex-conversion": {
@@ -54,7 +57,9 @@
54
57
  }
55
58
  },
56
59
  "exports": {
57
- ".": "./src/index.ts",
58
- "./context-sharing": "./src/context-sharing.ts"
60
+ ".": "./index.ts",
61
+ "./context-sharing": "./src/notes/context-sharing.ts",
62
+ "./saved-session": "./src/notes/saved-session.mjs",
63
+ "./saved-session-index": "./src/notes/saved-session-index.mjs"
59
64
  }
60
65
  }
@@ -0,0 +1,245 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ buildSessionContext,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ type SessionEntry,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type {
9
+ CODEX_CONTEXT_BRIEFING_TYPE,
10
+ CodexContextBriefing,
11
+ CodexContextBriefingHandler,
12
+ } from "@howaboua/pi-codex-conversion/developer-messages";
13
+ import { registerInferenceBriefing } from "./delivery.js";
14
+
15
+ // Conversion projects this durable protocol in inference, compaction and native replay.
16
+ const BRIEFING: typeof CODEX_CONTEXT_BRIEFING_TYPE = "codex-context-briefing";
17
+
18
+ export function registerContextBriefing(
19
+ pi: ExtensionAPI,
20
+ name: string,
21
+ relevant: (ctx: ExtensionContext) => boolean,
22
+ record: CodexContextBriefingHandler,
23
+ ) {
24
+ const hosted = registerInferenceBriefing(pi, record);
25
+ const warned = new Set<string>();
26
+ pi.on("context_with_system", async (event, ctx) => {
27
+ await hosted.ready;
28
+ if (hosted.hosted()) return;
29
+ if (
30
+ hosted.outdated &&
31
+ relevant(ctx) &&
32
+ !warned.has(ctx.sessionManager.getSessionId())
33
+ ) {
34
+ warned.add(ctx.sessionManager.getSessionId());
35
+ ctx.ui.notify(
36
+ `Update Codex Conversion and reload to preserve ${name} briefings through its context rollover and native replay. Native Pi briefings and other agent tools remain available.`,
37
+ "warning",
38
+ );
39
+ }
40
+ try {
41
+ await record(ctx, undefined, event.messages);
42
+ return { messages: projectNative(ctx, event.messages) };
43
+ } catch (error) {
44
+ ctx.abort();
45
+ throw error;
46
+ }
47
+ });
48
+ }
49
+
50
+ export function contextBriefingWindow(
51
+ ctx: ExtensionContext,
52
+ windowId?: string,
53
+ ) {
54
+ const branch = ctx.sessionManager.getBranch();
55
+ const compaction = branch.findLastIndex(
56
+ (entry) =>
57
+ entry.type === "compaction" &&
58
+ !(
59
+ entry.details &&
60
+ typeof entry.details === "object" &&
61
+ "strategy" in entry.details &&
62
+ entry.details.strategy === "codex-context-window"
63
+ ),
64
+ );
65
+ const boundary = branch.findLastIndex((entry) => briefingIdentity(entry));
66
+ return compaction > boundary
67
+ ? branch[compaction]!.id
68
+ : (windowId ??
69
+ (boundary >= 0
70
+ ? briefingIdentity(branch[boundary]!)?.currentWindowId
71
+ : undefined) ??
72
+ ctx.sessionManager.getSessionId());
73
+ }
74
+
75
+ export function hasContextRollover(ctx: ExtensionContext): boolean {
76
+ return ctx.sessionManager.getBranch().some((entry) => {
77
+ if (entry.type === "compaction") return true;
78
+ return (briefingIdentity(entry)?.windowNumber ?? 0) > 0;
79
+ });
80
+ }
81
+
82
+ /** Consume owner-authored identities without depending on an optional runtime. */
83
+ function briefingIdentity(entry: SessionEntry) {
84
+ if (entry.type !== "custom_message") return;
85
+ const details = entry.details;
86
+ if (!details || typeof details !== "object") return;
87
+ let identity: unknown;
88
+ if (
89
+ entry.customType === "notes-compaction:window:v1" &&
90
+ "protocol" in details &&
91
+ details.protocol === 1 &&
92
+ "kind" in details &&
93
+ details.kind === "window" &&
94
+ "identity" in details
95
+ )
96
+ identity = details.identity;
97
+ else if (
98
+ entry.customType === "codex-context-window" &&
99
+ "contextManagement" in details &&
100
+ details.contextManagement &&
101
+ typeof details.contextManagement === "object" &&
102
+ "kind" in details.contextManagement &&
103
+ details.contextManagement.kind === "window"
104
+ )
105
+ identity = details.contextManagement;
106
+ if (
107
+ identity &&
108
+ typeof identity === "object" &&
109
+ "currentWindowId" in identity &&
110
+ typeof identity.currentWindowId === "string" &&
111
+ identity.currentWindowId &&
112
+ "windowNumber" in identity &&
113
+ typeof identity.windowNumber === "number" &&
114
+ Number.isInteger(identity.windowNumber) &&
115
+ identity.windowNumber >= 0
116
+ )
117
+ return {
118
+ currentWindowId: identity.currentWindowId,
119
+ windowNumber: identity.windowNumber,
120
+ };
121
+ }
122
+
123
+ export async function recordContextBriefing(
124
+ pi: ExtensionAPI,
125
+ ctx: ExtensionContext,
126
+ owner: string,
127
+ key: string,
128
+ content: () => Promise<string | undefined>,
129
+ ) {
130
+ const saved = ctx.sessionManager
131
+ .getEntries()
132
+ .findLast(
133
+ (entry) =>
134
+ entry.type === "custom" &&
135
+ entry.customType === BRIEFING &&
136
+ readBriefing(entry.data).owner === owner &&
137
+ readBriefing(entry.data).key === key,
138
+ );
139
+ if (saved?.type === "custom") {
140
+ // Tree may select an ancestor before its metadata child. Reuse immutable bytes/ID.
141
+ if (
142
+ !ctx.sessionManager
143
+ .getBranch()
144
+ .some(
145
+ (entry) =>
146
+ entry.type === "custom" &&
147
+ entry.customType === BRIEFING &&
148
+ readBriefing(entry.data).owner === owner &&
149
+ readBriefing(entry.data).key === key,
150
+ )
151
+ )
152
+ pi.appendEntry(BRIEFING, readBriefing(saved.data));
153
+ return;
154
+ }
155
+ const value = await content();
156
+ if (value === undefined) return;
157
+ pi.appendEntry(BRIEFING, {
158
+ protocol: 1,
159
+ id: randomUUID(),
160
+ owner,
161
+ key,
162
+ content: value,
163
+ } satisfies CodexContextBriefing);
164
+ }
165
+
166
+ function projectNative(
167
+ ctx: ExtensionContext,
168
+ messages: NativeMessage[],
169
+ ): NativeMessage[] {
170
+ const entries = ctx.sessionManager.getBranch().map((entry) => {
171
+ if (entry.type !== "custom" || entry.customType !== BRIEFING) return entry;
172
+ const briefing = readBriefing(entry.data);
173
+ return {
174
+ ...entry,
175
+ type: "custom_message" as const,
176
+ content: briefing.content,
177
+ display: false,
178
+ details: briefing,
179
+ };
180
+ });
181
+ const reconstructed = buildSessionContext(entries).messages;
182
+ const positions = new Map<string, number[]>();
183
+ messages.forEach((message, index) => {
184
+ const key = messageKey(message);
185
+ const indices = positions.get(key) ?? [];
186
+ indices.push(index);
187
+ positions.set(key, indices);
188
+ });
189
+ const insertions = new Map<number, NativeMessage[]>();
190
+ let pending: NativeMessage[] = [];
191
+ let last = messages[0]?.role === "system" ? 0 : -1;
192
+ const insert = (index: number) => {
193
+ if (!pending.length) return;
194
+ const position =
195
+ messages[0]?.role === "system" ? Math.max(1, index) : index;
196
+ insertions.set(position, [...(insertions.get(position) ?? []), ...pending]);
197
+ pending = [];
198
+ };
199
+ for (const message of reconstructed) {
200
+ const index = positions.get(messageKey(message))?.shift();
201
+ if (index !== undefined) {
202
+ insert(index);
203
+ last = index;
204
+ } else if (message.role === "custom" && message.customType === BRIEFING) {
205
+ pending.push(message);
206
+ }
207
+ }
208
+ insert(last + 1);
209
+ return messages
210
+ .flatMap((message, index) => [...(insertions.get(index) ?? []), message])
211
+ .concat(insertions.get(messages.length) ?? []);
212
+ }
213
+
214
+ type NativeMessage = ReturnType<typeof buildSessionContext>["messages"][number];
215
+ function messageKey(message: NativeMessage) {
216
+ return JSON.stringify([
217
+ message.role,
218
+ message.timestamp,
219
+ message.role === "custom"
220
+ ? message.customType === BRIEFING
221
+ ? readBriefing(message.details).id
222
+ : message.customType
223
+ : message.role === "toolResult"
224
+ ? message.toolCallId
225
+ : undefined,
226
+ ]);
227
+ }
228
+ function readBriefing(value: unknown): CodexContextBriefing {
229
+ if (
230
+ !value ||
231
+ typeof value !== "object" ||
232
+ !("protocol" in value) ||
233
+ value.protocol !== 1 ||
234
+ !("id" in value) ||
235
+ typeof value.id !== "string" ||
236
+ !("owner" in value) ||
237
+ typeof value.owner !== "string" ||
238
+ !("key" in value) ||
239
+ typeof value.key !== "string" ||
240
+ !("content" in value) ||
241
+ typeof value.content !== "string"
242
+ )
243
+ throw new Error("Invalid saved context briefing");
244
+ return value as CodexContextBriefing;
245
+ }
@@ -0,0 +1,85 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type {
3
+ CodexContextBriefingHandler,
4
+ CodexDeveloperCustomMessage,
5
+ CodexDeveloperMessageOptions,
6
+ } from "@howaboua/pi-codex-conversion/developer-messages";
7
+
8
+ type Delivery =
9
+ typeof import("@howaboua/pi-codex-conversion/developer-messages");
10
+ let optionalDelivery: Promise<Delivery | undefined> | undefined;
11
+
12
+ function loadDelivery() {
13
+ return (optionalDelivery ??= import(
14
+ "@howaboua/pi-codex-conversion/developer-messages"
15
+ ).catch((error) => {
16
+ if (isMissingOptionalModule(error, "developer-messages")) return undefined;
17
+ throw error;
18
+ }));
19
+ }
20
+
21
+ export function isMissingOptionalModule(error: unknown, subpath: string) {
22
+ if (!(error instanceof Error) || !("code" in error)) return false;
23
+ const name = "@howaboua/pi-codex-conversion";
24
+ if (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED")
25
+ return (
26
+ error.message.includes(name) && error.message.includes(`./${subpath}`)
27
+ );
28
+ if (
29
+ error.code !== "ERR_MODULE_NOT_FOUND" &&
30
+ error.code !== "MODULE_NOT_FOUND"
31
+ )
32
+ return false;
33
+ const missing = error.message.match(
34
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
35
+ )?.[1];
36
+ return missing === name || missing === `${name}/${subpath}`;
37
+ }
38
+
39
+ let delivery: Delivery | undefined;
40
+ export async function initializeDelivery() {
41
+ delivery = await loadDelivery();
42
+ }
43
+
44
+ export function preparePolicyMessage(message: CodexDeveloperCustomMessage) {
45
+ return (
46
+ delivery?.withCodexDeveloperMessageDetails?.({
47
+ ...message,
48
+ details: message.details ?? {},
49
+ }) ?? message
50
+ );
51
+ }
52
+
53
+ export function registerInferenceBriefing(
54
+ pi: ExtensionAPI,
55
+ handler: CodexContextBriefingHandler,
56
+ ) {
57
+ let unregister: (() => void) | undefined;
58
+ const ready = loadDelivery().then((api) => {
59
+ delivery = api;
60
+ unregister = api?.registerCodexContextBriefing?.(pi, handler);
61
+ });
62
+ pi.on("session_shutdown", () => unregister?.());
63
+ return {
64
+ ready,
65
+ hosted: () => delivery?.hasCodexContextBriefingHost?.(pi) ?? false,
66
+ get outdated() {
67
+ return Boolean(delivery && !delivery.registerCodexContextBriefing);
68
+ },
69
+ };
70
+ }
71
+
72
+ export function sendPolicyMessage(
73
+ pi: ExtensionAPI,
74
+ message: CodexDeveloperCustomMessage,
75
+ options: CodexDeveloperMessageOptions,
76
+ ) {
77
+ if (delivery?.trySendCodexDeveloperCustomMessage?.(pi, message, options))
78
+ return;
79
+ pi.sendMessage(
80
+ message,
81
+ options.deliverAs === "nextTurn"
82
+ ? { ...options, deliverAs: "steer" }
83
+ : options,
84
+ );
85
+ }
@@ -0,0 +1,121 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ contextBriefingWindow,
7
+ recordContextBriefing,
8
+ registerContextBriefing,
9
+ } from "./board/context-briefing.js";
10
+ import type { FeatureSettings } from "./settings-navigation.js";
11
+
12
+ export interface CommsFeature extends FeatureSettings {
13
+ enabled(ctx: ExtensionContext): boolean;
14
+ gptPromptMode(): boolean;
15
+ }
16
+
17
+ /** Routing belongs here; feature carriers retain identity, recovery and navigation. */
18
+ function communicationGuidance(
19
+ notes: boolean,
20
+ board: boolean,
21
+ agents: boolean,
22
+ gpt = false,
23
+ ): string {
24
+ return [
25
+ board
26
+ ? gpt
27
+ ? "Board→peer findings/discovery, ownership/decisions/blockers affecting peers. Self-contained detail welcome; direct discovery≠parent relay. Existing thread replies; known shared peers→link≠repeat. No ack/status spam/duplicate completion reports."
28
+ : "Board: share findings, discoveries, ownership, decisions and blockers that change peers' work. Self-contained detail lets peers read directly, without a parent relay. Reply in existing threads. Link rather than repeat for peers with known Board access. Skip acknowledgements, routine status and duplicate completion reports."
29
+ : "",
30
+ notes
31
+ ? [
32
+ board
33
+ ? gpt
34
+ ? "Notes→current work/progress/recovery + Board references."
35
+ : "Notes: current work, progress and recovery, with Board references."
36
+ : "",
37
+ gpt
38
+ ? "Keep Notes checkpoints. Known recipient access→brief outcome/blocker + path; recipient READS checkpoint≠request full report."
39
+ : "Keep checkpoints in Notes. When the recipient is known to have access, return a brief outcome or blocker plus its path. The recipient reads the checkpoint for details rather than asking for a full report.",
40
+ ]
41
+ .filter(Boolean)
42
+ .join(" ")
43
+ : "",
44
+ notes || board
45
+ ? gpt
46
+ ? `${notes && board ? "Notes/Board" : notes ? "Notes" : "Board"} available here≠recipient access. Unknown/unshared access→self-contained actions taken/findings/unresolved state, not bare references.`
47
+ : `${notes && board ? "Notes and Board" : notes ? "Notes" : "Board"} availability here does not establish recipient access. If access is unknown or unshared, send a self-contained account of what you did, found and left unresolved, not just private references.`
48
+ : "",
49
+ agents && notes && board
50
+ ? gpt
51
+ ? "agents→assignments/urgent action≠default peer knowledge bus."
52
+ : "Use agents for assignments and urgent action, not as the default peer knowledge relay."
53
+ : "",
54
+ ]
55
+ .filter(Boolean)
56
+ .join(" ");
57
+ }
58
+
59
+ export function registerCommunicationGuidance(
60
+ pi: ExtensionAPI,
61
+ notes?: CommsFeature,
62
+ board?: CommsFeature,
63
+ ): void {
64
+ const owner =
65
+ notes && board
66
+ ? "agent-comms-routing"
67
+ : notes
68
+ ? "notes-routing"
69
+ : "board-routing";
70
+ registerContextBriefing(
71
+ pi,
72
+ "communication",
73
+ (ctx) => Boolean(notes?.enabled(ctx) || board?.enabled(ctx)),
74
+ async (ctx, windowId, messages) => {
75
+ // Feature owners supply enablement independently of provider declarations.
76
+ // Shepherdr keeps agents active, including as a nested Code/Notebook tool.
77
+ const capabilities = [
78
+ notes?.enabled(ctx) ?? false,
79
+ board?.enabled(ctx) ?? false,
80
+ pi.getActiveTools().includes("agents"),
81
+ Boolean(notes?.gptPromptMode() || board?.gptPromptMode()),
82
+ ] as const;
83
+ const routing = communicationGuidance(...capabilities);
84
+ const previous = messages
85
+ ?.flatMap((message) => {
86
+ if (
87
+ message.role !== "custom" ||
88
+ message.customType !== "codex-context-briefing"
89
+ )
90
+ return [];
91
+ const details = message.details;
92
+ return details &&
93
+ typeof details === "object" &&
94
+ "owner" in details &&
95
+ details.owner === owner &&
96
+ "id" in details &&
97
+ typeof details.id === "string"
98
+ ? [{ id: details.id, content: message.content }]
99
+ : [];
100
+ })
101
+ .at(-1);
102
+ if (!routing && !previous) return;
103
+ const content =
104
+ routing ||
105
+ `${notes && board ? "Notes and Board are" : notes ? "Notes is" : "Board is"} currently inactive. Earlier communication routing no longer applies.`;
106
+ if (previous?.content === content) return;
107
+ await recordContextBriefing(
108
+ pi,
109
+ ctx,
110
+ owner,
111
+ JSON.stringify([
112
+ ctx.sessionManager.getSessionId(),
113
+ contextBriefingWindow(ctx, windowId),
114
+ ...capabilities,
115
+ previous?.id,
116
+ ]),
117
+ async () => content,
118
+ );
119
+ },
120
+ );
121
+ }
@@ -0,0 +1,27 @@
1
+ - Fresh idle family binding accepts foreign plain `custom` startup metadata, not `custom_message` conversation or Notes ownership/work records. Identity checks stay session-wide, including abandoned branches. A host may supply only child-owned entries after validating an explicit inherited fork boundary; omission checks the full session.
2
+ - Public agent names derive from native Pi session IDs. Reject native ID `root` before routing or writes: it collides with legacy `/root`. Keep legacy storage addresses separate, including authenticated remote scopes. `/root` aliases only the family root (`threadId === sessionId`), never an arbitrary shared child. Restore unbound remote ownership only from its native-matching backend pin, not inherited prompt text.
3
+ - Notes owns continuity and its registrations. PCC is optional provider infrastructure. Use public code-mode, prompt-mode, developer-messages and compaction APIs, never arbitration or PCC internal imports.
4
+ - Resolve History's query-only search default before action-scoped hint filtering. Preserve explicit actions; never infer an operation from filters alone.
5
+ - Saved shared-note reads belong to Notes, not live orchestration. SQLite paths are hints, never membership evidence: verify native JSONL identity and an explicit family binding; do not require a live parent for immutable ordinary-family membership. Attachment routes and detach snapshots still own their addresses. Identity is session-wide; note revisions follow the selected branch. Preserve hybrid bases/cache; resolve `machine:local` relative to the containing saved session. Keep the public saved-session `.mjs` reader Node-only; Core bundles it without Pi or TypeScript. History reads Pi JSONL locally or through live family/attachment routing, never backend lookups or cached remote responses; preserve historical persisted records without rewriting them.
6
+ - Notes publishes one canonical payload as text and structuredContent with outputSchema. Preserve it through sharing and alias remapping; PCC consumes it directly. History keeps canonical content. Never derive values from freshness or routing details. Only Notes permits protected-output delivery.
7
+ - History's FTS index is derived and opt-in for the current session only. Disabled and other saved-session reads never build indexes; explicit pruning may delete existing rows. Reconcile committed JSONL pruning generations before indexing: the live SessionManager remains stale until restart. Rank only retired user/assistant visible text: Notes `trim=true` boundaries plus normal compaction's kept-entry cut, not window ID alone. Untrimmed initialization/rollover preserves live context. Never index calls, results, thinking or custom metadata. Explicit live/tool scopes and shared reads stay literal; full canonical reads remain intact. Scope ranked queries to selected JSONL entries after branch/window/tool filters; cached rows are not permission to return them. Keep user queries out of raw FTS syntax and Notes search unchanged.
8
+ - History caches lazy metadata by immutable Pi entry identity, not full rendered content: live entries retain cache values for the session lifetime. Never mutate cached entries. Its checked `.mjs` worker runs outside jiti; Node refuses type stripping under `node_modules`. Keep worker protocol imports type-only and probe a real installed-directory copy, not a checkout symlink.
9
+ - Register compaction preparation through the optional public PCC API so cancellation and projected branch preparation precede provider work in either load order. Manual notes rollover waits for user input. Tool-requested rollover continues.
10
+ - Pi's `Compaction cancelled` notice during Notes-only rollover is cosmetic, not a defect, blocker or delivery caveat. Check the actual window transition instead of chasing or repeatedly reporting the notice.
11
+ - Await optional context-window preparation before a notes-only history cut, then recheck session/window validity. Summary compaction owns its refresh already; identity-only windows do not repeat it.
12
+ - Pi-limited notes-only requests cancel their own eligible pre-compaction hook before provider work. Only that owned cancellation permits rollover; Pi's exact no-work errors retain the window, other failures remain failures. Request permission never changes idle or manual policy.
13
+ - new_context requires a successful own save in the immediately preceding tool-call group, including parallel peers, or completed same-group predecessors. Never flatten groups into a last-call check or accept saves from older groups. Reuse fresh-notes.ts receipts and completed outcomes, including exec/wait; its own unfinished call is not missing-write evidence. Routed writes neither satisfy nor invalidate a local checkpoint in a mixed cell. Idle freshness still requires a completed run.
14
+ - Persist pending nested-write evidence before execution; only its matching completion may replace it. `pending` is required: starts are `pending:true,saved:false`; successful completions are `pending:false,saved:true`. Keep producers, readiness readers, save indicator and cutoff on this persisted meaning; semantic changes require an explicit protocol change, not incidental release edits. Pi's incomplete nested-call log also means omitted arguments, not necessarily unfinished writes.
15
+ - Tree navigation to a user/custom prompt stops at its parent, possibly after that prompt's preparation marker. A marker without delivered conversation must not stale the previous saved checkpoint; explicit run-scoped write proof stays strict.
16
+ - Custom kickoffs skip input hooks. The custom-turn-admission event owns pre-kickoff idle rollover; compaction must finish before Pi reserves startup as busy. Successor custom turns run every before_agent_start hook.
17
+ - Model deactivation yields policy and tools, not committed history cuts. Untrimmed initialization never undoes a prior retirement; real compaction can supersede it. Preserve projection on context and compaction routes in either extension order.
18
+ - Native window checkpoints must cut the complete committed window atomically. Partial context edits invalidate Pi's usage accounting while leaving old history in its estimate. Keep the owned empty summary out of model projection; preserve raw entries and foreign compaction drafts. Restore idle native context before kickoff, never compact inside busy tree preparation.
19
+ - Restore compacted-away identity only in complete context, ahead of its summary. Keep replay slices untouched and developer metadata stable; never queue a turn to restore guidance.
20
+ - Persisted Tree archive/checkpoint/handoff readers preserve source IDs and original protected outputs. Pruning must protect effective archived checkpoints and kept entries at planning and commit, not only Pi's physical context. Never recreate the retired Tree writer or reinterpret missing fork archives as empty history.
21
+ - Return initial and rebound identity from before_agent_start, never send it during startup. Pi inserts its initial system entry ahead of returned hook messages; startup sends otherwise put per-session identity before the shared cache prefix.
22
+ - Automatic rollover uses the successor window message as its custom kickoff. That entry is not yet in the branch during before_agent_start; adopt its identity instead of restoring the outgoing window or returning another boundary.
23
+ - Compaction handoff reads are transient branch contributions anchored to their persisted summary. Rechain only the projected branch, never append contributions or persist their IDs as Pi's first-kept boundary. Compare projected entry identity, not branch length.
24
+ - Session pruning preserves JSONL order/count/IDs and unchanged raw lines; Observatory rebases derived source ranges using header `notesPruning` generations, never a tail receipt alone. Its final tail-copy/rename must contain no await. Released Pi's already-flushed same-path writes are append-only; re-trace SDK rewrite paths when changing this boundary. Do not mutate its live history or coordinate foreign JSONL writers.
25
+ - Pi persists incoming messages after before_agent_start, agent_start and message_end hooks, before returned startup messages. History assigns the kickoff prefix only to the first untrimmed window, never later or identity-only boundaries. Label saved-note continuation prompts in context once their entries exist. Schedule pruning from Notes' admitted window identity, then verify its persisted marker after settlement.
26
+ - Pruning must not turn removed delivered instruction carriers into pending-message redelivery. Coalesce only proven complete state snapshots per branch leaf; unknown custom protocols can contain deltas. Keep current Notes revisions, monitor snapshots, Board routes and notebook epochs, not historical model-facing text disguised as state.
27
+ - Role handoffs prepare the outgoing provider before selecting the successor model and starting the normal window kickoff. Keep checkpoint and compaction gates, rechecking session/window after async work. Role guidance exposes IDs/descriptions only. In-run compaction restores its persisted carrier before the summary without a new turn or prefix edit.