notesoup 0.43.0 → 0.45.0

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 (76) hide show
  1. package/README.md +1 -0
  2. package/cordis.patch.yml +14 -0
  3. package/dist/src/boot/snapshot.d.ts +2 -0
  4. package/dist/src/boot/snapshot.js +4 -0
  5. package/dist/src/boot/text.js +3 -1
  6. package/dist/src/claude/helper.js +2 -2
  7. package/dist/src/dsh/budget.d.ts +20 -0
  8. package/dist/src/dsh/budget.js +34 -0
  9. package/dist/src/dsh/engine.d.ts +22 -0
  10. package/dist/src/dsh/engine.js +193 -0
  11. package/dist/src/dsh/history.d.ts +6 -0
  12. package/dist/src/dsh/history.js +73 -0
  13. package/dist/src/dsh/index.d.ts +22 -0
  14. package/dist/src/dsh/index.js +63 -0
  15. package/dist/src/dsh/preflight.d.ts +8 -0
  16. package/dist/src/dsh/preflight.js +35 -0
  17. package/dist/src/dsh/tools.d.ts +3 -0
  18. package/dist/src/dsh/tools.js +111 -0
  19. package/dist/src/dsh/window.d.ts +46 -0
  20. package/dist/src/dsh/window.js +124 -0
  21. package/dist/src/notes/address.d.ts +2 -2
  22. package/dist/src/notes/address.js +5 -5
  23. package/dist/src/notes/identity.js +2 -1
  24. package/dist/src/notes/paths.d.ts +1 -6
  25. package/dist/src/notes/paths.js +5 -68
  26. package/dist/src/notes/project-home.d.ts +25 -0
  27. package/dist/src/notes/project-home.js +231 -0
  28. package/dist/src/notes/store.d.ts +3 -2
  29. package/dist/src/notes/store.js +14 -8
  30. package/dist/src/pi/boot.js +17 -5
  31. package/dist/src/pi/notes/adapter.js +1 -1
  32. package/dist/src/tools/notes.d.ts +47 -17
  33. package/dist/src/tools/notes.js +15 -4
  34. package/dist/test/claude-mod.test.js +32 -1
  35. package/dist/test/dependencies.test.js +27 -1
  36. package/dist/test/dsh-cli.test.d.ts +1 -0
  37. package/dist/test/dsh-cli.test.js +44 -0
  38. package/dist/test/dsh-compaction-parity.test.d.ts +1 -0
  39. package/dist/test/dsh-compaction-parity.test.js +143 -0
  40. package/dist/test/dsh.test.d.ts +1 -0
  41. package/dist/test/dsh.test.js +323 -0
  42. package/dist/test/helpers/dependency-graph.js +3 -3
  43. package/dist/test/helpers/dsh-messages.d.ts +29 -0
  44. package/dist/test/helpers/dsh-messages.js +33 -0
  45. package/dist/test/helpers/dsh.d.ts +17 -0
  46. package/dist/test/helpers/dsh.js +50 -0
  47. package/dist/test/notes.test.js +22 -19
  48. package/dist/test/project-home.test.d.ts +1 -0
  49. package/dist/test/project-home.test.js +134 -0
  50. package/docs/architecture.md +4 -1
  51. package/docs/dsh.md +61 -0
  52. package/docs/dsh.profile.patch.yml +34 -0
  53. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  54. package/mods/notesoup/dist/claude/helper.js +223 -56
  55. package/mods/notesoup/skills/memory/SKILL.md +1 -0
  56. package/package.json +63 -4
  57. package/skills/memory/SKILL.md +1 -0
  58. package/src/boot/snapshot.ts +5 -0
  59. package/src/boot/text.ts +3 -1
  60. package/src/claude/helper.ts +2 -2
  61. package/src/dsh/budget.ts +35 -0
  62. package/src/dsh/engine.ts +160 -0
  63. package/src/dsh/history.ts +57 -0
  64. package/src/dsh/index.ts +69 -0
  65. package/src/dsh/preflight.ts +29 -0
  66. package/src/dsh/tools.ts +107 -0
  67. package/src/dsh/window.ts +126 -0
  68. package/src/notes/address.ts +5 -5
  69. package/src/notes/identity.ts +1 -1
  70. package/src/notes/paths.ts +4 -60
  71. package/src/notes/project-home.ts +197 -0
  72. package/src/notes/store.ts +13 -9
  73. package/src/pi/boot.ts +15 -5
  74. package/src/pi/notes/adapter.ts +1 -1
  75. package/src/tools/notes.ts +16 -6
  76. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -0,0 +1,111 @@
1
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { Check, Errors } from "typebox/value";
4
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
5
+ import { historyList, historyRead, historyWindows } from "../tools/history.js";
6
+ import { success } from "../tools/result.js";
7
+ import { historyProjection } from "./history.js";
8
+ import { notesIdentity } from "./window.js";
9
+ import { measureBudget } from "./budget.js";
10
+ import { preflight } from "./preflight.js";
11
+ /** dsh enforces a small schema subset; TypeBox remains the full validator at execution. */
12
+ function hostSchema(schema) {
13
+ const value = JSON.parse(JSON.stringify(schema));
14
+ const result = {};
15
+ for (const key of ["type", "required", "additionalProperties", "enum", "const", "description", "title", "default", "examples"])
16
+ if (value[key] !== undefined)
17
+ result[key] = value[key];
18
+ const bounds = ["minimum", "maximum", "minLength", "maxLength", "minItems", "maxItems"].filter((key) => value[key] !== undefined).map((key) => `${key}=${value[key]}`);
19
+ if (bounds.length)
20
+ result.description = [value.description, bounds.join(", ")].filter(Boolean).join("; ");
21
+ if (Array.isArray(value.anyOf))
22
+ result.oneOf = value.anyOf.map((branch) => hostSchema(branch));
23
+ if (value.properties)
24
+ result.properties = Object.fromEntries(Object.entries(value.properties).map(([key, child]) => [key, hostSchema(child)]));
25
+ if (value.items)
26
+ result.items = hostSchema(value.items);
27
+ return result;
28
+ }
29
+ function requireAgent(exec) {
30
+ if (!exec.agent)
31
+ throw new HarnessError("notesoup: this tool needs an agent session; call it from a dsh agent.", "AGENT_REQUIRED");
32
+ exec.signal.throwIfAborted();
33
+ return exec.agent;
34
+ }
35
+ function register(ctx, operation, inputs) {
36
+ ctx.tools.register({
37
+ name: operation.name,
38
+ description: operation.description,
39
+ parameters: hostSchema(operation.parameters),
40
+ output: {
41
+ schema: hostSchema(operation.outputSchema),
42
+ render: (_args, value) => [{ type: "text", text: operation.render(success(value)) }],
43
+ },
44
+ async execute(args, exec) {
45
+ const agent = requireAgent(exec);
46
+ preflight(ctx);
47
+ if (!Check(operation.parameters, args)) {
48
+ const error = Errors(operation.parameters, args).find((problem) => problem.keyword !== "boolean");
49
+ throw new HarnessError(`notesoup: invalid ${operation.name} parameter ${error?.instancePath || "/"}: ${error?.message ?? "invalid value"}; use the tool schema's bounds.`, "INVALID_PARAMS");
50
+ }
51
+ const rest = await inputs(agent);
52
+ exec.signal.throwIfAborted();
53
+ const result = await operation.execute(args, ...rest);
54
+ if (!result.ok)
55
+ throw new HarnessError(operation.render(result), result.error.code);
56
+ return result.data;
57
+ },
58
+ });
59
+ }
60
+ export function registerTools(ctx, engine) {
61
+ const nestedResets = new WeakMap();
62
+ ctx.on("tools/result", (exec, result) => {
63
+ if (!exec.agent)
64
+ return;
65
+ const state = engine.windows.get(exec.agent.session);
66
+ if (exec.name === "clear_memory" && !result.isError && result.value.window_id === state.snapshot.windowId) {
67
+ if (!exec.parent)
68
+ state.pendingReset = true;
69
+ else {
70
+ const roots = nestedResets.get(exec.agent) ?? new Set();
71
+ roots.add(exec.rootCallId);
72
+ nestedResets.set(exec.agent, roots);
73
+ }
74
+ }
75
+ if (!exec.parent && nestedResets.get(exec.agent)?.delete(exec.rootCallId) && !result.isError)
76
+ state.pendingReset = true;
77
+ });
78
+ const identity = (agent) => notesIdentity(agent, engine.config);
79
+ register(ctx, notesWrite, (agent) => [identity(agent)]);
80
+ register(ctx, notesUpdate, (agent) => [identity(agent), (change) => change.kind === "none" ? "" : `note ${change.kind}`]);
81
+ register(ctx, notesRead, (agent) => [identity(agent)]);
82
+ register(ctx, notesList, (agent) => [identity(agent)]);
83
+ register(ctx, notesSearch, (agent) => [identity(agent)]);
84
+ register(ctx, historyList, async (agent) => [await historyProjection(ctx, agent.session.id)]);
85
+ register(ctx, historyRead, async (agent) => [await historyProjection(ctx, agent.session.id)]);
86
+ register(ctx, historyWindows, async (agent) => [await historyProjection(ctx, agent.session.id), agent.session.id]);
87
+ ctx.tools.register(defineTool({
88
+ name: "clear_memory",
89
+ description: "Open a fresh context window after this tool batch. Write recovery notes first; notes and raw history stay on disk.",
90
+ parameters: {},
91
+ output: { schema: { type: "object", properties: { window_id: { type: "string", required: true }, reset_requested: { type: "boolean", required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: `notesoup: reset requested for ${value.window_id}; finish this tool batch, then recover from your notes.` }] },
92
+ async execute(_args, exec) {
93
+ const agent = requireAgent(exec);
94
+ preflight(ctx);
95
+ const state = engine.windows.get(agent.session);
96
+ return { window_id: state.snapshot.windowId, reset_requested: true };
97
+ },
98
+ }));
99
+ ctx.tools.register(defineTool({
100
+ name: "get_context_remaining",
101
+ description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
102
+ parameters: {},
103
+ output: { schema: { type: "object", properties: { remaining_tokens: { oneOf: [{ type: "integer" }, { type: "null" }], required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
104
+ async execute(_args, exec) {
105
+ const agent = requireAgent(exec);
106
+ preflight(ctx);
107
+ const budget = await measureBudget(ctx, agent, engine.config, exec.signal);
108
+ return { remaining_tokens: budget?.countdown ?? null };
109
+ },
110
+ }));
111
+ }
@@ -0,0 +1,46 @@
1
+ import type { Agent } from "@deepseek-ai/dsh-agent";
2
+ import { type Session, type SessionEvent } from "@deepseek-ai/dsh-session";
3
+ import { type NotesIdentity } from "../notes/identity.js";
4
+ export declare const WINDOW_RECORD = "plugin:notesoup/window";
5
+ export declare const BOOT_SECTION = "notesoup:boot";
6
+ export type WindowSnapshot = Readonly<{
7
+ version: 1;
8
+ window: number;
9
+ windowId: string;
10
+ openedAt: number;
11
+ boot: string;
12
+ notesDigest: string;
13
+ }>;
14
+ export type WindowState = {
15
+ snapshot: WindowSnapshot;
16
+ pendingReset: boolean;
17
+ warned: boolean;
18
+ reminded: boolean;
19
+ };
20
+ export type NotesConfig = {
21
+ notesHome?: string;
22
+ agentName?: string;
23
+ };
24
+ export declare function restoreWarnings(state: WindowState, events: readonly SessionEvent[]): void;
25
+ declare module "@deepseek-ai/dsh-session/types" {
26
+ interface PluginRecordMap {
27
+ "plugin:notesoup/window": WindowSnapshot;
28
+ }
29
+ }
30
+ export declare function windowId(sessionId: string, window: number): string;
31
+ export declare function checkpointText(snapshot: WindowSnapshot): string;
32
+ export declare function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined;
33
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
34
+ export declare function checkpointSnapshot(event: SessionEvent): WindowSnapshot | undefined;
35
+ export declare function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined;
36
+ /** Identity is extracted here, never in the filesystem domain. */
37
+ export declare function notesIdentity(agent: Pick<Agent, "session" | "options">, config: NotesConfig): NotesIdentity;
38
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
39
+ export declare class Windows {
40
+ readonly config: NotesConfig;
41
+ private states;
42
+ constructor(config: NotesConfig);
43
+ get(session: Session): WindowState;
44
+ adopt(agent: Agent, signal?: AbortSignal): Promise<WindowState>;
45
+ mint(agent: Pick<Agent, "session" | "options">, window: number, openedAt: number): Promise<WindowSnapshot>;
46
+ }
@@ -0,0 +1,124 @@
1
+ import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
2
+ import { isCompactCheckpointSource } from "@deepseek-ai/dsh-compaction";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { loadNotesSnapshot } from "../boot/snapshot.js";
7
+ import { renderBootBlock } from "../boot/render.js";
8
+ import { CONTINUATION } from "../budget/text.js";
9
+ import { contentText } from "../history/history.js";
10
+ import { slugify } from "../notes/paths.js";
11
+ import { resolveProjectHome } from "../notes/project-home.js";
12
+ import { snapshotNotesIdentity } from "../notes/identity.js";
13
+ export const WINDOW_RECORD = "plugin:notesoup/window";
14
+ export const BOOT_SECTION = "notesoup:boot";
15
+ const BOOT_OPEN = "<notesoup-boot>\n";
16
+ const BOOT_CLOSE = "\n</notesoup-boot>";
17
+ const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
18
+ const TOOLS = { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "clear_memory" };
19
+ export function restoreWarnings(state, events) {
20
+ state.warned = false;
21
+ state.reminded = false;
22
+ for (const event of events) {
23
+ if (event.type === "user/message" && event.data.source.kind === "notesoup-budget" && event.data.source.windowId === state.snapshot.windowId) {
24
+ if (event.data.source.phase === "warning")
25
+ state.warned = true;
26
+ else
27
+ state.reminded = true;
28
+ }
29
+ }
30
+ }
31
+ export function windowId(sessionId, window) { return `dsh:${sessionId}:${window}`; }
32
+ function digest(boot) { return createHash("sha256").update(boot).digest("hex"); }
33
+ export function checkpointText(snapshot) { return snapshot.boot + CHECKPOINT_END + CONTINUATION + "\n</notesoup-continuation>"; }
34
+ export function recordSnapshot(event) {
35
+ const record = pluginRecordOf(event);
36
+ if (record?.type !== WINDOW_RECORD || typeof record.data !== "object" || record.data === null)
37
+ return undefined;
38
+ const value = record.data;
39
+ if (value.version !== 1 || !Number.isSafeInteger(value.window) || value.window < 0 || typeof value.windowId !== "string" || typeof value.openedAt !== "number" || typeof value.boot !== "string" || value.notesDigest !== digest(value.boot))
40
+ return undefined;
41
+ return Object.freeze(value);
42
+ }
43
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
44
+ export function checkpointSnapshot(event) {
45
+ if (event.type !== "user/message" || !isCompactCheckpointSource(event.data.source))
46
+ return undefined;
47
+ const text = contentText(event.data.content);
48
+ const end = text.lastIndexOf(CHECKPOINT_END);
49
+ if (end < 0 || !text.startsWith(BOOT_OPEN))
50
+ return undefined;
51
+ return snapshotFromBoot(text.slice(0, end), event.time);
52
+ }
53
+ function systemSnapshot(event) {
54
+ if (event.type !== "system/message")
55
+ return undefined;
56
+ const text = contentText(event.data.message.content);
57
+ const start = text.indexOf(BOOT_OPEN);
58
+ const end = text.lastIndexOf(BOOT_CLOSE);
59
+ if (start < 0 || end < 0)
60
+ return undefined;
61
+ return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
62
+ }
63
+ function snapshotFromBoot(boot, openedAt) {
64
+ const id = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
65
+ if (!id || !Number.isSafeInteger(Number(id[2])))
66
+ return undefined;
67
+ return Object.freeze({ version: 1, window: Number(id[2]), windowId: id[1], openedAt, boot, notesDigest: digest(boot) });
68
+ }
69
+ export function recoverSnapshot(events) {
70
+ let latest;
71
+ for (const event of events) {
72
+ const candidate = checkpointSnapshot(event) ?? recordSnapshot(event) ?? systemSnapshot(event);
73
+ if (candidate && (!latest || candidate.window >= latest.window))
74
+ latest = candidate;
75
+ }
76
+ return latest;
77
+ }
78
+ /** Identity is extracted here, never in the filesystem domain. */
79
+ export function notesIdentity(agent, config) {
80
+ const home = config.notesHome ?? join(homedir(), ".agents", "notes");
81
+ return snapshotNotesIdentity({
82
+ home,
83
+ sessionId: agent.session.id,
84
+ projectKey: resolveProjectHome(agent.session.header.cwd ?? process.cwd(), home).name,
85
+ agent: slugify(config.agentName ?? "dsh"),
86
+ model: slugify(agent.session.requestHeader()?.config.model ?? agent.options.model ?? "unknown"),
87
+ });
88
+ }
89
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
90
+ export class Windows {
91
+ config;
92
+ states = new WeakMap();
93
+ constructor(config) {
94
+ this.config = config;
95
+ }
96
+ get(session) {
97
+ const state = this.states.get(session);
98
+ if (!state)
99
+ throw Object.assign(new Error("notesoup: window missing; initialize at agent/created before sending a request."), { code: "WINDOW_MISSING" });
100
+ return state;
101
+ }
102
+ async adopt(agent, signal) {
103
+ const existing = this.states.get(agent.session);
104
+ if (existing)
105
+ return existing;
106
+ const restored = recoverSnapshot(agent.session.snapshotEvents());
107
+ const snapshot = restored ?? await this.mint(agent, 0, agent.session.header.createdAt);
108
+ signal?.throwIfAborted();
109
+ if (!restored)
110
+ appendPluginRecord(agent.session, WINDOW_RECORD, snapshot);
111
+ const state = { snapshot, pendingReset: false, warned: false, reminded: false };
112
+ restoreWarnings(state, agent.session.snapshotEvents());
113
+ this.states.set(agent.session, state);
114
+ return state;
115
+ }
116
+ async mint(agent, window, openedAt) {
117
+ const identity = notesIdentity(agent, this.config);
118
+ const notes = await loadNotesSnapshot(identity, openedAt);
119
+ const previous = this.states.get(agent.session)?.snapshot;
120
+ const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
121
+ const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId, currentWindowId: windowId(agent.session.id, window), ...(window ? { previousWindowId: previous?.windowId ?? windowId(agent.session.id, window - 1) } : {}), notes, tools: TOOLS }) + BOOT_CLOSE;
122
+ return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
123
+ }
124
+ }
@@ -5,7 +5,7 @@ export type NoteAddress = {
5
5
  path: string;
6
6
  who?: string;
7
7
  };
8
- export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
8
+ export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
9
9
  /**
10
10
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
11
11
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -18,7 +18,7 @@ export declare function globToRegExp(pattern: string): RegExp;
18
18
  export declare function assertGlobPattern(value: unknown): string | undefined;
19
19
  /**
20
20
  * Decode one public note address into its physical home and virtual path. @self and @model
21
- * are relative; explicit agents/models addresses always name a canonical slug.
21
+ * are relative; explicit projects/agents/models addresses always name one canonical slug.
22
22
  */
23
23
  export declare function assertAddress(value: unknown): NoteAddress;
24
24
  /** Render a virtual path in its one unambiguous address form, used to match patterns. */
@@ -1,6 +1,6 @@
1
1
  import { NoteError, shown } from "./errors.js";
2
2
  import { assertVirtualPath, SLUG_PATTERN } from "./paths.js";
3
- export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
3
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
4
4
  /**
5
5
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
6
6
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -43,7 +43,7 @@ export function assertGlobPattern(value) {
43
43
  }
44
44
  /**
45
45
  * Decode one public note address into its physical home and virtual path. @self and @model
46
- * are relative; explicit agents/models addresses always name a canonical slug.
46
+ * are relative; explicit projects/agents/models addresses always name one canonical slug.
47
47
  */
48
48
  export function assertAddress(value) {
49
49
  if (typeof value !== "string")
@@ -65,12 +65,12 @@ export function assertAddress(value) {
65
65
  scope = "agent";
66
66
  else if (head === "model")
67
67
  scope = "model";
68
- else if (head === "agents" || head === "models") {
68
+ else if (head === "projects" || head === "agents" || head === "models") {
69
69
  const nameEnd = tail.indexOf("/");
70
70
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
71
71
  if (!SLUG_PATTERN.test(who))
72
72
  throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
73
- scope = head === "agents" ? "agent" : "model";
73
+ scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
74
74
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
75
75
  }
76
76
  else {
@@ -91,7 +91,7 @@ export function canonicalAddressFor(identity, scope, path, who) {
91
91
  if (scope === "session")
92
92
  return path;
93
93
  if (scope === "project")
94
- return `@project/${path}`;
94
+ return who === undefined ? `@project/${path}` : `@projects/${who}/${path}`;
95
95
  if (scope === "human")
96
96
  return `@human/${path}`;
97
97
  if (scope === "agent")
@@ -20,7 +20,8 @@ export function snapshotNotesIdentity(value) {
20
20
  const agent = requireString("agent", value.agent);
21
21
  const model = requireString("model", value.model);
22
22
  assertDirectoryComponent("sessionId", sessionId);
23
- assertDirectoryComponent("projectKey", projectKey);
23
+ if (!SLUG_PATTERN.test(projectKey))
24
+ throw new TypeError("notes context projectKey must be a canonical lowercase slug");
24
25
  if (!SLUG_PATTERN.test(agent))
25
26
  throw new TypeError("notes context agent must be a canonical lowercase slug");
26
27
  if (!SLUG_PATTERN.test(model))
@@ -1,3 +1,4 @@
1
+ export { projectKey } from "./project-home.js";
1
2
  import type { NotesIdentity } from "./identity.js";
2
3
  export type Scope = "session" | "project" | "human" | "agent" | "model";
3
4
  /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
@@ -10,12 +11,6 @@ export declare function slugify(value: string): string;
10
11
  * caller that reaches a path without going through an address still cannot escape a home.
11
12
  */
12
13
  export declare function assertVirtualPath(value: unknown): string;
13
- /**
14
- * `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
15
- * with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
16
- * so canonicalizing here is what keeps one repository — and its worktrees — on one home.
17
- */
18
- export declare function projectKey(cwd: string): string;
19
14
  /** Absolute directory holding the per-session note homes. */
20
15
  export declare function sessionHomesRoot(home: string): string;
21
16
  /** Absolute directory holding one scope's notes. The identity's home is already resolved. */
@@ -1,7 +1,6 @@
1
- import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
3
1
  import { readdir } from "node:fs/promises";
4
- import { basename, dirname, join, resolve, sep } from "node:path";
2
+ import { join } from "node:path";
3
+ export { projectKey } from "./project-home.js";
5
4
  import { NoteError, shown } from "./errors.js";
6
5
  /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
7
6
  export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -25,68 +24,6 @@ export function assertVirtualPath(value) {
25
24
  throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
26
25
  return value;
27
26
  }
28
- /**
29
- * `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
30
- * with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
31
- * so canonicalizing here is what keeps one repository — and its worktrees — on one home.
32
- */
33
- export function projectKey(cwd) {
34
- const absolute = resolve(cwd);
35
- const spelled = gitRoot(absolute) ?? absolute;
36
- let root = spelled;
37
- try {
38
- root = realpathSync(spelled);
39
- }
40
- catch { /* An unresolvable path keeps its spelling. */ }
41
- const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
42
- return `${basename(root)}-${digest}`;
43
- }
44
- /**
45
- * Repository root behind one `.git` entry. A `.git` directory is the main checkout
46
- * itself. A `.git` file is a worktree or submodule pointer: a linked worktree names
47
- * `<main>/.git/worktrees/<name>` and resolves to `<main>`, so every worktree of one
48
- * repository shares one project identity. Submodules, bare repositories, and separate
49
- * git dirs keep the current directory.
50
- */
51
- function repositoryRoot(dir) {
52
- let stats;
53
- try {
54
- stats = statSync(join(dir, ".git"));
55
- }
56
- catch {
57
- return dir;
58
- }
59
- if (stats.isDirectory())
60
- return dir;
61
- let pointer;
62
- try {
63
- pointer = readFileSync(join(dir, ".git"), "utf8");
64
- }
65
- catch {
66
- return dir;
67
- }
68
- const match = /^gitdir:\s*(.+)$/m.exec(pointer);
69
- if (!match)
70
- return dir;
71
- const parts = resolve(dir, match[1].trim()).split(sep);
72
- const worktrees = parts.lastIndexOf("worktrees");
73
- if (worktrees <= 0 || worktrees !== parts.length - 2)
74
- return dir;
75
- const common = parts.slice(0, worktrees).join(sep);
76
- return basename(common) === ".git" ? dirname(common) : dir;
77
- }
78
- /** Absolute repository root for cwd, walking upward until a directory holds a `.git` entry. */
79
- function gitRoot(cwd) {
80
- let dir = resolve(cwd);
81
- for (;;) {
82
- if (existsSync(join(dir, ".git")))
83
- return repositoryRoot(dir);
84
- const parent = dirname(dir);
85
- if (parent === dir)
86
- return undefined;
87
- dir = parent;
88
- }
89
- }
90
27
  /** Absolute directory holding the per-session note homes. */
91
28
  export function sessionHomesRoot(home) {
92
29
  return join(home, "pi", "session");
@@ -95,12 +32,12 @@ export function sessionHomesRoot(home) {
95
32
  export function scopeDir(scope, identity, who) {
96
33
  if (!["session", "project", "human", "agent", "model"].includes(scope))
97
34
  throw new TypeError("invalid notes scope");
98
- if (who !== undefined && (scope !== "agent" && scope !== "model" || !SLUG_PATTERN.test(who)))
99
- throw new TypeError("who must be a canonical agent/model slug");
35
+ if (who !== undefined && (scope !== "project" && scope !== "agent" && scope !== "model" || !SLUG_PATTERN.test(who)))
36
+ throw new TypeError("who must be a canonical project/agent/model slug");
100
37
  if (scope === "human")
101
38
  return join(identity.home, "human");
102
39
  if (scope === "project")
103
- return join(identity.home, "project", identity.projectKey);
40
+ return join(identity.home, "project", who ?? identity.projectKey);
104
41
  if (scope === "agent")
105
42
  return join(identity.home, "agents", who ?? identity.agent);
106
43
  if (scope === "model")
@@ -0,0 +1,25 @@
1
+ export type ProjectMarker = {
2
+ id: string;
3
+ path: string;
4
+ };
5
+ export type ProjectHome = ProjectMarker & {
6
+ name: string;
7
+ dir: string;
8
+ };
9
+ /** Normalize the small set of Git remote spellings used by ordinary repositories. */
10
+ export declare function normalizeRemote(value: string): string;
11
+ /** Read marked project homes. Unmarked legacy directories are deliberately omitted. */
12
+ export declare function projectHomes(home: string): ProjectHome[];
13
+ /** Resolve and claim the readable home for one repository identity. */
14
+ export declare function resolveProjectHome(cwd: string, home: string): ProjectHome;
15
+ export type ProjectReceipt = {
16
+ project_root?: string;
17
+ project_siblings?: Array<{
18
+ name: string;
19
+ path: string;
20
+ }>;
21
+ };
22
+ /** Display-only context for an explicitly named project home. */
23
+ export declare function projectReceipt(home: string, name: string): ProjectReceipt;
24
+ /** Names a project home, claiming it when the notes home has not seen this identity. */
25
+ export declare function projectKey(cwd: string, home: string): string;