notesoup 0.0.0-stage → 0.39.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.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +21 -0
- package/dist/src/boot/text.js +52 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +151 -0
- package/dist/src/history/history.js +195 -0
- package/dist/src/history/query.d.ts +75 -0
- package/dist/src/history/query.js +143 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +104 -0
- package/dist/src/notes/store.js +478 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +10 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +11 -0
- package/dist/src/pi/tool-names.js +11 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +67 -0
- package/dist/src/tools/history.js +251 -0
- package/dist/src/tools/notes.d.ts +282 -0
- package/dist/src/tools/notes.js +378 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +79 -0
- package/dist/src/tools/result.js +130 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +368 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +556 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +300 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +497 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +528 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +88 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9324 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +241 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +66 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +270 -0
- package/src/history/query.ts +147 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +497 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +12 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +13 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +273 -0
- package/src/tools/notes.ts +394 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +169 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import type { Scope } from "./paths.js";
|
|
2
|
+
|
|
3
|
+
export type Origin = "user" | "self" | "external";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Harness-owned note metadata. The eight required keys are always written; the four optional
|
|
7
|
+
* sleep-shift keys survive this layer untouched when present. `[key: string]: unknown` carries
|
|
8
|
+
* any frontmatter key this layer does not know, preserved verbatim across rewrites.
|
|
9
|
+
*/
|
|
10
|
+
export type NoteMeta = {
|
|
11
|
+
scope: Scope;
|
|
12
|
+
origin: Origin;
|
|
13
|
+
/** Present only while the note is in the wastebasket; serialized as an ISO timestamp. */
|
|
14
|
+
crumpledAt?: string;
|
|
15
|
+
createdAt: number;
|
|
16
|
+
updatedAt: number;
|
|
17
|
+
lastAccessed: number;
|
|
18
|
+
accessCount: number;
|
|
19
|
+
sourceWindow?: string;
|
|
20
|
+
supersedes?: string;
|
|
21
|
+
recurrenceCount?: number;
|
|
22
|
+
recurrenceWindows?: string[];
|
|
23
|
+
/** Project ownership on newly-created session notes; legacy/invalid values are preserved as-is. */
|
|
24
|
+
project?: unknown;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const SCOPES: readonly Scope[] = ["session", "project", "human", "agent", "model"];
|
|
29
|
+
const ORIGINS: readonly Origin[] = ["user", "self", "external"];
|
|
30
|
+
const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"] as const;
|
|
31
|
+
/** Emission order, exactly the Design's key list. */
|
|
32
|
+
const KNOWN_KEYS = ["origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"] as const;
|
|
33
|
+
|
|
34
|
+
const pad2 = (value: number) => String(value).padStart(2, "0");
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Format epoch milliseconds as an ISO 8601 string in the host's local time zone with an
|
|
38
|
+
* explicit numeric offset (e.g. 2026-09-15T17:31:45.392+08:00). A UTC host renders
|
|
39
|
+
* "+00:00"; the "Z" designator is never used, and Date.parse round-trips the value.
|
|
40
|
+
*/
|
|
41
|
+
export function localIso(epochMs: number): string {
|
|
42
|
+
const date = new Date(epochMs);
|
|
43
|
+
const offsetMinutes = -date.getTimezoneOffset();
|
|
44
|
+
const absOffset = Math.abs(offsetMinutes);
|
|
45
|
+
const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
|
|
46
|
+
const wallClock = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, "0")}`;
|
|
47
|
+
return `${wallClock}${offset}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isScope(value: unknown): value is Scope {
|
|
51
|
+
return typeof value === "string" && (SCOPES as readonly string[]).includes(value);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function isOrigin(value: unknown): value is Origin {
|
|
55
|
+
return typeof value === "string" && (ORIGINS as readonly string[]).includes(value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function toEpoch(value: unknown, fallback: number): number {
|
|
59
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
60
|
+
if (typeof value === "string") {
|
|
61
|
+
const parsed = Date.parse(value);
|
|
62
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
63
|
+
}
|
|
64
|
+
return fallback;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A frontmatter scalar encoded as JSON, falling back to a plain string for hand-written YAML. */
|
|
68
|
+
function parseScalar(text: string): unknown {
|
|
69
|
+
const trimmed = text.trim();
|
|
70
|
+
if (trimmed === "") return "";
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(trimmed);
|
|
73
|
+
} catch {
|
|
74
|
+
if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) return trimmed.slice(1, -1);
|
|
75
|
+
return trimmed;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Split raw file text into its frontmatter fields and body. When the file does not open with
|
|
81
|
+
* a closed `---` block, the whole text is body and the field map is empty.
|
|
82
|
+
*/
|
|
83
|
+
function parseFrontmatter(raw: string): { fields: Record<string, unknown>; body: string } {
|
|
84
|
+
const stripped = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
|
|
85
|
+
const lines = stripped.split("\n").map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line));
|
|
86
|
+
if (lines[0]?.trim() !== "---") return { fields: {}, body: raw };
|
|
87
|
+
let close = -1;
|
|
88
|
+
for (let index = 1; index < lines.length; index++) {
|
|
89
|
+
if (lines[index]?.trim() === "---") {
|
|
90
|
+
close = index;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (close === -1) return { fields: {}, body: raw };
|
|
95
|
+
const fields = Object.create(null) as Record<string, unknown>;
|
|
96
|
+
for (let index = 1; index < close; index++) {
|
|
97
|
+
const line = lines[index]!;
|
|
98
|
+
const match = /^([A-Za-z_][A-Za-z0-9_-]*):(.*)$/.exec(line);
|
|
99
|
+
if (!match) continue;
|
|
100
|
+
const key = match[1]!;
|
|
101
|
+
const rest = match[2]!;
|
|
102
|
+
if (rest.trim() === "") {
|
|
103
|
+
// A bare key opens a block sequence of `- item` lines, the only multi-line shape we parse.
|
|
104
|
+
const items: unknown[] = [];
|
|
105
|
+
while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1]!)) {
|
|
106
|
+
index++;
|
|
107
|
+
items.push(parseScalar(lines[index]!.replace(/^\s*-\s+/, "")));
|
|
108
|
+
}
|
|
109
|
+
fields[key] = items;
|
|
110
|
+
} else {
|
|
111
|
+
fields[key] = parseScalar(rest);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const rest = lines.slice(close + 1);
|
|
115
|
+
if (rest[0] === "") rest.shift();
|
|
116
|
+
return { fields, body: rest.join("\n") };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Parse a note file. Missing known keys take the defaults (accessCount 0, timestamps now);
|
|
121
|
+
* crumpledAt stays absent until explicitly set, and unknown keys survive untouched.
|
|
122
|
+
*/
|
|
123
|
+
export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body: string } {
|
|
124
|
+
const { fields, body } = parseFrontmatter(raw);
|
|
125
|
+
const meta = { ...fields } as Record<string, unknown>;
|
|
126
|
+
// scope is a legacy on-disk field: store callers derive it from the file's home and
|
|
127
|
+
// overwrite it after parsing, so an absent or outdated value just falls back.
|
|
128
|
+
meta.scope = isScope(meta.scope) ? meta.scope : "session";
|
|
129
|
+
meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
|
|
130
|
+
for (const key of TIMESTAMP_KEYS) meta[key] = toEpoch(meta[key], now);
|
|
131
|
+
meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
|
|
132
|
+
return { meta: meta as NoteMeta, body };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise. */
|
|
136
|
+
function yamlScalar(value: unknown): string {
|
|
137
|
+
if (typeof value === "string") {
|
|
138
|
+
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;
|
|
140
|
+
}
|
|
141
|
+
return JSON.stringify(value);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
|
|
145
|
+
export function serializeNote(meta: NoteMeta, body: string): string {
|
|
146
|
+
const lines: string[] = [];
|
|
147
|
+
for (const key of KNOWN_KEYS) {
|
|
148
|
+
const value = meta[key];
|
|
149
|
+
if (value === undefined) continue;
|
|
150
|
+
if ((TIMESTAMP_KEYS as readonly string[]).includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value as number))}`);
|
|
151
|
+
else lines.push(`${key}: ${yamlScalar(value)}`);
|
|
152
|
+
}
|
|
153
|
+
for (const key of Object.keys(meta)) {
|
|
154
|
+
// scope is a legacy on-disk field. Store callers derive it from the home's location,
|
|
155
|
+
// but serialization intentionally drops it on the next write.
|
|
156
|
+
if (key === "scope" || (KNOWN_KEYS as readonly string[]).includes(key)) continue;
|
|
157
|
+
if (meta[key] === undefined) continue;
|
|
158
|
+
lines.push(`${key}: ${yamlScalar(meta[key])}`);
|
|
159
|
+
}
|
|
160
|
+
return `---\n${lines.join("\n")}\n---\n\n${body}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Strip a leading frontmatter block from user content, so a note body is pure content. */
|
|
164
|
+
export function stripLeadingFrontmatter(content: string): string {
|
|
165
|
+
return parseFrontmatter(content).body;
|
|
166
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** The store's own errno classification: a filesystem refusal, never a Node `ERR_*` code. */
|
|
2
|
+
export function isFilesystemError(error: unknown): boolean {
|
|
3
|
+
const code = typeof error === "object" && error !== null ? (error as NodeJS.ErrnoException).code : undefined;
|
|
4
|
+
return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
|
|
5
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { SLUG_PATTERN } from "./paths.js";
|
|
3
|
+
|
|
4
|
+
/** Explicit, host-neutral identity for one notes store. */
|
|
5
|
+
export type NotesIdentity = Readonly<{
|
|
6
|
+
home: string;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
projectKey: string;
|
|
9
|
+
agent: string;
|
|
10
|
+
model: string;
|
|
11
|
+
}>;
|
|
12
|
+
|
|
13
|
+
function requireString(field: string, value: unknown): string {
|
|
14
|
+
if (typeof value !== "string" || value.length === 0) throw new TypeError(`notes context ${field} must be a non-empty string`);
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function assertDirectoryComponent(field: string, value: string): void {
|
|
19
|
+
if (value === "." || value === ".." || /[\\/\0:]/.test(value)) {
|
|
20
|
+
throw new TypeError(`notes context ${field} must be a safe single directory component`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Validate and snapshot caller identity; no global or environment defaults are consulted. */
|
|
25
|
+
export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
|
|
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
|
+
const homeValue = requireString("home", value.home);
|
|
30
|
+
const sessionId = requireString("sessionId", value.sessionId);
|
|
31
|
+
const projectKey = requireString("projectKey", value.projectKey);
|
|
32
|
+
const agent = requireString("agent", value.agent);
|
|
33
|
+
const model = requireString("model", value.model);
|
|
34
|
+
assertDirectoryComponent("sessionId", sessionId);
|
|
35
|
+
assertDirectoryComponent("projectKey", projectKey);
|
|
36
|
+
if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
|
|
37
|
+
if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
|
|
38
|
+
const home = resolve(homeValue);
|
|
39
|
+
return Object.freeze({ home, sessionId, projectKey, agent, model });
|
|
40
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export { createNotesStore, noteIdentity } from "./store.js";
|
|
2
|
+
export { NoteError, type NoteErrorCode } from "./errors.js";
|
|
3
|
+
export { projectKey, slugify } from "./paths.js";
|
|
4
|
+
export type { NotesIdentity } from "./identity.js";
|
|
5
|
+
export type {
|
|
6
|
+
EditOperation,
|
|
7
|
+
EditOptions,
|
|
8
|
+
NoteChange,
|
|
9
|
+
NoteEditResult,
|
|
10
|
+
NoteMatch,
|
|
11
|
+
NoteMeta,
|
|
12
|
+
NoteQueryResult,
|
|
13
|
+
NoteQueryStatus,
|
|
14
|
+
NoteReadResult,
|
|
15
|
+
NoteRenameResult,
|
|
16
|
+
NoteRow,
|
|
17
|
+
NoteSearchRow,
|
|
18
|
+
NoteWriteResult,
|
|
19
|
+
NotesQuery,
|
|
20
|
+
NotesStore,
|
|
21
|
+
Origin,
|
|
22
|
+
Scope,
|
|
23
|
+
WriteOptions,
|
|
24
|
+
} from "./store.js";
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { readdir } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
5
|
+
import type { NotesIdentity } from "./identity.js";
|
|
6
|
+
|
|
7
|
+
export type Scope = "session" | "project" | "human" | "agent" | "model";
|
|
8
|
+
|
|
9
|
+
/** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
|
|
10
|
+
export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
11
|
+
|
|
12
|
+
/** Slugify a caller-declared identity; identity is never inferred from note content. */
|
|
13
|
+
export function slugify(value: string): string {
|
|
14
|
+
const slug = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
15
|
+
return slug.length > 0 ? slug : "root";
|
|
16
|
+
}
|
|
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
|
+
/**
|
|
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.
|
|
32
|
+
*/
|
|
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
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Absolute directory holding the per-session note homes. */
|
|
68
|
+
export function sessionHomesRoot(home: string): string {
|
|
69
|
+
return join(home, "pi", "session");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Absolute directory holding one scope's notes. The identity's home is already resolved. */
|
|
73
|
+
export function scopeDir(scope: Scope, identity: NotesIdentity, who?: string): string {
|
|
74
|
+
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");
|
|
76
|
+
if (scope === "human") return join(identity.home, "human");
|
|
77
|
+
if (scope === "project") return join(identity.home, "project", identity.projectKey);
|
|
78
|
+
if (scope === "agent") return join(identity.home, "agents", who ?? identity.agent);
|
|
79
|
+
if (scope === "model") return join(identity.home, "models", who ?? identity.model);
|
|
80
|
+
return join(sessionHomesRoot(identity.home), identity.sessionId);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Every existing home directory of the agents/ or models/ namespace, as names. */
|
|
84
|
+
export async function namespaceSlugs(namespace: "agents" | "models", home: string): Promise<string[]> {
|
|
85
|
+
try {
|
|
86
|
+
return (await readdir(join(home, namespace), { withFileTypes: true }))
|
|
87
|
+
.filter((entry) => entry.isDirectory())
|
|
88
|
+
.map((entry) => entry.name)
|
|
89
|
+
.sort();
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Notes are markdown files: a virtual path without an `.md` suffix gains one, an explicit
|
|
98
|
+
* `.md` is kept as-is, so `a/b` and `a/b.md` name the same physical file.
|
|
99
|
+
*/
|
|
100
|
+
export function noteFileName(vpath: string): string {
|
|
101
|
+
return vpath.endsWith(".md") ? vpath : `${vpath}.md`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Absolute file path for a virtual path in a scope. Callers validate the vpath first. */
|
|
105
|
+
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
|
+
return join(scopeDir(scope, identity, who), ...noteFileName(vpath).split("/"));
|
|
109
|
+
}
|