joycraft 0.7.10 → 0.7.12
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/README.md +25 -6
- package/dist/{chunk-RRMO5FBO.js → chunk-BZW5DR3O.js} +7 -3
- package/dist/chunk-BZW5DR3O.js.map +1 -0
- package/dist/{chunk-VU7KVQNL.js → chunk-DSVGHVYM.js} +26 -26
- package/dist/chunk-DSVGHVYM.js.map +1 -0
- package/dist/chunk-OAC5CVHJ.js +407 -0
- package/dist/chunk-OAC5CVHJ.js.map +1 -0
- package/dist/{chunk-ONGWPA4M.js → chunk-Q2ZQ6RGD.js} +110 -5
- package/dist/chunk-Q2ZQ6RGD.js.map +1 -0
- package/dist/cli.js +16 -4
- package/dist/cli.js.map +1 -1
- package/dist/{init-OJTXCK42.js → init-J5Q6RX3K.js} +122 -13
- package/dist/init-J5Q6RX3K.js.map +1 -0
- package/dist/{init-autofix-LYKPMI4J.js → init-autofix-YCSDK5ZR.js} +2 -2
- package/dist/telemetry-store-X7K5NYWD.js +14 -0
- package/dist/telemetry-store-X7K5NYWD.js.map +1 -0
- package/dist/{upgrade-USXMQXG6.js → upgrade-AHUSQZEQ.js} +27 -7
- package/dist/upgrade-AHUSQZEQ.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-ONGWPA4M.js.map +0 -1
- package/dist/chunk-RRMO5FBO.js.map +0 -1
- package/dist/chunk-VU7KVQNL.js.map +0 -1
- package/dist/init-OJTXCK42.js.map +0 -1
- package/dist/upgrade-USXMQXG6.js.map +0 -1
- /package/dist/{init-autofix-LYKPMI4J.js.map → init-autofix-YCSDK5ZR.js.map} +0 -0
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/telemetry-store.ts
|
|
4
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
|
|
5
|
+
import { dirname, join as join2 } from "path";
|
|
6
|
+
|
|
7
|
+
// src/telemetry.ts
|
|
8
|
+
import { existsSync, readdirSync, readFileSync } from "fs";
|
|
9
|
+
import { join, relative, isAbsolute, sep } from "path";
|
|
10
|
+
var KNOWLEDGE_PREFIXES = ["docs/context/", "docs/discoveries/", "docs/reference/"];
|
|
11
|
+
var KNOWLEDGE_FILES = ["AGENTS.md", "CLAUDE.md"];
|
|
12
|
+
function isKnowledgeLayerPath(relPath) {
|
|
13
|
+
if (KNOWLEDGE_FILES.includes(relPath)) return true;
|
|
14
|
+
return KNOWLEDGE_PREFIXES.some((prefix) => relPath.startsWith(prefix) && relPath.length > prefix.length);
|
|
15
|
+
}
|
|
16
|
+
var MANDATING_SKILLS = {
|
|
17
|
+
"joycraft-session-end": (p) => p.startsWith("docs/context/") || p.startsWith("docs/discoveries/"),
|
|
18
|
+
"joycraft-add-fact": (p) => p.startsWith("docs/context/"),
|
|
19
|
+
"joycraft-optimize": () => true
|
|
20
|
+
};
|
|
21
|
+
function isMandated(activeSkill, relPath) {
|
|
22
|
+
if (!activeSkill) return false;
|
|
23
|
+
const predicate = MANDATING_SKILLS[activeSkill];
|
|
24
|
+
return predicate ? predicate(relPath) : false;
|
|
25
|
+
}
|
|
26
|
+
function parseJson(line) {
|
|
27
|
+
const trimmed = line.trim();
|
|
28
|
+
if (!trimmed) return null;
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(trimmed);
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function result(ops, sessionId, skill) {
|
|
36
|
+
if (ops.length === 0 && !sessionId && !skill) return null;
|
|
37
|
+
return { ops, sessionId, skill };
|
|
38
|
+
}
|
|
39
|
+
var CLAUDE_READ_TOOLS = /* @__PURE__ */ new Set(["Read", "NotebookRead"]);
|
|
40
|
+
var CLAUDE_WRITE_TOOLS = /* @__PURE__ */ new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
|
|
41
|
+
function parseClaudeSessionLine(line) {
|
|
42
|
+
const record2 = parseJson(line);
|
|
43
|
+
if (!record2 || typeof record2 !== "object") return null;
|
|
44
|
+
const sessionId = typeof record2.sessionId === "string" ? record2.sessionId : null;
|
|
45
|
+
const content = record2.message?.content;
|
|
46
|
+
const ops = [];
|
|
47
|
+
let skill = null;
|
|
48
|
+
if (Array.isArray(content)) {
|
|
49
|
+
for (const block of content) {
|
|
50
|
+
if (!block || typeof block !== "object" || block.type !== "tool_use") continue;
|
|
51
|
+
const name = block.name;
|
|
52
|
+
if (name === "Skill") {
|
|
53
|
+
const invoked = block.input?.skill;
|
|
54
|
+
if (typeof invoked === "string") skill = invoked;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const filePath = block.input?.file_path;
|
|
58
|
+
if (typeof filePath !== "string" || !filePath) continue;
|
|
59
|
+
if (CLAUDE_READ_TOOLS.has(name)) ops.push({ kind: "read", path: filePath });
|
|
60
|
+
else if (CLAUDE_WRITE_TOOLS.has(name)) ops.push({ kind: "write", path: filePath });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return result(ops, sessionId, skill);
|
|
64
|
+
}
|
|
65
|
+
var PI_READ_TOOLS = /* @__PURE__ */ new Set(["read"]);
|
|
66
|
+
var PI_WRITE_TOOLS = /* @__PURE__ */ new Set(["write", "edit", "multi_edit"]);
|
|
67
|
+
var PI_SKILL_RE = /^\s*\/skill:([A-Za-z0-9._-]+)/;
|
|
68
|
+
function parsePiSessionLine(line) {
|
|
69
|
+
const record2 = parseJson(line);
|
|
70
|
+
if (!record2 || typeof record2 !== "object") return null;
|
|
71
|
+
if (record2.type === "session") {
|
|
72
|
+
const id = typeof record2.id === "string" ? record2.id : null;
|
|
73
|
+
return result([], id, null);
|
|
74
|
+
}
|
|
75
|
+
if (record2.type !== "message") return null;
|
|
76
|
+
const message = record2.message;
|
|
77
|
+
const content = message?.content;
|
|
78
|
+
const ops = [];
|
|
79
|
+
let skill = null;
|
|
80
|
+
if (Array.isArray(content)) {
|
|
81
|
+
for (const block of content) {
|
|
82
|
+
if (!block || typeof block !== "object") continue;
|
|
83
|
+
if (block.type === "text" && message?.role === "user" && typeof block.text === "string") {
|
|
84
|
+
const match = block.text.match(PI_SKILL_RE);
|
|
85
|
+
if (match) skill = match[1];
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (block.type !== "toolCall") continue;
|
|
89
|
+
const name = block.name;
|
|
90
|
+
const args = block.arguments;
|
|
91
|
+
if (name === "batch_read" && Array.isArray(args?.o)) {
|
|
92
|
+
for (const entry of args.o) {
|
|
93
|
+
if (entry && typeof entry === "object" && typeof entry.p === "string" && entry.p) {
|
|
94
|
+
ops.push({ kind: entry.o === "write" || entry.o === "edit" ? "write" : "read", path: entry.p });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const filePath = args?.path;
|
|
100
|
+
if (typeof filePath !== "string" || !filePath) continue;
|
|
101
|
+
if (PI_READ_TOOLS.has(name)) ops.push({ kind: "read", path: filePath });
|
|
102
|
+
else if (PI_WRITE_TOOLS.has(name)) ops.push({ kind: "write", path: filePath });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return result(ops, null, skill);
|
|
106
|
+
}
|
|
107
|
+
var CODEX_READ_COMMANDS = /* @__PURE__ */ new Set(["cat", "head", "tail", "sed", "grep", "less", "more"]);
|
|
108
|
+
function tokenizeShell(cmd) {
|
|
109
|
+
const tokens = [];
|
|
110
|
+
let current = "";
|
|
111
|
+
let started = false;
|
|
112
|
+
let quote = null;
|
|
113
|
+
for (const ch of cmd) {
|
|
114
|
+
if (quote) {
|
|
115
|
+
if (ch === quote) quote = null;
|
|
116
|
+
else current += ch;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (ch === '"' || ch === "'") {
|
|
120
|
+
quote = ch;
|
|
121
|
+
started = true;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (/\s/.test(ch)) {
|
|
125
|
+
if (started) tokens.push(current);
|
|
126
|
+
current = "";
|
|
127
|
+
started = false;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
current += ch;
|
|
131
|
+
started = true;
|
|
132
|
+
}
|
|
133
|
+
if (quote) return null;
|
|
134
|
+
if (started) tokens.push(current);
|
|
135
|
+
return tokens;
|
|
136
|
+
}
|
|
137
|
+
function opsFromSegment(tokens) {
|
|
138
|
+
if (tokens.length === 0) return [];
|
|
139
|
+
if (tokens.some((t) => t.includes("$") || t.includes("`"))) return [];
|
|
140
|
+
const writes = [];
|
|
141
|
+
const args = [];
|
|
142
|
+
for (let i = 1; i < tokens.length; i++) {
|
|
143
|
+
const token = tokens[i];
|
|
144
|
+
const redirect = token.match(/^\d*(>{1,2})(.*)$/);
|
|
145
|
+
if (redirect) {
|
|
146
|
+
const target = redirect[2] || tokens[++i];
|
|
147
|
+
if (target) writes.push(target);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (!token.startsWith("-")) args.push(token);
|
|
151
|
+
}
|
|
152
|
+
const ops = [];
|
|
153
|
+
const command = tokens[0];
|
|
154
|
+
if (CODEX_READ_COMMANDS.has(command)) {
|
|
155
|
+
const paths = command === "grep" || command === "sed" ? args.slice(1) : args;
|
|
156
|
+
for (const path of paths) ops.push({ kind: "read", path });
|
|
157
|
+
}
|
|
158
|
+
for (const path of writes) ops.push({ kind: "write", path });
|
|
159
|
+
return ops;
|
|
160
|
+
}
|
|
161
|
+
function parseCodexSessionLine(line) {
|
|
162
|
+
const record2 = parseJson(line);
|
|
163
|
+
if (!record2 || typeof record2 !== "object") return null;
|
|
164
|
+
if (record2.type === "session_meta") {
|
|
165
|
+
const payload2 = record2.payload;
|
|
166
|
+
const id = typeof payload2?.id === "string" ? payload2.id : null;
|
|
167
|
+
const cwd = typeof payload2?.cwd === "string" ? payload2.cwd : void 0;
|
|
168
|
+
if (!id && !cwd) return null;
|
|
169
|
+
return { ops: [], sessionId: id, skill: null, cwd };
|
|
170
|
+
}
|
|
171
|
+
const payload = record2.payload;
|
|
172
|
+
if (record2.type !== "response_item" || payload?.type !== "function_call") return null;
|
|
173
|
+
if (payload.name !== "exec_command" && payload.name !== "shell") return null;
|
|
174
|
+
const parsedArgs = typeof payload.arguments === "string" ? parseJson(payload.arguments) : payload.arguments;
|
|
175
|
+
const cmd = parsedArgs?.cmd ?? (Array.isArray(parsedArgs?.command) ? parsedArgs.command.join(" ") : null);
|
|
176
|
+
if (typeof cmd !== "string" || !cmd) return null;
|
|
177
|
+
if (/\b(for|while|if|do|done|fi)\b/.test(cmd)) return result([], null, null);
|
|
178
|
+
const ops = [];
|
|
179
|
+
for (const segment of cmd.split(/\||&&|;/)) {
|
|
180
|
+
const tokens = tokenizeShell(segment.trim());
|
|
181
|
+
if (!tokens) continue;
|
|
182
|
+
ops.push(...opsFromSegment(tokens));
|
|
183
|
+
}
|
|
184
|
+
return result(ops, null, null);
|
|
185
|
+
}
|
|
186
|
+
function encodedCwd(projectDir) {
|
|
187
|
+
return projectDir.replace(/\//g, "-");
|
|
188
|
+
}
|
|
189
|
+
function defaultClaudeTranscriptDir(projectDir) {
|
|
190
|
+
const home = process.env.HOME ?? "";
|
|
191
|
+
return join(home, ".claude", "projects", encodedCwd(projectDir));
|
|
192
|
+
}
|
|
193
|
+
function defaultPiTranscriptDir(projectDir) {
|
|
194
|
+
const home = process.env.HOME ?? "";
|
|
195
|
+
return join(home, ".pi", "agent", "sessions", `-${encodedCwd(projectDir)}--`);
|
|
196
|
+
}
|
|
197
|
+
function defaultCodexTranscriptDir() {
|
|
198
|
+
const home = process.env.HOME ?? "";
|
|
199
|
+
return join(home, ".codex", "sessions");
|
|
200
|
+
}
|
|
201
|
+
function toRepoRelative(projectDir, filePath) {
|
|
202
|
+
const absolute = isAbsolute(filePath) ? filePath : join(projectDir, filePath);
|
|
203
|
+
const rel = relative(projectDir, absolute);
|
|
204
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
|
|
205
|
+
return rel.split(sep).join("/");
|
|
206
|
+
}
|
|
207
|
+
function listSessionFiles(dir) {
|
|
208
|
+
try {
|
|
209
|
+
if (!existsSync(dir)) return [];
|
|
210
|
+
return readdirSync(dir).filter((name) => name.endsWith(".jsonl")).sort().map((name) => join(dir, name));
|
|
211
|
+
} catch {
|
|
212
|
+
return [];
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function listRolloutFiles(dir, depth = 0) {
|
|
216
|
+
if (depth > 4) return [];
|
|
217
|
+
try {
|
|
218
|
+
if (!existsSync(dir)) return [];
|
|
219
|
+
const files = [];
|
|
220
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
221
|
+
const full = join(dir, entry.name);
|
|
222
|
+
if (entry.isDirectory()) files.push(...listRolloutFiles(full, depth + 1));
|
|
223
|
+
else if (entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl")) files.push(full);
|
|
224
|
+
}
|
|
225
|
+
return files.sort();
|
|
226
|
+
} catch {
|
|
227
|
+
return [];
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
function record(acc, sessionId, relPath, op, mandated, fidelity) {
|
|
231
|
+
let counts = acc.docs.get(relPath);
|
|
232
|
+
if (!counts) {
|
|
233
|
+
counts = { reads: 0, mandatedReads: 0, voluntaryReads: 0, writes: 0, sessions: [] };
|
|
234
|
+
acc.docs.set(relPath, counts);
|
|
235
|
+
}
|
|
236
|
+
if (fidelity) counts.fidelity = fidelity;
|
|
237
|
+
if (op.kind === "write") {
|
|
238
|
+
counts.writes += 1;
|
|
239
|
+
} else {
|
|
240
|
+
counts.reads += 1;
|
|
241
|
+
if (mandated) counts.mandatedReads += 1;
|
|
242
|
+
else counts.voluntaryReads += 1;
|
|
243
|
+
}
|
|
244
|
+
if (!counts.sessions.includes(sessionId)) counts.sessions.push(sessionId);
|
|
245
|
+
}
|
|
246
|
+
function scanFile(acc, projectDir, filePath, parse, source = {}) {
|
|
247
|
+
let content;
|
|
248
|
+
try {
|
|
249
|
+
content = readFileSync(filePath, "utf-8");
|
|
250
|
+
} catch {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const fallbackId = filePath.split(sep).pop().replace(/\.jsonl$/, "");
|
|
254
|
+
let sessionId = null;
|
|
255
|
+
let activeSkill = null;
|
|
256
|
+
let cwdMatched = !source.requireCwdMatch;
|
|
257
|
+
const pending = [];
|
|
258
|
+
for (const line of content.split("\n")) {
|
|
259
|
+
const parsed = parse(line);
|
|
260
|
+
if (!parsed) continue;
|
|
261
|
+
if (parsed.sessionId) sessionId = parsed.sessionId;
|
|
262
|
+
if (parsed.skill) activeSkill = parsed.skill;
|
|
263
|
+
if (source.requireCwdMatch && parsed.cwd) {
|
|
264
|
+
if (parsed.cwd !== projectDir) return;
|
|
265
|
+
cwdMatched = true;
|
|
266
|
+
}
|
|
267
|
+
for (const op of parsed.ops) {
|
|
268
|
+
const rel = toRepoRelative(projectDir, op.path);
|
|
269
|
+
if (!rel || !isKnowledgeLayerPath(rel)) continue;
|
|
270
|
+
const mandated = source.forceMandated ? op.kind === "read" : isMandated(activeSkill, rel);
|
|
271
|
+
pending.push({ op: { kind: op.kind, path: rel }, mandated });
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (pending.length === 0 || !cwdMatched) return;
|
|
275
|
+
const bareId = sessionId ?? fallbackId;
|
|
276
|
+
const id = source.prefix ? `${source.prefix}:${bareId}` : bareId;
|
|
277
|
+
if (source.exclude?.has(id)) return;
|
|
278
|
+
acc.sessions.add(id);
|
|
279
|
+
for (const { op, mandated } of pending) {
|
|
280
|
+
record(acc, id, op.path, op, mandated, source.fidelity);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
async function scanTranscripts(projectDir, opts = {}) {
|
|
284
|
+
const acc = { docs: /* @__PURE__ */ new Map(), sessions: /* @__PURE__ */ new Set() };
|
|
285
|
+
const prefix = (harness) => opts.namespaceSessions ? harness : void 0;
|
|
286
|
+
const exclude = opts.excludeSessions;
|
|
287
|
+
const claudeDir = opts.claudeDir ?? defaultClaudeTranscriptDir(projectDir);
|
|
288
|
+
for (const file of listSessionFiles(claudeDir)) {
|
|
289
|
+
scanFile(acc, projectDir, file, parseClaudeSessionLine, { prefix: prefix("claude"), exclude });
|
|
290
|
+
}
|
|
291
|
+
const piDir = opts.piDir ?? defaultPiTranscriptDir(projectDir);
|
|
292
|
+
for (const file of listSessionFiles(piDir)) {
|
|
293
|
+
scanFile(acc, projectDir, file, parsePiSessionLine, { prefix: prefix("pi"), exclude });
|
|
294
|
+
}
|
|
295
|
+
const codexDir = opts.codexDir ?? defaultCodexTranscriptDir();
|
|
296
|
+
for (const file of listRolloutFiles(codexDir)) {
|
|
297
|
+
scanFile(acc, projectDir, file, parseCodexSessionLine, {
|
|
298
|
+
forceMandated: true,
|
|
299
|
+
fidelity: "degraded",
|
|
300
|
+
requireCwdMatch: true,
|
|
301
|
+
prefix: prefix("codex"),
|
|
302
|
+
exclude
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
const docs = {};
|
|
306
|
+
for (const key of [...acc.docs.keys()].sort()) {
|
|
307
|
+
docs[key] = acc.docs.get(key);
|
|
308
|
+
}
|
|
309
|
+
return { docs, sessions: [...acc.sessions] };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/telemetry-store.ts
|
|
313
|
+
var TELEMETRY_PATH = "docs/.joycraft/telemetry.json";
|
|
314
|
+
function loadTelemetryStore(storePath) {
|
|
315
|
+
try {
|
|
316
|
+
const parsed = JSON.parse(readFileSync2(storePath, "utf-8"));
|
|
317
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
318
|
+
if (parsed.version !== 1 || !Array.isArray(parsed.scannedSessions) || typeof parsed.docs !== "object") {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
return parsed;
|
|
322
|
+
} catch {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function emptyStore() {
|
|
327
|
+
return { version: 1, scannedSessions: [], docs: {} };
|
|
328
|
+
}
|
|
329
|
+
function mergeDocCounts(into, docs) {
|
|
330
|
+
for (const [path, counts] of Object.entries(docs)) {
|
|
331
|
+
const existing = into.docs[path];
|
|
332
|
+
if (!existing) {
|
|
333
|
+
into.docs[path] = {
|
|
334
|
+
reads: counts.reads,
|
|
335
|
+
mandatedReads: counts.mandatedReads,
|
|
336
|
+
voluntaryReads: counts.voluntaryReads,
|
|
337
|
+
writes: counts.writes,
|
|
338
|
+
sessions: [...counts.sessions],
|
|
339
|
+
...counts.fidelity ? { fidelity: counts.fidelity } : {}
|
|
340
|
+
};
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
existing.reads += counts.reads;
|
|
344
|
+
existing.mandatedReads += counts.mandatedReads;
|
|
345
|
+
existing.voluntaryReads += counts.voluntaryReads;
|
|
346
|
+
existing.writes += counts.writes;
|
|
347
|
+
for (const session of counts.sessions) {
|
|
348
|
+
if (!existing.sessions.includes(session)) existing.sessions.push(session);
|
|
349
|
+
}
|
|
350
|
+
if (counts.fidelity) existing.fidelity = counts.fidelity;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function saveStore(storePath, store) {
|
|
354
|
+
mkdirSync(dirname(storePath), { recursive: true });
|
|
355
|
+
const sortedDocs = {};
|
|
356
|
+
for (const key of Object.keys(store.docs).sort()) sortedDocs[key] = store.docs[key];
|
|
357
|
+
const payload = { version: store.version, scannedSessions: [...store.scannedSessions].sort(), docs: sortedDocs };
|
|
358
|
+
const tmp = `${storePath}.tmp-${process.pid}`;
|
|
359
|
+
writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n", "utf-8");
|
|
360
|
+
renameSync(tmp, storePath);
|
|
361
|
+
}
|
|
362
|
+
async function runTelemetryScan(projectDir, opts = {}) {
|
|
363
|
+
const storePath = opts.storePath ?? join2(projectDir, TELEMETRY_PATH);
|
|
364
|
+
const claudeDir = opts.claudeDir ?? defaultClaudeTranscriptDir(projectDir);
|
|
365
|
+
const piDir = opts.piDir ?? defaultPiTranscriptDir(projectDir);
|
|
366
|
+
const codexDir = opts.codexDir ?? defaultCodexTranscriptDir();
|
|
367
|
+
const existing = loadTelemetryStore(storePath);
|
|
368
|
+
const rebuiltStore = existing === null && existsSync2(storePath);
|
|
369
|
+
const store = existing ?? emptyStore();
|
|
370
|
+
if (![claudeDir, piDir, codexDir].some((dir) => existsSync2(dir))) {
|
|
371
|
+
return { status: "nothing-to-scan", newSessions: 0, docCount: Object.keys(store.docs).length, storePath };
|
|
372
|
+
}
|
|
373
|
+
const scan = await scanTranscripts(projectDir, {
|
|
374
|
+
claudeDir,
|
|
375
|
+
piDir,
|
|
376
|
+
codexDir,
|
|
377
|
+
namespaceSessions: true,
|
|
378
|
+
excludeSessions: new Set(store.scannedSessions)
|
|
379
|
+
});
|
|
380
|
+
mergeDocCounts(store, scan.docs);
|
|
381
|
+
for (const session of scan.sessions) {
|
|
382
|
+
if (!store.scannedSessions.includes(session)) store.scannedSessions.push(session);
|
|
383
|
+
}
|
|
384
|
+
saveStore(storePath, store);
|
|
385
|
+
return {
|
|
386
|
+
status: "ok",
|
|
387
|
+
newSessions: scan.sessions.length,
|
|
388
|
+
docCount: Object.keys(store.docs).length,
|
|
389
|
+
storePath,
|
|
390
|
+
...rebuiltStore ? { rebuiltStore: true } : {}
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function formatTelemetrySummary(result2) {
|
|
394
|
+
if (result2.status === "nothing-to-scan") {
|
|
395
|
+
return "Telemetry: nothing to scan \u2014 no transcript directories found for this project.";
|
|
396
|
+
}
|
|
397
|
+
const rebuilt = result2.rebuiltStore ? " (previous store was malformed and rebuilt)" : "";
|
|
398
|
+
return `Telemetry: ${result2.newSessions} new session(s) scanned, ${result2.docCount} doc(s) tracked \u2192 ${TELEMETRY_PATH}${rebuilt}`;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export {
|
|
402
|
+
TELEMETRY_PATH,
|
|
403
|
+
loadTelemetryStore,
|
|
404
|
+
runTelemetryScan,
|
|
405
|
+
formatTelemetrySummary
|
|
406
|
+
};
|
|
407
|
+
//# sourceMappingURL=chunk-OAC5CVHJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/telemetry-store.ts","../src/telemetry.ts"],"sourcesContent":["// Persistence for the read-telemetry scanner (src/telemetry.ts).\n//\n// Accumulates scan results into a machine-local, gitignored store at\n// docs/.joycraft/telemetry.json — repo-relative doc paths, counters, and\n// namespaced scanned-session ids only, never transcript content. Sessions\n// already in the scanned list are skipped, so each transcript file is parsed\n// once and counters accumulate across invocations.\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport {\n scanTranscripts,\n defaultClaudeTranscriptDir,\n defaultPiTranscriptDir,\n defaultCodexTranscriptDir,\n type DocCounts,\n} from './telemetry.js';\n\n/** Repo-relative store location, beside docs/.joycraft/state.json. Gitignored under every profile. */\nexport const TELEMETRY_PATH = 'docs/.joycraft/telemetry.json';\n\nexport interface TelemetryStore {\n version: 1;\n /** Namespaced ids (`claude:<id>`, `pi:<id>`, `codex:<id>`) of sessions already counted. */\n scannedSessions: string[];\n docs: Record<string, DocCounts>;\n}\n\nexport interface TelemetryScanOptions {\n claudeDir?: string;\n piDir?: string;\n codexDir?: string;\n /** Store file location. Defaults to `<projectDir>/docs/.joycraft/telemetry.json`. */\n storePath?: string;\n}\n\nexport interface TelemetryScanResult {\n status: 'ok' | 'nothing-to-scan';\n newSessions: number;\n docCount: number;\n storePath: string;\n /** True when an existing store was unreadable and replaced. */\n rebuiltStore?: boolean;\n}\n\n/** Parse an existing store, or null when absent or malformed. */\nexport function loadTelemetryStore(storePath: string): TelemetryStore | null {\n try {\n const parsed = JSON.parse(readFileSync(storePath, 'utf-8'));\n if (!parsed || typeof parsed !== 'object') return null;\n if (parsed.version !== 1 || !Array.isArray(parsed.scannedSessions) || typeof parsed.docs !== 'object') {\n return null;\n }\n return parsed as TelemetryStore;\n } catch {\n return null;\n }\n}\n\nfunction emptyStore(): TelemetryStore {\n return { version: 1, scannedSessions: [], docs: {} };\n}\n\nfunction mergeDocCounts(into: TelemetryStore, docs: Record<string, DocCounts>): void {\n for (const [path, counts] of Object.entries(docs)) {\n const existing = into.docs[path];\n if (!existing) {\n into.docs[path] = {\n reads: counts.reads,\n mandatedReads: counts.mandatedReads,\n voluntaryReads: counts.voluntaryReads,\n writes: counts.writes,\n sessions: [...counts.sessions],\n ...(counts.fidelity ? { fidelity: counts.fidelity } : {}),\n };\n continue;\n }\n existing.reads += counts.reads;\n existing.mandatedReads += counts.mandatedReads;\n existing.voluntaryReads += counts.voluntaryReads;\n existing.writes += counts.writes;\n for (const session of counts.sessions) {\n if (!existing.sessions.includes(session)) existing.sessions.push(session);\n }\n if (counts.fidelity) existing.fidelity = counts.fidelity;\n }\n}\n\n/** Write temp + rename so concurrent runs are last-writer-wins, never torn JSON. */\nfunction saveStore(storePath: string, store: TelemetryStore): void {\n mkdirSync(dirname(storePath), { recursive: true });\n const sortedDocs: Record<string, DocCounts> = {};\n for (const key of Object.keys(store.docs).sort()) sortedDocs[key] = store.docs[key];\n const payload = { version: store.version, scannedSessions: [...store.scannedSessions].sort(), docs: sortedDocs };\n const tmp = `${storePath}.tmp-${process.pid}`;\n writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\\n', 'utf-8');\n renameSync(tmp, storePath);\n}\n\n/**\n * Scan this project's transcripts and accumulate the result into the store.\n * Missing transcript dirs report `nothing-to-scan`; a malformed store is\n * rebuilt rather than crashed on.\n */\nexport async function runTelemetryScan(\n projectDir: string,\n opts: TelemetryScanOptions = {},\n): Promise<TelemetryScanResult> {\n const storePath = opts.storePath ?? join(projectDir, TELEMETRY_PATH);\n\n const claudeDir = opts.claudeDir ?? defaultClaudeTranscriptDir(projectDir);\n const piDir = opts.piDir ?? defaultPiTranscriptDir(projectDir);\n const codexDir = opts.codexDir ?? defaultCodexTranscriptDir();\n\n const existing = loadTelemetryStore(storePath);\n const rebuiltStore = existing === null && existsSync(storePath);\n const store = existing ?? emptyStore();\n\n if (![claudeDir, piDir, codexDir].some((dir) => existsSync(dir))) {\n return { status: 'nothing-to-scan', newSessions: 0, docCount: Object.keys(store.docs).length, storePath };\n }\n\n const scan = await scanTranscripts(projectDir, {\n claudeDir,\n piDir,\n codexDir,\n namespaceSessions: true,\n excludeSessions: new Set(store.scannedSessions),\n });\n\n mergeDocCounts(store, scan.docs);\n for (const session of scan.sessions) {\n if (!store.scannedSessions.includes(session)) store.scannedSessions.push(session);\n }\n saveStore(storePath, store);\n\n return {\n status: 'ok',\n newSessions: scan.sessions.length,\n docCount: Object.keys(store.docs).length,\n storePath,\n ...(rebuiltStore ? { rebuiltStore: true } : {}),\n };\n}\n\n/** One-line summary for the CLI. */\nexport function formatTelemetrySummary(result: TelemetryScanResult): string {\n if (result.status === 'nothing-to-scan') {\n return 'Telemetry: nothing to scan — no transcript directories found for this project.';\n }\n const rebuilt = result.rebuiltStore ? ' (previous store was malformed and rebuilt)' : '';\n return `Telemetry: ${result.newSessions} new session(s) scanned, ${result.docCount} doc(s) tracked → ${TELEMETRY_PATH}${rebuilt}`;\n}\n","// Read-telemetry scanner for the knowledge layer.\n//\n// Parses AI-harness session transcripts into per-document read/write counts so\n// optimize's Reaper pass can cite evidence instead of judgment. Read-only and\n// network-free: nothing here writes a file, and no transcript content ever\n// reaches the result — paths and counters only.\n//\n// Transcript layouts (derived at runtime from $HOME + dash-encoded cwd, never\n// shipped as literal absolute paths — the src/frontmatter.ts defaultMemoryDir idiom):\n// Claude Code: $HOME/.claude/projects/<cwd-with-slashes-as-dashes>/*.jsonl\n// Pi: $HOME/.pi/agent/sessions/--<cwd-with-slashes-as-dashes>--/*.jsonl\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join, relative, isAbsolute, sep } from 'node:path';\n\nexport type FileOpKind = 'read' | 'write';\n\nexport interface FileOp {\n kind: FileOpKind;\n path: string;\n}\n\n/** What one transcript line contributes: file ops, a session id, an active-skill change. */\nexport interface ParsedLine {\n ops: FileOp[];\n sessionId: string | null;\n skill: string | null;\n /** The session's working directory, when the transcript records one (Codex session_meta). */\n cwd?: string;\n}\n\nexport interface DocCounts {\n reads: number;\n mandatedReads: number;\n voluntaryReads: number;\n writes: number;\n sessions: string[];\n /** Present when any contribution came from a shell-string parse (Codex) — counts are best-effort. */\n fidelity?: 'degraded';\n}\n\nexport interface ScanResult {\n docs: Record<string, DocCounts>;\n sessions: string[];\n}\n\nexport interface ScanOptions {\n /** Claude Code transcript directory. Defaults to the $HOME-derived path. */\n claudeDir?: string;\n /** Pi transcript directory. Defaults to the $HOME-derived path. */\n piDir?: string;\n /** Codex transcript directory (rollout-*.jsonl). Defaults to the $HOME-derived path. */\n codexDir?: string;\n /** Prefix session ids per harness (`claude:<id>`, `pi:<id>`, `codex:<id>`) in the result. */\n namespaceSessions?: boolean;\n /** Sessions to skip entirely (matched against ids as they appear in the result). */\n excludeSessions?: ReadonlySet<string>;\n}\n\n// --- knowledge-layer filter -------------------------------------------------\n\nconst KNOWLEDGE_PREFIXES = ['docs/context/', 'docs/discoveries/', 'docs/reference/'];\nconst KNOWLEDGE_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n/** True for the five knowledge-layer shapes, given a repo-relative POSIX path. */\nexport function isKnowledgeLayerPath(relPath: string): boolean {\n if (KNOWLEDGE_FILES.includes(relPath)) return true;\n return KNOWLEDGE_PREFIXES.some((prefix) => relPath.startsWith(prefix) && relPath.length > prefix.length);\n}\n\n// --- mandated/voluntary classification --------------------------------------\n\n// A read is `mandated` when the active skill's own text opens that doc: session-end\n// Step 1b routes to the context docs, add-fact Step 2b overlap-greps them, optimize's\n// Reaper pass reads the whole knowledge layer. Everything else is `voluntary` — the\n// agent followed a pointer mid-task, which is the only evidence that earns keep/retire.\nconst MANDATING_SKILLS: Record<string, (relPath: string) => boolean> = {\n 'joycraft-session-end': (p) => p.startsWith('docs/context/') || p.startsWith('docs/discoveries/'),\n 'joycraft-add-fact': (p) => p.startsWith('docs/context/'),\n 'joycraft-optimize': () => true,\n};\n\nfunction isMandated(activeSkill: string | null, relPath: string): boolean {\n if (!activeSkill) return false;\n const predicate = MANDATING_SKILLS[activeSkill];\n return predicate ? predicate(relPath) : false;\n}\n\n// --- per-harness line parsers -----------------------------------------------\n\nfunction parseJson(line: string): any | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n try {\n return JSON.parse(trimmed);\n } catch {\n return null;\n }\n}\n\nfunction result(ops: FileOp[], sessionId: string | null, skill: string | null): ParsedLine | null {\n if (ops.length === 0 && !sessionId && !skill) return null;\n return { ops, sessionId, skill };\n}\n\nconst CLAUDE_READ_TOOLS = new Set(['Read', 'NotebookRead']);\nconst CLAUDE_WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);\n\n/**\n * Claude Code JSONL: `tool_use` blocks inside `message.content`, with the path on\n * `input.file_path`, and skill invocations as a `Skill` tool_use.\n */\nexport function parseClaudeSessionLine(line: string): ParsedLine | null {\n const record = parseJson(line);\n if (!record || typeof record !== 'object') return null;\n\n const sessionId = typeof record.sessionId === 'string' ? record.sessionId : null;\n const content = record.message?.content;\n const ops: FileOp[] = [];\n let skill: string | null = null;\n\n if (Array.isArray(content)) {\n for (const block of content) {\n if (!block || typeof block !== 'object' || block.type !== 'tool_use') continue;\n const name = block.name;\n if (name === 'Skill') {\n const invoked = block.input?.skill;\n if (typeof invoked === 'string') skill = invoked;\n continue;\n }\n const filePath = block.input?.file_path;\n if (typeof filePath !== 'string' || !filePath) continue;\n if (CLAUDE_READ_TOOLS.has(name)) ops.push({ kind: 'read', path: filePath });\n else if (CLAUDE_WRITE_TOOLS.has(name)) ops.push({ kind: 'write', path: filePath });\n }\n }\n\n return result(ops, sessionId, skill);\n}\n\nconst PI_READ_TOOLS = new Set(['read']);\nconst PI_WRITE_TOOLS = new Set(['write', 'edit', 'multi_edit']);\nconst PI_SKILL_RE = /^\\s*\\/skill:([A-Za-z0-9._-]+)/;\n\n/**\n * Pi JSONL: typed events. `session` carries the id; `message` events hold\n * `toolCall` blocks whose path lives on `arguments.path` (or `arguments.o[].p`\n * for `batch_read`). Skills are invoked by a `/skill:<name>` user message.\n */\nexport function parsePiSessionLine(line: string): ParsedLine | null {\n const record = parseJson(line);\n if (!record || typeof record !== 'object') return null;\n\n if (record.type === 'session') {\n const id = typeof record.id === 'string' ? record.id : null;\n return result([], id, null);\n }\n if (record.type !== 'message') return null;\n\n const message = record.message;\n const content = message?.content;\n const ops: FileOp[] = [];\n let skill: string | null = null;\n\n if (Array.isArray(content)) {\n for (const block of content) {\n if (!block || typeof block !== 'object') continue;\n\n if (block.type === 'text' && message?.role === 'user' && typeof block.text === 'string') {\n const match = block.text.match(PI_SKILL_RE);\n if (match) skill = match[1];\n continue;\n }\n\n if (block.type !== 'toolCall') continue;\n const name = block.name;\n const args = block.arguments;\n\n if (name === 'batch_read' && Array.isArray(args?.o)) {\n for (const entry of args.o) {\n if (entry && typeof entry === 'object' && typeof entry.p === 'string' && entry.p) {\n ops.push({ kind: entry.o === 'write' || entry.o === 'edit' ? 'write' : 'read', path: entry.p });\n }\n }\n continue;\n }\n\n const filePath = args?.path;\n if (typeof filePath !== 'string' || !filePath) continue;\n if (PI_READ_TOOLS.has(name)) ops.push({ kind: 'read', path: filePath });\n else if (PI_WRITE_TOOLS.has(name)) ops.push({ kind: 'write', path: filePath });\n }\n }\n\n return result(ops, null, skill);\n}\n\n// --- Codex parser (degraded fidelity) ----------------------------------------\n//\n// Codex rollout-*.jsonl records file operations only as `exec_command` shell\n// strings, so this parser tokenizes command text and keeps only high-confidence\n// patterns: a recognized command with an explicit literal path argument, or an\n// output redirect. Anything with variables, substitutions, or unbalanced quoting\n// is dropped rather than guessed — best-effort by design, no parity claim.\n\nconst CODEX_READ_COMMANDS = new Set(['cat', 'head', 'tail', 'sed', 'grep', 'less', 'more']);\n\n/** Split a shell string into tokens, honoring quotes. Null on unbalanced quoting. */\nfunction tokenizeShell(cmd: string): string[] | null {\n const tokens: string[] = [];\n let current = '';\n let started = false;\n let quote: '\"' | \"'\" | null = null;\n for (const ch of cmd) {\n if (quote) {\n if (ch === quote) quote = null;\n else current += ch;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n started = true;\n continue;\n }\n if (/\\s/.test(ch)) {\n if (started) tokens.push(current);\n current = '';\n started = false;\n continue;\n }\n current += ch;\n started = true;\n }\n if (quote) return null;\n if (started) tokens.push(current);\n return tokens;\n}\n\n/** File ops recognized in one pipeline segment; empty when nothing is high-confidence. */\nfunction opsFromSegment(tokens: string[]): FileOp[] {\n if (tokens.length === 0) return [];\n // Variables and substitutions anywhere make the segment untrustworthy.\n if (tokens.some((t) => t.includes('$') || t.includes('`'))) return [];\n\n const writes: string[] = [];\n const args: string[] = [];\n for (let i = 1; i < tokens.length; i++) {\n const token = tokens[i];\n const redirect = token.match(/^\\d*(>{1,2})(.*)$/);\n if (redirect) {\n const target = redirect[2] || tokens[++i];\n if (target) writes.push(target);\n continue;\n }\n if (!token.startsWith('-')) args.push(token);\n }\n\n const ops: FileOp[] = [];\n const command = tokens[0];\n if (CODEX_READ_COMMANDS.has(command)) {\n // grep's first non-flag argument is the pattern, sed's is the script — skip it.\n const paths = command === 'grep' || command === 'sed' ? args.slice(1) : args;\n for (const path of paths) ops.push({ kind: 'read', path });\n }\n for (const path of writes) ops.push({ kind: 'write', path });\n return ops;\n}\n\n/**\n * Codex JSONL: `session_meta` carries the id and cwd; `response_item` lines hold\n * `function_call` payloads whose `arguments` is a JSON string with the `cmd` text.\n */\nexport function parseCodexSessionLine(line: string): ParsedLine | null {\n const record = parseJson(line);\n if (!record || typeof record !== 'object') return null;\n\n if (record.type === 'session_meta') {\n const payload = record.payload;\n const id = typeof payload?.id === 'string' ? payload.id : null;\n const cwd = typeof payload?.cwd === 'string' ? payload.cwd : undefined;\n if (!id && !cwd) return null;\n return { ops: [], sessionId: id, skill: null, cwd };\n }\n\n const payload = record.payload;\n if (record.type !== 'response_item' || payload?.type !== 'function_call') return null;\n if (payload.name !== 'exec_command' && payload.name !== 'shell') return null;\n const parsedArgs = typeof payload.arguments === 'string' ? parseJson(payload.arguments) : payload.arguments;\n const cmd = parsedArgs?.cmd ?? (Array.isArray(parsedArgs?.command) ? parsedArgs.command.join(' ') : null);\n if (typeof cmd !== 'string' || !cmd) return null;\n\n // Compound structures (loops, conditionals) are beyond conservative parsing.\n if (/\\b(for|while|if|do|done|fi)\\b/.test(cmd)) return result([], null, null);\n\n const ops: FileOp[] = [];\n for (const segment of cmd.split(/\\||&&|;/)) {\n const tokens = tokenizeShell(segment.trim());\n if (!tokens) continue;\n ops.push(...opsFromSegment(tokens));\n }\n return result(ops, null, null);\n}\n\n// --- default transcript locations -------------------------------------------\n\nfunction encodedCwd(projectDir: string): string {\n return projectDir.replace(/\\//g, '-');\n}\n\nexport function defaultClaudeTranscriptDir(projectDir: string): string {\n const home = process.env.HOME ?? '';\n return join(home, '.claude', 'projects', encodedCwd(projectDir));\n}\n\nexport function defaultPiTranscriptDir(projectDir: string): string {\n const home = process.env.HOME ?? '';\n return join(home, '.pi', 'agent', 'sessions', `-${encodedCwd(projectDir)}--`);\n}\n\n/** Codex sessions are global (date-nested, not per-project) — the scan guards on session_meta cwd. */\nexport function defaultCodexTranscriptDir(): string {\n const home = process.env.HOME ?? '';\n return join(home, '.codex', 'sessions');\n}\n\n// --- scan -------------------------------------------------------------------\n\n/** Repo-relative POSIX path, or null when the op is outside the project. */\nfunction toRepoRelative(projectDir: string, filePath: string): string | null {\n const absolute = isAbsolute(filePath) ? filePath : join(projectDir, filePath);\n const rel = relative(projectDir, absolute);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n}\n\nfunction listSessionFiles(dir: string): string[] {\n try {\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((name) => name.endsWith('.jsonl'))\n .sort()\n .map((name) => join(dir, name));\n } catch {\n return [];\n }\n}\n\n/** Recursive rollout-*.jsonl listing for Codex's date-nested layout. Depth-capped. */\nfunction listRolloutFiles(dir: string, depth = 0): string[] {\n if (depth > 4) return [];\n try {\n if (!existsSync(dir)) return [];\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) files.push(...listRolloutFiles(full, depth + 1));\n else if (entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) files.push(full);\n }\n return files.sort();\n } catch {\n return [];\n }\n}\n\ninterface Accumulator {\n docs: Map<string, DocCounts>;\n sessions: Set<string>;\n}\n\nfunction record(\n acc: Accumulator,\n sessionId: string,\n relPath: string,\n op: FileOp,\n mandated: boolean,\n fidelity?: 'degraded',\n): void {\n let counts = acc.docs.get(relPath);\n if (!counts) {\n counts = { reads: 0, mandatedReads: 0, voluntaryReads: 0, writes: 0, sessions: [] };\n acc.docs.set(relPath, counts);\n }\n if (fidelity) counts.fidelity = fidelity;\n if (op.kind === 'write') {\n counts.writes += 1;\n } else {\n counts.reads += 1;\n if (mandated) counts.mandatedReads += 1;\n else counts.voluntaryReads += 1;\n }\n if (!counts.sessions.includes(sessionId)) counts.sessions.push(sessionId);\n}\n\ninterface SourceProfile {\n /** Codex: skill attribution is unavailable from shell strings — default reads to mandated. */\n forceMandated?: boolean;\n fidelity?: 'degraded';\n /** Codex: sessions are global, so count a file only when its session_meta cwd names this project. */\n requireCwdMatch?: boolean;\n /** Harness namespace prepended to session ids (`claude:<id>`). */\n prefix?: string;\n /** Sessions (as namespaced when a prefix is set) whose files are skipped. */\n exclude?: ReadonlySet<string>;\n}\n\nfunction scanFile(\n acc: Accumulator,\n projectDir: string,\n filePath: string,\n parse: (line: string) => ParsedLine | null,\n source: SourceProfile = {},\n): void {\n let content: string;\n try {\n content = readFileSync(filePath, 'utf-8');\n } catch {\n return;\n }\n\n // Fall back to the file's own name as the session id — Pi names its files\n // <timestamp>_<uuid>.jsonl and Claude names them <sessionId>.jsonl, so a\n // transcript whose id line is missing or truncated still attributes.\n const fallbackId = filePath.split(sep).pop()!.replace(/\\.jsonl$/, '');\n let sessionId: string | null = null;\n let activeSkill: string | null = null;\n let cwdMatched = !source.requireCwdMatch;\n const pending: Array<{ op: FileOp; mandated: boolean }> = [];\n\n for (const line of content.split('\\n')) {\n const parsed = parse(line);\n if (!parsed) continue;\n if (parsed.sessionId) sessionId = parsed.sessionId;\n if (parsed.skill) activeSkill = parsed.skill;\n if (source.requireCwdMatch && parsed.cwd) {\n if (parsed.cwd !== projectDir) return;\n cwdMatched = true;\n }\n\n for (const op of parsed.ops) {\n const rel = toRepoRelative(projectDir, op.path);\n if (!rel || !isKnowledgeLayerPath(rel)) continue;\n const mandated = source.forceMandated ? op.kind === 'read' : isMandated(activeSkill, rel);\n pending.push({ op: { kind: op.kind, path: rel }, mandated });\n }\n }\n\n if (pending.length === 0 || !cwdMatched) return;\n const bareId = sessionId ?? fallbackId;\n const id = source.prefix ? `${source.prefix}:${bareId}` : bareId;\n if (source.exclude?.has(id)) return;\n acc.sessions.add(id);\n for (const { op, mandated } of pending) {\n record(acc, id, op.path, op, mandated, source.fidelity);\n }\n}\n\n/**\n * Scan a project's Claude and Pi transcripts into per-document counts for the\n * knowledge layer. Missing transcript directories yield an empty contribution;\n * malformed lines and unreadable files are skipped, never thrown.\n */\nexport async function scanTranscripts(projectDir: string, opts: ScanOptions = {}): Promise<ScanResult> {\n const acc: Accumulator = { docs: new Map(), sessions: new Set() };\n\n const prefix = (harness: string): string | undefined => (opts.namespaceSessions ? harness : undefined);\n const exclude = opts.excludeSessions;\n\n const claudeDir = opts.claudeDir ?? defaultClaudeTranscriptDir(projectDir);\n for (const file of listSessionFiles(claudeDir)) {\n scanFile(acc, projectDir, file, parseClaudeSessionLine, { prefix: prefix('claude'), exclude });\n }\n\n const piDir = opts.piDir ?? defaultPiTranscriptDir(projectDir);\n for (const file of listSessionFiles(piDir)) {\n scanFile(acc, projectDir, file, parsePiSessionLine, { prefix: prefix('pi'), exclude });\n }\n\n const codexDir = opts.codexDir ?? defaultCodexTranscriptDir();\n for (const file of listRolloutFiles(codexDir)) {\n scanFile(acc, projectDir, file, parseCodexSessionLine, {\n forceMandated: true,\n fidelity: 'degraded',\n requireCwdMatch: true,\n prefix: prefix('codex'),\n exclude,\n });\n }\n\n const docs: Record<string, DocCounts> = {};\n for (const key of [...acc.docs.keys()].sort()) {\n docs[key] = acc.docs.get(key)!;\n }\n return { docs, sessions: [...acc.sessions] };\n}\n"],"mappings":";;;AAQA,SAAS,cAAAA,aAAY,WAAW,gBAAAC,eAAc,YAAY,qBAAqB;AAC/E,SAAS,SAAS,QAAAC,aAAY;;;ACG9B,SAAS,YAAY,aAAa,oBAAoB;AACtD,SAAS,MAAM,UAAU,YAAY,WAAW;AAgDhD,IAAM,qBAAqB,CAAC,iBAAiB,qBAAqB,iBAAiB;AACnF,IAAM,kBAAkB,CAAC,aAAa,WAAW;AAG1C,SAAS,qBAAqB,SAA0B;AAC7D,MAAI,gBAAgB,SAAS,OAAO,EAAG,QAAO;AAC9C,SAAO,mBAAmB,KAAK,CAAC,WAAW,QAAQ,WAAW,MAAM,KAAK,QAAQ,SAAS,OAAO,MAAM;AACzG;AAQA,IAAM,mBAAiE;AAAA,EACrE,wBAAwB,CAAC,MAAM,EAAE,WAAW,eAAe,KAAK,EAAE,WAAW,mBAAmB;AAAA,EAChG,qBAAqB,CAAC,MAAM,EAAE,WAAW,eAAe;AAAA,EACxD,qBAAqB,MAAM;AAC7B;AAEA,SAAS,WAAW,aAA4B,SAA0B;AACxE,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,YAAY,iBAAiB,WAAW;AAC9C,SAAO,YAAY,UAAU,OAAO,IAAI;AAC1C;AAIA,SAAS,UAAU,MAA0B;AAC3C,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;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;","names":["existsSync","readFileSync","join","record","payload","readFileSync","join","existsSync","result"]}
|
|
@@ -1,5 +1,108 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
+
// src/folder-map.ts
|
|
4
|
+
import { readdirSync } from "fs";
|
|
5
|
+
import { join } from "path";
|
|
6
|
+
var FOLDER_MAP_OPEN = "<!-- joycraft:folder-map -->";
|
|
7
|
+
var FOLDER_MAP_CLOSE = "<!-- /joycraft:folder-map -->";
|
|
8
|
+
var FOLDER_MAP_PLACEHOLDER = "_TODO: one line on what lives here_";
|
|
9
|
+
var MAX_ROWS = 30;
|
|
10
|
+
var SKIPPED_DIRS = /* @__PURE__ */ new Set([
|
|
11
|
+
"node_modules",
|
|
12
|
+
"dist",
|
|
13
|
+
"build",
|
|
14
|
+
"out",
|
|
15
|
+
"coverage",
|
|
16
|
+
"target",
|
|
17
|
+
"vendor",
|
|
18
|
+
"__pycache__",
|
|
19
|
+
"venv",
|
|
20
|
+
".venv",
|
|
21
|
+
"tmp",
|
|
22
|
+
"temp"
|
|
23
|
+
]);
|
|
24
|
+
var KEY_PARENTS = /* @__PURE__ */ new Set(["src", "docs"]);
|
|
25
|
+
var KNOWN_DESCRIPTIONS = {
|
|
26
|
+
"src/": "Source code",
|
|
27
|
+
"docs/": "Documentation",
|
|
28
|
+
"tests/": "Test suite",
|
|
29
|
+
"test/": "Test suite",
|
|
30
|
+
"scripts/": "Maintenance and build scripts",
|
|
31
|
+
"templates/": "Templates",
|
|
32
|
+
"public/": "Static assets served as-is",
|
|
33
|
+
"assets/": "Static assets",
|
|
34
|
+
"examples/": "Usage examples",
|
|
35
|
+
"packages/": "Monorepo packages",
|
|
36
|
+
"apps/": "Monorepo applications",
|
|
37
|
+
"config/": "Configuration",
|
|
38
|
+
"docs/context/": "Knowledge layer \u2014 operational fact-docs and reference",
|
|
39
|
+
"docs/features/": "Per-feature briefs, designs, and atomic specs",
|
|
40
|
+
"docs/discoveries/": "Session surprises worth remembering",
|
|
41
|
+
"docs/templates/": "Bundled output and reference templates",
|
|
42
|
+
"docs/backlog/": "Deferred work, one file per item",
|
|
43
|
+
"docs/research/": "Research notes and findings"
|
|
44
|
+
};
|
|
45
|
+
function listDirs(dir) {
|
|
46
|
+
try {
|
|
47
|
+
return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && !SKIPPED_DIRS.has(e.name)).map((e) => e.name).sort();
|
|
48
|
+
} catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function walkFolders(dir) {
|
|
53
|
+
const tops = listDirs(dir);
|
|
54
|
+
const folders = tops.map((top) => `${top}/`);
|
|
55
|
+
for (const top of tops) {
|
|
56
|
+
if (KEY_PARENTS.has(top)) {
|
|
57
|
+
for (const sub of listDirs(join(dir, top))) {
|
|
58
|
+
folders.push(`${top}/${sub}/`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const capped = folders.length > MAX_ROWS;
|
|
63
|
+
return { folders: capped ? folders.slice(0, MAX_ROWS) : folders, capped };
|
|
64
|
+
}
|
|
65
|
+
function parseRows(block) {
|
|
66
|
+
const rows = /* @__PURE__ */ new Map();
|
|
67
|
+
for (const line of block.split("\n")) {
|
|
68
|
+
const match = line.match(/^\| `([^`]+)` \| (.*) \|$/);
|
|
69
|
+
if (match) rows.set(match[1], match[2]);
|
|
70
|
+
}
|
|
71
|
+
return rows;
|
|
72
|
+
}
|
|
73
|
+
function renderFolderMap(dir, existingBlock) {
|
|
74
|
+
const { folders, capped } = walkFolders(dir);
|
|
75
|
+
const previous = existingBlock ? parseRows(existingBlock) : /* @__PURE__ */ new Map();
|
|
76
|
+
const lines = [FOLDER_MAP_OPEN, "| Folder | What lives here |", "|--------|-----------------|"];
|
|
77
|
+
for (const folder of folders) {
|
|
78
|
+
const description = previous.get(folder) ?? KNOWN_DESCRIPTIONS[folder] ?? FOLDER_MAP_PLACEHOLDER;
|
|
79
|
+
lines.push(`| \`${folder}\` | ${description} |`);
|
|
80
|
+
}
|
|
81
|
+
if (capped) {
|
|
82
|
+
lines.push("", `_Capped at ${MAX_ROWS} rows \u2014 this tree is past root-map scale; use the growth path below._`);
|
|
83
|
+
}
|
|
84
|
+
lines.push(
|
|
85
|
+
"",
|
|
86
|
+
"Past multi-team scale, replace this root map with nested per-directory instruction files (`joycraft-collaborative-setup`) \u2014 never a bigger tree.",
|
|
87
|
+
FOLDER_MAP_CLOSE
|
|
88
|
+
);
|
|
89
|
+
return lines.join("\n");
|
|
90
|
+
}
|
|
91
|
+
var BLOCK_RE = new RegExp(`${FOLDER_MAP_OPEN}[\\s\\S]*?${FOLDER_MAP_CLOSE}`);
|
|
92
|
+
function ensureFolderMapSection(markdown, dir) {
|
|
93
|
+
const existingBlock = markdown.match(BLOCK_RE)?.[0];
|
|
94
|
+
if (existingBlock) {
|
|
95
|
+
return markdown.replace(BLOCK_RE, renderFolderMap(dir, existingBlock));
|
|
96
|
+
}
|
|
97
|
+
if (/^## .*architecture/im.test(markdown)) return markdown;
|
|
98
|
+
return `${markdown.trimEnd()}
|
|
99
|
+
|
|
100
|
+
## Architecture
|
|
101
|
+
|
|
102
|
+
${renderFolderMap(dir)}
|
|
103
|
+
`;
|
|
104
|
+
}
|
|
105
|
+
|
|
3
106
|
// src/execution-profile.ts
|
|
4
107
|
import { createInterface } from "readline";
|
|
5
108
|
var EXECUTION_PROFILE_OPEN = "<!-- joycraft:execution-profile -->";
|
|
@@ -92,7 +195,7 @@ async function resolveExecutionProfile(harnesses, interactive) {
|
|
|
92
195
|
|
|
93
196
|
// src/gitattributes.ts
|
|
94
197
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
95
|
-
import { join } from "path";
|
|
198
|
+
import { join as join2 } from "path";
|
|
96
199
|
var GITATTRIBUTES_COMMENT = "# Joycraft: collapse generated workflow docs in PR review (expand with one click)";
|
|
97
200
|
var GITATTRIBUTES_ENTRIES = [
|
|
98
201
|
"docs/features/** linguist-generated=true",
|
|
@@ -101,7 +204,7 @@ var GITATTRIBUTES_ENTRIES = [
|
|
|
101
204
|
"docs/templates/** linguist-generated=true"
|
|
102
205
|
];
|
|
103
206
|
function applyGitattributes(targetDir) {
|
|
104
|
-
const gitattributesPath =
|
|
207
|
+
const gitattributesPath = join2(targetDir, ".gitattributes");
|
|
105
208
|
const current = existsSync(gitattributesPath) ? readFileSync(gitattributesPath, "utf-8") : "";
|
|
106
209
|
const present = new Set(current.split("\n").map((l) => l.trim()));
|
|
107
210
|
const missing = GITATTRIBUTES_ENTRIES.filter((e) => !present.has(e.trim()));
|
|
@@ -115,10 +218,10 @@ function applyGitattributes(targetDir) {
|
|
|
115
218
|
// src/package-version.ts
|
|
116
219
|
import { readFileSync as readFileSync2 } from "fs";
|
|
117
220
|
import { fileURLToPath } from "url";
|
|
118
|
-
import { dirname, join as
|
|
221
|
+
import { dirname, join as join3 } from "path";
|
|
119
222
|
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
120
223
|
function getPackageVersion() {
|
|
121
|
-
const pkgPath =
|
|
224
|
+
const pkgPath = join3(__dirname, "..", "package.json");
|
|
122
225
|
const raw = readFileSync2(pkgPath, "utf-8");
|
|
123
226
|
const pkg = JSON.parse(raw);
|
|
124
227
|
if (typeof pkg.version !== "string" || pkg.version.length === 0) {
|
|
@@ -128,6 +231,8 @@ function getPackageVersion() {
|
|
|
128
231
|
}
|
|
129
232
|
|
|
130
233
|
export {
|
|
234
|
+
renderFolderMap,
|
|
235
|
+
ensureFolderMapSection,
|
|
131
236
|
defaultExecutionProfile,
|
|
132
237
|
renderExecutionProfileSection,
|
|
133
238
|
ensureExecutionProfileSection,
|
|
@@ -135,4 +240,4 @@ export {
|
|
|
135
240
|
applyGitattributes,
|
|
136
241
|
getPackageVersion
|
|
137
242
|
};
|
|
138
|
-
//# sourceMappingURL=chunk-
|
|
243
|
+
//# sourceMappingURL=chunk-Q2ZQ6RGD.js.map
|