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
@@ -1,21 +1,6 @@
1
- import { NoteError } from "./errors.js";
2
- import { 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.";
4
- /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
5
- function shown(value) {
6
- const json = JSON.stringify(value);
7
- return json === undefined ? String(value) : json;
8
- }
9
- export function assertVirtualPath(value) {
10
- if (typeof value !== "string" || value.length === 0)
11
- throw new NoteError("invalid_address", "The address is empty; give the note a path.");
12
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
13
- throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
14
- const parts = value.split("/");
15
- if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
16
- throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
17
- return value;
18
- }
1
+ import { NoteError, shown } from "./errors.js";
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; @projects/<name>/<path> reads a named project home.";
19
4
  /**
20
5
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
21
6
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -37,6 +22,9 @@ export function globToRegExp(pattern) {
37
22
  source += "[^/]*";
38
23
  }
39
24
  }
25
+ else if (char === "?") {
26
+ source += "[^/]";
27
+ }
40
28
  else {
41
29
  source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
42
30
  }
@@ -55,7 +43,7 @@ export function assertGlobPattern(value) {
55
43
  }
56
44
  /**
57
45
  * Decode one public note address into its physical home and virtual path. @self and @model
58
- * are relative; explicit agents/models addresses always name a canonical slug.
46
+ * are relative; explicit projects/agents/models addresses always name one canonical slug.
59
47
  */
60
48
  export function assertAddress(value) {
61
49
  if (typeof value !== "string")
@@ -77,12 +65,12 @@ export function assertAddress(value) {
77
65
  scope = "agent";
78
66
  else if (head === "model")
79
67
  scope = "model";
80
- else if (head === "agents" || head === "models") {
68
+ else if (head === "projects" || head === "agents" || head === "models") {
81
69
  const nameEnd = tail.indexOf("/");
82
70
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
83
71
  if (!SLUG_PATTERN.test(who))
84
72
  throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
85
- scope = head === "agents" ? "agent" : "model";
73
+ scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
86
74
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
87
75
  }
88
76
  else {
@@ -103,7 +91,7 @@ export function canonicalAddressFor(identity, scope, path, who) {
103
91
  if (scope === "session")
104
92
  return path;
105
93
  if (scope === "project")
106
- return `@project/${path}`;
94
+ return who === undefined ? `@project/${path}` : `@projects/${who}/${path}`;
107
95
  if (scope === "human")
108
96
  return `@human/${path}`;
109
97
  if (scope === "agent")
@@ -9,3 +9,5 @@ export declare class NoteError extends Error {
9
9
  editIndex?: number;
10
10
  });
11
11
  }
12
+ /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
13
+ export declare function shown(value: unknown): string;
@@ -11,3 +11,8 @@ export class NoteError extends Error {
11
11
  this.editIndex = extra.editIndex;
12
12
  }
13
13
  }
14
+ /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
15
+ export function shown(value) {
16
+ const json = JSON.stringify(value);
17
+ return json === undefined ? String(value) : json;
18
+ }
@@ -107,15 +107,29 @@ export function parseNote(raw, now = Date.now()) {
107
107
  meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
108
108
  return { meta: meta, body };
109
109
  }
110
- /** Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise. */
110
+ /**
111
+ * Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
112
+ * A quoted string must not come back as another type: a value that `JSON.parse` reads as a
113
+ * non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
114
+ * with its type intact.
115
+ */
111
116
  function yamlScalar(value) {
112
117
  if (typeof value === "string") {
113
118
  const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
114
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()))
119
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value))
115
120
  return value;
116
121
  }
117
122
  return JSON.stringify(value);
118
123
  }
124
+ /** True when a bare scalar would be read back as a number, boolean or null instead of text. */
125
+ function parsesAsNonString(text) {
126
+ try {
127
+ return typeof JSON.parse(text) !== "string";
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
119
133
  /** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
120
134
  export function serializeNote(meta, body) {
121
135
  const lines = [];
@@ -14,16 +14,14 @@ function assertDirectoryComponent(field, value) {
14
14
  export function snapshotNotesIdentity(value) {
15
15
  if (typeof value !== "object" || value === null || Array.isArray(value))
16
16
  throw new TypeError("notes context must be a plain object");
17
- const prototype = Object.getPrototypeOf(value);
18
- if (prototype !== Object.prototype && prototype !== null)
19
- throw new TypeError("notes context must be a plain object");
20
17
  const homeValue = requireString("home", value.home);
21
18
  const sessionId = requireString("sessionId", value.sessionId);
22
19
  const projectKey = requireString("projectKey", value.projectKey);
23
20
  const agent = requireString("agent", value.agent);
24
21
  const model = requireString("model", value.model);
25
22
  assertDirectoryComponent("sessionId", sessionId);
26
- assertDirectoryComponent("projectKey", projectKey);
23
+ if (!SLUG_PATTERN.test(projectKey))
24
+ throw new TypeError("notes context projectKey must be a canonical lowercase slug");
27
25
  if (!SLUG_PATTERN.test(agent))
28
26
  throw new TypeError("notes context agent must be a canonical lowercase slug");
29
27
  if (!SLUG_PATTERN.test(model))
@@ -1,11 +1,16 @@
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. */
4
5
  export declare const SLUG_PATTERN: RegExp;
5
6
  /** Slugify a caller-declared identity; identity is never inferred from note content. */
6
7
  export declare function slugify(value: string): string;
7
- /** `<basename(absGitRoot)-sha1(absGitRoot)[:8]>`, or the same formula over cwd with no git root. */
8
- export declare function projectKey(cwd: string): string;
8
+ /**
9
+ * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
10
+ * segment. Both the address decoder and the physical-path builder enforce it here, so a
11
+ * caller that reaches a path without going through an address still cannot escape a home.
12
+ */
13
+ export declare function assertVirtualPath(value: unknown): string;
9
14
  /** Absolute directory holding the per-session note homes. */
10
15
  export declare function sessionHomesRoot(home: string): string;
11
16
  /** Absolute directory holding one scope's notes. The identity's home is already resolved. */
@@ -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
  /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
6
6
  export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
7
7
  /** Slugify a caller-declared identity; identity is never inferred from note content. */
@@ -9,58 +9,20 @@ export function slugify(value) {
9
9
  const slug = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
10
10
  return slug.length > 0 ? slug : "root";
11
11
  }
12
- /** `<basename(absGitRoot)-sha1(absGitRoot)[:8]>`, or the same formula over cwd with no git root. */
13
- export function projectKey(cwd) {
14
- const absolute = resolve(cwd);
15
- const root = gitRoot(absolute) ?? absolute;
16
- const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
17
- return `${basename(root)}-${digest}`;
18
- }
19
12
  /**
20
- * Repository root behind one `.git` entry. A `.git` directory is the main checkout
21
- * itself. A `.git` file is a worktree or submodule pointer: a linked worktree names
22
- * `<main>/.git/worktrees/<name>` and resolves to `<main>`, so every worktree of one
23
- * repository shares one project identity. Submodules, bare repositories, and separate
24
- * git dirs keep the current directory.
13
+ * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
14
+ * segment. Both the address decoder and the physical-path builder enforce it here, so a
15
+ * caller that reaches a path without going through an address still cannot escape a home.
25
16
  */
26
- function repositoryRoot(dir) {
27
- let stats;
28
- try {
29
- stats = statSync(join(dir, ".git"));
30
- }
31
- catch {
32
- return dir;
33
- }
34
- if (stats.isDirectory())
35
- return dir;
36
- let pointer;
37
- try {
38
- pointer = readFileSync(join(dir, ".git"), "utf8");
39
- }
40
- catch {
41
- return dir;
42
- }
43
- const match = /^gitdir:\s*(.+)$/m.exec(pointer);
44
- if (!match)
45
- return dir;
46
- const parts = resolve(dir, match[1].trim()).split(sep);
47
- const worktrees = parts.lastIndexOf("worktrees");
48
- if (worktrees <= 0 || worktrees !== parts.length - 2)
49
- return dir;
50
- const common = parts.slice(0, worktrees).join(sep);
51
- return basename(common) === ".git" ? dirname(common) : dir;
52
- }
53
- /** Absolute repository root for cwd, walking upward until a directory holds a `.git` entry. */
54
- function gitRoot(cwd) {
55
- let dir = resolve(cwd);
56
- for (;;) {
57
- if (existsSync(join(dir, ".git")))
58
- return repositoryRoot(dir);
59
- const parent = dirname(dir);
60
- if (parent === dir)
61
- return undefined;
62
- dir = parent;
63
- }
17
+ export function assertVirtualPath(value) {
18
+ if (typeof value !== "string" || value.length === 0)
19
+ throw new NoteError("invalid_address", "The address is empty; give the note a path.");
20
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
21
+ throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
22
+ const parts = value.split("/");
23
+ if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
24
+ throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
25
+ return value;
64
26
  }
65
27
  /** Absolute directory holding the per-session note homes. */
66
28
  export function sessionHomesRoot(home) {
@@ -70,12 +32,12 @@ export function sessionHomesRoot(home) {
70
32
  export function scopeDir(scope, identity, who) {
71
33
  if (!["session", "project", "human", "agent", "model"].includes(scope))
72
34
  throw new TypeError("invalid notes scope");
73
- if (who !== undefined && (scope !== "agent" && scope !== "model" || !SLUG_PATTERN.test(who)))
74
- 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");
75
37
  if (scope === "human")
76
38
  return join(identity.home, "human");
77
39
  if (scope === "project")
78
- return join(identity.home, "project", identity.projectKey);
40
+ return join(identity.home, "project", who ?? identity.projectKey);
79
41
  if (scope === "agent")
80
42
  return join(identity.home, "agents", who ?? identity.agent);
81
43
  if (scope === "model")
@@ -105,9 +67,5 @@ export function noteFileName(vpath) {
105
67
  }
106
68
  /** Absolute file path for a virtual path in a scope. Callers validate the vpath first. */
107
69
  export function physicalPath(scope, vpath, identity, who) {
108
- if (typeof vpath !== "string" || vpath.length === 0 || vpath.includes("\0") || vpath.includes("\\") || vpath.startsWith("/"))
109
- throw new TypeError("path must be a safe virtual relative path");
110
- if (vpath.split("/").some((part) => part.length === 0 || part === "." || part === ".."))
111
- throw new TypeError("path contains an unsupported component");
112
70
  return join(scopeDir(scope, identity, who), ...noteFileName(vpath).split("/"));
113
71
  }
@@ -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;
@@ -0,0 +1,231 @@
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
+ function errno(error) {
6
+ return typeof error === "object" && error !== null ? error.code : undefined;
7
+ }
8
+ /** Normalize the small set of Git remote spellings used by ordinary repositories. */
9
+ export function normalizeRemote(value) {
10
+ let text = value.trim();
11
+ const scp = /^(?:[^/@]+)@([^:/]+):(.+)$/.exec(text);
12
+ if (scp)
13
+ text = `${scp[1].toLowerCase()}/${scp[2]}`;
14
+ else if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(text)) {
15
+ try {
16
+ const url = new URL(text);
17
+ const host = url.hostname.toLowerCase();
18
+ const port = url.port.length > 0 ? `:${url.port}` : "";
19
+ text = `${host}${port}${url.pathname}`;
20
+ }
21
+ catch {
22
+ text = text.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//, "").replace(/^[^/@]+@/, "");
23
+ }
24
+ }
25
+ else {
26
+ text = text.replace(/^[^/@]+@/, "");
27
+ const slash = text.indexOf("/");
28
+ if (slash > 0)
29
+ text = `${text.slice(0, slash).toLowerCase()}${text.slice(slash)}`;
30
+ }
31
+ text = text.replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
32
+ return text;
33
+ }
34
+ function canonicalRoot(cwd) {
35
+ const absolute = resolve(cwd);
36
+ const spelled = gitRoot(absolute) ?? absolute;
37
+ try {
38
+ return realpathSync(spelled);
39
+ }
40
+ catch {
41
+ return spelled;
42
+ }
43
+ }
44
+ function originRemote(root) {
45
+ let gitDir = join(root, ".git");
46
+ let raw;
47
+ try {
48
+ if (!statSync(gitDir).isDirectory()) {
49
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(gitDir, "utf8"));
50
+ if (!pointer)
51
+ return undefined;
52
+ gitDir = resolve(root, pointer[1].trim());
53
+ }
54
+ try {
55
+ gitDir = resolve(gitDir, readFileSync(join(gitDir, "commondir"), "utf8").trim());
56
+ }
57
+ catch (error) {
58
+ if (errno(error) !== "ENOENT")
59
+ throw error;
60
+ }
61
+ raw = readFileSync(join(gitDir, "config"), "utf8");
62
+ }
63
+ catch (error) {
64
+ if (errno(error) === "ENOENT")
65
+ return undefined;
66
+ throw error;
67
+ }
68
+ let origin = false;
69
+ for (const line of raw.split(/\r?\n/)) {
70
+ const section = /^\s*\[remote\s+"([^"]+)"\]\s*$/.exec(line);
71
+ if (section) {
72
+ origin = section[1] === "origin";
73
+ continue;
74
+ }
75
+ if (/^\s*\[/.test(line))
76
+ origin = false;
77
+ if (origin) {
78
+ const url = /^\s*url\s*=\s*(.*?)\s*$/.exec(line);
79
+ if (url)
80
+ return normalizeRemote(url[1].replace(/^"(.*)"$/, "$1")) || undefined;
81
+ }
82
+ }
83
+ return undefined;
84
+ }
85
+ function readMarker(dir) {
86
+ let raw;
87
+ try {
88
+ raw = readFileSync(join(dir, ".project"), "utf8");
89
+ }
90
+ catch (error) {
91
+ if (errno(error) === "ENOENT")
92
+ return undefined;
93
+ throw error;
94
+ }
95
+ try {
96
+ const value = JSON.parse(raw);
97
+ if (typeof value.id !== "string" || value.id.length === 0 || typeof value.path !== "string" || value.path.length === 0)
98
+ return undefined;
99
+ return { name: basename(dir), dir, id: value.id, path: value.path };
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ }
105
+ function projectRoot(home) {
106
+ return join(home, "project");
107
+ }
108
+ /** Read marked project homes. Unmarked legacy directories are deliberately omitted. */
109
+ export function projectHomes(home) {
110
+ const root = projectRoot(home);
111
+ let entries;
112
+ try {
113
+ entries = readdirSync(root, { withFileTypes: true });
114
+ }
115
+ catch (error) {
116
+ if (errno(error) === "ENOENT")
117
+ return [];
118
+ throw error;
119
+ }
120
+ return entries.filter(entry => entry.isDirectory()).map(entry => readMarker(join(root, entry.name))).filter((entry) => entry !== undefined).sort((a, b) => a.name.localeCompare(b.name));
121
+ }
122
+ function updateMarker(home, marker) {
123
+ const markerPath = join(home.dir, ".project");
124
+ const temp = `${markerPath}.${process.pid}.${randomUUID()}.tmp`;
125
+ try {
126
+ writeFileSync(temp, JSON.stringify(marker));
127
+ renameSync(temp, markerPath);
128
+ }
129
+ catch (error) {
130
+ try {
131
+ rmSync(temp, { force: true });
132
+ }
133
+ catch { /* Preserve the marker update failure. */ }
134
+ throw error;
135
+ }
136
+ return { ...home, ...marker };
137
+ }
138
+ /** Resolve and claim the readable home for one repository identity. */
139
+ export function resolveProjectHome(cwd, home) {
140
+ const root = canonicalRoot(cwd);
141
+ const remote = originRemote(root);
142
+ const id = remote ?? root;
143
+ const markerRoot = projectRoot(home);
144
+ mkdirSync(markerRoot, { recursive: true });
145
+ const homes = projectHomes(home);
146
+ let found = homes.find(candidate => candidate.id === id);
147
+ if (!found && remote) {
148
+ found = homes.find(candidate => candidate.id === root);
149
+ if (found)
150
+ found = updateMarker(found, { id: remote, path: root });
151
+ }
152
+ if (found) {
153
+ if (found.path !== root)
154
+ found = updateMarker(found, { id: found.id, path: root });
155
+ return found;
156
+ }
157
+ const base = slugify(basename(root));
158
+ // Existing unmarked homes are taken; only directories appearing after this scan can be raced.
159
+ const taken = new Set(readdirSync(markerRoot));
160
+ for (let suffix = 0;; suffix++) {
161
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
162
+ if (taken.has(name))
163
+ continue;
164
+ const dir = join(markerRoot, name);
165
+ try {
166
+ mkdirSync(dir, { recursive: true });
167
+ writeFileSync(join(dir, ".project"), JSON.stringify({ id, path: root }), { flag: "wx" });
168
+ return { name, dir, id, path: root };
169
+ }
170
+ catch (error) {
171
+ if (errno(error) === "EEXIST")
172
+ continue;
173
+ throw error;
174
+ }
175
+ }
176
+ }
177
+ /** Existing root discovery, including linked worktrees, without invoking Git. */
178
+ function gitRoot(cwd) {
179
+ let dir = resolve(cwd);
180
+ for (;;) {
181
+ if (existsSync(join(dir, ".git")))
182
+ return repositoryRoot(dir);
183
+ const parent = dirname(dir);
184
+ if (parent === dir)
185
+ return undefined;
186
+ dir = parent;
187
+ }
188
+ }
189
+ function repositoryRoot(dir) {
190
+ let stats;
191
+ try {
192
+ stats = statSync(join(dir, ".git"));
193
+ }
194
+ catch {
195
+ return dir;
196
+ }
197
+ if (stats.isDirectory())
198
+ return dir;
199
+ let pointer;
200
+ try {
201
+ pointer = readFileSync(join(dir, ".git"), "utf8");
202
+ }
203
+ catch {
204
+ return dir;
205
+ }
206
+ const match = /^gitdir:\s*(.+)$/m.exec(pointer);
207
+ if (!match)
208
+ return dir;
209
+ const parts = resolve(dir, match[1].trim()).split(sep);
210
+ const worktrees = parts.lastIndexOf("worktrees");
211
+ if (worktrees <= 0 || worktrees !== parts.length - 2)
212
+ return dir;
213
+ const common = parts.slice(0, worktrees).join(sep);
214
+ return basename(common) === ".git" ? dirname(common) : dir;
215
+ }
216
+ /** Display-only context for an explicitly named project home. */
217
+ export function projectReceipt(home, name) {
218
+ const project = readMarker(join(projectRoot(home), name));
219
+ if (!project)
220
+ return {};
221
+ const base = slugify(basename(project.path));
222
+ const siblings = projectHomes(home).filter(candidate => candidate.name !== name && slugify(basename(candidate.path)) === base);
223
+ return {
224
+ project_root: project.path,
225
+ ...(siblings.length === 0 ? {} : { project_siblings: siblings.map(({ name, path }) => ({ name, path })) }),
226
+ };
227
+ }
228
+ /** Names a project home, claiming it when the notes home has not seen this identity. */
229
+ export function projectKey(cwd, home) {
230
+ return resolveProjectHome(cwd, home).name;
231
+ }
@@ -1,6 +1,7 @@
1
1
  import { type NotesIdentity } from "./identity.js";
2
2
  import { type NoteMeta, type Origin } from "./frontmatter.js";
3
3
  import { type Scope } from "./paths.js";
4
+ import { type ProjectReceipt } from "./project-home.js";
4
5
  export type { NoteMeta, Origin, Scope };
5
6
  export type NoteRow = {
6
7
  address: string;
@@ -76,6 +77,7 @@ export type NoteRenameResult = {
76
77
  meta: NoteMeta;
77
78
  replacedCrumpledTarget: boolean;
78
79
  };
80
+ /** A home, or one unreadable note inside it, that a status-reporting query could not read. */
79
81
  export type NoteQueryStatus = {
80
82
  homesUnavailable: string[];
81
83
  };
@@ -83,11 +85,11 @@ export type NoteQueryResult<T> = {
83
85
  rows: T[];
84
86
  status: NoteQueryStatus;
85
87
  };
86
- /** Public identity resolved for an operation, never a filesystem path. */
88
+ /** Public note identity; named projects also carry their display root and sibling hints. */
87
89
  export declare function noteIdentity(identity: NotesIdentity, address: string): {
88
90
  address: string;
89
91
  project_key?: string;
90
- };
92
+ } & ProjectReceipt;
91
93
  /** Host-neutral, filesystem-backed notes API. */
92
94
  export interface NotesStore {
93
95
  write(address: string, content: string, options?: WriteOptions): Promise<NoteWriteResult>;