joycraft 0.7.12 → 0.7.14

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 (54) hide show
  1. package/README.md +30 -16
  2. package/dist/chunk-7BPB2IKY.js +255 -0
  3. package/dist/chunk-7BPB2IKY.js.map +1 -0
  4. package/dist/chunk-B73DPYYC.js +377 -0
  5. package/dist/chunk-B73DPYYC.js.map +1 -0
  6. package/dist/{chunk-DSVGHVYM.js → chunk-JYPBXPGD.js} +117 -90
  7. package/dist/chunk-JYPBXPGD.js.map +1 -0
  8. package/dist/{chunk-OAC5CVHJ.js → chunk-K4AI6FKB.js} +12 -2
  9. package/dist/chunk-K4AI6FKB.js.map +1 -0
  10. package/dist/{chunk-PBOICMDE.js → chunk-KKDKC4FM.js} +11 -73
  11. package/dist/chunk-KKDKC4FM.js.map +1 -0
  12. package/dist/chunk-OMFGDJW4.js +97 -0
  13. package/dist/chunk-OMFGDJW4.js.map +1 -0
  14. package/dist/chunk-PR4QDKPL.js +3755 -0
  15. package/dist/chunk-PR4QDKPL.js.map +1 -0
  16. package/dist/chunk-Z5JFEGWG.js +563 -0
  17. package/dist/chunk-Z5JFEGWG.js.map +1 -0
  18. package/dist/cli.js +389 -56
  19. package/dist/cli.js.map +1 -1
  20. package/dist/index.d.ts +235 -1
  21. package/dist/index.js +691 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/init-S5JU5BHL.js +60 -0
  24. package/dist/init-S5JU5BHL.js.map +1 -0
  25. package/dist/{init-autofix-YCSDK5ZR.js → init-autofix-WSKUT2HN.js} +4 -3
  26. package/dist/{init-autofix-YCSDK5ZR.js.map → init-autofix-WSKUT2HN.js.map} +1 -1
  27. package/dist/install-manifest-EQHT4474.js +37 -0
  28. package/dist/joycraft-release.json +8 -0
  29. package/dist/release-artifact-4TL5L2ZY.js +14 -0
  30. package/dist/release-resolver-P2H46QTU.js +293 -0
  31. package/dist/release-resolver-P2H46QTU.js.map +1 -0
  32. package/dist/{telemetry-store-X7K5NYWD.js → telemetry-store-IBO5GRTA.js} +2 -2
  33. package/dist/telemetry-store-IBO5GRTA.js.map +1 -0
  34. package/dist/update-HNTXCEKB.js +19 -0
  35. package/dist/update-HNTXCEKB.js.map +1 -0
  36. package/dist/update-check-YT765NE7.js +36 -0
  37. package/dist/update-check-YT765NE7.js.map +1 -0
  38. package/dist/upgrade-LZOND7OZ.js +28 -0
  39. package/dist/upgrade-LZOND7OZ.js.map +1 -0
  40. package/package.json +5 -2
  41. package/dist/chunk-BZW5DR3O.js +0 -91
  42. package/dist/chunk-BZW5DR3O.js.map +0 -1
  43. package/dist/chunk-DSVGHVYM.js.map +0 -1
  44. package/dist/chunk-OAC5CVHJ.js.map +0 -1
  45. package/dist/chunk-PBOICMDE.js.map +0 -1
  46. package/dist/chunk-Q2ZQ6RGD.js +0 -243
  47. package/dist/chunk-Q2ZQ6RGD.js.map +0 -1
  48. package/dist/init-J5Q6RX3K.js +0 -1307
  49. package/dist/init-J5Q6RX3K.js.map +0 -1
  50. package/dist/upgrade-AHUSQZEQ.js +0 -643
  51. package/dist/upgrade-AHUSQZEQ.js.map +0 -1
  52. package/dist/version-B2CCAEMC.js +0 -28
  53. /package/dist/{telemetry-store-X7K5NYWD.js.map → install-manifest-EQHT4474.js.map} +0 -0
  54. /package/dist/{version-B2CCAEMC.js.map → release-artifact-4TL5L2ZY.js.map} +0 -0
@@ -194,6 +194,10 @@ function defaultPiTranscriptDir(projectDir) {
194
194
  const home = process.env.HOME ?? "";
195
195
  return join(home, ".pi", "agent", "sessions", `-${encodedCwd(projectDir)}--`);
196
196
  }
197
+ function defaultOmpTranscriptDir(projectDir) {
198
+ const home = process.env.HOME ?? "";
199
+ return join(home, ".omp", "agent", "sessions", encodedCwd(projectDir));
200
+ }
197
201
  function defaultCodexTranscriptDir() {
198
202
  const home = process.env.HOME ?? "";
199
203
  return join(home, ".codex", "sessions");
@@ -292,6 +296,10 @@ async function scanTranscripts(projectDir, opts = {}) {
292
296
  for (const file of listSessionFiles(piDir)) {
293
297
  scanFile(acc, projectDir, file, parsePiSessionLine, { prefix: prefix("pi"), exclude });
294
298
  }
299
+ const ompDir = opts.ompDir ?? defaultOmpTranscriptDir(projectDir);
300
+ for (const file of listSessionFiles(ompDir)) {
301
+ scanFile(acc, projectDir, file, parsePiSessionLine, { prefix: prefix("omp"), exclude });
302
+ }
295
303
  const codexDir = opts.codexDir ?? defaultCodexTranscriptDir();
296
304
  for (const file of listRolloutFiles(codexDir)) {
297
305
  scanFile(acc, projectDir, file, parseCodexSessionLine, {
@@ -364,16 +372,18 @@ async function runTelemetryScan(projectDir, opts = {}) {
364
372
  const claudeDir = opts.claudeDir ?? defaultClaudeTranscriptDir(projectDir);
365
373
  const piDir = opts.piDir ?? defaultPiTranscriptDir(projectDir);
366
374
  const codexDir = opts.codexDir ?? defaultCodexTranscriptDir();
375
+ const ompDir = opts.ompDir ?? defaultOmpTranscriptDir(projectDir);
367
376
  const existing = loadTelemetryStore(storePath);
368
377
  const rebuiltStore = existing === null && existsSync2(storePath);
369
378
  const store = existing ?? emptyStore();
370
- if (![claudeDir, piDir, codexDir].some((dir) => existsSync2(dir))) {
379
+ if (![claudeDir, piDir, codexDir, ompDir].some((dir) => existsSync2(dir))) {
371
380
  return { status: "nothing-to-scan", newSessions: 0, docCount: Object.keys(store.docs).length, storePath };
372
381
  }
373
382
  const scan = await scanTranscripts(projectDir, {
374
383
  claudeDir,
375
384
  piDir,
376
385
  codexDir,
386
+ ompDir,
377
387
  namespaceSessions: true,
378
388
  excludeSessions: new Set(store.scannedSessions)
379
389
  });
@@ -404,4 +414,4 @@ export {
404
414
  runTelemetryScan,
405
415
  formatTelemetrySummary
406
416
  };
407
- //# sourceMappingURL=chunk-OAC5CVHJ.js.map
417
+ //# sourceMappingURL=chunk-K4AI6FKB.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 defaultOmpTranscriptDir,\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>`, `omp:<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 ompDir?: 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 const ompDir = opts.ompDir ?? defaultOmpTranscriptDir(projectDir);\n\n const existing = loadTelemetryStore(storePath);\n const rebuiltStore = existing === null && existsSync(storePath);\n const store = existing ?? emptyStore();\n\n if (![claudeDir, piDir, codexDir, ompDir].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 ompDir,\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// omp: $HOME/.omp/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 /** omp transcript directory. Defaults to the $HOME-derived path. */\n ompDir?: string;\n /** Prefix session ids per harness (`claude:<id>`, `pi:<id>`, `codex:<id>`, `omp:<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/** omp uses Pi's session layout but a plain encoded cwd — no `-…--` affixes. */\nexport function defaultOmpTranscriptDir(projectDir: string): string {\n const home = process.env.HOME ?? '';\n return join(home, '.omp', '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, Pi, omp, and Codex 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 // omp writes the Pi JSONL family, so it reuses parsePiSessionLine verbatim.\n const ompDir = opts.ompDir ?? defaultOmpTranscriptDir(projectDir);\n for (const file of listSessionFiles(ompDir)) {\n scanFile(acc, projectDir, file, parsePiSessionLine, { prefix: prefix('omp'), 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;;;ACI9B,SAAS,YAAY,aAAa,oBAAoB;AACtD,SAAS,MAAM,UAAU,YAAY,WAAW;AAkDhD,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;A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A,IACA;AAAA,IACA;AAAA,IACA,mBAAmB;AAAA,IACnB,iBAAiB,IAAI,IAAI,MAAM,eAAe;AAAA,EAChD,CAAC;AAED,iBAAe,OAAO,KAAK,IAAI;AAC/B,aAAW,WAAW,KAAK,UAAU;AACnC,QAAI,CAAC,MAAM,gBAAgB,SAAS,OAAO,EAAG,OAAM,gBAAgB,KAAK,OAAO;AAAA,EAClF;AACA,YAAU,WAAW,KAAK;AAE1B,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,aAAa,KAAK,SAAS;AAAA,IAC3B,UAAU,OAAO,KAAK,MAAM,IAAI,EAAE;AAAA,IAClC;AAAA,IACA,GAAI,eAAe,EAAE,cAAc,KAAK,IAAI,CAAC;AAAA,EAC/C;AACF;AAGO,SAAS,uBAAuBC,SAAqC;AAC1E,MAAIA,QAAO,WAAW,mBAAmB;AACvC,WAAO;AAAA,EACT;AACA,QAAM,UAAUA,QAAO,eAAe,gDAAgD;AACtF,SAAO,cAAcA,QAAO,WAAW,4BAA4BA,QAAO,QAAQ,0BAAqB,cAAc,GAAG,OAAO;AACjI;","names":["existsSync","readFileSync","join","record","payload","readFileSync","join","existsSync","result"]}
@@ -1,18 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/version.ts
4
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
5
- import { join, dirname } from "path";
6
- import { createHash } from "crypto";
7
-
8
3
  // src/harness.ts
9
4
  import { createInterface } from "readline";
10
- var HARNESSES = ["claude", "codex", "pi", "copilot"];
5
+ var HARNESSES = ["claude", "codex", "pi", "copilot", "omp"];
11
6
  var HARNESS_LABELS = {
12
7
  claude: "Claude Code (.claude/)",
13
8
  codex: "OpenAI Codex (.agents/)",
14
9
  pi: "Pi (.pi/)",
15
- copilot: "GitHub Copilot (.github/)"
10
+ copilot: "GitHub Copilot (.github/)",
11
+ omp: "Oh My Pi (.omp/)"
16
12
  };
17
13
  function isHarness(value) {
18
14
  return HARNESSES.includes(value);
@@ -68,21 +64,17 @@ async function resolveHarnesses(interactive) {
68
64
  }
69
65
 
70
66
  // src/version.ts
71
- var STATE_PATH = join("docs", ".joycraft", "state.json");
67
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, lstatSync, realpathSync, renameSync, unlinkSync } from "fs";
68
+ import { join, dirname } from "path";
69
+ import { createHash } from "crypto";
70
+ var STATE_PATH = "docs/.joycraft/state.json";
72
71
  var LEGACY_VERSION_FILE = ".joycraft-version";
73
- var LEGACY_CLAUDE_STATE_PATH = join(".claude", ".joycraft", "state.json");
74
- var HASH_LENGTH = 16;
72
+ var LEGACY_CLAUDE_STATE_PATH = ".claude/.joycraft/state.json";
75
73
  var DEFAULT_GITIGNORE_PROFILE = "shared";
76
74
  function parseGitignoreProfile(value) {
77
75
  const v = typeof value === "string" ? value.trim().toLowerCase() : value;
78
76
  return v === "shared" || v === "private" ? v : null;
79
77
  }
80
- function hashContent(content) {
81
- return createHash("sha256").update(content).digest("hex");
82
- }
83
- function truncateHash(hash) {
84
- return hash.slice(0, HASH_LENGTH);
85
- }
86
78
  function readVersion(dir) {
87
79
  const filePath = join(dir, STATE_PATH);
88
80
  if (!existsSync(filePath)) return null;
@@ -107,71 +99,17 @@ function readVersion(dir) {
107
99
  return null;
108
100
  }
109
101
  }
110
- function writeVersion(dir, version, files, gitignoreProfile, harnesses, autoOpen) {
111
- const filePath = join(dir, STATE_PATH);
112
- const existing = readVersion(dir);
113
- const profile = gitignoreProfile ?? existing?.gitignoreProfile;
114
- const selectedHarnesses = harnesses ?? existing?.harnesses;
115
- const openSetting = autoOpen ?? existing?.autoOpen;
116
- let unknownKeys = {};
117
- if (existsSync(filePath)) {
118
- try {
119
- const raw = JSON.parse(readFileSync(filePath, "utf-8"));
120
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
121
- const {
122
- version: _v,
123
- files: _f,
124
- gitignoreProfile: _g,
125
- harnesses: _h,
126
- autoOpen: _a,
127
- ...rest
128
- } = raw;
129
- unknownKeys = rest;
130
- }
131
- } catch {
132
- }
133
- }
134
- const truncated = {};
135
- for (const [path, hash] of Object.entries(files)) {
136
- truncated[path] = truncateHash(hash);
137
- }
138
- const data = {
139
- version,
140
- files: truncated,
141
- ...profile ? { gitignoreProfile: profile } : {},
142
- ...selectedHarnesses ? { harnesses: selectedHarnesses } : {},
143
- ...openSetting !== void 0 ? { autoOpen: openSetting } : {},
144
- ...unknownKeys
145
- };
146
- mkdirSync(dirname(filePath), { recursive: true });
147
- writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n", "utf-8");
148
- }
149
- function getAutoOpen(dir) {
150
- return readVersion(dir)?.autoOpen ?? true;
151
- }
152
- function getLevel(dir) {
153
- const hasAutofix = existsSync(join(dir, ".github", "workflows", "autofix.yml"));
154
- if (!hasAutofix) return 4;
155
- const claudeMdPath = join(dir, "CLAUDE.md");
156
- if (!existsSync(claudeMdPath)) return 4;
157
- const content = readFileSync(claudeMdPath, "utf-8");
158
- return content.includes("## External Validation") ? 5 : 4;
159
- }
160
102
 
161
103
  export {
162
104
  HARNESSES,
163
105
  sanitizeHarnesses,
106
+ parseHarnessSelection,
164
107
  resolveHarnesses,
165
108
  STATE_PATH,
166
109
  LEGACY_VERSION_FILE,
167
110
  LEGACY_CLAUDE_STATE_PATH,
168
111
  DEFAULT_GITIGNORE_PROFILE,
169
112
  parseGitignoreProfile,
170
- hashContent,
171
- truncateHash,
172
- readVersion,
173
- writeVersion,
174
- getAutoOpen,
175
- getLevel
113
+ readVersion
176
114
  };
177
- //# sourceMappingURL=chunk-PBOICMDE.js.map
115
+ //# sourceMappingURL=chunk-KKDKC4FM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harness.ts","../src/version.ts"],"sourcesContent":["import { createInterface } from 'node:readline';\n\n/**\n * The AI coding harnesses Joycraft can install into a project. Each maps to a\n * config dir:\n * - claude → .claude/ (Claude Code)\n * - codex → .agents/ (OpenAI Codex)\n * - pi → .pi/ (Pi)\n * - copilot → .github/ (GitHub Copilot)\n * - omp → .omp/ (Oh My Pi)\n *\n * Single source of truth: the menu, the parser, and the install gates in\n * init.ts all derive from this list so a new harness can't leave a path stale.\n */\nexport const HARNESSES = ['claude', 'codex', 'pi', 'copilot', 'omp'] as const;\nexport type Harness = (typeof HARNESSES)[number];\n\n/** Human-readable one-liner per harness, shown in the interactive menu. */\nconst HARNESS_LABELS: Record<Harness, string> = {\n claude: 'Claude Code (.claude/)',\n codex: 'OpenAI Codex (.agents/)',\n pi: 'Pi (.pi/)',\n copilot: 'GitHub Copilot (.github/)',\n omp: 'Oh My Pi (.omp/)',\n};\n\nfunction isHarness(value: string): value is Harness {\n return (HARNESSES as readonly string[]).includes(value);\n}\n\n/**\n * Sanitize an arbitrary value (e.g. parsed from state.json) into a harness list,\n * dropping anything unrecognized rather than rejecting the whole list — old or\n * hand-edited state must degrade gracefully. Returns null when the input isn't\n * an array at all (caller treats null as \"no recorded selection\"). Order follows\n * the canonical HARNESSES order and is deduped.\n */\nexport function sanitizeHarnesses(value: unknown): Harness[] | null {\n if (!Array.isArray(value)) return null;\n const present = new Set(\n value.filter((v): v is string => typeof v === 'string').map((v) => v.trim().toLowerCase())\n );\n return HARNESSES.filter((h) => present.has(h));\n}\n\n/**\n * Parse a comma/space-separated answer into a deduped, validated harness list.\n * Returns null when any token is unrecognized so the caller can re-ask rather\n * than silently dropping a typo. An empty answer yields an empty array (the\n * \"install nothing\" case the caller handles explicitly).\n */\nexport function parseHarnessSelection(answer: string): Harness[] | null {\n const tokens = answer\n .split(/[,\\s]+/)\n .map((t) => t.trim().toLowerCase())\n .filter((t) => t.length > 0);\n\n // \"all\" is a convenience alias for every harness.\n if (tokens.length === 1 && tokens[0] === 'all') {\n return [...HARNESSES];\n }\n\n const selected: Harness[] = [];\n for (const token of tokens) {\n if (!isHarness(token)) return null;\n if (!selected.includes(token)) selected.push(token);\n }\n return selected;\n}\n\n/**\n * Interactive multi-select for which harnesses to install. An empty answer is a\n * deliberate \"none\" — the caller prints the run-again message and bails. An\n * unrecognized token re-asks instead of being coerced.\n */\nasync function promptHarnesses(): Promise<Harness[]> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n console.log('\\nWhich AI harnesses should Joycraft install?');\n for (const h of HARNESSES) {\n console.log(` ${h.padEnd(7)} — ${HARNESS_LABELS[h]}`);\n }\n return new Promise((resolve) => {\n const ask = (): void => {\n rl.question('Harnesses [comma-separated, or \"all\"] (none): ', (answer) => {\n const parsed = parseHarnessSelection(answer);\n if (parsed !== null) {\n rl.close();\n resolve(parsed);\n return;\n }\n console.log(\n `Unrecognized harness in '${answer.trim()}' — choose from ${HARNESSES.join(', ')} (comma-separated), or leave empty for none.`\n );\n ask();\n });\n };\n ask();\n });\n}\n\n/**\n * Resolve which harnesses to install:\n * - interactive (TTY): show the multi-select menu; honor an empty \"none\"\n * - non-interactive: install all available harnesses, preserving long-standing init behavior\n * for scripted/CI runs that can't answer a prompt.\n */\nexport async function resolveHarnesses(interactive: boolean): Promise<Harness[]> {\n if (interactive) {\n return promptHarnesses();\n }\n return [...HARNESSES];\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync, lstatSync, realpathSync, renameSync, unlinkSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { createHash } from 'node:crypto';\nimport { sanitizeHarnesses, type Harness } from './harness.js';\nimport { CHECK_SETTINGS_PATH } from './update-check.js';\n\n/**\n * Project-relative path to Joycraft's upgrade-state file.\n *\n * Hidden inside `docs/` — the one directory `init` always creates regardless of\n * which harnesses are selected — so a single-harness install carries no\n * foreign-harness footprint (a Codex-only project has no `.claude/`, etc.). The\n * state is Joycraft's own bookkeeping (version, file hashes, gitignore profile),\n * not a harness artifact, so it lives in a harness-neutral home. Never at the\n * repo root, never committed (init/upgrade gitignore it).\n *\n * Two legacy locations are migrated on upgrade: the original repo-root\n * `.joycraft-version` (see LEGACY_VERSION_FILE) and the later\n * `.claude/.joycraft/state.json` (see LEGACY_CLAUDE_STATE_PATH).\n */\nexport const STATE_PATH = 'docs/.joycraft/state.json';\n\n/** Project-local preferences introduced with the installation manifest. */\nexport const LOCAL_SETTINGS_PATH = CHECK_SETTINGS_PATH;\n\n/** The original repo-root state path. Kept only so `upgrade` can migrate it. */\nexport const LEGACY_VERSION_FILE = '.joycraft-version';\n\n/**\n * The interim `.claude/`-nested state path, used before state moved to a\n * harness-neutral `docs/` home. Kept only so `upgrade` can migrate it (and so a\n * Codex/Pi-only re-init stops leaving a stray `.claude/` behind).\n */\nexport const LEGACY_CLAUDE_STATE_PATH = '.claude/.joycraft/state.json';\n\n/**\n * Length we truncate stored hashes to. Full SHA-256 is 64 hex chars; 16 hex\n * (64 bits) is ample to detect customization across ~100 managed files and\n * shrinks the state ~4×. Compare truncated-on-both-sides (see upgrade.ts).\n */\nconst HASH_LENGTH = 16;\n\n/**\n * How much of the Joycraft harness is tracked in git.\n * - `shared` — commit skills/agents/pi so teammates get the workflow (default).\n * - `private` — gitignore .claude/, .agents/, .pi/; track only CLAUDE.md,\n * AGENTS.md, and docs/.\n */\nexport type GitignoreProfile = 'shared' | 'private';\n\nexport const DEFAULT_GITIGNORE_PROFILE: GitignoreProfile = 'shared';\n\n/**\n * Narrow an arbitrary value to a GitignoreProfile, or null if unrecognized.\n * Strings are normalized (trim + lowercase) here so every call site — flag,\n * prompt, persisted state — gets the same case-insensitivity for free.\n */\nexport function parseGitignoreProfile(value: unknown): GitignoreProfile | null {\n const v = typeof value === 'string' ? value.trim().toLowerCase() : value;\n return v === 'shared' || v === 'private' ? v : null;\n}\n\nexport interface VersionInfo {\n version: string;\n /**\n * The last recorded vendor baseline for each managed file. These values are\n * deliberately independent from the bytes currently on disk: when a user\n * declines a customized replacement, the previous value remains the\n * comparison base. An absent entry means vendor ownership is unknown.\n */\n files: Record<string, string>;\n /**\n * The gitignore profile chosen at init/upgrade. Absent on state written by\n * Joycraft versions before this field existed — treat absent as `shared`.\n */\n gitignoreProfile?: GitignoreProfile;\n /**\n * The harnesses installed at init (claude/codex/pi). `upgrade` reads this so\n * it only refreshes the harnesses the project actually uses. Absent on state\n * written before harness selection existed — callers treat absent as \"all\n * three\" for backward compatibility.\n */\n harnesses?: Harness[];\n /**\n * Whether gate skills auto-open rendered HTML artifacts (`open`/`xdg-open`).\n * Absent means true — auto-open was unconditional before this field existed.\n * Persisted here (not a new file) per D12; tune offers the toggle.\n */\n autoOpen?: boolean;\n}\n\nexport function hashContent(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n}\n\n/** Truncate a (full) content hash to the stored length. Idempotent for already-short input. */\nexport function truncateHash(hash: string): string {\n return hash.slice(0, HASH_LENGTH);\n}\n\nexport function readVersion(dir: string): VersionInfo | null {\n const filePath = join(dir, STATE_PATH);\n if (!existsSync(filePath)) return null;\n try {\n const raw = readFileSync(filePath, 'utf-8');\n const parsed = JSON.parse(raw);\n if (typeof parsed.version === 'string' && typeof parsed.files === 'object') {\n // Sanitize the profile: ignore unknown/legacy values rather than\n // returning them (absent or bogus → undefined, callers default to shared).\n const profile = parseGitignoreProfile(parsed.gitignoreProfile);\n // Sanitize harnesses similarly: drop unknown tokens; null (not an array)\n // means \"no recorded selection\" → callers default to all available.\n const harnesses = sanitizeHarnesses(parsed.harnesses);\n return {\n version: parsed.version,\n files: parsed.files,\n ...(profile ? { gitignoreProfile: profile } : {}),\n ...(harnesses ? { harnesses } : {}),\n // Only a real boolean counts; anything else is treated as absent\n // (and absent means true at every call site).\n ...(typeof parsed.autoOpen === 'boolean' ? { autoOpen: parsed.autoOpen } : {}),\n };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nexport function writeVersion(\n dir: string,\n version: string,\n files: Record<string, string>,\n gitignoreProfile?: GitignoreProfile,\n harnesses?: Harness[],\n autoOpen?: boolean\n): void {\n const filePath = join(dir, STATE_PATH);\n // An omitted profile/harness-list/autoOpen means \"no new decision\", not\n // \"clear it\": preserve whatever is already persisted so call sites that only\n // refresh version/hashes can never silently strip a saved choice.\n const existing = readVersion(dir);\n const profile = gitignoreProfile ?? existing?.gitignoreProfile;\n const selectedHarnesses = harnesses ?? existing?.harnesses;\n const openSetting = autoOpen ?? existing?.autoOpen;\n // Unknown keys survive rewrites (D12): a newer Joycraft may have stamped\n // fields this version doesn't know about. Known keys are stripped from the\n // raw pass-through so the sanitized values above stay authoritative.\n let unknownKeys: Record<string, unknown> = {};\n if (existsSync(filePath)) {\n try {\n const raw = JSON.parse(readFileSync(filePath, 'utf-8'));\n if (raw && typeof raw === 'object' && !Array.isArray(raw)) {\n const {\n version: _v,\n files: _f,\n gitignoreProfile: _g,\n harnesses: _h,\n autoOpen: _a,\n ...rest\n } = raw as Record<string, unknown>;\n unknownKeys = rest;\n }\n } catch {\n // Unreadable state is rewritten from scratch — same as readVersion's null.\n }\n }\n // Store truncated hashes — single source of truth for the on-disk shape.\n const truncated: Record<string, string> = {};\n for (const [path, hash] of Object.entries(files)) {\n truncated[path] = truncateHash(hash);\n }\n const data: VersionInfo = {\n version,\n files: truncated,\n ...(profile ? { gitignoreProfile: profile } : {}),\n ...(selectedHarnesses ? { harnesses: selectedHarnesses } : {}),\n ...(openSetting !== undefined ? { autoOpen: openSetting } : {}),\n ...unknownKeys,\n };\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, JSON.stringify(data, null, 2) + '\\n', 'utf-8');\n}\n\n/**\n * The persisted auto-open setting for gate HTML renders. Missing local settings\n * or a missing/invalid key means true; legacy state is consulted only when the\n * local settings file has not been created yet.\n */\nexport interface LocalSettings {\n autoOpen?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Resolve the local settings path while rejecting symlinked descendants.\n * The project root itself may be a symlink, matching the checker path policy.\n */\ninterface LocalSettingsPathState {\n path: string;\n present: boolean;\n safe: boolean;\n}\n\nfunction localSettingsPathState(dir: string): LocalSettingsPathState | undefined {\n let current: string;\n try {\n current = realpathSync(dir);\n if (!lstatSync(current).isDirectory()) return undefined;\n } catch {\n return undefined;\n }\n\n const parts = LOCAL_SETTINGS_PATH.split('/');\n const destination = join(current, ...parts);\n for (const [index, part] of parts.entries()) {\n current = join(current, part);\n try {\n const stat = lstatSync(current);\n if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory())) {\n return { path: destination, present: true, safe: false };\n }\n if (index === parts.length - 1) return { path: destination, present: true, safe: stat.isFile() };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { path: destination, present: false, safe: true };\n return { path: destination, present: true, safe: false };\n }\n }\n return { path: destination, present: false, safe: true };\n}\n\nfunction readLocalSettings(dir: string): LocalSettings | undefined {\n const state = localSettingsPathState(dir);\n if (!state || !state.safe || !state.present) return undefined;\n try {\n const value: unknown = JSON.parse(readFileSync(state.path, 'utf-8'));\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as LocalSettings\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Read auto-open from local settings, falling back to legacy state for migration. */\nexport function getAutoOpen(dir: string): boolean {\n const localState = localSettingsPathState(dir);\n // An unsafe or malformed local settings file must not silently authorize a\n // legacy preference; the safe default is the same as a missing key.\n if (localState && (!localState.safe || localState.present)) {\n const local = readLocalSettings(dir);\n return typeof local?.autoOpen === 'boolean' ? local.autoOpen : true;\n }\n return readVersion(dir)?.autoOpen ?? true;\n}\n\n/**\n * Persist auto-open in local settings while preserving every other local key.\n * A malformed or symlinked settings path is left untouched and reports failure.\n */\nexport function writeAutoOpen(dir: string, autoOpen: boolean): boolean {\n const localState = localSettingsPathState(dir);\n if (!localState || !localState.safe) return false;\n const path = localState.path;\n\n let existing: LocalSettings = {};\n if (localState.present) {\n try {\n if (!lstatSync(path).isFile()) return false;\n const value: unknown = JSON.parse(readFileSync(path, 'utf-8'));\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n existing = value as LocalSettings;\n } catch {\n return false;\n }\n }\n\n const parent = dirname(path);\n const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;\n try {\n mkdirSync(parent, { recursive: true });\n // Recheck after creating parents so a concurrent replacement cannot turn\n // this into a write through a symlink.\n const rechecked = localSettingsPathState(dir);\n if (!rechecked || !rechecked.safe || rechecked.path !== path) return false;\n writeFileSync(temporary, JSON.stringify({ ...existing, autoOpen }, null, 2) + '\\n', {\n encoding: 'utf-8',\n flag: 'wx',\n });\n renameSync(temporary, path);\n return true;\n } catch {\n try { unlinkSync(temporary); } catch { /* best effort cleanup */ }\n return false;\n }\n}\n\n/**\n * Detect the current Joycraft harness level for a project directory.\n * Returns 5 if Level 5 artifacts (autofix workflow + External Validation) are present, 4 otherwise.\n */\nexport function getLevel(dir: string): number {\n const hasAutofix = existsSync(join(dir, '.github', 'workflows', 'autofix.yml'));\n if (!hasAutofix) return 4;\n const claudeMdPath = join(dir, 'CLAUDE.md');\n if (!existsSync(claudeMdPath)) return 4;\n const content = readFileSync(claudeMdPath, 'utf-8');\n return content.includes('## External Validation') ? 5 : 4;\n}\n"],"mappings":";;;AAAA,SAAS,uBAAuB;AAczB,IAAM,YAAY,CAAC,UAAU,SAAS,MAAM,WAAW,KAAK;AAInE,IAAM,iBAA0C;AAAA,EAC9C,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,KAAK;AACP;AAEA,SAAS,UAAU,OAAiC;AAClD,SAAQ,UAAgC,SAAS,KAAK;AACxD;AASO,SAAS,kBAAkB,OAAkC;AAClE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,QAAM,UAAU,IAAI;AAAA,IAClB,MAAM,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC;AAAA,EAC3F;AACA,SAAO,UAAU,OAAO,CAAC,MAAM,QAAQ,IAAI,CAAC,CAAC;AAC/C;AAQO,SAAS,sBAAsB,QAAkC;AACtE,QAAM,SAAS,OACZ,MAAM,QAAQ,EACd,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,EACjC,OAAO,CAAC,MAAM,EAAE,SAAS,C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S,sBAAsB,OAAyC;AAC7E,QAAM,IAAI,OAAO,UAAU,WAAW,MAAM,KAAK,EAAE,YAAY,IAAI;AACnE,SAAO,MAAM,YAAY,MAAM,YAAY,IAAI;AACjD;AAwCO,SAAS,YAAY,KAAiC;AAC3D,QAAM,WAAW,KAAK,KAAK,UAAU;AACrC,MAAI,CAAC,WAAW,QAAQ,EAAG,QAAO;AAClC,MAAI;AACF,UAAM,MAAM,aAAa,UAAU,OAAO;AAC1C,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,QAAI,OAAO,OAAO,YAAY,YAAY,OAAO,OAAO,UAAU,UAAU;AAG1E,YAAM,UAAU,sBAAsB,OAAO,gBAAgB;AAG7D,YAAM,YAAY,kBAAkB,OAAO,SAAS;AACpD,aAAO;AAAA,QACL,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,QACd,GAAI,UAAU,EAAE,kBAAkB,QAAQ,IAAI,CAAC;AAAA,QAC/C,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;AAAA;AAAA;AAAA,QAGjC,GAAI,OAAO,OAAO,aAAa,YAAY,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;AAAA,MAC9E;AAAA,IACF;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ normalizeManifestPath
4
+ } from "./chunk-Z5JFEGWG.js";
5
+
6
+ // src/update-paths.ts
7
+ import { lstatSync, realpathSync } from "fs";
8
+ import { isAbsolute, join, relative, sep } from "path";
9
+ var UpdatePathError = class extends Error {
10
+ code;
11
+ path;
12
+ constructor(code, path, message) {
13
+ super(message);
14
+ this.name = "UpdatePathError";
15
+ this.code = code;
16
+ this.path = path;
17
+ }
18
+ };
19
+ function validatePortableComponents(path) {
20
+ for (const component of path.split("/")) {
21
+ if (component.endsWith(".") || component.endsWith(" ")) {
22
+ throw new Error(`Update path component must not end with a dot or space: '${component}'.`);
23
+ }
24
+ if (component.includes(":")) {
25
+ throw new Error(`Update path component must not contain a colon: '${component}'.`);
26
+ }
27
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(component)) {
28
+ throw new Error(`Update path component uses a reserved Windows device name: '${component}'.`);
29
+ }
30
+ }
31
+ }
32
+ function resolveUpdatePath(root, relativePath) {
33
+ let portable;
34
+ try {
35
+ portable = normalizeManifestPath(relativePath);
36
+ } catch (error) {
37
+ throw new UpdatePathError(
38
+ "invalid-path",
39
+ relativePath,
40
+ error instanceof Error ? error.message : `Invalid update path '${relativePath}'.`
41
+ );
42
+ }
43
+ try {
44
+ validatePortableComponents(portable);
45
+ } catch (error) {
46
+ throw new UpdatePathError(
47
+ "invalid-path",
48
+ relativePath,
49
+ error instanceof Error ? error.message : `Invalid update path '${relativePath}'.`
50
+ );
51
+ }
52
+ if (isAbsolute(portable)) {
53
+ throw new UpdatePathError("outside-root", portable, `Update path must stay inside the project root: '${portable}'.`);
54
+ }
55
+ let canonicalRoot;
56
+ try {
57
+ canonicalRoot = realpathSync(root);
58
+ if (!lstatSync(canonicalRoot).isDirectory()) {
59
+ throw new Error("root is not a directory");
60
+ }
61
+ } catch (error) {
62
+ throw new UpdatePathError(
63
+ "missing-root",
64
+ root,
65
+ `Unable to resolve project root '${root}': ${error instanceof Error ? error.message : String(error)}`
66
+ );
67
+ }
68
+ const candidate = join(canonicalRoot, ...portable.split("/"));
69
+ const escaped = relative(canonicalRoot, candidate);
70
+ if (escaped === ".." || escaped.startsWith(`..${sep}`) || isAbsolute(escaped)) {
71
+ throw new UpdatePathError("outside-root", portable, `Update path escapes the project root: '${portable}'.`);
72
+ }
73
+ let current = canonicalRoot;
74
+ const parts = portable.split("/");
75
+ for (let index = 0; index < parts.length; index += 1) {
76
+ current = join(current, parts[index]);
77
+ let stat;
78
+ try {
79
+ stat = lstatSync(current);
80
+ } catch (error) {
81
+ if (error.code === "ENOENT") break;
82
+ throw new UpdatePathError("invalid-path", portable, `Unable to inspect update path '${portable}': ${String(error)}`);
83
+ }
84
+ if (stat.isSymbolicLink()) {
85
+ throw new UpdatePathError("symlink", portable, `Update path traverses a symlink: '${portable}'.`);
86
+ }
87
+ if (index < parts.length - 1 && !stat.isDirectory()) {
88
+ throw new UpdatePathError("nondirectory-ancestor", portable, `Update path has a non-directory ancestor: '${portable}'.`);
89
+ }
90
+ }
91
+ return candidate;
92
+ }
93
+
94
+ export {
95
+ resolveUpdatePath
96
+ };
97
+ //# sourceMappingURL=chunk-OMFGDJW4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/update-paths.ts"],"sourcesContent":["import { lstatSync, realpathSync } from 'node:fs';\nimport { isAbsolute, join, relative, sep } from 'node:path';\n\nimport { normalizeManifestPath } from './install-manifest.js';\n\nexport type UpdatePathErrorCode =\n | 'invalid-path'\n | 'outside-root'\n | 'missing-root'\n | 'symlink'\n | 'nondirectory-ancestor';\n\n/** A path rejected before an updater can stage, inspect, or mutate it. */\nexport class UpdatePathError extends Error {\n readonly code: UpdatePathErrorCode;\n readonly path: string;\n\n constructor(code: UpdatePathErrorCode, path: string, message: string) {\n super(message);\n this.name = 'UpdatePathError';\n this.code = code;\n this.path = path;\n }\n}\n\nfunction validatePortableComponents(path: string): void {\n for (const component of path.split('/')) {\n if (component.endsWith('.') || component.endsWith(' ')) {\n throw new Error(`Update path component must not end with a dot or space: '${component}'.`);\n }\n if (component.includes(':')) {\n throw new Error(`Update path component must not contain a colon: '${component}'.`);\n }\n // Windows reserves these device basenames even when an extension is\n // present. Reject them on every host so an update plan remains portable.\n if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\..*)?$/i.test(component)) {\n throw new Error(`Update path component uses a reserved Windows device name: '${component}'.`);\n }\n }\n}\n\n/**\n * Resolve a persisted project-relative path beneath a canonical project root.\n *\n * Every existing descendant is inspected with lstat, so symlinks are rejected\n * even when they point back inside the project. Missing trailing components are\n * allowed for staging and first-time writes; an existing ancestor must remain\n * a directory. Callers should repeat this check immediately before a mutation.\n */\nexport function resolveUpdatePath(root: string, relativePath: string): string {\n let portable: string;\n try {\n portable = normalizeManifestPath(relativePath);\n } catch (error) {\n throw new UpdatePathError(\n 'invalid-path',\n relativePath,\n error instanceof Error ? error.message : `Invalid update path '${relativePath}'.`,\n );\n }\n try {\n validatePortableComponents(portable);\n } catch (error) {\n throw new UpdatePathError(\n 'invalid-path',\n relativePath,\n error instanceof Error ? error.message : `Invalid update path '${relativePath}'.`,\n );\n }\n\n // normalizeManifestPath already rejects absolute paths, but retain an\n // explicit check at this boundary so this function remains safe if the\n // persistence validator changes later.\n if (isAbsolute(portable)) {\n throw new UpdatePathError('outside-root', portable, `Update path must stay inside the project root: '${portable}'.`);\n }\n\n let canonicalRoot: string;\n try {\n canonicalRoot = realpathSync(root);\n if (!lstatSync(canonicalRoot).isDirectory()) {\n throw new Error('root is not a directory');\n }\n } catch (error) {\n throw new UpdatePathError(\n 'missing-root',\n root,\n `Unable to resolve project root '${root}': ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const candidate = join(canonicalRoot, ...portable.split('/'));\n const escaped = relative(canonicalRoot, candidate);\n if (escaped === '..' || escaped.startsWith(`..${sep}`) || isAbsolute(escaped)) {\n throw new UpdatePathError('outside-root', portable, `Update path escapes the project root: '${portable}'.`);\n }\n\n let current = canonicalRoot;\n const parts = portable.split('/');\n for (let index = 0; index < parts.length; index += 1) {\n current = join(current, parts[index]);\n let stat;\n try {\n stat = lstatSync(current);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') break;\n throw new UpdatePathError('invalid-path', portable, `Unable to inspect update path '${portable}': ${String(error)}`);\n }\n if (stat.isSymbolicLink()) {\n throw new UpdatePathError('symlink', portable, `Update path traverses a symlink: '${portable}'.`);\n }\n if (index < parts.length - 1 && !stat.isDirectory()) {\n throw new UpdatePathError('nondirectory-ancestor', portable, `Update path has a non-directory ancestor: '${portable}'.`);\n }\n }\n\n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