pi-posthorse 0.10.28 → 0.10.29

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.28",
3
+ "version": "0.10.29",
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": [
package/src/budget.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  MAX_HANDOFF_CHARS,
5
5
  MAX_PAGE_CHARS,
6
6
  PAGE_MARGIN_TOKENS,
7
+ formatCount,
7
8
  type CompactionPolicy,
8
9
  type ContextUsage,
9
10
  type MessageLike,
@@ -95,11 +96,10 @@ export function budgetGuidanceKey(ctx: PolicyContext): string {
95
96
  : `1:${budget.contextWindow}:${budget.reserveTokens}`;
96
97
  }
97
98
  export function unsupportedMessage(budget: Budget, newContextAvailable = true): string {
98
- const n = (value: number) => value.toLocaleString("en-US");
99
99
  const reset = newContextAvailable
100
100
  ? " new_context remains available with a model-aware handoff limit."
101
101
  : "";
102
- return `Posthorse: unsupported configuration. The model's context window (${n(budget.contextWindow)} tokens) minus Pi's compaction.reserveTokens (${n(budget.reserveTokens)}) leaves ${n(budget.usable)} usable tokens; Posthorse needs at least ${n(MIN_USABLE_TOKENS)}. Automatic Posthorse rollover and checkpoint reminders are off for this model, so Pi's own compaction applies. Lower compaction.reserveTokens in Pi settings or use a larger-context model.${reset}`;
102
+ return `Posthorse: unsupported configuration. The model's context window (${formatCount(budget.contextWindow)} tokens) minus Pi's compaction.reserveTokens (${formatCount(budget.reserveTokens)}) leaves ${formatCount(budget.usable)} usable tokens; Posthorse needs at least ${formatCount(MIN_USABLE_TOKENS)}. Automatic Posthorse rollover and checkpoint reminders are off for this model, so Pi's own compaction applies. Lower compaction.reserveTokens in Pi settings or use a larger-context model.${reset}`;
103
103
  }
104
104
  function automaticGuidance(
105
105
  budget: Budget | undefined,
@@ -116,7 +116,7 @@ function automaticGuidance(
116
116
  const line =
117
117
  budget === undefined
118
118
  ? ""
119
- : `The rollover line is ${budget.rolloverAt.toLocaleString("en-US")} tokens used. `;
119
+ : `The rollover line is ${formatCount(budget.rolloverAt)} tokens used. `;
120
120
  const reset = tools.newContext ? " new_context is an optional clean reset." : "";
121
121
  return `Pi rolls context over automatically, so the context window is not a deadline. Do not reduce scope, skip steps or verification, or write a final summary because rollover is near, and do not wait for the user to say "continue". Finish when the requested work and its verification are complete, or report a genuine blocker.
122
122
  ${line}Rollover keeps a recent-message tail without summarizing. One task-note reminder may arrive at the end of a working turn near the line: update the note only if it is stale, or write one if the task has none, then continue with the next step in the same run.${reset}`;
@@ -131,7 +131,7 @@ export function buildGuidance(
131
131
  const capacity =
132
132
  budget === undefined
133
133
  ? "Configured context capacity is unknown."
134
- : `Configured context capacity: ${budget.contextWindow.toLocaleString("en-US")} tokens (not remaining space).`;
134
+ : `Configured context capacity: ${formatCount(budget.contextWindow)} tokens (not remaining space).`;
135
135
  const checkRemaining = tools.getContextRemaining
136
136
  ? " Before reporting a remaining-token count or changing your work plan because of context limits, call get_context_remaining."
137
137
  : "";
@@ -3,13 +3,8 @@ import { Type } from "typebox";
3
3
  import { toolCards, type PosthorseDisplay } from "../ui.ts";
4
4
  import { budgetFor, freshPayloadChars, unsupportedMessage, type Budget } from "./budget.ts";
5
5
  import { activeGuidanceTools } from "./guidance.ts";
6
- import {
7
- EMPTY_HANDOFF,
8
- MAX_HANDOFF_CHARS,
9
- textResult,
10
- type PolicyContext,
11
- type TextResult,
12
- } from "./contracts.ts";
6
+ import { EMPTY_HANDOFF, MAX_HANDOFF_CHARS, formatCount, type PolicyContext } from "./contracts.ts";
7
+ import { textResult, type TextResult } from "./ui/display.ts";
13
8
 
14
9
  function rolloverStatus(budget: Budget | undefined): "disabled" | "enabled" | "unsupported" {
15
10
  return budget?.state ?? "disabled";
@@ -21,16 +16,15 @@ function contextReport(host: PolicyContext, newContextAvailable: boolean): TextR
21
16
  kind: "context",
22
17
  });
23
18
  }
24
- const n = (value: number) => value.toLocaleString("en-US");
25
19
  const budget = budgetFor(host, usage.contextWindow);
26
20
  const rollover = rolloverStatus(budget);
27
21
  const display: PosthorseDisplay = {
28
22
  kind: "context",
29
23
  usage,
30
24
  rollover,
31
- rolloverAt: budget?.rolloverAt,
25
+ ...(budget?.rolloverAt === undefined ? {} : { rolloverAt: budget.rolloverAt }),
32
26
  };
33
- const configured = `≈${n(Math.max(0, usage.contextWindow - usage.tokens))} tokens until the configured context limit (${n(usage.tokens)}/${n(usage.contextWindow)} used, ${Math.round(usage.percent ?? 0)}%). Best available native estimate.`;
27
+ const configured = `≈${formatCount(Math.max(0, usage.contextWindow - usage.tokens))} tokens until the configured context limit (${formatCount(usage.tokens)}/${formatCount(usage.contextWindow)} used, ${Math.round(usage.percent ?? 0)}%). Best available native estimate.`;
34
28
  if (budget === undefined || budget.state === "disabled") {
35
29
  return textResult(
36
30
  `Automatic rollover is disabled in the available settings (Pi compaction.enabled=false). ${configured}`,
@@ -46,7 +40,7 @@ function contextReport(host: PolicyContext, newContextAvailable: boolean): TextR
46
40
  );
47
41
  }
48
42
  return textResult(
49
- `≈${n(Math.max(0, budget.rolloverAt - usage.tokens))} tokens until automatic rollover (line at ${n(budget.rolloverAt)}); ${configured}`,
43
+ `≈${formatCount(Math.max(0, budget.rolloverAt - usage.tokens))} tokens until automatic rollover (line at ${formatCount(budget.rolloverAt)}); ${configured}`,
50
44
  [],
51
45
  display,
52
46
  );
@@ -77,7 +71,7 @@ export function registerContextTools(
77
71
  const limit = freshPayloadChars(policy(ctx), activeToolTokens());
78
72
  if (trimmed !== undefined && trimmed !== "" && trimmed.length > limit) {
79
73
  throw new Error(
80
- `Handoff is too large for the active model (${trimmed.length.toLocaleString("en-US")} characters; limit ${limit.toLocaleString("en-US")}). Save fuller state in notes, then retry with a shorter handoff or no handoff.`,
74
+ `Handoff is too large for the active model (${formatCount(trimmed.length)} characters; limit ${formatCount(limit)}). Save fuller state in notes, then retry with a shorter handoff or no handoff.`,
81
75
  );
82
76
  }
83
77
  const result = textResult(
package/src/contracts.ts CHANGED
@@ -1,7 +1,24 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { PosthorseDisplay } from "./ui/display.ts";
3
2
 
4
- export { isRecord } from "./records.ts";
3
+ export function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+
7
+ export type Immutable<T> = T extends
8
+ | string
9
+ | number
10
+ | boolean
11
+ | bigint
12
+ | symbol
13
+ | null
14
+ | undefined
15
+ | ((...args: never[]) => unknown)
16
+ ? T
17
+ : T extends readonly (infer Item)[]
18
+ ? readonly Immutable<Item>[]
19
+ : T extends object
20
+ ? { readonly [Key in keyof T]: Immutable<T[Key]> }
21
+ : T;
5
22
 
6
23
  export type CompactionPolicy = {
7
24
  readonly enabled: boolean;
@@ -98,12 +115,6 @@ export type ReminderFingerprint = {
98
115
  readonly contextWindow?: number | undefined;
99
116
  readonly reserveTokens?: number | undefined;
100
117
  };
101
- export type TextResult = {
102
- content: Array<
103
- { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }
104
- >;
105
- details: PosthorseDisplay | undefined;
106
- };
107
118
 
108
119
  export const MAX_HANDOFF_CHARS = 20_000;
109
120
  export const MAX_PAGE_CHARS = 40_000;
@@ -111,6 +122,8 @@ export const MIN_PAGE_CHARS = 1_000;
111
122
  export const PAGE_MARGIN_TOKENS = 1_000;
112
123
  export const ESTIMATED_IMAGE_CHARS = 4_800;
113
124
  export const REMINDER_TYPE = "posthorse-reminder";
125
+ /** The session's model may answer an owner question; only the plain tool registration is owner provenance. */
126
+ export const OWNER_QUESTION_TOOL = "ask_question";
114
127
  export const AUTO_HANDOFF_PREFIX = "Automatic context rollover recovery record.";
115
128
  export const EMPTY_HANDOFF = "Fresh context. Restore relevant notes and history before continuing.";
116
129
 
@@ -162,6 +175,12 @@ export function unknownArray(value: unknown): readonly unknown[] | undefined {
162
175
  export function optionalString(value: unknown): string | undefined {
163
176
  return typeof value === "string" ? value : undefined;
164
177
  }
178
+ export function errorCode(error: unknown): string | undefined {
179
+ return isRecord(error) ? optionalString(error.code) : undefined;
180
+ }
181
+ export function formatCount(value: number): string {
182
+ return value.toLocaleString("en-US");
183
+ }
165
184
  /** Some models send every optional argument; an empty string means the argument was omitted. */
166
185
  export function presentText(value: unknown): string | undefined {
167
186
  return typeof value === "string" && value !== "" ? value : undefined;
@@ -175,10 +194,3 @@ export function requireValue(value: string | undefined, name: string, op: string
175
194
  export function isReminderType(customType: unknown): boolean {
176
195
  return customType === REMINDER_TYPE;
177
196
  }
178
- export function textResult(
179
- text: string,
180
- images: readonly ImageLike[] = [],
181
- display?: PosthorseDisplay,
182
- ): TextResult {
183
- return { content: [{ type: "text", text }, ...images], details: display };
184
- }
package/src/files.ts CHANGED
@@ -25,20 +25,20 @@ import {
25
25
  } from "node:fs/promises";
26
26
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
27
27
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
28
- import { isRecord } from "./contracts.ts";
28
+ import { errorCode } from "./contracts.ts";
29
29
 
30
30
  async function lstatOrMissing(path: string) {
31
31
  try {
32
32
  return await lstat(path);
33
33
  } catch (error) {
34
- if (isRecord(error) && error.code === "ENOENT") {
34
+ if (errorCode(error) === "ENOENT") {
35
35
  return;
36
36
  }
37
37
  throw error;
38
38
  }
39
39
  }
40
40
  /** Resolve every link before normalization, preserving path traversal constraints. */
41
- export async function resolveFileTarget(absolutePath: string): Promise<string> {
41
+ async function resolveFileTarget(absolutePath: string): Promise<string> {
42
42
  let target = absolutePath;
43
43
  const links = new Set<string>();
44
44
  for (;;) {
@@ -53,10 +53,8 @@ export async function resolveFileTarget(absolutePath: string): Promise<string> {
53
53
  if (!(await stat(parentInput)).isDirectory()) {
54
54
  throw Object.assign(new Error(`Not a directory: ${parentInput}`), { code: "ENOTDIR" });
55
55
  }
56
- // Each parent must resolve before its child link can be examined.
57
56
  const parent = await realpath(parentInput);
58
57
  target = join(parent, basename(target));
59
- // Link targets cannot be known before examining the current link.
60
58
  const info = await lstatOrMissing(target);
61
59
  if (info === undefined) {
62
60
  return target;
@@ -300,7 +298,7 @@ export function notesDir(cwd: string): string {
300
298
  }
301
299
  try {
302
300
  // Sessions still running an older Posthorse keep reaching the notes until they reload.
303
- symlinkSync(moved, local, "junction");
301
+ symlinkSync(moved, local);
304
302
  } catch (error) {
305
303
  if (lstatSync(local, { throwIfNoEntry: false })?.isDirectory() === true) {
306
304
  throw error;
@@ -3,7 +3,7 @@ import { presentText, unknownArray } from "./contracts.ts";
3
3
  /** Where a search page stopped: the anchor entry, its rank, its offset, and the search it belongs to. */
4
4
  export type HistoryCursor = readonly [id: string, priority: 0 | 1, offset: number, key: string];
5
5
 
6
- export function encodeCursor(cursor: HistoryCursor): string {
6
+ function encodeCursor(cursor: HistoryCursor): string {
7
7
  return Buffer.from(JSON.stringify(cursor)).toString("base64url");
8
8
  }
9
9
  export function cursorFor(
@@ -9,6 +9,7 @@ import {
9
9
  import { isWindow } from "./boundary.ts";
10
10
  import {
11
11
  assistantFailure,
12
+ contentText,
12
13
  excerptAround,
13
14
  imageSummary,
14
15
  imagesOf,
@@ -59,19 +60,19 @@ export function flattenEntry(entry: EntryLike): string | undefined {
59
60
  case "context_window":
60
61
  return `[context_window] ${entry.handoff === undefined || entry.handoff === "" ? "No handoff" : `Handoff: ${entry.handoff}`}`;
61
62
  case "custom_message":
62
- return `[custom:${entry.customType ?? "unknown"}] ${contentText(entry.content)}`;
63
+ return `[custom:${entry.customType ?? "unknown"}] ${entryBodyText(entry.content)}`;
63
64
  case "context_edit":
64
65
  return entry.replacement === undefined || entry.replacement === null
65
66
  ? undefined
66
- : `[context_edit] ${contentText(entry.replacement.content)}`;
67
+ : `[context_edit] ${entryBodyText(entry.replacement.content)}`;
67
68
  case undefined:
68
69
  return undefined;
69
70
  default:
70
71
  return undefined;
71
72
  }
72
73
  }
73
- function contentText(content: unknown): string {
74
- return [textOf({ content }), imageSummary(imagesOf(content))]
74
+ function entryBodyText(content: unknown): string {
75
+ return [contentText(content), imageSummary(imagesOf(content))]
75
76
  .filter((part) => part !== "")
76
77
  .join("\n");
77
78
  }
@@ -83,7 +84,7 @@ function ownAssistantText(message: MessageLike, images: WindowedEntry["images"])
83
84
  originals.push(current);
84
85
  current = "";
85
86
  } else {
86
- const partText = textOf({ content: [part] });
87
+ const partText = contentText([part]);
87
88
  if (partText !== "") {
88
89
  current = current === "" ? partText : `${current}\n${partText}`;
89
90
  }
@@ -159,7 +160,7 @@ export function historyHit(
159
160
  headerLength: header.length,
160
161
  };
161
162
  }
162
- export function entryContent(entry: EntryLike): unknown {
163
+ function entryContent(entry: EntryLike): unknown {
163
164
  switch (entry.type) {
164
165
  case "context_edit":
165
166
  return entry.replacement?.content;
@@ -1,12 +1,11 @@
1
1
  import {
2
2
  MIN_PAGE_CHARS,
3
3
  ESTIMATED_IMAGE_CHARS,
4
- textResult,
5
4
  type HistoryHit,
6
5
  type PolicyContext,
7
- type TextResult,
8
6
  type WindowedEntry,
9
7
  } from "./contracts.ts";
8
+ import { textResult, type TextResult } from "./ui/display.ts";
10
9
  import { excerpt, shortKey, sourceTag } from "./message-text.ts";
11
10
  import { cursorFor as cursorAt } from "./history-cursor.ts";
12
11
  import type { HistoryMatches, HistoryParams } from "./history-search.ts";
@@ -1,10 +1,12 @@
1
1
  import { relative, resolve } from "node:path";
2
+ import { Type, type Static } from "typebox";
2
3
  import type { LineMatcher } from "./session-lines.ts";
3
4
  import {
4
5
  isReminderType,
5
6
  requireValue,
6
7
  type EntryLike,
7
8
  type HistoryHit,
9
+ type Immutable,
8
10
  type ProjectedEntry,
9
11
  } from "./contracts.ts";
10
12
  import { decodeCursor, type HistoryCursor } from "./history-cursor.ts";
@@ -17,16 +19,41 @@ import {
17
19
  sessionWindowEntries,
18
20
  } from "./session-files.ts";
19
21
 
20
- export type HistoryParams = {
21
- readonly op: "search" | "read";
22
- readonly query?: string;
23
- readonly id?: string;
24
- readonly all?: boolean;
25
- readonly limit?: number;
26
- readonly cursor?: string;
27
- readonly offset?: number;
28
- readonly imageOffset?: number;
29
- };
22
+ export const historyParameters = Type.Object({
23
+ op: Type.Union([Type.Literal("search"), Type.Literal("read")], {
24
+ description: "Operation to perform",
25
+ }),
26
+ query: Type.Optional(Type.String({ description: "Case-insensitive text to find (search)" })),
27
+ id: Type.Optional(Type.String({ description: "Entry id exactly as search printed it (read)" })),
28
+ all: Type.Optional(
29
+ Type.Boolean({
30
+ description: "Also search this project's other sessions and subagent runs",
31
+ }),
32
+ ),
33
+ limit: Type.Optional(
34
+ Type.Integer({
35
+ description: "Maximum search results per page (default 10, max 50)",
36
+ minimum: 1,
37
+ maximum: 50,
38
+ }),
39
+ ),
40
+ cursor: Type.Optional(
41
+ Type.String({
42
+ description: "Continuation from the previous search page; keep query and all unchanged",
43
+ maxLength: 512,
44
+ }),
45
+ ),
46
+ offset: Type.Optional(
47
+ Type.Integer({ description: "Character offset for read (default 0)", minimum: 0 }),
48
+ ),
49
+ imageOffset: Type.Optional(
50
+ Type.Integer({
51
+ description: "First image to return (read); use the value from the continuation",
52
+ minimum: 0,
53
+ }),
54
+ ),
55
+ });
56
+ export type HistoryParams = Immutable<Static<typeof historyParameters>>;
30
57
  export type HistorySource = {
31
58
  readonly dir: string;
32
59
  readonly cwd: string;
package/src/history.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import { relative, resolve } from "node:path";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { Type } from "typebox";
4
3
  import { toolCards } from "../ui.ts";
5
4
  import { requireValue, type PolicyContext, type WindowedEntry } from "./contracts.ts";
6
5
  import { toWindowedEntry, windowProjection } from "./history-entries.ts";
7
6
  import { historyReadPage, searchPage } from "./history-pages.ts";
8
- import { historyMatches, type HistorySource } from "./history-search.ts";
7
+ import { historyMatches, historyParameters, type HistorySource } from "./history-search.ts";
9
8
  import type { PageAccess } from "./paging.ts";
10
9
  import { scopedSessionFiles, sessionWindowEntries } from "./session-files.ts";
11
10
 
@@ -87,46 +86,7 @@ export function registerHistory(
87
86
  promptGuidelines: [
88
87
  "Use history search first, then history read with the entry id exactly as printed",
89
88
  ],
90
- parameters: Type.Object({
91
- op: Type.Union([Type.Literal("search"), Type.Literal("read")], {
92
- description: "Operation to perform",
93
- }),
94
- query: Type.Optional(
95
- Type.String({ description: "Case-insensitive text to find (search)" }),
96
- ),
97
- id: Type.Optional(
98
- Type.String({ description: "Entry id exactly as search printed it (read)" }),
99
- ),
100
- all: Type.Optional(
101
- Type.Boolean({
102
- description: "Also search this project's other sessions and subagent runs",
103
- }),
104
- ),
105
- limit: Type.Optional(
106
- Type.Integer({
107
- description: "Maximum search results per page (default 10, max 50)",
108
- minimum: 1,
109
- maximum: 50,
110
- }),
111
- ),
112
- cursor: Type.Optional(
113
- Type.String({
114
- description:
115
- "Continuation from the previous search page; keep query and all unchanged",
116
- maxLength: 512,
117
- }),
118
- ),
119
- offset: Type.Optional(
120
- Type.Integer({ description: "Character offset for read (default 0)", minimum: 0 }),
121
- ),
122
- imageOffset: Type.Optional(
123
- Type.Integer({
124
- description:
125
- "First image to return (read); use the value from the continuation",
126
- minimum: 0,
127
- }),
128
- ),
129
- }),
89
+ parameters: historyParameters,
130
90
  async execute(...[, params, signal, , ctx]) {
131
91
  const source = historySource(ctx);
132
92
  if (params.op === "search") {
package/src/host.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { EntryLike, ProjectedEntry } from "./contracts.ts";
1
+ import { OWNER_QUESTION_TOOL, type EntryLike, type ProjectedEntry } from "./contracts.ts";
2
2
 
3
3
  /** Only the session-manager members Posthorse reads; a host may omit any of them. */
4
4
  export type SessionHost = {
@@ -20,8 +20,6 @@ export type ToolRegistry = {
20
20
  readonly getActiveTools: () => readonly string[];
21
21
  readonly getAllTools: () => readonly ToolInfo[];
22
22
  };
23
- /** The session's model may answer an owner question; only the plain tool registration is owner provenance. */
24
- export const OWNER_QUESTION_TOOL = "ask_question";
25
23
  export type SessionIdentity = {
26
24
  readonly sessionId: string;
27
25
  readonly file: string | undefined;
@@ -9,7 +9,7 @@ import {
9
9
  type ToolCallLike,
10
10
  } from "./contracts.ts";
11
11
 
12
- export function isImage(part: unknown): part is ImageLike {
12
+ function isImage(part: unknown): part is ImageLike {
13
13
  return (
14
14
  isRecord(part) &&
15
15
  part.type === "image" &&
@@ -47,7 +47,7 @@ export function executionArgumentsText(call: ToolCallLike): string {
47
47
  ? ""
48
48
  : `\nExecution arguments: ${safeJsonStringify(call.executionArguments)}`;
49
49
  }
50
- export function toolCallOf(part: unknown): ToolCallLike | undefined {
50
+ function toolCallOf(part: unknown): ToolCallLike | undefined {
51
51
  if (!isRecord(part) || part.type !== "toolCall") {
52
52
  return undefined;
53
53
  }
@@ -83,15 +83,18 @@ function blockText(part: unknown): string {
83
83
  }
84
84
  return `${toolIdentity(call.name, call.namespace)} ${safeJsonStringify(call.arguments ?? {})}${call.id === undefined ? "" : `\nCall ID: ${call.id}`}${executionArgumentsText(call)}`;
85
85
  }
86
- export function textOf(message: MessageLike): string {
87
- if (typeof message.content === "string") {
88
- return message.content;
86
+ export function contentText(content: unknown): string {
87
+ if (typeof content === "string") {
88
+ return content;
89
89
  }
90
- return (unknownArray(message.content) ?? [])
90
+ return (unknownArray(content) ?? [])
91
91
  .map(blockText)
92
92
  .filter((text) => text !== "")
93
93
  .join("\n");
94
94
  }
95
+ export function textOf(message: MessageLike): string {
96
+ return contentText(message.content);
97
+ }
95
98
  export function assistantFailure(message: MessageLike): string {
96
99
  if (message.role !== "assistant") {
97
100
  return "";
@@ -1,6 +1,6 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
2
  import { basename, join, relative } from "node:path";
3
- import { isRecord } from "./contracts.ts";
3
+ import { errorCode, type EntryLike } from "./contracts.ts";
4
4
  import { isPublicationTemporaryName } from "./files.ts";
5
5
  import { sessionNoteTouches } from "./note-evidence.ts";
6
6
  import { notesUnder, type NoteFile } from "./note-inventory.ts";
@@ -49,7 +49,7 @@ async function projectScopes(
49
49
  ];
50
50
  const directory = join(session.binding.root, ".forks");
51
51
  const entries = await readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
52
- if (isRecord(error) && error.code === "ENOENT") {
52
+ if (errorCode(error) === "ENOENT") {
53
53
  return [];
54
54
  }
55
55
  throw error;
@@ -102,7 +102,7 @@ async function scopedFiles(
102
102
  function noteKey(address: NoteAddress): string {
103
103
  return JSON.stringify([address.root, address.scope, address.path]);
104
104
  }
105
- export function noteReadTarget(note: DiscoveredNote): string {
105
+ function noteReadTarget(note: DiscoveredNote): string {
106
106
  return JSON.stringify({ scope: scopeDirectory(note.address), path: note.address.path });
107
107
  }
108
108
  export function noteLabel(note: DiscoveredNote, session: SessionNotes, labeled: boolean): string {
@@ -120,16 +120,17 @@ async function readReference(
120
120
  session: SessionNotes,
121
121
  path: string,
122
122
  signal: AbortSignal | undefined,
123
+ sourceEntries: readonly EntryLike[],
123
124
  ): Promise<DiscoveredNote | undefined> {
124
125
  if (isPublicationTemporaryName(basename(path))) {
125
126
  return;
126
127
  }
127
- const target = await session.access(path, { signal });
128
+ const target = await session.access(path, { signal, sourceEntries });
128
129
  if (target.kind === "own") {
129
130
  return;
130
131
  }
131
132
  const info = await stat(target.path).catch((error: unknown) => {
132
- if (isRecord(error) && error.code === "ENOENT") {
133
+ if (errorCode(error) === "ENOENT") {
133
134
  return;
134
135
  }
135
136
  throw error;
@@ -258,8 +259,12 @@ export class NoteDiscovery {
258
259
  path === options.path ||
259
260
  path.startsWith(`${options.path}/`),
260
261
  );
262
+ if (candidates.length === 0) {
263
+ return [];
264
+ }
265
+ const sourceEntries = await session.ancestorEntries(options.signal);
261
266
  const resolved = await mapBatch(candidates, (path) =>
262
- readReference(session, path, options.signal),
267
+ readReference(session, path, options.signal, sourceEntries),
263
268
  );
264
269
  return resolved.filter((file): file is DiscoveredNote => file !== undefined);
265
270
  }
@@ -16,9 +16,6 @@ import type { NoteCall, NotesStore, SessionNotes } from "./note-store.ts";
16
16
  /** Native core tools expand @/~ paths; pi-apply-edits deliberately treats them literally. */
17
17
  function toolPath(tool: string, path: string, cwd: string): string {
18
18
  if (tool !== "read" && tool !== "write" && tool !== "edit") {
19
- if (process.platform === "win32") {
20
- return resolve(cwd, path);
21
- }
22
19
  return isAbsolute(path) ? path : `${cwd}/${path}`;
23
20
  }
24
21
  let normalized = path
@@ -1,6 +1,6 @@
1
1
  import { readdir, realpath, stat } from "node:fs/promises";
2
2
  import { basename, join } from "node:path";
3
- import { isRecord, presentText } from "./contracts.ts";
3
+ import { errorCode, presentText } from "./contracts.ts";
4
4
  import { isPublicationTemporaryName } from "./files.ts";
5
5
  import {
6
6
  canonicalPath,
@@ -19,7 +19,8 @@ async function statIfPresent(path: string) {
19
19
  try {
20
20
  return await stat(path);
21
21
  } catch (error) {
22
- if (isRecord(error) && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
22
+ const code = errorCode(error);
23
+ if (code === "ENOENT" || code === "ENOTDIR") {
23
24
  return;
24
25
  }
25
26
  throw error;
@@ -1,7 +1,7 @@
1
1
  import { statSync } from "node:fs";
2
2
  import { isAbsolute, join } from "node:path";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
- import { isRecord, type EntryLike } from "./contracts.ts";
4
+ import { errorCode, type EntryLike } from "./contracts.ts";
5
5
  import { sessionLines } from "./session-lines.ts";
6
6
  import { parseSessionLine } from "./session-files.ts";
7
7
  import { sessionNoteTouches } from "./note-evidence.ts";
@@ -51,7 +51,7 @@ async function journalMetadata(
51
51
  }
52
52
  }
53
53
  } catch (error) {
54
- if (!isRecord(error) || error.code !== "ENOENT") {
54
+ if (errorCode(error) !== "ENOENT") {
55
55
  throw error;
56
56
  }
57
57
  }
@@ -2,7 +2,7 @@ import { realpathSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { Type, type Static } from "typebox";
4
4
  import { Check } from "typebox/value";
5
- import { isRecord, type EntryLike } from "./contracts.ts";
5
+ import { errorCode, type EntryLike, type Immutable } from "./contracts.ts";
6
6
 
7
7
  export const NOTES_BINDING = "posthorse-notes-scope";
8
8
  export const NOTES_TOUCH = "posthorse-note-touch";
@@ -60,11 +60,6 @@ const touchSchema = Type.Object({
60
60
  }),
61
61
  ),
62
62
  });
63
- type Immutable<T> = T extends readonly (infer Item)[]
64
- ? readonly Immutable<Item>[]
65
- : T extends object
66
- ? { readonly [Key in keyof T]: Immutable<T[Key]> }
67
- : T;
68
63
  export type NoteOwner = Immutable<Static<typeof ownerSchema>>;
69
64
  export type NoteScope = Immutable<Static<typeof scopeSchema>>;
70
65
  export type NoteAddress = Immutable<Static<typeof addressSchema>>;
@@ -149,7 +144,8 @@ export function canonicalPath(path: string): string {
149
144
  try {
150
145
  return realpathSync(absolute);
151
146
  } catch (error) {
152
- if (!isRecord(error) || (error.code !== "ENOENT" && error.code !== "ENOTDIR")) {
147
+ const code = errorCode(error);
148
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
153
149
  throw error;
154
150
  }
155
151
  const parent = dirname(absolute);
@@ -15,7 +15,7 @@ import {
15
15
  } from "node:fs/promises";
16
16
  import { dirname, join } from "node:path";
17
17
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
18
- import { isRecord } from "./contracts.ts";
18
+ import { errorCode } from "./contracts.ts";
19
19
  import { publishFile } from "./files.ts";
20
20
  import {
21
21
  addressIn,
@@ -75,10 +75,8 @@ export async function readManifest(directory: string): Promise<ForkBinding | und
75
75
  ? binding
76
76
  : undefined;
77
77
  } catch (error) {
78
- if (
79
- error instanceof SyntaxError ||
80
- (isRecord(error) && (error.code === "ENOENT" || error.code === "ENOTDIR"))
81
- ) {
78
+ const code = errorCode(error);
79
+ if (error instanceof SyntaxError || code === "ENOENT" || code === "ENOTDIR") {
82
80
  return;
83
81
  }
84
82
  throw error;
@@ -165,7 +163,7 @@ async function prepareSnapshot(
165
163
  const container = dirname(directory);
166
164
  if (
167
165
  await lstat(container).catch((error: unknown) => {
168
- if (isRecord(error) && error.code === "ENOENT") {
166
+ if (errorCode(error) === "ENOENT") {
169
167
  return;
170
168
  }
171
169
  throw error;
@@ -229,7 +227,7 @@ export async function ensureManifest(binding: NoteBinding): Promise<void> {
229
227
  try {
230
228
  await writeFile(path, JSON.stringify(binding), { flag: "wx" });
231
229
  } catch (error) {
232
- if (!isRecord(error) || error.code !== "EEXIST") {
230
+ if (errorCode(error) !== "EEXIST") {
233
231
  throw error;
234
232
  }
235
233
  const existing = await readManifest(scopeDirectory(binding));