notesoup 0.42.0 → 0.44.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 (126) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.d.ts +2 -0
  3. package/dist/src/boot/snapshot.js +4 -5
  4. package/dist/src/boot/text.js +4 -2
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +2 -0
  9. package/dist/src/budget/text.js +2 -0
  10. package/dist/src/claude/helper.js +3 -4
  11. package/dist/src/claude/thresholds.js +45 -66
  12. package/dist/src/dream/lock.js +6 -13
  13. package/dist/src/dream/report.js +5 -15
  14. package/dist/src/history/history.js +4 -2
  15. package/dist/src/history/query.js +10 -22
  16. package/dist/src/notes/address.d.ts +2 -3
  17. package/dist/src/notes/address.js +10 -22
  18. package/dist/src/notes/errors.d.ts +2 -0
  19. package/dist/src/notes/errors.js +5 -0
  20. package/dist/src/notes/frontmatter.js +16 -2
  21. package/dist/src/notes/identity.js +2 -4
  22. package/dist/src/notes/paths.d.ts +7 -2
  23. package/dist/src/notes/paths.js +18 -60
  24. package/dist/src/notes/project-home.d.ts +25 -0
  25. package/dist/src/notes/project-home.js +231 -0
  26. package/dist/src/notes/store.d.ts +4 -2
  27. package/dist/src/notes/store.js +52 -45
  28. package/dist/src/pi/boot.js +17 -9
  29. package/dist/src/pi/budget.d.ts +3 -3
  30. package/dist/src/pi/budget.js +11 -11
  31. package/dist/src/pi/dream/cli.js +43 -11
  32. package/dist/src/pi/estimate.d.ts +1 -5
  33. package/dist/src/pi/estimate.js +4 -4
  34. package/dist/src/pi/history.js +1 -4
  35. package/dist/src/pi/notes/adapter.d.ts +1 -1
  36. package/dist/src/pi/notes/adapter.js +3 -3
  37. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  38. package/dist/src/pi/reset/artifacts.js +4 -4
  39. package/dist/src/pi/reset/committed.js +2 -2
  40. package/dist/src/pi/runtime.js +8 -5
  41. package/dist/src/pi/thresholds.js +5 -9
  42. package/dist/src/pi/tool-result.d.ts +1 -4
  43. package/dist/src/pi/tool-result.js +1 -1
  44. package/dist/src/pi/window.d.ts +5 -0
  45. package/dist/src/pi/window.js +7 -0
  46. package/dist/src/settings.d.ts +2 -0
  47. package/dist/src/settings.js +4 -3
  48. package/dist/src/tools/history.js +4 -7
  49. package/dist/src/tools/notes.d.ts +47 -21
  50. package/dist/src/tools/notes.js +20 -19
  51. package/dist/src/tools/output.d.ts +0 -3
  52. package/dist/src/tools/output.js +1 -9
  53. package/dist/src/tools/result.d.ts +1 -0
  54. package/dist/src/tools/result.js +14 -20
  55. package/dist/src/tools/schema.d.ts +0 -1
  56. package/dist/src/tools/schema.js +0 -1
  57. package/dist/test/agent-loop.test.js +1 -2
  58. package/dist/test/boot.integration.test.js +1 -1
  59. package/dist/test/claude-mod.test.js +253 -10
  60. package/dist/test/claude-validation.test.d.ts +1 -0
  61. package/dist/test/claude-validation.test.js +73 -0
  62. package/dist/test/dream-skill.test.js +2 -4
  63. package/dist/test/dream.test.js +14 -0
  64. package/dist/test/helpers/extension.js +1 -1
  65. package/dist/test/history.integration.test.js +2 -1
  66. package/dist/test/host-neutral.test.js +15 -0
  67. package/dist/test/notes-library.test.js +30 -1
  68. package/dist/test/notes.integration.test.js +7 -7
  69. package/dist/test/notes.test.js +36 -14
  70. package/dist/test/project-home.test.d.ts +1 -0
  71. package/dist/test/project-home.test.js +134 -0
  72. package/dist/test/reset-lifecycle.test.js +1 -1
  73. package/docs/claude-code-mod.md +5 -3
  74. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  75. package/mods/notesoup/dist/claude/helper.js +359 -218
  76. package/mods/notesoup/hooks/register.ts +158 -67
  77. package/mods/notesoup/playbook.md +1 -1
  78. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  79. package/mods/notesoup/skills/memory/SKILL.md +62 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +2 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +5 -5
  86. package/src/boot/text.ts +4 -2
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +3 -0
  90. package/src/claude/helper.ts +4 -4
  91. package/src/claude/thresholds.ts +45 -62
  92. package/src/dream/lock.ts +3 -9
  93. package/src/dream/report.ts +5 -10
  94. package/src/history/history.ts +4 -2
  95. package/src/history/query.ts +10 -23
  96. package/src/notes/address.ts +9 -21
  97. package/src/notes/errors.ts +6 -0
  98. package/src/notes/frontmatter.ts +12 -2
  99. package/src/notes/identity.ts +1 -3
  100. package/src/notes/paths.ts +14 -52
  101. package/src/notes/project-home.ts +197 -0
  102. package/src/notes/store.ts +46 -45
  103. package/src/pi/boot.ts +15 -17
  104. package/src/pi/budget.ts +10 -11
  105. package/src/pi/dream/cli.ts +35 -10
  106. package/src/pi/estimate.ts +4 -4
  107. package/src/pi/history.ts +1 -5
  108. package/src/pi/notes/adapter.ts +3 -3
  109. package/src/pi/reset/artifacts.ts +4 -4
  110. package/src/pi/reset/committed.ts +2 -2
  111. package/src/pi/runtime.ts +7 -6
  112. package/src/pi/thresholds.ts +5 -11
  113. package/src/pi/tool-result.ts +1 -1
  114. package/src/pi/window.ts +8 -0
  115. package/src/settings.ts +4 -3
  116. package/src/tools/history.ts +4 -8
  117. package/src/tools/notes.ts +22 -25
  118. package/src/tools/output.ts +1 -12
  119. package/src/tools/result.ts +14 -19
  120. package/src/tools/schema.ts +0 -1
  121. package/dist/src/dream/playbook.d.ts +0 -1
  122. package/dist/src/dream/playbook.js +0 -2
  123. package/dist/src/pi/reset/text.d.ts +0 -4
  124. package/dist/src/pi/reset/text.js +0 -7
  125. package/src/dream/playbook.ts +0 -3
  126. package/src/pi/reset/text.ts +0 -9
@@ -132,15 +132,25 @@ export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body
132
132
  return { meta: meta as NoteMeta, body };
133
133
  }
134
134
 
135
- /** Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise. */
135
+ /**
136
+ * Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
137
+ * A quoted string must not come back as another type: a value that `JSON.parse` reads as a
138
+ * non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
139
+ * with its type intact.
140
+ */
136
141
  function yamlScalar(value: unknown): string {
137
142
  if (typeof value === "string") {
138
143
  const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
139
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase())) return value;
144
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
140
145
  }
141
146
  return JSON.stringify(value);
142
147
  }
143
148
 
149
+ /** True when a bare scalar would be read back as a number, boolean or null instead of text. */
150
+ function parsesAsNonString(text: string): boolean {
151
+ try { return typeof JSON.parse(text) !== "string"; } catch { return false; }
152
+ }
153
+
144
154
  /** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
145
155
  export function serializeNote(meta: NoteMeta, body: string): string {
146
156
  const lines: string[] = [];
@@ -24,15 +24,13 @@ function assertDirectoryComponent(field: string, value: string): void {
24
24
  /** Validate and snapshot caller identity; no global or environment defaults are consulted. */
25
25
  export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
26
26
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("notes context must be a plain object");
27
- const prototype = Object.getPrototypeOf(value);
28
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("notes context must be a plain object");
29
27
  const homeValue = requireString("home", value.home);
30
28
  const sessionId = requireString("sessionId", value.sessionId);
31
29
  const projectKey = requireString("projectKey", value.projectKey);
32
30
  const agent = requireString("agent", value.agent);
33
31
  const model = requireString("model", value.model);
34
32
  assertDirectoryComponent("sessionId", sessionId);
35
- assertDirectoryComponent("projectKey", projectKey);
33
+ if (!SLUG_PATTERN.test(projectKey)) throw new TypeError("notes context projectKey must be a canonical lowercase slug");
36
34
  if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
37
35
  if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
38
36
  const home = resolve(homeValue);
@@ -1,7 +1,7 @@
1
- import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, 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";
4
+ import { NoteError, shown } from "./errors.js";
5
5
  import type { NotesIdentity } from "./identity.js";
6
6
 
7
7
  export type Scope = "session" | "project" | "human" | "agent" | "model";
@@ -15,53 +15,17 @@ export function slugify(value: string): string {
15
15
  return slug.length > 0 ? slug : "root";
16
16
  }
17
17
 
18
- /** `<basename(absGitRoot)-sha1(absGitRoot)[:8]>`, or the same formula over cwd with no git root. */
19
- export function projectKey(cwd: string): string {
20
- const absolute = resolve(cwd);
21
- const root = gitRoot(absolute) ?? absolute;
22
- const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
23
- return `${basename(root)}-${digest}`;
24
- }
25
-
26
18
  /**
27
- * Repository root behind one `.git` entry. A `.git` directory is the main checkout
28
- * itself. A `.git` file is a worktree or submodule pointer: a linked worktree names
29
- * `<main>/.git/worktrees/<name>` and resolves to `<main>`, so every worktree of one
30
- * repository shares one project identity. Submodules, bare repositories, and separate
31
- * git dirs keep the current directory.
19
+ * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
20
+ * segment. Both the address decoder and the physical-path builder enforce it here, so a
21
+ * caller that reaches a path without going through an address still cannot escape a home.
32
22
  */
33
- function repositoryRoot(dir: string): string {
34
- let stats;
35
- try {
36
- stats = statSync(join(dir, ".git"));
37
- } catch {
38
- return dir;
39
- }
40
- if (stats.isDirectory()) return dir;
41
- let pointer: string;
42
- try {
43
- pointer = readFileSync(join(dir, ".git"), "utf8");
44
- } catch {
45
- return dir;
46
- }
47
- const match = /^gitdir:\s*(.+)$/m.exec(pointer);
48
- if (!match) return dir;
49
- const parts = resolve(dir, match[1]!.trim()).split(sep);
50
- const worktrees = parts.lastIndexOf("worktrees");
51
- if (worktrees <= 0 || worktrees !== parts.length - 2) return dir;
52
- const common = parts.slice(0, worktrees).join(sep);
53
- return basename(common) === ".git" ? dirname(common) : dir;
54
- }
55
-
56
- /** Absolute repository root for cwd, walking upward until a directory holds a `.git` entry. */
57
- function gitRoot(cwd: string): string | undefined {
58
- let dir = resolve(cwd);
59
- for (;;) {
60
- if (existsSync(join(dir, ".git"))) return repositoryRoot(dir);
61
- const parent = dirname(dir);
62
- if (parent === dir) return undefined;
63
- dir = parent;
64
- }
23
+ export function assertVirtualPath(value: unknown): string {
24
+ if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
25
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
26
+ const parts = value.split("/");
27
+ if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
28
+ return value;
65
29
  }
66
30
 
67
31
  /** Absolute directory holding the per-session note homes. */
@@ -72,9 +36,9 @@ export function sessionHomesRoot(home: string): string {
72
36
  /** Absolute directory holding one scope's notes. The identity's home is already resolved. */
73
37
  export function scopeDir(scope: Scope, identity: NotesIdentity, who?: string): string {
74
38
  if (!["session", "project", "human", "agent", "model"].includes(scope)) throw new TypeError("invalid notes scope");
75
- if (who !== undefined && (scope !== "agent" && scope !== "model" || !SLUG_PATTERN.test(who))) throw new TypeError("who must be a canonical agent/model slug");
39
+ if (who !== undefined && (scope !== "project" && scope !== "agent" && scope !== "model" || !SLUG_PATTERN.test(who))) throw new TypeError("who must be a canonical project/agent/model slug");
76
40
  if (scope === "human") return join(identity.home, "human");
77
- if (scope === "project") return join(identity.home, "project", identity.projectKey);
41
+ if (scope === "project") return join(identity.home, "project", who ?? identity.projectKey);
78
42
  if (scope === "agent") return join(identity.home, "agents", who ?? identity.agent);
79
43
  if (scope === "model") return join(identity.home, "models", who ?? identity.model);
80
44
  return join(sessionHomesRoot(identity.home), identity.sessionId);
@@ -103,7 +67,5 @@ export function noteFileName(vpath: string): string {
103
67
 
104
68
  /** Absolute file path for a virtual path in a scope. Callers validate the vpath first. */
105
69
  export function physicalPath(scope: Scope, vpath: string, identity: NotesIdentity, who?: string): string {
106
- if (typeof vpath !== "string" || vpath.length === 0 || vpath.includes("\0") || vpath.includes("\\") || vpath.startsWith("/")) throw new TypeError("path must be a safe virtual relative path");
107
- if (vpath.split("/").some((part) => part.length === 0 || part === "." || part === "..")) throw new TypeError("path contains an unsupported component");
108
70
  return join(scopeDir(scope, identity, who), ...noteFileName(vpath).split("/"));
109
71
  }
@@ -0,0 +1,197 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, resolve, sep } from "node:path";
4
+ import { slugify } from "./paths.js";
5
+
6
+ export type ProjectMarker = { id: string; path: string };
7
+ export type ProjectHome = ProjectMarker & { name: string; dir: string };
8
+
9
+ function errno(error: unknown): string | undefined {
10
+ return typeof error === "object" && error !== null ? (error as NodeJS.ErrnoException).code : undefined;
11
+ }
12
+
13
+ /** Normalize the small set of Git remote spellings used by ordinary repositories. */
14
+ export function normalizeRemote(value: string): string {
15
+ let text = value.trim();
16
+ const scp = /^(?:[^/@]+)@([^:/]+):(.+)$/.exec(text);
17
+ if (scp) text = `${scp[1]!.toLowerCase()}/${scp[2]}`;
18
+ else if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(text)) {
19
+ try {
20
+ const url = new URL(text);
21
+ const host = url.hostname.toLowerCase();
22
+ const port = url.port.length > 0 ? `:${url.port}` : "";
23
+ text = `${host}${port}${url.pathname}`;
24
+ } catch {
25
+ text = text.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//, "").replace(/^[^/@]+@/, "");
26
+ }
27
+ } else {
28
+ text = text.replace(/^[^/@]+@/, "");
29
+ const slash = text.indexOf("/");
30
+ if (slash > 0) text = `${text.slice(0, slash).toLowerCase()}${text.slice(slash)}`;
31
+ }
32
+ text = text.replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
33
+ return text;
34
+ }
35
+
36
+ function canonicalRoot(cwd: string): string {
37
+ const absolute = resolve(cwd);
38
+ const spelled = gitRoot(absolute) ?? absolute;
39
+ try { return realpathSync(spelled); } catch { return spelled; }
40
+ }
41
+
42
+ function originRemote(root: string): string | undefined {
43
+ let gitDir = join(root, ".git");
44
+ let raw: string;
45
+ try {
46
+ if (!statSync(gitDir).isDirectory()) {
47
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(gitDir, "utf8"));
48
+ if (!pointer) return undefined;
49
+ gitDir = resolve(root, pointer[1]!.trim());
50
+ }
51
+ try { gitDir = resolve(gitDir, readFileSync(join(gitDir, "commondir"), "utf8").trim()); } catch (error) {
52
+ if (errno(error) !== "ENOENT") throw error;
53
+ }
54
+ raw = readFileSync(join(gitDir, "config"), "utf8");
55
+ } catch (error) {
56
+ if (errno(error) === "ENOENT") return undefined;
57
+ throw error;
58
+ }
59
+ let origin = false;
60
+ for (const line of raw.split(/\r?\n/)) {
61
+ const section = /^\s*\[remote\s+"([^"]+)"\]\s*$/.exec(line);
62
+ if (section) {
63
+ origin = section[1] === "origin";
64
+ continue;
65
+ }
66
+ if (/^\s*\[/.test(line)) origin = false;
67
+ if (origin) {
68
+ const url = /^\s*url\s*=\s*(.*?)\s*$/.exec(line);
69
+ if (url) return normalizeRemote(url[1]!.replace(/^"(.*)"$/, "$1")) || undefined;
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ function readMarker(dir: string): ProjectHome | undefined {
76
+ let raw: string;
77
+ try { raw = readFileSync(join(dir, ".project"), "utf8"); } catch (error) {
78
+ if (errno(error) === "ENOENT") return undefined;
79
+ throw error;
80
+ }
81
+ try {
82
+ const value = JSON.parse(raw) as Partial<ProjectMarker>;
83
+ if (typeof value.id !== "string" || value.id.length === 0 || typeof value.path !== "string" || value.path.length === 0) return undefined;
84
+ return { name: basename(dir), dir, id: value.id, path: value.path };
85
+ } catch {
86
+ return undefined;
87
+ }
88
+ }
89
+
90
+ function projectRoot(home: string): string {
91
+ return join(home, "project");
92
+ }
93
+
94
+ /** Read marked project homes. Unmarked legacy directories are deliberately omitted. */
95
+ export function projectHomes(home: string): ProjectHome[] {
96
+ const root = projectRoot(home);
97
+ let entries;
98
+ try { entries = readdirSync(root, { withFileTypes: true }); } catch (error) {
99
+ if (errno(error) === "ENOENT") return [];
100
+ throw error;
101
+ }
102
+ return entries.filter(entry => entry.isDirectory()).map(entry => readMarker(join(root, entry.name))).filter((entry): entry is ProjectHome => entry !== undefined).sort((a, b) => a.name.localeCompare(b.name));
103
+ }
104
+
105
+ function updateMarker(home: ProjectHome, marker: ProjectMarker): ProjectHome {
106
+ const markerPath = join(home.dir, ".project");
107
+ const temp = `${markerPath}.${process.pid}.${randomUUID()}.tmp`;
108
+ try {
109
+ writeFileSync(temp, JSON.stringify(marker));
110
+ renameSync(temp, markerPath);
111
+ } catch (error) {
112
+ try { rmSync(temp, { force: true }); } catch { /* Preserve the marker update failure. */ }
113
+ throw error;
114
+ }
115
+ return { ...home, ...marker };
116
+ }
117
+
118
+ /** Resolve and claim the readable home for one repository identity. */
119
+ export function resolveProjectHome(cwd: string, home: string): ProjectHome {
120
+ const root = canonicalRoot(cwd);
121
+ const remote = originRemote(root);
122
+ const id = remote ?? root;
123
+ const markerRoot = projectRoot(home);
124
+ mkdirSync(markerRoot, { recursive: true });
125
+ const homes = projectHomes(home);
126
+ let found = homes.find(candidate => candidate.id === id);
127
+ if (!found && remote) {
128
+ found = homes.find(candidate => candidate.id === root);
129
+ if (found) found = updateMarker(found, { id: remote, path: root });
130
+ }
131
+ if (found) {
132
+ if (found.path !== root) found = updateMarker(found, { id: found.id, path: root });
133
+ return found;
134
+ }
135
+
136
+ const base = slugify(basename(root));
137
+ // Existing unmarked homes are taken; only directories appearing after this scan can be raced.
138
+ const taken = new Set(readdirSync(markerRoot));
139
+ for (let suffix = 0; ; suffix++) {
140
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
141
+ if (taken.has(name)) continue;
142
+ const dir = join(markerRoot, name);
143
+ try {
144
+ mkdirSync(dir, { recursive: true });
145
+ writeFileSync(join(dir, ".project"), JSON.stringify({ id, path: root }), { flag: "wx" });
146
+ return { name, dir, id, path: root };
147
+ } catch (error) {
148
+ if (errno(error) === "EEXIST") continue;
149
+ throw error;
150
+ }
151
+ }
152
+ }
153
+
154
+ /** Existing root discovery, including linked worktrees, without invoking Git. */
155
+ function gitRoot(cwd: string): string | undefined {
156
+ let dir = resolve(cwd);
157
+ for (;;) {
158
+ if (existsSync(join(dir, ".git"))) return repositoryRoot(dir);
159
+ const parent = dirname(dir);
160
+ if (parent === dir) return undefined;
161
+ dir = parent;
162
+ }
163
+ }
164
+
165
+ function repositoryRoot(dir: string): string {
166
+ let stats;
167
+ try { stats = statSync(join(dir, ".git")); } catch { return dir; }
168
+ if (stats.isDirectory()) return dir;
169
+ let pointer: string;
170
+ try { pointer = readFileSync(join(dir, ".git"), "utf8"); } catch { return dir; }
171
+ const match = /^gitdir:\s*(.+)$/m.exec(pointer);
172
+ if (!match) return dir;
173
+ const parts = resolve(dir, match[1]!.trim()).split(sep);
174
+ const worktrees = parts.lastIndexOf("worktrees");
175
+ if (worktrees <= 0 || worktrees !== parts.length - 2) return dir;
176
+ const common = parts.slice(0, worktrees).join(sep);
177
+ return basename(common) === ".git" ? dirname(common) : dir;
178
+ }
179
+
180
+ export type ProjectReceipt = { project_root?: string; project_siblings?: Array<{ name: string; path: string }> };
181
+
182
+ /** Display-only context for an explicitly named project home. */
183
+ export function projectReceipt(home: string, name: string): ProjectReceipt {
184
+ const project = readMarker(join(projectRoot(home), name));
185
+ if (!project) return {};
186
+ const base = slugify(basename(project.path));
187
+ const siblings = projectHomes(home).filter(candidate => candidate.name !== name && slugify(basename(candidate.path)) === base);
188
+ return {
189
+ project_root: project.path,
190
+ ...(siblings.length === 0 ? {} : { project_siblings: siblings.map(({ name, path }) => ({ name, path })) }),
191
+ };
192
+ }
193
+
194
+ /** Names a project home, claiming it when the notes home has not seen this identity. */
195
+ export function projectKey(cwd: string, home: string): string {
196
+ return resolveProjectHome(cwd, home).name;
197
+ }
@@ -10,6 +10,7 @@ import { NoteError } from "./errors.js";
10
10
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
11
11
  import { isOrigin, isScope, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
12
12
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, SLUG_PATTERN, type Scope } from "./paths.js";
13
+ import { projectHomes, projectReceipt, type ProjectReceipt } from "./project-home.js";
13
14
 
14
15
  export type { NoteMeta, Origin, Scope };
15
16
 
@@ -40,15 +41,16 @@ export type NoteChange =
40
41
  | { kind: "body" | "metadata"; before: string; after: string };
41
42
  export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange };
42
43
  export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
44
+ /** A home, or one unreadable note inside it, that a status-reporting query could not read. */
43
45
  export type NoteQueryStatus = { homesUnavailable: string[] };
44
46
  export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
45
47
 
46
- /** Public identity resolved for an operation, never a filesystem path. */
47
- export function noteIdentity(identity: NotesIdentity, address: string): { address: string; project_key?: string } {
48
+ /** Public note identity; named projects also carry their display root and sibling hints. */
49
+ export function noteIdentity(identity: NotesIdentity, address: string): { address: string; project_key?: string } & ProjectReceipt {
48
50
  const resolved = assertAddress(address);
49
51
  return {
50
52
  address: addressFor(identity, resolved.scope, noteFileName(resolved.path), resolved.who),
51
- ...(resolved.scope === "project" ? { project_key: identity.projectKey } : {}),
53
+ ...(resolved.scope !== "project" ? {} : resolved.who === undefined ? { project_key: identity.projectKey } : projectReceipt(identity.home, resolved.who)),
52
54
  };
53
55
  }
54
56
 
@@ -114,11 +116,6 @@ async function walkMarkdown(dir: string, base = dir): Promise<string[]> {
114
116
  return paths;
115
117
  }
116
118
 
117
- function matcherFor(pattern: unknown): RegExp | undefined {
118
- const normalized = assertGlobPattern(pattern);
119
- return normalized === undefined ? undefined : globToRegExp(normalized);
120
- }
121
-
122
119
  /** Which homes one call iterates; reserved heads narrow traversal before any file is read. */
123
120
  type HomeRef = { scope: Scope; who?: string };
124
121
 
@@ -129,11 +126,12 @@ async function homesForPattern(pattern: string | undefined, identity: NotesIdent
129
126
  if (head === "human") return [{ scope: "human" }];
130
127
  if (head === "self") return [{ scope: "agent" }];
131
128
  if (head === "model") return [{ scope: "model" }];
132
- if (head === "agents" || head === "models") {
133
- const scope: Scope = head === "agents" ? "agent" : "model";
129
+ if (head === "projects" || head === "agents" || head === "models") {
130
+ const scope: Scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
134
131
  const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
135
132
  if (name.length > 0 && !/[*?]/.test(name)) return [{ scope, who: assertWho(name) }];
136
- return (await namespaceSlugs(head, identity.home)).map((who) => ({ scope, who }));
133
+ const names = head === "projects" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head, identity.home);
134
+ return names.map((who) => ({ scope, who }));
137
135
  }
138
136
  return [];
139
137
  }
@@ -146,11 +144,6 @@ function normalizePattern(pattern: string | undefined, identity: NotesIdentity):
146
144
  return pattern;
147
145
  }
148
146
 
149
- function assertScope(value: unknown): Scope {
150
- if (!isScope(value)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(value)})`);
151
- return value;
152
- }
153
-
154
147
  function assertOrigin(value: unknown): Origin {
155
148
  if (!isOrigin(value)) throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
156
149
  return value;
@@ -165,7 +158,8 @@ function assertWho(value: unknown): string {
165
158
 
166
159
  async function homesFor(identity: NotesIdentity, opts: NotesQuery): Promise<HomeRef[]> {
167
160
  if (opts.scope !== undefined) {
168
- const scope = assertScope(opts.scope);
161
+ if (!isScope(opts.scope)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
162
+ const scope = opts.scope;
169
163
  if (opts.who !== undefined) {
170
164
  const who = assertWho(opts.who);
171
165
  if (scope !== "agent" && scope !== "model") throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
@@ -246,23 +240,16 @@ function frontmatterOf(meta: NoteMeta): string {
246
240
  return serializeNote(meta, "").slice(0, -2);
247
241
  }
248
242
 
249
- /** Named agent/model homes are read-only to whoever is not running there. */
243
+ /** Explicit project homes are always read-only; agent/model homes allow their owner. */
250
244
  function assertWritableHome(scope: Scope, who: string | undefined, identity: NotesIdentity): void {
251
245
  if (who === undefined) return;
246
+ if (scope === "project") throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
252
247
  const current = scope === "agent" ? identity.agent : identity.model;
253
248
  if (who === current) return;
254
249
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
255
250
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
256
251
  }
257
252
 
258
- /** Normalize parsed metadata exactly as a read does, including its access mutation. */
259
- function accessedMeta(meta: NoteMeta, scope: Scope, now: number): NoteMeta {
260
- const next = { ...meta, scope };
261
- next.lastAccessed = now;
262
- next.accessCount = (typeof next.accessCount === "number" ? next.accessCount : 0) + 1;
263
- return next;
264
- }
265
-
266
253
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
267
254
  export function createNotesStore(input: NotesIdentity): NotesStore {
268
255
  const identity = snapshotNotesIdentity(input);
@@ -273,7 +260,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
273
260
  assertWritablePath(destination.path);
274
261
  const scope = destination.scope;
275
262
  assertWritableHome(scope, destination.who, identity);
276
- const origin = assertOrigin(stableOptions.origin ?? "self");
263
+ // Absent means "keep whatever the note already says": replacing a note must not silently
264
+ // re-attribute a user-written note to the agent that happened to rewrite it.
265
+ const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
277
266
  const path = physicalPath(scope, destination.path, identity, destination.who);
278
267
  return withPathQueue(path, async () => {
279
268
  const now = writeStamp();
@@ -283,7 +272,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
283
272
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
284
273
  const meta: NoteMeta = existing ?? {
285
274
  scope,
286
- origin,
275
+ origin: origin ?? "self",
287
276
  createdAt: now,
288
277
  updatedAt: now,
289
278
  lastAccessed: now,
@@ -291,7 +280,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
291
280
  ...(scope === "session" ? { project: identity.projectKey } : {}),
292
281
  };
293
282
  meta.scope = scope;
294
- meta.origin = origin;
283
+ if (origin !== undefined) meta.origin = origin;
295
284
  delete meta.crumpledAt;
296
285
  meta.updatedAt = now;
297
286
  const serialized = serializeNote(meta, cleanBody);
@@ -310,7 +299,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
310
299
  if (raw === undefined) return undefined;
311
300
  const now = Date.now();
312
301
  const parsed = parseNote(raw, now);
313
- const meta = accessedMeta(parsed.meta, scope, now);
302
+ if (scope === "project" && destination.who !== undefined) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
303
+ // A read records its own access, exactly as a write records an edit.
304
+ const meta: NoteMeta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
314
305
  await atomicWrite(path, serializeNote(meta, parsed.body));
315
306
  return { meta, body: parsed.body, resolvedScope: scope };
316
307
  });
@@ -413,36 +404,46 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
413
404
  }
414
405
 
415
406
  async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
416
- const matcher = matcherFor(normalizePattern(options.glob, identity));
407
+ const pattern = normalizePattern(options.glob, identity);
408
+ const normalized = assertGlobPattern(pattern);
409
+ const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
417
410
  let homes: HomeRef[];
418
411
  try {
419
412
  homes = await homesFor(identity, options);
420
413
  } catch (error) {
421
- if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.glob ?? "")) throw error;
422
- status.homesUnavailable.push(options.glob!.startsWith("@agents/") ? "@agents" : "@models");
414
+ if (!status || !isFilesystemError(error) || !/^@(projects|agents|models)\//.test(options.glob ?? "")) throw error;
415
+ status.homesUnavailable.push(options.glob!.split("/")[0]!);
423
416
  return;
424
417
  }
425
418
  for (const home of homes) {
426
419
  const scope = home.scope;
427
420
  const root = scopeDir(scope, identity, home.who);
428
- const homeRows: Array<Omit<NoteRow, "sizeBytes">> = [];
421
+ let paths: string[];
429
422
  try {
430
- for (const path of await walkMarkdown(root)) {
431
- if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
432
- const address = addressFor(identity, scope, path, home.who);
433
- const fullPath = join(root, path);
434
- const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
435
- const { meta, body } = parseNote(raw);
436
- meta.scope = scope;
437
- if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
438
- homeRows.push({ address, scope, path, meta, body });
439
- }
423
+ paths = await walkMarkdown(root);
440
424
  } catch (error) {
441
425
  if (!status || !isFilesystemError(error)) throw error;
442
426
  status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
443
427
  continue;
444
428
  }
445
- for (const row of homeRows) yield row;
429
+ for (const path of paths) {
430
+ if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
431
+ const address = addressFor(identity, scope, path, home.who);
432
+ const fullPath = join(root, path);
433
+ let raw: string;
434
+ try {
435
+ raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
436
+ } catch (error) {
437
+ // One unreadable note is named on its own; its home's readable notes still list.
438
+ if (!status || !isFilesystemError(error)) throw error;
439
+ status.homesUnavailable.push(address);
440
+ continue;
441
+ }
442
+ const { meta, body } = parseNote(raw);
443
+ meta.scope = scope;
444
+ if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
445
+ yield { address, scope, path, meta, body };
446
+ }
446
447
  }
447
448
  }
448
449
 
package/src/pi/boot.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { PI_TOOL_NAMES } from "./tool-names.js";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { notesIdentityFromPi } from "./notes/adapter.js";
4
- import { loadNotesSnapshot, type NotesSnapshot } from "../boot/snapshot.js";
3
+ import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
4
+ import { loadNotesSnapshot, unavailableNotesSnapshot, type NotesSnapshot } from "../boot/snapshot.js";
5
+ import { isFilesystemError } from "../notes/fs-error.js";
5
6
  import { BOOT_TYPE } from "./entries.js";
6
7
  import { renderBootBlock } from "../boot/render.js";
7
8
  import { currentReset, currentWindowId, isWindowBoot, rootWindowId } from "./window.js";
@@ -17,18 +18,6 @@ export type BootMessage = {
17
18
  readonly details: { windowId: string };
18
19
  };
19
20
 
20
- /** Render the boot block from one pre-await identity and acquired notes snapshot. */
21
- function bootContent(
22
- agentName: string,
23
- modelName: string,
24
- firstWindowId: string,
25
- currentId: string,
26
- previousId: string | undefined,
27
- notes: NotesSnapshot,
28
- ): string {
29
- return renderBootBlock({ agentName, modelName, firstWindowId, currentWindowId: currentId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES });
30
- }
31
-
32
21
  /**
33
22
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
34
23
  * fields are captured synchronously before the first filesystem await.
@@ -40,12 +29,21 @@ export async function buildBootMessage(
40
29
  notifyIncompleteNotes?: IncompleteNotesNotifier,
41
30
  isCurrent: () => boolean = () => true,
42
31
  ): Promise<BootMessage> {
43
- const identity = notesIdentityFromPi(ctx);
44
- const notes = await loadNotesSnapshot(identity, Date.now());
32
+ const agentName = agentSlug();
33
+ const modelName = modelSlug(ctx);
34
+ const sessionId = ctx.sessionManager.getSessionId();
35
+ const openedAt = Date.now();
36
+ let notes: NotesSnapshot;
37
+ try {
38
+ notes = await loadNotesSnapshot(notesIdentityFromPi(ctx), openedAt);
39
+ } catch (error) {
40
+ if (!isFilesystemError(error)) throw error;
41
+ notes = unavailableNotesSnapshot(openedAt);
42
+ }
45
43
  if (isCurrent()) notifyIncompleteNotes?.(ctx, windowId, notes);
46
44
  return {
47
45
  customType: BOOT_TYPE,
48
- content: bootContent(identity.agent, identity.model, rootWindowId(identity.sessionId), windowId, previousId, notes),
46
+ content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES }),
49
47
  display: false,
50
48
  details: { windowId },
51
49
  };