pi-posthorse 0.10.36 → 0.10.38

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-posthorse",
3
- "version": "0.10.36",
3
+ "version": "0.10.38",
4
4
  "type": "module",
5
5
  "description": "Posthorse: fresh context, same journey. No-summary context rollover for Pi, with sparse budget reminders, handoffs, notes, and history.",
6
6
  "keywords": [
@@ -51,11 +51,15 @@
51
51
  "lint:fix:oxlint": "oxlint --fix ."
52
52
  },
53
53
  "peerDependencies": {
54
- "@earendil-works/pi-coding-agent": ">=1.5.2",
55
- "@earendil-works/pi-tui": ">=1.5.2",
54
+ "@earendil-works/pi-ai": "*",
55
+ "@earendil-works/pi-coding-agent": "*",
56
+ "@earendil-works/pi-tui": "*",
56
57
  "typebox": "*"
57
58
  },
58
59
  "peerDependenciesMeta": {
60
+ "@earendil-works/pi-ai": {
61
+ "optional": true
62
+ },
59
63
  "@earendil-works/pi-coding-agent": {
60
64
  "optional": true
61
65
  },
@@ -67,9 +71,9 @@
67
71
  }
68
72
  },
69
73
  "devDependencies": {
70
- "@earendil-works/pi-ai": "1.5.2",
71
- "@earendil-works/pi-coding-agent": "1.5.2",
72
- "@earendil-works/pi-tui": "1.5.2",
74
+ "@earendil-works/pi-ai": "1.6.0",
75
+ "@earendil-works/pi-coding-agent": "1.6.0",
76
+ "@earendil-works/pi-tui": "1.6.0",
73
77
  "@types/node": "24.19.1",
74
78
  "oxc-parser": "0.157.0",
75
79
  "oxfmt": "0.79.0",
@@ -0,0 +1,214 @@
1
+ import type { ContextWithSystemEvent } from "@earendil-works/pi-coding-agent";
2
+ import type { MessageLike, ProjectedEntry } from "./contracts.ts";
3
+ import type { SessionContext } from "./epoch-cache.ts";
4
+ import { sessionProjection } from "./host.ts";
5
+ import { messagesHeldByProviderSummary } from "./provider-summary.ts";
6
+ import { matchesProjectedMessage } from "./retained-tail.ts";
7
+
8
+ export type GuidanceUpdate = {
9
+ readonly entryId: string | undefined;
10
+ readonly text: string;
11
+ };
12
+ export type GuidancePlan = {
13
+ readonly anchorId: string | undefined;
14
+ readonly firstPostAnchorId: string | undefined;
15
+ readonly leading: string;
16
+ readonly current: string;
17
+ readonly updates: readonly GuidanceUpdate[];
18
+ };
19
+ export type GuidanceInsertion = {
20
+ readonly at: number;
21
+ readonly text: string;
22
+ };
23
+ export type GuidancePlacement = {
24
+ readonly leading: string;
25
+ readonly insertions: readonly GuidanceInsertion[];
26
+ };
27
+
28
+ type ContextMessage = MessageLike & { readonly role: string };
29
+
30
+ export function wrapGuidanceSection(text: string): string {
31
+ return `<posthorse>\n${text}\n</posthorse>`;
32
+ }
33
+ export function guidanceUpdateMessage(text: string): {
34
+ readonly role: "system";
35
+ readonly content: string;
36
+ readonly sections: Record<string, string>;
37
+ readonly timestamp: number;
38
+ } {
39
+ return {
40
+ role: "system",
41
+ content: "",
42
+ sections: { posthorse: wrapGuidanceSection(text) },
43
+ timestamp: 0,
44
+ };
45
+ }
46
+ function findProjectedMessage(
47
+ messages: readonly ContextMessage[],
48
+ from: number,
49
+ journal: MessageLike,
50
+ ): number {
51
+ for (let index = from; index < messages.length; index++) {
52
+ const candidate = messages[index];
53
+ if (candidate === undefined) {
54
+ continue;
55
+ }
56
+ if (
57
+ journal.role === "system"
58
+ ? candidate.role === "system" && candidate.timestamp === journal.timestamp
59
+ : matchesProjectedMessage(journal, candidate)
60
+ ) {
61
+ return index;
62
+ }
63
+ }
64
+ return -1;
65
+ }
66
+ function advanceCursor(
67
+ messages: readonly ContextMessage[],
68
+ cursor: number,
69
+ projectedMessages: readonly MessageLike[],
70
+ ): number {
71
+ let next = cursor;
72
+ for (const msg of projectedMessages) {
73
+ const found = findProjectedMessage(messages, next, msg);
74
+ if (found >= 0) {
75
+ next = found + 1;
76
+ }
77
+ }
78
+ return next;
79
+ }
80
+ function buildUpdateMap(updates: readonly GuidanceUpdate[]): Map<string, string> {
81
+ const byId = new Map<string, string>();
82
+ for (const update of updates) {
83
+ if (update.entryId !== undefined) {
84
+ byId.set(update.entryId, update.text);
85
+ }
86
+ }
87
+ return byId;
88
+ }
89
+ function isCompactionSummaryEntry(item: ProjectedEntry): boolean {
90
+ return (
91
+ item.sourceEntry.type === "compaction" &&
92
+ item.messages.some((message) => message.role === "compactionSummary")
93
+ );
94
+ }
95
+ function carriedSummarizedGuidance(
96
+ projection: readonly ProjectedEntry[],
97
+ plan: GuidancePlan,
98
+ updateById: ReadonlyMap<string, string>,
99
+ summaryEntryIndex: number,
100
+ ): string | undefined {
101
+ const projectedIds = new Set(
102
+ projection.flatMap((item) =>
103
+ typeof item.sourceEntry.id === "string" && item.sourceEntry.id !== ""
104
+ ? [item.sourceEntry.id]
105
+ : [],
106
+ ),
107
+ );
108
+ let carried: string | undefined;
109
+ for (const update of plan.updates) {
110
+ if (update.entryId !== undefined && projectedIds.has(update.entryId)) {
111
+ break;
112
+ }
113
+ carried = update.text;
114
+ }
115
+ if (carried === undefined || carried === plan.leading) {
116
+ return undefined;
117
+ }
118
+ if (summaryEntryIndex >= 0) {
119
+ const supersededInTail = projection
120
+ .slice(0, summaryEntryIndex)
121
+ .some(
122
+ (item) => item.sourceEntry.id !== undefined && updateById.has(item.sourceEntry.id),
123
+ );
124
+ if (supersededInTail) {
125
+ return undefined;
126
+ }
127
+ }
128
+ return carried;
129
+ }
130
+ function projectionWindowStart(
131
+ messages: readonly ContextMessage[],
132
+ projection: readonly ProjectedEntry[],
133
+ plan: GuidancePlan,
134
+ ): { readonly entryIndex: number; readonly cursor: number } {
135
+ if (
136
+ plan.anchorId === undefined ||
137
+ projection[0]?.sourceEntry.id !== plan.anchorId ||
138
+ messagesHeldByProviderSummary(messages) > 0
139
+ ) {
140
+ return { entryIndex: 0, cursor: 0 };
141
+ }
142
+ const summaryIndex = messages.findLastIndex((message) => message.role === "compactionSummary");
143
+ const entryIndex =
144
+ plan.firstPostAnchorId === undefined
145
+ ? projection.length
146
+ : projection.findIndex((item) => item.sourceEntry.id === plan.firstPostAnchorId);
147
+ if (summaryIndex < 0 || entryIndex < 0) {
148
+ return { entryIndex: 0, cursor: 0 };
149
+ }
150
+ return { entryIndex, cursor: summaryIndex + 1 };
151
+ }
152
+ function collectUpdateInsertions(
153
+ messages: readonly ContextMessage[],
154
+ projection: readonly ProjectedEntry[],
155
+ plan: GuidancePlan,
156
+ ): GuidanceInsertion[] {
157
+ const updateById = buildUpdateMap(plan.updates);
158
+ const summaryEntryIndex = projection.findLastIndex(isCompactionSummaryEntry);
159
+ const carried =
160
+ messagesHeldByProviderSummary(messages) > 0
161
+ ? carriedSummarizedGuidance(projection, plan, updateById, summaryEntryIndex)
162
+ : undefined;
163
+ const start = projectionWindowStart(messages, projection, plan);
164
+ const insertions: GuidanceInsertion[] = [];
165
+ let cursor = start.cursor;
166
+ for (let index = start.entryIndex; index < projection.length; index++) {
167
+ const item = projection[index];
168
+ if (item === undefined) {
169
+ continue;
170
+ }
171
+ cursor = advanceCursor(messages, cursor, item.messages);
172
+ if (carried !== undefined && index === summaryEntryIndex) {
173
+ insertions.push({ at: cursor, text: carried });
174
+ continue;
175
+ }
176
+ const updateText =
177
+ item.sourceEntry.id === undefined ? undefined : updateById.get(item.sourceEntry.id);
178
+ if (updateText !== undefined) {
179
+ insertions.push({ at: cursor, text: updateText });
180
+ }
181
+ }
182
+ return insertions;
183
+ }
184
+ /**
185
+ * Computes the immutable leading guidance text and anchored mid-conversation section updates.
186
+ * Hosts with a session projection anchor each update directly after the message that preceded its
187
+ * journal entry; hosts without one fall back to appending once an assistant reply locks the prefix.
188
+ */
189
+ export function resolveGuidancePlacement(
190
+ messages: ContextWithSystemEvent["messages"],
191
+ ctx: SessionContext,
192
+ plan: GuidancePlan,
193
+ ): GuidancePlacement {
194
+ if (plan.updates.length === 0 && plan.leading === plan.current) {
195
+ return { leading: plan.leading, insertions: [] };
196
+ }
197
+ const projection = sessionProjection(ctx.sessionManager);
198
+ if (projection !== undefined && projection.length > 0) {
199
+ const insertions = collectUpdateInsertions(messages, projection, plan);
200
+ if (insertions.length > 0) {
201
+ return { leading: plan.leading, insertions };
202
+ }
203
+ }
204
+ if (plan.current === plan.leading) {
205
+ return { leading: plan.leading, insertions: [] };
206
+ }
207
+ if (messages.some((message) => message.role === "assistant")) {
208
+ return {
209
+ leading: plan.leading,
210
+ insertions: [{ at: messages.length, text: plan.current }],
211
+ };
212
+ }
213
+ return { leading: plan.current, insertions: [] };
214
+ }
package/src/guidance.ts CHANGED
@@ -10,6 +10,13 @@ import {
10
10
  import type { EntryLike, PolicyContext, SnapshotReader } from "./contracts.ts";
11
11
  import { startsFreshGuidanceEpoch } from "./boundary.ts";
12
12
  import { createEpochCache, type EpochValue, type SessionContext } from "./epoch-cache.ts";
13
+ import {
14
+ guidanceUpdateMessage,
15
+ resolveGuidancePlacement,
16
+ wrapGuidanceSection,
17
+ type GuidancePlan,
18
+ type GuidanceUpdate,
19
+ } from "./guidance-placement.ts";
13
20
  import {
14
21
  sessionEntry,
15
22
  toolFacts,
@@ -18,6 +25,8 @@ import {
18
25
  type ToolRegistry,
19
26
  } from "./host.ts";
20
27
 
28
+ export type { GuidancePlan, GuidanceUpdate } from "./guidance-placement.ts";
29
+
21
30
  export const WINDOW_GUIDANCE_TYPE = "posthorse-window-guidance";
22
31
  const guidanceRecordSchema = Type.Object({
23
32
  version: Type.Literal(1),
@@ -29,19 +38,31 @@ const guidanceRecordSchema = Type.Object({
29
38
  }),
30
39
  });
31
40
  type WindowGuidanceRecord = Static<typeof guidanceRecordSchema>;
41
+ type GuidanceTimeline = {
42
+ readonly byBudget: ReadonlyMap<string, string>;
43
+ readonly tools: GuidanceTools | undefined;
44
+ readonly leadingText: string | undefined;
45
+ readonly activeText: string | undefined;
46
+ readonly sawAssistant: boolean;
47
+ readonly hasMessageSinceLastUpdate: boolean;
48
+ readonly updates: readonly GuidanceUpdate[];
49
+ };
32
50
  type MemoryEpoch = {
33
51
  readonly byBudget: Map<string, string>;
34
52
  tools: GuidanceTools | undefined;
53
+ leadingText: string | undefined;
54
+ activeText: string | undefined;
35
55
  };
36
- type GuidanceEpoch = {
56
+ type GuidanceEpoch = GuidanceTimeline & {
37
57
  readonly anchorKey: string;
38
- readonly byBudget: ReadonlyMap<string, string>;
39
- readonly tools: GuidanceTools | undefined;
58
+ readonly anchorId: string | undefined;
59
+ readonly firstPostAnchorId: string | undefined;
40
60
  };
41
61
  export type WindowGuidance = {
42
62
  /** Only the session manager is read; the same context the epoch cache accepts. */
43
63
  readonly resolve: (ctx: SessionContext, host: PolicyContext) => string;
44
64
  readonly deliver: (ctx: SessionContext, host: PolicyContext) => string;
65
+ readonly plan: (ctx: SessionContext, host: PolicyContext) => GuidancePlan;
45
66
  readonly reset: () => void;
46
67
  };
47
68
 
@@ -52,33 +73,118 @@ export function activeGuidanceTools(pi: ToolRegistry): GuidanceTools {
52
73
  getContextRemaining: activeUnnamespaced.has("get_context_remaining"),
53
74
  };
54
75
  }
55
- /** Replay oldest first: the last text per budget wins, while the first record fixes epoch tools. */
76
+ function isCompletedAssistantEntry(entry: EntryLike): boolean {
77
+ return (
78
+ entry.type === "message" &&
79
+ entry.message?.role === "assistant" &&
80
+ entry.message.stopReason !== "error" &&
81
+ entry.message.stopReason !== "aborted"
82
+ );
83
+ }
84
+ function isMessageProducingEntry(entry: EntryLike): boolean {
85
+ if (entry.type === "message") {
86
+ return entry.message?.role !== "system" && entry.message?.excludeFromContext !== true;
87
+ }
88
+ return (
89
+ entry.type === "custom_message" ||
90
+ entry.type === "branch_summary" ||
91
+ entry.type === "compaction"
92
+ );
93
+ }
94
+ function nextUpdates(
95
+ state: GuidanceTimeline,
96
+ entryId: string | undefined,
97
+ text: string,
98
+ ): readonly GuidanceUpdate[] {
99
+ if (!state.hasMessageSinceLastUpdate && state.updates.length > 0) {
100
+ const priorText = state.updates.at(-2)?.text ?? state.leadingText;
101
+ if (text === priorText) {
102
+ return state.updates.slice(0, -1);
103
+ }
104
+ return [...state.updates.slice(0, -1), { entryId, text }];
105
+ }
106
+ return [...state.updates, { entryId, text }];
107
+ }
108
+ function applyGuidanceRecord(
109
+ state: GuidanceTimeline,
110
+ entryId: string | undefined,
111
+ record: WindowGuidanceRecord,
112
+ ): GuidanceTimeline {
113
+ const byBudget = new Map(state.byBudget);
114
+ byBudget.set(record.budgetKey, record.text);
115
+ const tools = state.tools ?? record.tools;
116
+ if (state.leadingText === undefined || !state.sawAssistant) {
117
+ return {
118
+ ...state,
119
+ byBudget,
120
+ tools,
121
+ leadingText: record.text,
122
+ activeText: record.text,
123
+ };
124
+ }
125
+ if (record.text === state.activeText) {
126
+ return { ...state, byBudget, tools };
127
+ }
128
+ return {
129
+ ...state,
130
+ byBudget,
131
+ tools,
132
+ activeText: record.text,
133
+ hasMessageSinceLastUpdate: false,
134
+ updates: nextUpdates(state, entryId, record.text),
135
+ };
136
+ }
137
+ function stepNonGuidanceEntry(state: GuidanceTimeline, entry: EntryLike): GuidanceTimeline {
138
+ const sawAssistant =
139
+ state.sawAssistant || (state.leadingText !== undefined && isCompletedAssistantEntry(entry));
140
+ const hasMessageSinceLastUpdate =
141
+ state.hasMessageSinceLastUpdate || isMessageProducingEntry(entry);
142
+ if (
143
+ sawAssistant === state.sawAssistant &&
144
+ hasMessageSinceLastUpdate === state.hasMessageSinceLastUpdate
145
+ ) {
146
+ return state;
147
+ }
148
+ return { ...state, sawAssistant, hasMessageSinceLastUpdate };
149
+ }
150
+ function emptyTimeline(): GuidanceTimeline {
151
+ return {
152
+ byBudget: new Map<string, string>(),
153
+ tools: undefined,
154
+ leadingText: undefined,
155
+ activeText: undefined,
156
+ sawAssistant: false,
157
+ hasMessageSinceLastUpdate: false,
158
+ updates: [],
159
+ };
160
+ }
161
+ /**
162
+ * Replay oldest first: the last text per budget wins, the first record fixes epoch tools, and once
163
+ * a completed assistant reply follows the initial delivery, later text changes become mid-window
164
+ * updates anchored to their journal entries so the leading system message stays immutable.
165
+ */
56
166
  function collectGuidanceEntries(
57
167
  entries: readonly EntryLike[],
58
- baseByBudget?: ReadonlyMap<string, string>,
59
- baseTools?: GuidanceTools,
60
- ): { readonly byBudget: Map<string, string>; readonly tools: GuidanceTools | undefined } {
61
- const byBudget = new Map<string, string>(baseByBudget);
62
- let tools = baseTools;
168
+ base?: GuidanceTimeline,
169
+ ): GuidanceTimeline {
170
+ let state = base ?? emptyTimeline();
63
171
  for (const entry of entries) {
64
172
  if (
65
173
  entry.type === "custom" &&
66
174
  entry.customType === WINDOW_GUIDANCE_TYPE &&
67
175
  Check(guidanceRecordSchema, entry.data)
68
176
  ) {
69
- byBudget.set(entry.data.budgetKey, entry.data.text);
70
- tools ??= entry.data.tools;
177
+ state = applyGuidanceRecord(state, entry.id, entry.data);
178
+ } else {
179
+ state = stepNonGuidanceEntry(state, entry);
71
180
  }
72
181
  }
73
- return { byBudget, tools };
182
+ return state;
74
183
  }
75
184
  function withMemoryEpoch(
76
- collected: {
77
- readonly byBudget: Map<string, string>;
78
- readonly tools: GuidanceTools | undefined;
79
- },
185
+ collected: GuidanceTimeline,
80
186
  memory: MemoryEpoch | undefined,
81
- ): { readonly byBudget: ReadonlyMap<string, string>; readonly tools: GuidanceTools | undefined } {
187
+ ): GuidanceTimeline {
82
188
  if (memory === undefined) {
83
189
  return collected;
84
190
  }
@@ -88,7 +194,26 @@ function withMemoryEpoch(
88
194
  merged.set(key, text);
89
195
  }
90
196
  }
91
- return { byBudget: merged, tools: collected.tools ?? memory.tools };
197
+ return {
198
+ ...collected,
199
+ byBudget: merged,
200
+ tools: collected.tools ?? memory.tools,
201
+ leadingText: collected.leadingText ?? memory.leadingText,
202
+ activeText: collected.activeText ?? memory.activeText,
203
+ };
204
+ }
205
+ function extendPreviousEpoch(
206
+ previous: GuidanceEpoch,
207
+ tail: readonly EntryLike[],
208
+ memoryByEpoch: ReadonlyMap<string, MemoryEpoch> | undefined,
209
+ ): GuidanceEpoch {
210
+ const collected = collectGuidanceEntries(tail, previous);
211
+ return {
212
+ anchorKey: previous.anchorKey,
213
+ anchorId: previous.anchorId,
214
+ firstPostAnchorId: previous.firstPostAnchorId ?? tail[0]?.id,
215
+ ...withMemoryEpoch(collected, memoryByEpoch?.get(previous.anchorKey)),
216
+ };
92
217
  }
93
218
  function scanGuidanceEpoch(
94
219
  manager: SessionHost,
@@ -104,15 +229,7 @@ function scanGuidanceEpoch(
104
229
  entry = sessionEntry(manager, entry.parentId)
105
230
  ) {
106
231
  if (previous !== undefined && previous.identity.leaf === entry) {
107
- const collected = collectGuidanceEntries(
108
- reversed.reverse(),
109
- previous.value.byBudget,
110
- previous.value.tools,
111
- );
112
- return {
113
- anchorKey: previous.value.anchorKey,
114
- ...withMemoryEpoch(collected, memoryByEpoch?.get(previous.value.anchorKey)),
115
- };
232
+ return extendPreviousEpoch(previous.value, reversed.reverse(), memoryByEpoch);
116
233
  }
117
234
  if (startsFreshGuidanceEpoch(entry)) {
118
235
  anchor = entry;
@@ -120,16 +237,64 @@ function scanGuidanceEpoch(
120
237
  }
121
238
  reversed.push(entry);
122
239
  }
240
+ const ordered = reversed.reverse();
123
241
  const anchorKey =
124
242
  anchor === undefined
125
243
  ? `${identity.sessionId}:root`
126
244
  : `${identity.sessionId}:${anchor.id ?? "boundary"}`;
127
- const collected = collectGuidanceEntries(reversed.reverse());
245
+ const collected = collectGuidanceEntries(ordered);
128
246
  return {
129
247
  anchorKey,
248
+ anchorId: anchor?.id,
249
+ firstPostAnchorId: ordered[0]?.id,
130
250
  ...withMemoryEpoch(collected, memoryByEpoch?.get(anchorKey)),
131
251
  };
132
252
  }
253
+ /**
254
+ * A fresh anchor retires every earlier one on this branch: nothing reads an old epoch again
255
+ * without /tree, which resets all memory. Keep only the current anchor's delivered text.
256
+ */
257
+ function pruneRetiredEpochs(
258
+ memoryByManager: WeakMap<object, Map<string, MemoryEpoch>>,
259
+ manager: object,
260
+ anchorKey: string,
261
+ ): void {
262
+ const byEpoch = memoryByManager.get(manager);
263
+ if (byEpoch === undefined) {
264
+ return;
265
+ }
266
+ for (const key of byEpoch.keys()) {
267
+ if (key !== anchorKey) {
268
+ byEpoch.delete(key);
269
+ }
270
+ }
271
+ }
272
+ function recordMemoryEpoch(
273
+ memoryByManager: WeakMap<object, Map<string, MemoryEpoch>>,
274
+ manager: object,
275
+ anchorKey: string,
276
+ entry: { readonly key: string; readonly text: string; readonly tools: GuidanceTools },
277
+ ): void {
278
+ let byEpoch = memoryByManager.get(manager);
279
+ if (byEpoch === undefined) {
280
+ byEpoch = new Map();
281
+ memoryByManager.set(manager, byEpoch);
282
+ }
283
+ let memory = byEpoch.get(anchorKey);
284
+ if (memory === undefined) {
285
+ memory = {
286
+ byBudget: new Map(),
287
+ tools: entry.tools,
288
+ leadingText: entry.text,
289
+ activeText: entry.text,
290
+ };
291
+ byEpoch.set(anchorKey, memory);
292
+ }
293
+ memory.byBudget.set(entry.key, entry.text);
294
+ memory.tools ??= entry.tools;
295
+ memory.leadingText ??= entry.text;
296
+ memory.activeText = entry.text;
297
+ }
133
298
  /** The journal and tool-registry members guidance borrows; the host's full API satisfies these. */
134
299
  export type GuidanceRegistry = ToolRegistry & Pick<ExtensionAPI, "appendEntry">;
135
300
 
@@ -144,19 +309,44 @@ export function createWindowGuidance(pi: GuidanceRegistry): WindowGuidance {
144
309
  ),
145
310
  );
146
311
  /**
147
- * A fresh anchor retires every earlier one on this branch: nothing reads an old epoch again
148
- * without /tree, which resets all memory. Keep only the current anchor's delivered text.
312
+ * Delivering guidance from inside the request hook must persist before the request: a
313
+ * restart after a rollover with a provider summary block has to reuse these exact bytes —
314
+ * the leading system message is sent unchanged, and in-memory delivery state does not
315
+ * survive. On the fork, the provider-summary request runs this hook mid-compaction. That
316
+ * is safe twice over: the request that reached the rollover threshold already delivered
317
+ * this budget's text, so the summary request reuses it and writes nothing; and a
318
+ * compaction with a summary block keeps the previous guidance anchor, so even a budget
319
+ * change mid-compaction appends inside the epoch the next window still reads.
149
320
  */
150
- const pruneRetiredEpochs = (manager: object, anchorKey: string): void => {
151
- const byEpoch = memoryByManager.get(manager);
152
- if (byEpoch === undefined) {
153
- return;
154
- }
155
- for (const key of byEpoch.keys()) {
156
- if (key !== anchorKey) {
157
- byEpoch.delete(key);
158
- }
321
+ const plan = (ctx: SessionContext, host: PolicyContext): GuidancePlan => {
322
+ let epoch = epochs.read(ctx);
323
+ pruneRetiredEpochs(memoryByManager, ctx.sessionManager, epoch.anchorKey);
324
+ const key = budgetGuidanceKey(host);
325
+ const desired =
326
+ epoch.byBudget.get(key) ?? buildGuidance(host, epoch.tools ?? activeGuidanceTools(pi));
327
+ if (epoch.activeText !== desired) {
328
+ const tools = epoch.tools ?? activeGuidanceTools(pi);
329
+ recordMemoryEpoch(memoryByManager, ctx.sessionManager, epoch.anchorKey, {
330
+ key,
331
+ text: desired,
332
+ tools,
333
+ });
334
+ epochs.reset();
335
+ pi.appendEntry(WINDOW_GUIDANCE_TYPE, {
336
+ version: 1,
337
+ budgetKey: key,
338
+ text: desired,
339
+ tools,
340
+ } satisfies WindowGuidanceRecord);
341
+ epoch = epochs.read(ctx);
159
342
  }
343
+ return {
344
+ anchorId: epoch.anchorId,
345
+ firstPostAnchorId: epoch.firstPostAnchorId,
346
+ leading: epoch.leadingText ?? desired,
347
+ current: desired,
348
+ updates: epoch.updates,
349
+ };
160
350
  };
161
351
  return {
162
352
  resolve(ctx, host) {
@@ -166,47 +356,10 @@ export function createWindowGuidance(pi: GuidanceRegistry): WindowGuidance {
166
356
  epoch.byBudget.get(key) ?? buildGuidance(host, epoch.tools ?? ALL_GUIDANCE_TOOLS)
167
357
  );
168
358
  },
169
- /**
170
- * Delivering guidance from inside the request hook must persist before the request: a
171
- * restart after a rollover with a provider summary block has to reuse these exact bytes —
172
- * the leading system message is sent unchanged, and in-memory delivery state does not
173
- * survive. On the fork, the provider-summary request runs this hook mid-compaction. That
174
- * is safe twice over: the request that reached the rollover threshold already delivered
175
- * this budget's text, so the summary request reuses it and writes nothing; and a
176
- * compaction with a summary block keeps the previous guidance anchor, so even a budget
177
- * change mid-compaction appends inside the epoch the next window still reads.
178
- */
179
359
  deliver(ctx, host) {
180
- const epoch = epochs.read(ctx);
181
- pruneRetiredEpochs(ctx.sessionManager, epoch.anchorKey);
182
- const key = budgetGuidanceKey(host);
183
- const existing = epoch.byBudget.get(key);
184
- if (existing !== undefined) {
185
- return existing;
186
- }
187
- const tools = epoch.tools ?? activeGuidanceTools(pi);
188
- const text = buildGuidance(host, tools);
189
- let byEpoch = memoryByManager.get(ctx.sessionManager);
190
- if (byEpoch === undefined) {
191
- byEpoch = new Map();
192
- memoryByManager.set(ctx.sessionManager, byEpoch);
193
- }
194
- let memory = byEpoch.get(epoch.anchorKey);
195
- if (memory === undefined) {
196
- memory = { byBudget: new Map(), tools };
197
- byEpoch.set(epoch.anchorKey, memory);
198
- }
199
- memory.byBudget.set(key, text);
200
- memory.tools ??= tools;
201
- epochs.reset();
202
- pi.appendEntry(WINDOW_GUIDANCE_TYPE, {
203
- version: 1,
204
- budgetKey: key,
205
- text,
206
- tools,
207
- } satisfies WindowGuidanceRecord);
208
- return text;
360
+ return plan(ctx, host).current;
209
361
  },
362
+ plan,
210
363
  reset() {
211
364
  epochs.reset();
212
365
  memoryByManager = new WeakMap();
@@ -228,13 +381,9 @@ export function registerGuidance(
228
381
  promptOptions = undefined;
229
382
  });
230
383
  pi.on("context_with_system", (event, ctx) => {
231
- const guidance = windowGuidance.deliver(ctx, policy(ctx));
232
- const system =
233
- event.messages.findLast(
234
- (message) =>
235
- message.role === "system" && typeof message.sections?.posthorse === "string",
236
- ) ?? event.messages.find((message) => message.role === "system");
237
- if (system === undefined || system.role !== "system") {
384
+ const plan = windowGuidance.plan(ctx, policy(ctx));
385
+ const system = event.messages.find((message) => message.role === "system");
386
+ if (system === undefined) {
238
387
  return;
239
388
  }
240
389
  if (promptOptions?.forceSystemPrompt !== undefined) {
@@ -245,15 +394,21 @@ export function registerGuidance(
245
394
  event.messages.splice(conversation === -1 ? event.messages.length : conversation, 0, {
246
395
  role: "custom",
247
396
  customType: "posthorse-guidance",
248
- content: guidance,
397
+ content: plan.current,
249
398
  display: false,
250
399
  timestamp: 0,
251
400
  });
252
- } else {
253
- system.sections = {
254
- ...system.sections,
255
- posthorse: `<posthorse>\n${guidance}\n</posthorse>`,
256
- };
401
+ return;
402
+ }
403
+ const placement = resolveGuidancePlacement(event.messages, ctx, plan);
404
+ system.sections = {
405
+ ...system.sections,
406
+ posthorse: wrapGuidanceSection(placement.leading),
407
+ };
408
+ let offset = 0;
409
+ for (const item of placement.insertions) {
410
+ event.messages.splice(item.at + offset, 0, guidanceUpdateMessage(item.text));
411
+ offset += 1;
257
412
  }
258
413
  });
259
414
  }
package/src/reminders.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { ExtensionContext, TurnEndEvent } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionContext, TurnEndEvent } from "@earendil-works/pi-coding-agent";
2
+ import { Type, type Static } from "typebox";
3
+ import { Check } from "typebox/value";
2
4
  import { budgetFor, type Budget } from "./budget.ts";
3
5
  import {
4
6
  LEGACY_WINDOW_TYPE,
@@ -10,11 +12,20 @@ import {
10
12
  } from "./contracts.ts";
11
13
  import { contextStart, isWindow } from "./boundary.ts";
12
14
  import { createEpochCache, type EpochValue, type SessionContext } from "./epoch-cache.ts";
13
- import { sessionEntry, type SessionHost } from "./host.ts";
15
+ import { sessionEntry, sessionProjection, type SessionHost } from "./host.ts";
16
+ import { messagesHeldByProviderSummary } from "./provider-summary.ts";
17
+
18
+ export const SUPPRESSED_REMINDER_TYPE = "posthorse-suppressed-reminder";
19
+ const suppressedReminderSchema = Type.Object({
20
+ version: Type.Literal(1),
21
+ entryIds: Type.Array(Type.String()),
22
+ });
23
+ type SuppressedReminderRecord = Static<typeof suppressedReminderSchema>;
14
24
 
15
25
  type ReminderFacts = {
16
26
  readonly windowId: string;
17
27
  readonly reminders: readonly EntryLike[];
28
+ readonly suppressedIds: ReadonlySet<string>;
18
29
  };
19
30
  export type ReminderLookup = {
20
31
  readonly reset: () => void;
@@ -23,10 +34,14 @@ export type ReminderLookup = {
23
34
  export type ContextMessage = {
24
35
  readonly role: string;
25
36
  readonly customType?: string | undefined;
37
+ readonly content?: unknown;
26
38
  readonly details?: unknown;
27
39
  };
28
40
  export type StaleReminderPredicate = (message: ContextMessage) => boolean;
29
41
 
42
+ function reminderWindowMatches(details: unknown, windowId: string): boolean {
43
+ return isRecord(details) && details.windowId === windowId;
44
+ }
30
45
  function reminderMatches(details: unknown, fingerprint: ReminderFingerprint): boolean {
31
46
  if (!isRecord(details)) {
32
47
  return false;
@@ -48,6 +63,15 @@ function hasReminder(entries: readonly EntryLike[], fingerprint: ReminderFingerp
48
63
  function isReminderMessage(message: ContextMessage): boolean {
49
64
  return message.role === "custom" && isReminderType(message.customType);
50
65
  }
66
+ function reminderContentKey(message: {
67
+ readonly customType?: string | undefined;
68
+ readonly content?: unknown;
69
+ readonly details?: unknown;
70
+ }): string {
71
+ // Live CustomMessage timestamps (Date.now) and persisted entry ISO timestamps can differ by 1ms,
72
+ // so match reminders by type, payload, and fingerprint in chronological order.
73
+ return JSON.stringify([message.customType, message.content, message.details]);
74
+ }
51
75
  /** A host may project a legacy fork's display marker; its window id outranks the journal scan. */
52
76
  function contextMarker(messages: readonly ContextMessage[]): {
53
77
  readonly present: boolean;
@@ -79,29 +103,188 @@ export function reminderFingerprint(
79
103
  const windowId = marker.present ? marker.windowId : reminders.read(ctx).windowId;
80
104
  return typeof windowId === "string" ? fingerprintOf(windowId, host) : undefined;
81
105
  }
106
+ type JournalReminder = { readonly id: string; readonly key: string };
107
+ function activeJournalReminders(
108
+ ctx: SessionContext,
109
+ state: ReminderFacts,
110
+ ): readonly JournalReminder[] {
111
+ const projection = sessionProjection(ctx.sessionManager);
112
+ if (projection !== undefined && projection.length > 0) {
113
+ const projected: JournalReminder[] = [];
114
+ for (const item of projection) {
115
+ const id = item.sourceEntry.id;
116
+ const first = item.messages[0];
117
+ if (
118
+ typeof id === "string" &&
119
+ id !== "" &&
120
+ item.sourceEntry.type === "custom_message" &&
121
+ isReminderType(item.sourceEntry.customType) &&
122
+ first !== undefined
123
+ ) {
124
+ projected.push({ id, key: reminderContentKey(first) });
125
+ }
126
+ }
127
+ return projected;
128
+ }
129
+ return state.reminders.flatMap((entry) =>
130
+ typeof entry.id === "string" && entry.id !== ""
131
+ ? [{ id: entry.id, key: reminderContentKey(entry) }]
132
+ : [],
133
+ );
134
+ }
135
+ function matchReminderEntryIds(
136
+ messages: readonly ContextMessage[],
137
+ journal: readonly JournalReminder[],
138
+ ): Map<number, string> {
139
+ const matched = new Map<number, string>();
140
+ if (journal.length === 0) {
141
+ return matched;
142
+ }
143
+ let cursor = 0;
144
+ for (let index = 0; index < messages.length && cursor < journal.length; index++) {
145
+ const message = messages[index];
146
+ if (message === undefined || !isReminderMessage(message)) {
147
+ continue;
148
+ }
149
+ const key = reminderContentKey(message);
150
+ const found = journal.findIndex((entry, at) => at >= cursor && entry.key === key);
151
+ if (found >= 0) {
152
+ const entry = journal[found];
153
+ if (entry !== undefined) {
154
+ matched.set(index, entry.id);
155
+ }
156
+ cursor = found + 1;
157
+ }
158
+ }
159
+ return matched;
160
+ }
161
+ export type RemovableReminderPredicate = (message: ContextMessage, index: number) => boolean;
162
+ export type ReminderFilterResult = {
163
+ readonly stale: StaleReminderPredicate;
164
+ readonly removable: RemovableReminderPredicate;
165
+ readonly newlySuppressedIds: readonly string[];
166
+ };
167
+ function collectNewlySuppressedIds(
168
+ messages: readonly ContextMessage[],
169
+ state: {
170
+ readonly held: number;
171
+ readonly lastAssistant: number;
172
+ readonly windowId: string;
173
+ readonly stale: StaleReminderPredicate;
174
+ readonly suppressedIds: ReadonlySet<string>;
175
+ readonly entryIds: ReadonlyMap<number, string>;
176
+ },
177
+ ): string[] {
178
+ const newlySuppressed: string[] = [];
179
+ const seen = new Set<string>();
180
+ for (let index = state.held; index < messages.length; index++) {
181
+ const message = messages[index];
182
+ if (
183
+ message === undefined ||
184
+ index <= state.lastAssistant ||
185
+ !state.stale(message) ||
186
+ !reminderWindowMatches(message.details, state.windowId)
187
+ ) {
188
+ continue;
189
+ }
190
+ const entryId = state.entryIds.get(index);
191
+ if (entryId !== undefined && !state.suppressedIds.has(entryId) && !seen.has(entryId)) {
192
+ seen.add(entryId);
193
+ newlySuppressed.push(entryId);
194
+ }
195
+ }
196
+ return newlySuppressed;
197
+ }
82
198
  /**
83
- * Reminders that no longer describe this window or budget leave the context. When Pi compaction is
84
- * off, no reminder can fire again, so every reminder is stale.
199
+ * Classifies reminders in `messages` for stale checks and monotone, prefix-safe removal.
200
+ *
201
+ * A reminder from an ended window was never sent in the new window (unless held under a provider
202
+ * summary block), so filtering it keeps the new window's prefix consistent from its first request.
203
+ * A current-window reminder that became stale after a model, reserve, or compaction-setting change
204
+ * may only be removed from the trailing unsent tail after the last assistant reply; once omitted,
205
+ * its journal entry id is marked suppressed so later assistant replies or setting reversals never
206
+ * re-insert it mid-history.
85
207
  */
86
- export function staleReminderPredicate(
208
+ export function reminderFilter(
87
209
  messages: readonly ContextMessage[],
88
210
  ctx: SessionContext,
89
211
  host: PolicyContext,
90
212
  reminders: ReminderLookup,
91
- ): StaleReminderPredicate {
213
+ ): ReminderFilterResult {
214
+ const never = () => false;
92
215
  if (!messages.some(isReminderMessage)) {
93
- return () => false;
216
+ return { stale: never, removable: never, newlySuppressedIds: [] };
94
217
  }
95
218
  const budget = budgetFor(host);
96
219
  const compactionDisabled =
97
220
  budget === undefined ? !host.getCompactionSettings().enabled : budget.state === "disabled";
98
221
  const fingerprint = reminderFingerprint(ctx, host, reminders, messages);
99
222
  if (fingerprint === undefined) {
100
- return () => false;
223
+ return { stale: never, removable: never, newlySuppressedIds: [] };
101
224
  }
102
- return (message) =>
225
+ const stale: StaleReminderPredicate = (message) =>
103
226
  isReminderMessage(message) &&
104
227
  (compactionDisabled || !reminderMatches(message.details, fingerprint));
228
+ const hasCurrentWindow = messages.some(
229
+ (message) =>
230
+ isReminderMessage(message) &&
231
+ reminderWindowMatches(message.details, fingerprint.windowId),
232
+ );
233
+ const facts = hasCurrentWindow ? reminders.read(ctx) : undefined;
234
+ const suppressedIds = facts?.suppressedIds ?? new Set<string>();
235
+ const entryIds =
236
+ facts === undefined
237
+ ? new Map<number, string>()
238
+ : matchReminderEntryIds(messages, activeJournalReminders(ctx, facts));
239
+ const held = messagesHeldByProviderSummary(messages);
240
+ const lastAssistant = messages.findLastIndex((message) => message.role === "assistant");
241
+ const removable: RemovableReminderPredicate = (message, index) => {
242
+ if (index < held || !isReminderMessage(message)) {
243
+ return false;
244
+ }
245
+ const entryId = entryIds.get(index);
246
+ if (entryId !== undefined && suppressedIds.has(entryId)) {
247
+ return true;
248
+ }
249
+ return (
250
+ stale(message) &&
251
+ (index > lastAssistant || !reminderWindowMatches(message.details, fingerprint.windowId))
252
+ );
253
+ };
254
+ const newlySuppressedIds = collectNewlySuppressedIds(messages, {
255
+ held,
256
+ lastAssistant,
257
+ windowId: fingerprint.windowId,
258
+ stale,
259
+ suppressedIds,
260
+ entryIds,
261
+ });
262
+ return { stale, removable, newlySuppressedIds };
263
+ }
264
+ /** Persist filtered trailing current-window reminder IDs so subsequent turns never re-insert them. */
265
+ export function persistSuppressedReminders(
266
+ pi: Pick<ExtensionAPI, "appendEntry">,
267
+ entryIds: readonly string[],
268
+ ): void {
269
+ if (entryIds.length === 0) {
270
+ return;
271
+ }
272
+ pi.appendEntry(SUPPRESSED_REMINDER_TYPE, {
273
+ version: 1,
274
+ entryIds: [...entryIds],
275
+ } satisfies SuppressedReminderRecord);
276
+ }
277
+ /**
278
+ * Reminders that no longer describe this window or budget leave the context. When Pi compaction is
279
+ * off, no reminder can fire again, so every reminder is stale.
280
+ */
281
+ export function staleReminderPredicate(
282
+ messages: readonly ContextMessage[],
283
+ ctx: SessionContext,
284
+ host: PolicyContext,
285
+ reminders: ReminderLookup,
286
+ ): StaleReminderPredicate {
287
+ return reminderFilter(messages, ctx, host, reminders).stale;
105
288
  }
106
289
  const REMINDER_BUFFER_TOKENS = 32_000;
107
290
  type ReminderDecision =
@@ -175,6 +358,24 @@ function onlyReminders(entries: readonly EntryLike[]): EntryLike[] {
175
358
  (entry) => entry.type === "custom_message" && isReminderType(entry.customType),
176
359
  );
177
360
  }
361
+ function collectSuppressedIds(
362
+ entries: readonly EntryLike[],
363
+ base?: ReadonlySet<string>,
364
+ ): Set<string> {
365
+ const suppressed = new Set<string>(base);
366
+ for (const entry of entries) {
367
+ if (
368
+ entry.type === "custom" &&
369
+ entry.customType === SUPPRESSED_REMINDER_TYPE &&
370
+ Check(suppressedReminderSchema, entry.data)
371
+ ) {
372
+ for (const id of entry.data.entryIds) {
373
+ suppressed.add(id);
374
+ }
375
+ }
376
+ }
377
+ return suppressed;
378
+ }
178
379
  type ScanProgress = {
179
380
  readonly boundary?: EntryLike | undefined;
180
381
  readonly window?: EntryLike | undefined;
@@ -205,9 +406,11 @@ function scanAncestry(
205
406
  previous !== undefined &&
206
407
  previous.identity.leaf === entry
207
408
  ) {
409
+ const tail = reversed.reverse();
208
410
  return {
209
411
  windowId: previous.value.windowId,
210
- reminders: [...previous.value.reminders, ...onlyReminders(reversed.reverse())],
412
+ reminders: [...previous.value.reminders, ...onlyReminders(tail)],
413
+ suppressedIds: collectSuppressedIds(tail, previous.value.suppressedIds),
211
414
  };
212
415
  }
213
416
  reversed.push(entry);
@@ -218,14 +421,15 @@ function scanAncestry(
218
421
  }
219
422
  }
220
423
  const entries = reversed.reverse();
424
+ const active = entries.slice(contextStart(entries).start);
221
425
  return {
222
426
  windowId: progress.window?.id ?? "initial",
223
- reminders: onlyReminders(entries.slice(contextStart(entries).start)),
427
+ reminders: onlyReminders(active),
428
+ suppressedIds: collectSuppressedIds(active),
224
429
  };
225
430
  }
226
431
  export function createReminderLookup(): ReminderLookup {
227
- const cache = createEpochCache<ReminderFacts>((ctx, identity, previous) =>
432
+ return createEpochCache<ReminderFacts>((ctx, identity, previous) =>
228
433
  scanAncestry(ctx.sessionManager, identity.leaf, previous),
229
434
  );
230
- return { reset: cache.reset, read: cache.read };
231
435
  }
@@ -85,7 +85,7 @@ export function retainedTailEnd(
85
85
  if (message === undefined || journal === undefined) {
86
86
  break;
87
87
  }
88
- if (sameRetainedMessage(journal, message) || isOpaquePresentation(journal, message)) {
88
+ if (matchesProjectedMessage(journal, message)) {
89
89
  expected += 1;
90
90
  end = index + 1;
91
91
  }
@@ -180,6 +180,11 @@ function isOpaquePresentation(journal: MessageLike, event: MessageLike): boolean
180
180
  );
181
181
  }
182
182
 
183
+ /** Whether `event` is the provider-context presentation of projected journal message `journal`. */
184
+ export function matchesProjectedMessage(journal: MessageLike, event: MessageLike): boolean {
185
+ return sameRetainedMessage(journal, event) || isOpaquePresentation(journal, event);
186
+ }
187
+
183
188
  /**
184
189
  * Identity of a retained message as the provider context carries it: same payload and receipt
185
190
  * linkage, and a role an earlier handler may only present as `system`. Journal and
package/src/rollover.ts CHANGED
@@ -22,11 +22,7 @@ import { registerContextTools } from "./context-tools.ts";
22
22
  import { registerGuidance, type WindowGuidance } from "./guidance.ts";
23
23
  import { ownerQuestionRegistered as ownerQuestionTool } from "./host.ts";
24
24
  import { safeJsonStringify } from "./message-text.ts";
25
- import {
26
- hostMakesProviderSummary,
27
- messagesHeldByProviderSummary,
28
- type ProviderSummaryRequest,
29
- } from "./provider-summary.ts";
25
+ import { hostMakesProviderSummary, type ProviderSummaryRequest } from "./provider-summary.ts";
30
26
  import { hasRetainedRolloverMarker } from "./recovery.ts";
31
27
  import { automaticRecovery } from "./retention.ts";
32
28
  import { ResetRequests, type ResetOutcome } from "./reset-requests.ts";
@@ -38,8 +34,9 @@ type RolloverResources = {
38
34
  };
39
35
  import {
40
36
  createReminderLookup,
37
+ persistSuppressedReminders,
41
38
  reminderDecision,
42
- staleReminderPredicate,
39
+ reminderFilter,
43
40
  type ReminderLookup,
44
41
  type StaleReminderPredicate,
45
42
  } from "./reminders.ts";
@@ -117,13 +114,18 @@ function registerReminderFilter(
117
114
  reminders: ReminderLookup,
118
115
  ): void {
119
116
  pi.on("context_with_system", (event, ctx) => {
120
- const stale = staleReminderPredicate(event.messages, ctx, policy(ctx), reminders);
121
- const held = messagesHeldByProviderSummary(event.messages);
122
- const removable = (message: (typeof event.messages)[number], index: number) =>
123
- index >= held && stale(message);
117
+ const { stale, removable, newlySuppressedIds } = reminderFilter(
118
+ event.messages,
119
+ ctx,
120
+ policy(ctx),
121
+ reminders,
122
+ );
124
123
  const filtered = event.messages.some(removable)
125
124
  ? event.messages.filter((message, index) => !removable(message, index))
126
125
  : event.messages;
126
+ if (newlySuppressedIds.length > 0) {
127
+ persistSuppressedReminders(pi, newlySuppressedIds);
128
+ }
127
129
  const ordered = chronologicalRetainedTail(filtered, ctx, stale);
128
130
  if (ordered !== event.messages) {
129
131
  return { messages: ordered };