-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.mjs
More file actions
328 lines (291 loc) · 11.2 KB
/
Copy pathlib.mjs
File metadata and controls
328 lines (291 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// projectstore — shared helpers used by commands and hooks.
// Pure node, no external deps. Keep this single-file & dependency-free
// so plugin install does not require npm install.
import { readFileSync, writeFileSync, existsSync, readdirSync, statSync, mkdirSync, utimesSync, unlinkSync } from "node:fs";
import { join, dirname, basename, resolve } from "node:path";
import { hostname } from "node:os";
// ─── Paths ─────────────────────────────────────────────────────────────
export function projectRoot() {
return process.env.CLAUDE_PROJECT_DIR || process.cwd();
}
export function pluginRoot() {
return process.env.CLAUDE_PLUGIN_ROOT || dirname(dirname(new URL(import.meta.url).pathname));
}
export function configPath() {
return join(projectRoot(), ".claude", "projectstore.json");
}
// ─── Config ────────────────────────────────────────────────────────────
export function readConfig() {
const p = configPath();
if (!existsSync(p)) return null;
try {
return JSON.parse(readFileSync(p, "utf8"));
} catch (e) {
return null;
}
}
export function writeConfig(cfg) {
const p = configPath();
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, JSON.stringify(cfg, null, 2) + "\n", "utf8");
}
// ─── Layouts ───────────────────────────────────────────────────────────
export function loadLayout(name) {
const p = join(pluginRoot(), "scaffold", "layouts", `${name}.json`);
if (!existsSync(p)) {
throw new Error(`Layout not found: ${name} (expected at ${p})`);
}
return JSON.parse(readFileSync(p, "utf8"));
}
export function folderByKind(layout, kind) {
return layout.folders.find((f) => f.kind === kind) || null;
}
// ─── Templates ─────────────────────────────────────────────────────────
export function loadTemplate(lang, name) {
const p = join(pluginRoot(), "templates", lang, `${name}.md.tmpl`);
if (!existsSync(p)) {
throw new Error(`Template not found: templates/${lang}/${name}.md.tmpl`);
}
return readFileSync(p, "utf8");
}
export function renderTemplate(template, vars) {
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
if (key in vars) {
const v = vars[key];
if (Array.isArray(v)) return JSON.stringify(v);
return String(v);
}
return "";
});
}
// ─── Slug / numbering ──────────────────────────────────────────────────
export function slugify(s) {
return s
.toLowerCase()
.replace(/[^\w\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
}
export function nextNumber(dir, prefix, pad = 3) {
if (!existsSync(dir)) return String(1).padStart(pad, "0");
const rx = new RegExp(`^${prefix}(\\d+)`);
const nums = readdirSync(dir)
.map((n) => n.match(rx))
.filter(Boolean)
.map((m) => parseInt(m[1], 10));
const next = (nums.length ? Math.max(...nums) : 0) + 1;
return String(next).padStart(pad, "0");
}
export function today() {
return new Date().toISOString().slice(0, 10);
}
// ─── Vault map (for SessionStart hook) ─────────────────────────────────
export function buildVaultMap(cfg) {
const lines = [];
const vault = cfg.vault_path;
if (!existsSync(vault)) {
return `# projectstore: vault not found at ${vault}\n`;
}
lines.push(`# Projectstore vault: ${vault}`);
lines.push(`# Layout: ${cfg.layout}`);
lines.push("");
const rootReadme = join(vault, "README.md");
if (existsSync(rootReadme)) {
lines.push(readFileSync(rootReadme, "utf8"));
}
if ((cfg.inject_depth ?? 1) >= 1) {
const layout = loadLayout(cfg.layout);
for (const folder of layout.folders) {
const readme = join(vault, folder.path, "README.md");
if (existsSync(readme)) {
lines.push(`\n---\n\n## ${folder.path}/\n\n${readFileSync(readme, "utf8")}`);
}
}
}
if ((cfg.inject_depth ?? 1) >= 2) {
const layout = loadLayout(cfg.layout);
lines.push(`\n---\n\n## File index (depth 2)\n`);
for (const folder of layout.folders) {
const dir = join(vault, folder.path);
if (!existsSync(dir)) continue;
lines.push(`\n### ${folder.path}/\n`);
const files = readdirSync(dir).filter((n) => n.endsWith(".md") && n !== "README.md");
for (const f of files) {
lines.push(`- \`${folder.path}/${f}\``);
}
}
}
return lines.join("\n");
}
// ─── Session awareness (layer 2 — multi-Claude coordination) ──────────
//
// Each Claude Code session registers itself in
// <vault>/.projectstore/sessions/<id>.json, where <id> is Claude's own
// session_id (from hook stdin input). Two Claude instances in the same
// project therefore get distinct files. Other sessions reading the vault
// can detect each other and warn the agent to avoid topic / numbering
// collisions. mtime is used as a liveness proxy: a session whose file
// has not been touched in 30 minutes is considered idle; >24h => stale,
// removed on next SessionStart.
export function sessionsDir(vault) {
return join(vault, ".projectstore", "sessions");
}
export function sessionFilePath(vault, sessionId) {
return join(sessionsDir(vault), `${sessionId}.json`);
}
// Read Claude's own session_id from hook stdin JSON. Returns null on any
// parse error — callers must no-op silently in that case.
export function readStdinJson() {
try {
const raw = readFileSync(0, "utf8").trim();
if (!raw) return null;
return JSON.parse(raw);
} catch {
return null;
}
}
export function ensureSessionsDir(vault) {
const dir = sessionsDir(vault);
mkdirSync(dir, { recursive: true });
// Make sure no session metadata leaks into git, regardless of where the
// vault lives. A nested .gitignore inside .projectstore/ is the simplest
// way to handle this idempotently.
const gi = join(vault, ".projectstore", ".gitignore");
if (!existsSync(gi)) {
writeFileSync(gi, "# projectstore — runtime data, do not commit\n*\n", "utf8");
}
return dir;
}
// Idempotent: preserves started_at and recent_activity if the session file
// already exists (e.g. when SessionStart fires after touch-session has
// already bootstrapped the record).
export function writeSession(vault, sessionId, projectRoot) {
ensureSessionsDir(vault);
const path = sessionFilePath(vault, sessionId);
let existing = null;
if (existsSync(path)) {
try { existing = JSON.parse(readFileSync(path, "utf8")); } catch {}
}
const data = {
id: sessionId,
started_at: existing?.started_at || new Date().toISOString(),
project_root: projectRoot,
host: hostname(),
pid: process.pid,
recent_activity: Array.isArray(existing?.recent_activity) ? existing.recent_activity : [],
};
writeFileSync(path, JSON.stringify(data, null, 2), "utf8");
return path;
}
export function touchSession(vault, sessionId) {
const p = sessionFilePath(vault, sessionId);
if (!existsSync(p)) return false;
const now = new Date();
try {
utimesSync(p, now, now);
return true;
} catch {
return false;
}
}
export function readActiveSessions(vault, currentSessionId, maxAgeMinutes = 30) {
const dir = sessionsDir(vault);
if (!existsSync(dir)) return [];
const cutoff = Date.now() - maxAgeMinutes * 60 * 1000;
const out = [];
for (const name of readdirSync(dir)) {
if (!name.endsWith(".json")) continue;
const path = join(dir, name);
let stat;
try { stat = statSync(path); } catch { continue; }
if (stat.mtimeMs < cutoff) continue;
let data;
try { data = JSON.parse(readFileSync(path, "utf8")); } catch { continue; }
if (data.id === currentSessionId) continue;
out.push({ ...data, last_active: stat.mtime });
}
return out;
}
export function cleanupStaleSessions(vault, maxAgeHours = 24) {
const dir = sessionsDir(vault);
if (!existsSync(dir)) return 0;
const cutoff = Date.now() - maxAgeHours * 60 * 60 * 1000;
let removed = 0;
for (const name of readdirSync(dir)) {
if (!name.endsWith(".json")) continue;
const path = join(dir, name);
try {
if (statSync(path).mtimeMs < cutoff) {
unlinkSync(path);
removed++;
}
} catch {}
}
return removed;
}
// One-shot migration helper: delete .claude/.projectstore-session-id left
// behind by v0.3 – v0.5 (file-based per-project session id). Safe to call
// on every session start; no-op if the file is absent. Kept until v0.7.
export function removeLegacySessionIdFile(projectDir) {
const p = join(projectDir || projectRoot(), ".claude", ".projectstore-session-id");
if (existsSync(p)) {
try { unlinkSync(p); } catch {}
}
}
// ─── Session activity log (for PreCompact survival packet) ─────────────
//
// Each session file may carry a `recent_activity` array, populated by
// touch-session.mjs from PreToolUse events. Capped at 50 entries, deduped
// by path (latest tool/timestamp wins). Used by hooks/pre-compact.mjs.
const ACTIVITY_CAP = 50;
export function appendActivity(vault, sessionId, filePath, toolName) {
const sp = sessionFilePath(vault, sessionId);
if (!existsSync(sp)) return false;
let data;
try {
data = JSON.parse(readFileSync(sp, "utf8"));
} catch {
return false;
}
const recent = Array.isArray(data.recent_activity) ? data.recent_activity : [];
const filtered = recent.filter((e) => e && e.path !== filePath);
filtered.unshift({ path: filePath, tool: toolName, at: new Date().toISOString() });
data.recent_activity = filtered.slice(0, ACTIVITY_CAP);
try {
writeFileSync(sp, JSON.stringify(data, null, 2));
return true;
} catch {
return false;
}
}
export function readSessionActivity(vault, sessionId) {
const sp = sessionFilePath(vault, sessionId);
if (!existsSync(sp)) return [];
try {
const data = JSON.parse(readFileSync(sp, "utf8"));
return Array.isArray(data.recent_activity) ? data.recent_activity : [];
} catch {
return [];
}
}
export function isInsideVault(filePath, vaultPath) {
if (!filePath || !vaultPath) return false;
const norm = filePath.endsWith("/") ? filePath.slice(0, -1) : filePath;
return norm === vaultPath || norm.startsWith(vaultPath + "/");
}
// ─── Frontmatter parsing (minimal) ─────────────────────────────────────
export function parseFrontmatter(md) {
const m = md.match(/^---\n([\s\S]*?)\n---/);
if (!m) return { data: {}, body: md };
const data = {};
for (const line of m[1].split("\n")) {
const kv = line.match(/^(\w+):\s*(.*)$/);
if (!kv) continue;
let v = kv[2].trim();
if (v === "null") v = null;
else if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1);
data[kv[1]] = v;
}
return { data, body: md.slice(m[0].length) };
}