@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @howaboua/pi-notes-compaction
2
2
 
3
+ ## 0.0.17
4
+
5
+ - Notes lookup warnings now distinguish unavailable remote notes from local checkpoints.
6
+ - Notes guidance calls for fewer, shorter updates, using task notes and/or checkpoints with History links instead of copied investigation or harness detail.
7
+ - Notes guidance keeps no-action report updates to their ID and outcome when checkpointing is needed.
8
+ - Retired session records are removed automatically after Pi exits.
9
+ - Notes guidance distinguishes non-waking writes from direct messages, regardless of messaging tool.
10
+ - Notes settings now open on Enabled, with Off, On and Whitelist choices.
11
+
12
+ ## 0.0.16
13
+
14
+ - Requires Node.js 22.19 or newer.
15
+ - Notes now offers Off and defers inactive initialisation without deleting saved data or retired context boundaries.
16
+ - Notes now accepts `content` as a body alias for `text` in typed tool calls.
17
+ - Notes reads now accept `end_line` as an alias for `stop_line`.
18
+ - Notes results now omit routine bookkeeping while retaining paths, content, search matches and truncation.
19
+ - Context recovery now checks selected past user messages for intent and communication preferences, with current instructions taking precedence.
20
+ - Context window openings now omit UUIDs; history still exposes window references.
21
+ - Notes guidance now consolidates changed checkpoints near the end of substantive turns.
22
+ - Shared notes and history now report recovery options when saved context cannot be accessed.
23
+ - History searches no longer retain full rendered copies of tool arguments and messages for the session lifetime.
24
+ - Notes now uses minute precision in displayed dates, preserving existing records.
25
+ - Replaced the TypeBox dependency with Pi's native schema validation.
26
+
3
27
  ## 0.0.15
4
28
 
5
29
  - 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.
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
@@ -82,10 +84,23 @@ unsupported reasoning levels. Provider capabilities and context limits still
82
84
  apply, and switching does not guarantee cache reuse. Context retirement and
83
85
  recovery keep their existing Notes settings.
84
86
 
87
+ ### Session pruning
88
+
89
+ Open **Session auto-pruning** in `/notes` to set this session's retention limits. **Run now** previews and confirms irreversible removal of retired payloads. Automatic pruning runs after a new window's first completed turn. Saved SQLite notes and current context remain intact. Settings follow the session on resume. New and forked sessions start with pruning off.
90
+
91
+ Live pruning keeps every history entry ID so Pi can still navigate its in-memory tree safely. With retention enabled, Notes automatically removes retired empty records after Pi exits. A separate helper waits for the actual process to end before changing the saved tree. Reloading, forking and switching sessions do not trigger this cleanup. No command or additional confirmation is needed. No backup is kept. Memory savings apply when the pruned session next opens.
92
+
93
+ Physical cleanup currently requires Linux and an available `node` executable. Other platforms retain live payload pruning. Cleanup skips another registered local Notes process using the same saved session, known open-file holders and files that change during preparation. A simultaneous reopen is checked against the saved generation. If cleanup won that race, the new Pi process stops and asks you to reopen it rather than continue with a stale tree. Failures are reported when the session next opens. Tree branches, labels, compaction boundaries and supported Notes archive references are retained. Other content and saved notes are unchanged.
94
+
95
+ Coordination covers local processes running this Notes release under the same OS user. Keep session storage free of concurrent writers from other machines, other OS users, older Notes versions and external JSONL editors while a Notes-enabled process is closing. Unrelated sessions do not block cleanup.
96
+
97
+ Update Observatory before applying if you use its historical index. Older versions may block the rewritten file. Current versions reconcile removed records without discarding indexed statistics.
98
+
85
99
  ### Notes settings
86
100
 
87
101
  `/notes` opens the settings panel in interactive Pi. It shows continuity status, storage counts and remote capabilities. Changes save immediately.
88
- - **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.
102
+
103
+ - **Enabled** selects **Off**, **On** (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. Off disables Notes without deleting saved data.
89
104
  - **Normal compaction** uses the installed Pi or PCC compaction flow for `/compact` and `new_context`. Off keeps notes-only rollover, the default.
90
105
  - **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.
91
106
  - **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.15",
3
+ "version": "0.0.17",
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.9",
44
+ "@howaboua/pi-codex-conversion": "5.0.0",
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.9",
49
- "typebox": "*"
52
+ "@howaboua/pi-codex-conversion": ">=5.0.0"
50
53
  },
51
54
  "peerDependenciesMeta": {
52
55
  "@howaboua/pi-codex-conversion": {
@@ -54,9 +57,9 @@
54
57
  }
55
58
  },
56
59
  "exports": {
57
- ".": "./src/index.ts",
58
- "./context-sharing": "./src/context-sharing.ts",
59
- "./saved-session": "./src/saved-session.mjs",
60
- "./saved-session-index": "./src/saved-session-index.mjs"
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"
61
64
  }
62
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
+ gpt = false,
22
+ ): string {
23
+ return [
24
+ board
25
+ ? gpt
26
+ ? "Board→new peer-work findings/decisions/ownership/blockers only; no change→no post. Peers read directly; no parent relay. No idle wake; active subscribers may be interrupted."
27
+ : "Board: post only findings, decisions, ownership changes or blockers that change peers' work. Peers read posts directly; do not relay them through the parent. Posts do not wake idle agents but may interrupt active subscribers."
28
+ : "",
29
+ notes
30
+ ? [
31
+ gpt
32
+ ? "Notes writes don't wake peers."
33
+ : "Notes writes do not wake peers.",
34
+ board
35
+ ? gpt
36
+ ? "Notes→recovery; link Board evidence."
37
+ : "Notes holds recovery checkpoints; link Board evidence."
38
+ : "",
39
+ gpt
40
+ ? "Known recipient Notes access→brief outcome/blocker + checkpoint path; recipient reads checkpoint instead of requesting its contents."
41
+ : "With known recipient Notes access, return a brief outcome or blocker plus the checkpoint path; the recipient reads the checkpoint instead of requesting its contents.",
42
+ ]
43
+ .filter(Boolean)
44
+ .join(" ")
45
+ : "",
46
+ notes || board
47
+ ? gpt
48
+ ? `${notes && board ? "Notes/Board" : notes ? "Notes" : "Board"} available here≠recipient access. Known access→link≠repeat; otherwise self-contained actions/findings/unresolved state.`
49
+ : `${notes && board ? "Notes and Board" : notes ? "Notes" : "Board"} availability here does not establish recipient access. Link rather than repeat when access is known; otherwise give a self-contained account of actions, findings and unresolved state.`
50
+ : "",
51
+ notes || board
52
+ ? gpt
53
+ ? "Direct messages→assignments or urgent action, not status or courtesy updates."
54
+ : "Use direct messages for assignments or urgent action, not status or courtesy updates."
55
+ : "",
56
+ ]
57
+ .filter(Boolean)
58
+ .join(" ");
59
+ }
60
+
61
+ export function registerCommunicationGuidance(
62
+ pi: ExtensionAPI,
63
+ notes?: CommsFeature,
64
+ board?: CommsFeature,
65
+ ): void {
66
+ const owner =
67
+ notes && board
68
+ ? "agent-comms-routing"
69
+ : notes
70
+ ? "notes-routing"
71
+ : "board-routing";
72
+ registerContextBriefing(
73
+ pi,
74
+ "communication",
75
+ (ctx) => Boolean(notes?.enabled(ctx) || board?.enabled(ctx)),
76
+ async (ctx, windowId, messages) => {
77
+ // Feature owners supply enablement independently of provider declarations.
78
+ const capabilities = [
79
+ notes?.enabled(ctx) ?? false,
80
+ board?.enabled(ctx) ?? false,
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
+ - Live session pruning preserves JSONL order/count/IDs. Sparse cleanup runs only after the owning Pi process exits, never inside shutdown or on reload/fork. Retain roots, leaves, branchpoints, physical last and supported structured reference targets; skip live registered owners. FD checks do not prove an idle manager has closed. Observatory rebases derived ranges using new header `notesPruning` generations, never tail receipts alone. Final validation/rename must contain no await. Never mutate Pi's 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.