joycraft 0.7.12 → 0.7.13

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.
@@ -1 +0,0 @@
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;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;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","result"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/init.ts","../src/detect.ts","../src/improve-claude-md.ts","../src/agents-md.ts","../src/permissions.ts","../src/safeguard.ts","../src/tsconfig.ts","../src/auto-memory.ts"],"sourcesContent":["import { mkdirSync, existsSync, writeFileSync, readFileSync, readdirSync, statSync, chmodSync } from 'node:fs';\nimport { join, basename, resolve, dirname } from 'node:path';\nimport { detectStack } from './detect.js';\nimport { generateCLAUDEMd, generateClaudeMdPointer } from './improve-claude-md.js';\nimport { generateAgentsMd } from './agents-md.js';\nimport { generatePermissions } from './permissions.js';\nimport { installSafeguardHooks } from './safeguard.js';\nimport { SKILLS, TEMPLATES, CODEX_SKILLS, PI_SKILLS, PI_SCRIPTS, PI_EXTENSIONS, PI_AGENTS, COPILOT_SKILLS } from './bundled-files.js';\nimport {\n writeVersion,\n readVersion,\n hashContent,\n STATE_PATH,\n DEFAULT_GITIGNORE_PROFILE,\n type GitignoreProfile,\n} from './version.js';\nimport {\n applyGitignoreProfile,\n resolveGitignoreProfile,\n PRIVATE_DIRS_DISPLAY,\n PRIVATE_UNTRACK_COMMAND,\n} from './gitignore.js';\nimport { applyGitattributes } from './gitattributes.js';\nimport { getPackageVersion } from './package-version.js';\nimport { resolveHarnesses, type Harness } from './harness.js';\nimport { resolveExecutionProfile } from './execution-profile.js';\nimport { ensurePiExcludedFromTsconfig } from './tsconfig.js';\nimport { resolveAutoMemoryOffer, AUTO_MEMORY_KEY } from './auto-memory.js';\n\nexport interface InitOptions {\n force: boolean;\n /** Raw --gitignore value from the CLI, if provided. Validated in init(). */\n gitignore?: string;\n}\n\ninterface InitResult {\n created: string[];\n skipped: string[];\n modified: string[];\n warnings: string[];\n}\n\n/**\n * Stub README for docs/backlog/. It documents the convention (deferred work\n * captured mid-sprint, one file per item) and keeps the otherwise-empty\n * directory present in git so the CLAUDE.md / AGENTS.md backlog pointer never\n * dangles. Skills append real entries beside it on user confirmation.\n */\nconst BACKLOG_README = `# Backlog\n\nDeferred work lives here — ideas and follow-ups you surface mid-sprint but\ncan't take on in the current feature. Capturing them keeps the current spec\nfocused without losing the thread.\n\n- One file per item: \\`docs/backlog/YYYY-MM-DD-<short-name>.md\\`.\n- Joycraft skills (\\`/joycraft-interview\\`, \\`/joycraft-new-feature\\`,\n \\`/joycraft-design\\`) offer to write entries here — always with your\n confirmation, never automatically.\n- Promote an item by turning it into a Feature Brief under\n \\`docs/features/<slug>/\\` when you're ready to build it.\n`;\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\nfunction writeFile(path: string, content: string, force: boolean, result: InitResult): void {\n if (existsSync(path) && !force) {\n result.skipped.push(path);\n return;\n }\n writeFileSync(path, content, 'utf-8');\n result.created.push(path);\n}\n\nexport async function init(dir: string, opts: InitOptions): Promise<void> {\n const targetDir = resolve(dir);\n const result: InitResult = { created: [], skipped: [], modified: [], warnings: [] };\n\n // Detect stack\n const stack = await detectStack(targetDir);\n\n // Pi detection — check if project uses Pi coding agent\n const isPi = existsSync(join(targetDir, '.pi'));\n\n // Resolve which harnesses to install (interactive multi-select; non-interactive\n // installs all available). Done before any scaffolding so a \"none\" selection is\n // a clean no-op — and before the gitignore prompt so we don't ask a second\n // question when there's nothing to track.\n const harnesses = await resolveHarnesses(process.stdin.isTTY === true);\n const wants = (h: Harness): boolean => harnesses.includes(h);\n if (harnesses.length === 0) {\n console.log(\n '\\nNo harness selected — Joycraft will not install any skills.\\n' +\n 'Please run init again and select at least one harness (claude, codex, pi, copilot).'\n );\n return;\n }\n\n // Capture the Execution Profile (D6) for the harnesses just selected — swarm\n // opt-in and free-text model/effort per harness. Interactive asks;\n // non-interactive takes the explicit-no default so a scripted run never\n // blocks. It is written into AGENTS.md below (its one and only home).\n const executionProfile = await resolveExecutionProfile(harnesses, process.stdin.isTTY === true);\n\n // Resolve the gitignore profile up front (flag → persisted → prompt → default)\n // so it governs both the .gitignore writes and the \"teammates won't get skills\"\n // warning below. Unlike upgrade, init persists even the non-interactive\n // default: init creates the state fresh, and `shared` is the documented\n // default for a first run.\n const { profile: gitignoreProfile } = await resolveGitignoreProfile({\n flag: opts.gitignore,\n persisted: readVersion(targetDir)?.gitignoreProfile,\n interactive: process.stdin.isTTY === true,\n promptIntro: '\\nHow should Joycraft files be tracked in git?',\n });\n\n // Offer to disable Claude Code auto-memory for this project — one home for\n // facts (see auto-memory.ts). Asked here with the other interactive questions;\n // the guarded write happens with the rest of the settings.json merge below.\n // Only meaningful when the Claude harness is being installed at all.\n const disableAutoMemory = wants('claude')\n ? await resolveAutoMemoryOffer(process.stdin.isTTY === true)\n : false;\n\n // 1. Create the Joycraft-managed docs/ subdirectories that the generated\n // CLAUDE.md / AGENTS.md point at up front, so no generated pointer dangles:\n // - context/ — the project context layer (gather-context populates it)\n // - backlog/ — where deferred work is captured mid-sprint; CLAUDE.md and\n // AGENTS.md both reference it, so it must exist after init even\n // before a skill writes its first entry. A README stub explains\n // the convention and keeps the otherwise-empty dir in git.\n // Everything else (briefs/specs/discoveries/decisions/contracts/features/...)\n // stays lazy-created by the skills that write to them. Solo-first: minimal\n // preemptive ceremony, but never a dangling pointer.\n ensureDir(join(targetDir, 'docs', 'context'));\n ensureDir(join(targetDir, 'docs', 'backlog'));\n writeFile(join(targetDir, 'docs', 'backlog', 'README.md'), BACKLOG_README, opts.force, result);\n\n // 1b. Scan for existing non-Joycraft skills before copying ours (claude only).\n const skillsDir = join(targetDir, '.claude', 'skills');\n let existingSkills: string[] = [];\n if (wants('claude') && existsSync(skillsDir)) {\n existingSkills = readdirSync(skillsDir)\n .filter(name => {\n if (name.startsWith('joycraft-')) return false;\n if (name.startsWith('.')) return false;\n const fullPath = join(skillsDir, name);\n try {\n return statSync(fullPath).isDirectory();\n } catch {\n return false;\n }\n });\n }\n\n // 2. Copy skill files to .claude/skills/<name>/SKILL.md\n if (wants('claude')) {\n for (const [filename, content] of Object.entries(SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n const skillDir = join(skillsDir, skillName);\n ensureDir(skillDir);\n writeFile(join(skillDir, 'SKILL.md'), content, opts.force, result);\n }\n }\n\n // 2b. Copy Codex skill files to .agents/skills/<name>/SKILL.md\n if (wants('codex')) {\n const codexSkillsDir = join(targetDir, '.agents', 'skills');\n for (const [filename, content] of Object.entries(CODEX_SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n const skillDir = join(codexSkillsDir, skillName);\n ensureDir(skillDir);\n writeFile(join(skillDir, 'SKILL.md'), content, opts.force, result);\n }\n }\n\n // 2c–2f. Install the Pi harness: skills, runtime scripts, extension, subagents.\n if (wants('pi')) {\n const piSkillsDir = join(targetDir, '.pi', 'skills');\n for (const [filename, content] of Object.entries(PI_SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n const skillDir = join(piSkillsDir, skillName);\n ensureDir(skillDir);\n writeFile(join(skillDir, 'SKILL.md'), content, opts.force, result);\n }\n\n const piScriptsDir = join(targetDir, '.pi', 'scripts', 'joycraft');\n ensureDir(piScriptsDir);\n for (const [name, content] of Object.entries(PI_SCRIPTS)) {\n const scriptPath = join(piScriptsDir, name);\n writeFile(scriptPath, content, opts.force, result);\n if (name !== 'README.md') {\n try { chmodSync(scriptPath, 0o755); } catch { /* non-fatal */ }\n }\n }\n\n const piExtDir = join(targetDir, '.pi', 'extensions');\n ensureDir(piExtDir);\n for (const [name, content] of Object.entries(PI_EXTENSIONS)) {\n writeFile(join(piExtDir, name), content, opts.force, result);\n }\n\n const piAgentsDir = join(targetDir, '.pi', 'agents');\n ensureDir(piAgentsDir);\n for (const [name, content] of Object.entries(PI_AGENTS)) {\n writeFile(join(piAgentsDir, name), content, opts.force, result);\n }\n }\n\n // 2g. Install the Copilot harness: skills to .github/skills/.\n // Copilot reads AGENTS.md directly, so no separate instructions file is needed.\n if (wants('copilot')) {\n const githubDir = join(targetDir, '.github');\n ensureDir(githubDir);\n\n // Copilot skills — same SKILL.md pattern as other harnesses.\n const copilotSkillsDir = join(githubDir, 'skills');\n ensureDir(copilotSkillsDir);\n for (const [filename, content] of Object.entries(COPILOT_SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n const skillDir = join(copilotSkillsDir, skillName);\n ensureDir(skillDir);\n writeFile(join(skillDir, 'SKILL.md'), content, opts.force, result);\n }\n }\n\n // 3. Copy template files to docs/templates/\n const templatesDir = join(targetDir, 'docs', 'templates');\n ensureDir(templatesDir);\n for (const [filename, content] of Object.entries(TEMPLATES)) {\n ensureDir(dirname(join(templatesDir, filename)));\n writeFile(join(templatesDir, filename), content, opts.force, result);\n }\n\n // 4/5. Handle CLAUDE.md + AGENTS.md — only create if missing, never modify\n // existing (unless --force).\n //\n // Multi-tool install (Codex, Pi, and/or Copilot selected): AGENTS.md is the\n // single shared instruction file and CLAUDE.md is Anthropic's documented import\n // pointer (`@AGENTS.md`) — Claude Code doesn't read AGENTS.md natively, and\n // two full sibling files drift. Claude-only install: classic full CLAUDE.md\n // plus the slim AGENTS.md, unchanged.\n const multiTool = wants('codex') || wants('pi') || wants('copilot');\n const claudeMdPath = join(targetDir, 'CLAUDE.md');\n if (existsSync(claudeMdPath) && !opts.force) {\n result.skipped.push(claudeMdPath);\n } else {\n const projectName = basename(targetDir);\n const content = multiTool\n ? generateClaudeMdPointer()\n : generateCLAUDEMd(projectName, stack, existingSkills, {\n privateProfile: gitignoreProfile === 'private',\n projectDir: targetDir,\n });\n writeFileSync(claudeMdPath, content, 'utf-8');\n result.created.push(claudeMdPath);\n }\n\n const agentsMdPath = join(targetDir, 'AGENTS.md');\n if (existsSync(agentsMdPath) && !opts.force) {\n // An existing AGENTS.md is never touched by init — not even to insert the\n // Execution Profile. Init's contract is create-if-missing (NEVER overwrite\n // user files without --force), and a user's AGENTS.md is theirs. The\n // insert-if-absent path belongs to `joycraft upgrade` (and the interactive\n // offer to `/joycraft-tune`), which is where users opt into Joycraft\n // editing files they already own.\n result.skipped.push(agentsMdPath);\n } else {\n const projectName = basename(targetDir);\n const content = multiTool\n ? generateCLAUDEMd(projectName, stack, existingSkills, {\n privateProfile: gitignoreProfile === 'private',\n multiTool: true,\n executionProfile,\n projectDir: targetDir,\n })\n : generateAgentsMd(projectName, stack, gitignoreProfile === 'private', executionProfile, undefined, targetDir);\n writeFileSync(agentsMdPath, content, 'utf-8');\n result.created.push(agentsMdPath);\n }\n\n // 6. Write the hidden state (docs/.joycraft/state.json) with hashes of the\n // files we actually installed. Only hash a harness's files when that harness\n // was selected — otherwise upgrade would later see the unwritten files as\n // missing/drifted. Templates are harness-agnostic and always installed.\n const fileHashes: Record<string, string> = {};\n if (wants('claude')) {\n for (const [filename, content] of Object.entries(SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n fileHashes[join('.claude', 'skills', skillName, 'SKILL.md')] = hashContent(content);\n }\n }\n if (wants('codex')) {\n for (const [filename, content] of Object.entries(CODEX_SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n fileHashes[join('.agents', 'skills', skillName, 'SKILL.md')] = hashContent(content);\n }\n }\n for (const [filename, content] of Object.entries(TEMPLATES)) {\n fileHashes[join('docs', 'templates', filename)] = hashContent(content);\n }\n if (wants('pi')) {\n for (const [filename, content] of Object.entries(PI_SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n fileHashes[join('.pi', 'skills', skillName, 'SKILL.md')] = hashContent(content);\n }\n for (const [name, content] of Object.entries(PI_SCRIPTS)) {\n fileHashes[join('.pi', 'scripts', 'joycraft', name)] = hashContent(content);\n }\n for (const [name, content] of Object.entries(PI_EXTENSIONS)) {\n fileHashes[join('.pi', 'extensions', name)] = hashContent(content);\n }\n for (const [name, content] of Object.entries(PI_AGENTS)) {\n fileHashes[join('.pi', 'agents', name)] = hashContent(content);\n }\n }\n if (wants('copilot')) {\n for (const [filename, content] of Object.entries(COPILOT_SKILLS)) {\n const skillName = filename.replace(/\\.md$/, '');\n fileHashes[join('.github', 'skills', skillName, 'SKILL.md')] = hashContent(content);\n }\n }\n writeVersion(targetDir, getPackageVersion(), fileHashes, gitignoreProfile, harnesses);\n\n // 6b. Apply the chosen gitignore profile.\n // - shared: ignore only the hidden upgrade-state file (npm-lockfile-style;\n // tool-managed state that should never land in commits).\n // - private: ignore .claude/, .agents/, .pi/ — track only CLAUDE.md,\n // AGENTS.md, docs/.\n // Append-only + create-if-absent + idempotent (never clobbers existing entries).\n applyGitignoreProfile(targetDir, gitignoreProfile);\n\n // 6b'. Mark workflow-exhaust docs (features, bugfixes, discoveries,\n // templates) linguist-generated so GitHub collapses them in PR review.\n // Same append-only/idempotent contract as the .gitignore writes; durable\n // knowledge (CLAUDE.md, docs/context/) stays visible.\n applyGitattributes(targetDir);\n\n // 6c. Pi only: keep the installed `.pi/extensions/*.ts` runtime out of the\n // user's TypeScript program. It imports a Pi-only package the project doesn't\n // depend on, so a default `**​/*.ts` toolchain (e.g. create-next-app) would\n // fail `tsc`/build on it. Surgically add `.pi` to tsconfig exclude, idempotent,\n // and report transparently (never silently rewrites — see tsconfig.ts).\n if (wants('pi')) {\n const outcome = ensurePiExcludedFromTsconfig(targetDir);\n if (outcome.status === 'added') {\n result.modified.push(outcome.path);\n result.warnings.push(\n 'Added \".pi\" to tsconfig.json \"exclude\" so the Pi extension stays out of your TypeScript build.'\n );\n } else if (outcome.status === 'skipped') {\n result.warnings.push(outcome.reason);\n }\n }\n\n // Steps 7–9 configure the Claude Code harness (.claude/hooks + settings.json).\n // Skip entirely when claude isn't a selected harness — a codex/pi-only install\n // must not create a .claude/ tree.\n if (wants('claude')) {\n // 7. Install version check hook\n const hooksDir = join(targetDir, '.claude', 'hooks');\n ensureDir(hooksDir);\n const hookScript = `// Joycraft version check — runs on Claude Code session start\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\ntry {\n const data = JSON.parse(readFileSync(join(process.cwd(), '${STATE_PATH.split(/[\\\\/]/).join(\"', '\")}'), 'utf-8'));\n const res = await fetch('https://registry.npmjs.org/joycraft/latest', { signal: AbortSignal.timeout(3000) });\n if (res.ok) {\n const latest = (await res.json()).version;\n if (data.version !== latest) console.log('Joycraft ' + latest + ' available (you have ' + data.version + '). Run: npx joycraft@latest upgrade');\n }\n} catch {}\n`;\n writeFile(join(hooksDir, 'joycraft-version-check.mjs'), hookScript, opts.force, result);\n\n // Update .claude/settings.json with SessionStart hook\n const settingsPath = join(targetDir, '.claude', 'settings.json');\n let settings: Record<string, unknown> = {};\n let settingsMalformed = false;\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n settingsMalformed = true;\n result.warnings.push(\n 'settings.json exists but is malformed — skipping settings merge to protect your config.\\n' +\n ' Fix the JSON in .claude/settings.json and re-run init.'\n );\n }\n }\n if (!settingsMalformed) {\n if (!settings.hooks) settings.hooks = {};\n const hooksConfig = settings.hooks as Record<string, unknown>;\n if (!hooksConfig.SessionStart) hooksConfig.SessionStart = [];\n const sessionStartHooks = hooksConfig.SessionStart as Array<Record<string, unknown>>;\n const hasJoycraftHook = sessionStartHooks.some(h => {\n const innerHooks = h.hooks as Array<Record<string, unknown>> | undefined;\n return innerHooks?.some(ih => typeof ih.command === 'string' && ih.command.includes('joycraft'));\n });\n\n // Enable Claude Code agent teams (experimental) so skills like\n // /joycraft-research can fan out to subagents without the user having to\n // hand-edit settings.json. Idempotent: only set when absent — never clobber\n // an explicit user value.\n if (!settings.env) settings.env = {};\n const env = settings.env as Record<string, unknown>;\n const envMissing = !('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS' in env);\n if (envMissing) {\n env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = '1';\n }\n\n // Apply the accepted auto-memory offer. Idempotent and non-destructive by\n // the same rule as the env write above: only set when the key is absent, so\n // an explicit user value (true or false) is never clobbered. Project scope\n // only — this path is `<targetDir>/.claude/settings.json`, never ~/.claude.\n const autoMemoryMissing = !(AUTO_MEMORY_KEY in settings);\n const writeAutoMemory = disableAutoMemory && autoMemoryMissing;\n if (writeAutoMemory) {\n settings[AUTO_MEMORY_KEY] = false;\n }\n\n if (!hasJoycraftHook) {\n sessionStartHooks.push({\n matcher: '',\n hooks: [{\n type: 'command',\n command: 'node .claude/hooks/joycraft-version-check.mjs',\n }],\n });\n }\n if (!hasJoycraftHook || envMissing || writeAutoMemory) {\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n if (!result.created.includes(settingsPath)) result.created.push(settingsPath);\n }\n\n // 8. Generate and merge permission rules into settings.json\n const permissions = generatePermissions(stack);\n // Re-read settings in case it was just created by hook step\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n result.warnings.push(\n 'settings.json became unreadable after hook merge — skipping permissions merge.\\n' +\n ' Fix the JSON in .claude/settings.json and re-run init.'\n );\n settingsMalformed = true;\n }\n }\n if (!settingsMalformed) {\n if (!settings.permissions) settings.permissions = {};\n const perms = settings.permissions as Record<string, string[]>;\n if (!perms.allow) perms.allow = [];\n if (!perms.deny) perms.deny = [];\n for (const rule of permissions.allow) {\n if (!perms.allow.includes(rule)) perms.allow.push(rule);\n }\n for (const rule of permissions.deny) {\n if (!perms.deny.includes(rule)) perms.deny.push(rule);\n }\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n }\n }\n\n // 9. Install safeguard hooks (PreToolUse deny-pattern blocking)\n const hookResult = installSafeguardHooks(targetDir, [], opts.force, settingsMalformed);\n result.created.push(...hookResult.created);\n result.skipped.push(...hookResult.skipped);\n } // end if (wants('claude'))\n\n // 10. Check .gitignore for .claude/ exclusion.\n // Only a concern under the `shared` profile, where the intent is to commit\n // skills so teammates get them. Under `private`, ignoring .claude/ is the\n // user's deliberate choice — surfacing a warning there would be wrong.\n if (gitignoreProfile === 'shared' && wants('claude')) {\n const gitignorePath = join(targetDir, '.gitignore');\n if (existsSync(gitignorePath)) {\n const gitignore = readFileSync(gitignorePath, 'utf-8');\n if (/^\\.claude\\/?$/m.test(gitignore) || /^\\.claude\\/\\*$/m.test(gitignore)) {\n result.warnings.push(\n '.claude/ is in your .gitignore — teammates won\\'t get Joycraft skills.\\n' +\n ' Add this line to .gitignore to fix: !.claude/skills/'\n );\n }\n }\n }\n\n // 11. Print summary\n printSummary(result, stack, existingSkills, isPi, gitignoreProfile, harnesses);\n}\n\nfunction printSummary(result: InitResult, stack: import('./detect.js').StackInfo, existingSkills: string[] = [], isPi: boolean = false, gitignoreProfile: GitignoreProfile = DEFAULT_GITIGNORE_PROFILE, harnesses: Harness[] = []): void {\n console.log('\\nJoycraft initialized!\\n');\n\n if (harnesses.length > 0) {\n console.log(` Installed harnesses: ${harnesses.join(', ')}`);\n }\n\n if (stack.language !== 'unknown') {\n const fw = stack.framework ? ` + ${stack.framework}` : '';\n console.log(` Detected stack: ${stack.language}${fw} (${stack.packageManager})`);\n } else {\n console.log(' Detected stack: unknown (no recognized manifest found)');\n }\n\n if (isPi) {\n console.log(' Detected agent: Pi');\n }\n\n if (gitignoreProfile === 'private') {\n console.log(` Gitignore profile: private (${PRIVATE_DIRS_DISPLAY} are gitignored — only CLAUDE.md, AGENTS.md, docs/ are tracked)`);\n } else {\n console.log(' Gitignore profile: shared (skills and docs are tracked for your team)');\n }\n\n if (result.created.length > 0) {\n console.log(`\\n Created ${result.created.length} file(s):`);\n for (const f of result.created) {\n console.log(` + ${f}`);\n }\n }\n\n if (result.modified.length > 0) {\n console.log(`\\n Modified ${result.modified.length} file(s):`);\n for (const f of result.modified) {\n console.log(` ~ ${f}`);\n }\n }\n\n if (result.skipped.length > 0) {\n console.log(`\\n Skipped ${result.skipped.length} file(s) (already exist, use --force to overwrite):`);\n for (const f of result.skipped) {\n console.log(` - ${f}`);\n }\n }\n\n if (result.warnings.length > 0) {\n console.log('\\n Warnings:');\n for (const w of result.warnings) {\n console.log(` ⚠ ${w}`);\n }\n }\n\n if (existingSkills.length > 0) {\n console.log(`\\n Found existing skills: ${existingSkills.join(', ')}. These are preserved — Joycraft is additive.`);\n }\n\n const hasExistingClaude = result.skipped.some(f => f.endsWith('CLAUDE.md'));\n\n console.log('\\n Next steps:');\n console.log(' 1. Run Claude Code and try /joycraft-setup — the first-run door that sets up and assesses your project');\n if (hasExistingClaude) {\n console.log(' (it routes to /joycraft-tune to assess and improve your existing CLAUDE.md)');\n } else {\n console.log(' (then review and customize the generated CLAUDE.md for your project)');\n }\n console.log(' 2. Try /joycraft-new-feature to start building with the spec-driven workflow');\n console.log(' (feature artifacts are written to docs/features/<slug>/ as you go)');\n if (gitignoreProfile === 'private') {\n console.log(` 3. Commit CLAUDE.md, AGENTS.md, and docs/ — ${PRIVATE_DIRS_DISPLAY} stay local (gitignored)`);\n console.log(` (if any harness files were already committed, run: ${PRIVATE_UNTRACK_COMMAND})`);\n } else {\n console.log(' 3. Commit .claude/skills/ and docs/ so your team gets the same workflow');\n }\n if (!isPi) {\n console.log(' Pi: Skills installed to .pi/skills/. Use /skill:joycraft-* to invoke.');\n }\n console.log('');\n}\n","import { readFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface TestingStrategy {\n backbone: 'playwright' | 'maestro' | 'api' | 'native';\n testFormat: string;\n layers: ('ui' | 'api' | 'logic' | 'static')[];\n}\n\nexport interface StackInfo {\n language: string;\n packageManager: string;\n commands: {\n build?: string;\n test?: string;\n lint?: string;\n typecheck?: string;\n deploy?: string;\n };\n framework?: string;\n testingStrategy?: TestingStrategy;\n}\n\nconst WEB_FRAMEWORKS = new Set(['Next.js', 'Nuxt', 'Remix', 'React', 'Vue', 'Svelte']);\nconst API_FRAMEWORKS = new Set(['Express', 'Fastify', 'FastAPI', 'Django', 'Flask', 'Gin', 'Fiber', 'Echo', 'Actix', 'Axum', 'Rocket']);\n\nfunction buildTestingStrategy(backbone: TestingStrategy['backbone']): TestingStrategy {\n switch (backbone) {\n case 'playwright':\n return { backbone, testFormat: '.spec.ts', layers: ['ui', 'api', 'logic', 'static'] };\n case 'maestro':\n return { backbone, testFormat: '.yaml', layers: ['ui', 'api', 'logic', 'static'] };\n case 'api':\n return { backbone, testFormat: '.test.ts', layers: ['api', 'logic', 'static'] };\n case 'native':\n return { backbone, testFormat: '.test.ts', layers: ['logic', 'static'] };\n }\n}\n\nfunction readFile(path: string): string | null {\n try {\n return readFileSync(path, 'utf-8');\n } catch {\n return null;\n }\n}\n\nfunction detectNodeFramework(pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }): string | undefined {\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (allDeps['next']) return 'Next.js';\n if (allDeps['nuxt']) return 'Nuxt';\n if (allDeps['@remix-run/node'] || allDeps['@remix-run/react']) return 'Remix';\n if (allDeps['express']) return 'Express';\n if (allDeps['fastify']) return 'Fastify';\n if (allDeps['react']) return 'React';\n if (allDeps['vue']) return 'Vue';\n if (allDeps['svelte']) return 'Svelte';\n return undefined;\n}\n\nfunction detectNodeTestFramework(pkg: { devDependencies?: Record<string, string>; dependencies?: Record<string, string> }): string | undefined {\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (allDeps['vitest']) return 'vitest';\n if (allDeps['jest']) return 'jest';\n if (allDeps['mocha']) return 'mocha';\n return undefined;\n}\n\nfunction detectNodePackageManager(dir: string): string {\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun';\n return 'npm';\n}\n\nfunction detectNode(dir: string): StackInfo | null {\n const raw = readFile(join(dir, 'package.json'));\n if (raw === null) return null;\n\n let pkg: Record<string, unknown>;\n try {\n pkg = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const pm = detectNodePackageManager(dir);\n const run = pm === 'npm' ? 'npm run' : pm;\n const scripts = (pkg.scripts ?? {}) as Record<string, string>;\n const framework = detectNodeFramework(pkg as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> });\n const testFramework = detectNodeTestFramework(pkg as { devDependencies?: Record<string, string>; dependencies?: Record<string, string> });\n\n const commands: StackInfo['commands'] = {};\n if (scripts.build) commands.build = `${run} build`;\n else commands.build = `${run} build`;\n if (scripts.test) commands.test = `${run} test`;\n else if (testFramework) commands.test = `${run} test`;\n else commands.test = `${pm === 'npm' ? 'npm' : pm} test`;\n if (scripts.lint) commands.lint = `${run} lint`;\n if (scripts.typecheck) commands.typecheck = `${run} typecheck`;\n else if ((pkg.devDependencies as Record<string, string> | undefined)?.['typescript']) {\n commands.typecheck = 'tsc --noEmit';\n }\n\n const allDeps = { ...(pkg.dependencies as Record<string, string> | undefined), ...(pkg.devDependencies as Record<string, string> | undefined) };\n let testingStrategy: TestingStrategy;\n if (allDeps['react-native']) {\n testingStrategy = buildTestingStrategy('maestro');\n } else if (framework && WEB_FRAMEWORKS.has(framework)) {\n testingStrategy = buildTestingStrategy('playwright');\n } else if (framework && API_FRAMEWORKS.has(framework)) {\n testingStrategy = buildTestingStrategy('api');\n } else {\n testingStrategy = buildTestingStrategy('native');\n }\n\n return {\n language: 'node',\n packageManager: pm,\n commands,\n framework,\n testingStrategy,\n };\n}\n\nfunction detectPythonFramework(content: string): string | undefined {\n if (/fastapi/i.test(content)) return 'FastAPI';\n if (/django/i.test(content)) return 'Django';\n if (/flask/i.test(content)) return 'Flask';\n return undefined;\n}\n\nfunction detectPython(dir: string): StackInfo | null {\n const pyproject = readFile(join(dir, 'pyproject.toml'));\n if (pyproject !== null) {\n const isPoetry = /\\[tool\\.poetry\\]/.test(pyproject);\n const isUv = existsSync(join(dir, 'uv.lock'));\n\n let pm: string;\n let run: string;\n if (isUv) {\n pm = 'uv';\n run = 'uv run';\n } else if (isPoetry) {\n pm = 'poetry';\n run = 'poetry run';\n } else {\n pm = 'pip';\n run = 'python -m';\n }\n\n const framework = detectPythonFramework(pyproject);\n const hasPytest = /pytest/i.test(pyproject);\n\n const testingStrategy = framework && API_FRAMEWORKS.has(framework)\n ? buildTestingStrategy('api')\n : buildTestingStrategy('native');\n\n return {\n language: 'python',\n packageManager: pm,\n commands: {\n build: `${pm === 'poetry' ? 'poetry' : pm} build`,\n test: hasPytest ? `${run} pytest` : `${run} pytest`,\n lint: `${run} ruff check .`,\n },\n framework,\n testingStrategy,\n };\n }\n\n const requirements = readFile(join(dir, 'requirements.txt'));\n if (requirements !== null) {\n const framework = detectPythonFramework(requirements);\n const testingStrategy = framework && API_FRAMEWORKS.has(framework)\n ? buildTestingStrategy('api')\n : buildTestingStrategy('native');\n\n return {\n language: 'python',\n packageManager: 'pip',\n commands: {\n build: 'pip install -e .',\n test: 'python -m pytest',\n lint: 'python -m ruff check .',\n },\n framework,\n testingStrategy,\n };\n }\n\n return null;\n}\n\nfunction detectRust(dir: string): StackInfo | null {\n const cargo = readFile(join(dir, 'Cargo.toml'));\n if (cargo === null) return null;\n\n let framework: string | undefined;\n if (/actix-web/.test(cargo)) framework = 'Actix';\n else if (/axum/.test(cargo)) framework = 'Axum';\n else if (/rocket/.test(cargo)) framework = 'Rocket';\n\n const testingStrategy = framework && API_FRAMEWORKS.has(framework)\n ? buildTestingStrategy('api')\n : buildTestingStrategy('native');\n\n return {\n language: 'rust',\n packageManager: 'cargo',\n commands: {\n build: 'cargo build',\n test: 'cargo test',\n lint: 'cargo clippy',\n },\n framework,\n testingStrategy,\n };\n}\n\nfunction detectGo(dir: string): StackInfo | null {\n const gomod = readFile(join(dir, 'go.mod'));\n if (gomod === null) return null;\n\n let framework: string | undefined;\n if (/github\\.com\\/gin-gonic\\/gin/.test(gomod)) framework = 'Gin';\n else if (/github\\.com\\/gofiber\\/fiber/.test(gomod)) framework = 'Fiber';\n else if (/github\\.com\\/labstack\\/echo/.test(gomod)) framework = 'Echo';\n\n const testingStrategy = framework && API_FRAMEWORKS.has(framework)\n ? buildTestingStrategy('api')\n : buildTestingStrategy('native');\n\n return {\n language: 'go',\n packageManager: 'go',\n commands: {\n build: 'go build ./...',\n test: 'go test ./...',\n lint: 'golangci-lint run',\n },\n framework,\n testingStrategy,\n };\n}\n\nfunction detectSwift(dir: string): StackInfo | null {\n const pkg = readFile(join(dir, 'Package.swift'));\n if (pkg === null) return null;\n\n return {\n language: 'swift',\n packageManager: 'swift',\n commands: {\n build: 'swift build',\n test: 'swift test',\n },\n testingStrategy: buildTestingStrategy('native'),\n };\n}\n\nfunction detectFlutter(dir: string): StackInfo | null {\n const pubspec = readFile(join(dir, 'pubspec.yaml'));\n if (pubspec === null) return null;\n if (!/flutter/i.test(pubspec)) return null;\n\n return {\n language: 'dart',\n packageManager: 'flutter',\n commands: {\n build: 'flutter build',\n test: 'flutter test',\n lint: 'flutter analyze',\n },\n framework: 'Flutter',\n testingStrategy: buildTestingStrategy('maestro'),\n };\n}\n\nfunction detectXcode(dir: string): StackInfo | null {\n // Check for .xcodeproj or .xcworkspace directories\n try {\n const entries = readdirSync(dir);\n const hasXcode = entries.some(e => e.endsWith('.xcodeproj') || e.endsWith('.xcworkspace'));\n if (!hasXcode) return null;\n } catch {\n return null;\n }\n\n return {\n language: 'swift',\n packageManager: 'xcode',\n commands: {\n build: 'xcodebuild build',\n test: 'xcodebuild test',\n },\n testingStrategy: buildTestingStrategy('maestro'),\n };\n}\n\nfunction detectMakefile(dir: string): StackInfo | null {\n const makefile = readFile(join(dir, 'Makefile'));\n if (makefile === null) return null;\n\n const commands: StackInfo['commands'] = {};\n commands.build = 'make build';\n if (/^test:/m.test(makefile)) commands.test = 'make test';\n if (/^lint:/m.test(makefile)) commands.lint = 'make lint';\n\n return {\n language: 'unknown',\n packageManager: 'make',\n commands,\n };\n}\n\nfunction detectDockerfile(dir: string): StackInfo | null {\n if (!existsSync(join(dir, 'Dockerfile'))) return null;\n\n return {\n language: 'unknown',\n packageManager: 'docker',\n commands: {\n build: 'docker build .',\n },\n };\n}\n\nexport async function detectStack(dir: string): Promise<StackInfo> {\n const detectors = [\n detectNode,\n detectPython,\n detectRust,\n detectGo,\n detectFlutter,\n detectSwift,\n detectXcode,\n detectMakefile,\n detectDockerfile,\n ];\n\n for (const detect of detectors) {\n const result = detect(dir);\n if (result) return result;\n }\n\n return { language: 'unknown', packageManager: '', commands: {} };\n}\n","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { StackInfo } from './detect.js';\nimport { renderFolderMap, ensureFolderMapSection, FOLDER_MAP_OPEN } from './folder-map.js';\nimport {\n ensureExecutionProfileSection,\n renderExecutionProfileSection,\n type ExecutionProfile,\n} from './execution-profile.js';\n\nexport interface ImproveOptions {\n projectDir?: string;\n /**\n * When true, the project gitignores the harness dirs (`private` profile), so\n * teammates who clone won't get the skill files. A discreet setup note is\n * emitted telling them to run `npx joycraft init` to regenerate them locally.\n */\n privateProfile?: boolean;\n /**\n * When true, the generated document is the single shared AGENTS.md for a\n * multi-tool install (Codex, Pi, and/or Copilot selected alongside or instead of\n * Claude Code). Adds the External API Safety rules and a per-tool skill\n * invocation note, since the one document serves every harness. CLAUDE.md\n * then becomes an `@AGENTS.md` import pointer (see generateClaudeMdPointer).\n */\n multiTool?: boolean;\n /**\n * The project's Execution Profile (D6). When supplied, a sentinel-delimited\n * `## Execution Profile` section is written (generate) or inserted-if-absent\n * (improve). An existing region is never rewritten — it's the user's data.\n * Only meaningful for documents that serve as AGENTS.md.\n */\n executionProfile?: ExecutionProfile;\n /**\n * Elicited directional content (D5). When supplied and non-empty, one\n * `## Product Identity` section is appended — never a TODO stub, so the\n * section only exists once gather-context/interview collected real answers.\n */\n identity?: ProductIdentity;\n}\n\n/**\n * Directional content for the `## Product Identity` section. Every field is\n * optional; only non-empty ones become subsections.\n */\nexport interface ProductIdentity {\n values?: string[];\n glossary?: Record<string, string>;\n taste?: string[];\n}\n\nexport const PRODUCT_IDENTITY_HEADER_PATTERN = /product\\s*identity/i;\n\nfunction nonEmptyLines(items?: string[]): string[] {\n return (items ?? []).map(s => s.trim()).filter(s => s.length > 0);\n}\n\nfunction glossaryEntries(glossary?: Record<string, string>): [string, string][] {\n return Object.entries(glossary ?? [])\n .map(([term, def]) => [term.trim(), def.trim()] as [string, string])\n .filter(([term, def]) => term.length > 0 && def.length > 0);\n}\n\n/**\n * Renders the identity section, or `null` when there is nothing to say.\n * Dated so D5's pre-committed optimize review is self-announcing.\n */\nexport function generateProductIdentitySection(identity?: ProductIdentity): string | null {\n if (!identity) return null;\n\n const values = nonEmptyLines(identity.values);\n const taste = nonEmptyLines(identity.taste);\n const glossary = glossaryEntries(identity.glossary);\n if (values.length === 0 && taste.length === 0 && glossary.length === 0) return null;\n\n const today = new Date().toISOString().slice(0, 10);\n const parts: string[] = ['## Product Identity', '', `_Added ${today} — review at next optimize run_`];\n\n if (values.length > 0) {\n parts.push('', '### Values', '', ...values.map(v => `- ${v}`));\n }\n if (glossary.length > 0) {\n parts.push('', '### Glossary', '', ...glossary.map(([term, def]) => `- **${term}** — ${def}`));\n }\n if (taste.length > 0) {\n parts.push('', '### Taste', '', ...taste.map(t => `- ${t}`));\n }\n\n return parts.join('\\n');\n}\n\n/**\n * Stable phrase used to detect (and avoid duplicating) the private-mode setup\n * note across re-runs. Kept terse so it lives quietly in the Getting Started\n * footer rather than spending a heading.\n */\nexport const PRIVATE_SETUP_NOTE_MARKER = 'After cloning, run';\n\nexport function generatePrivateSetupNote(): string {\n return `> **Private setup:** The harness dirs (\\`.claude/\\`, \\`.agents/\\`, \\`.pi/\\`) are gitignored in this repo, so they aren't committed. ${PRIVATE_SETUP_NOTE_MARKER} \\`npx joycraft init\\` to regenerate the skill files locally — it only creates missing files and leaves your committed \\`CLAUDE.md\\`, \\`AGENTS.md\\`, and \\`docs/\\` untouched (use \\`--force\\` only if you deliberately want to regenerate them).`;\n}\n\ninterface Section {\n header: string;\n content: string;\n}\n\nfunction parseSections(markdown: string): Section[] {\n const lines = markdown.split('\\n');\n const sections: Section[] = [];\n let currentHeader = '';\n let currentLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith('## ')) {\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n currentHeader = line;\n currentLines = [];\n } else {\n currentLines.push(line);\n }\n }\n\n // Push the last section\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n\n return sections;\n}\n\nfunction hasSection(sections: Section[], pattern: RegExp): boolean {\n return sections.some(s => pattern.test(s.header));\n}\n\nfunction generateCommandsBlock(stack: StackInfo): string {\n const lines: string[] = ['```bash'];\n if (stack.commands.build) lines.push(`# Build\\n${stack.commands.build}`);\n if (stack.commands.test) lines.push(`# Test\\n${stack.commands.test}`);\n if (stack.commands.lint) lines.push(`# Lint\\n${stack.commands.lint}`);\n if (stack.commands.typecheck) lines.push(`# Type check\\n${stack.commands.typecheck}`);\n if (stack.commands.deploy) lines.push(`# Deploy\\n${stack.commands.deploy}`);\n lines.push('```');\n return lines.join('\\n');\n}\n\nexport function generateExternalApiSafetySection(): string {\n return '### External API Safety\\n- Read official docs and type definitions before writing code against a third-party SDK\\n- Add third-party SDKs as devDependencies so typecheck runs against real types, not stubs\\n- Critical integration paths should have a smoke test that validates against the real runtime';\n}\n\n/**\n * The CLAUDE.md written for a multi-tool install, following Anthropic's\n * documented pattern for repos that use AGENTS.md with other coding agents:\n * a single shared AGENTS.md imported via `@AGENTS.md`, with a section for\n * Claude-specific additions. Claude Code does not read AGENTS.md natively —\n * the import line is what makes both tools read the same instructions.\n * https://code.claude.com/docs/en/memory (\"AGENTS.md\")\n */\nexport function generateClaudeMdPointer(): string {\n return `@AGENTS.md\n\n## Claude Code\n\n_Shared project instructions — boundaries, workflow, architecture — live in \\`AGENTS.md\\`, imported above so every AI tool reads the same source. Add Claude Code–specific instructions in this section only._\n`;\n}\n\nexport function generateBoundariesSection(): string {\n return `## Behavioral Boundaries\n\n### ALWAYS\n- Run tests and type-check before committing\n- Run tests before implementing new features -- confirm they fail first, then implement until they pass\n- Use \\`verb: concise message\\` format for commits\n- Commit after completing each discrete task (atomic commits)\n- Stage specific files by name (not \\`git add -A\\` or \\`git add .\\`)\n- Read \\`docs/context/\\` before making infrastructure or config changes\n- Follow existing code patterns and style\n\n### ASK FIRST\n- Pushing to remote\n- Creating or merging pull requests\n- Adding new dependencies\n- Modifying database schema or data models\n- Changing authentication or authorization flows\n- Any destructive git operation (force-push, reset --hard, branch deletion)\n\n### NEVER\n- Push directly to main/master without approval\n- Commit .env files, secrets, or credentials\n- Use --no-verify to skip hooks\n- Amend commits that have been pushed\n- Skip type-checking or linting\n- Commit code that doesn't build`;\n}\n\nfunction generateWorkflowSection(stack: StackInfo): string {\n return `## Development Workflow\n\n${generateCommandsBlock(stack)}\n\n**Default execution mode:** batch\n\n_How \\`/joycraft-implement\\` wraps up after each spec. \\`joycraft-decompose\\` reads this line (absent ⇒ \\`batch\\`) and recommends a per-spec mode you approve. Modes: \\`batch\\` (implement a cluster, wrap once at the end), \\`checkpoint\\` (commit + status bump after each spec), \\`isolated\\` (fresh context per spec — on Pi, the \\`joycraft-implement-loop\\` driver). Change the value above to set your project default._\n\n**Deferred work → \\`docs/backlog/\\`.** Ideas and follow-ups you surface mid-sprint but can't take on now go to \\`docs/backlog/\\` (one file per item) so the current spec stays focused without losing the thread. Promote an entry to a Feature Brief under \\`docs/features/<slug>/\\` when you're ready to build it.`;\n}\n\nfunction generateArchitectureSection(projectDir?: string): string {\n // With a real directory, emit the check-shaped folder map (D6) — a walk of\n // the actual tree — instead of a hand-maintained prose tree that only drifts.\n if (projectDir) {\n return `## Architecture\\n\\n${renderFolderMap(projectDir)}`;\n }\n return `## Architecture\n\n_TODO: Add a brief description of your project's architecture and key directories._`;\n}\n\nfunction generateKeyFilesSection(): string {\n return `## Key Files\n\n| File | Purpose |\n|------|---------|\n| _TODO_ | _Add key files and their purposes_ |`;\n}\n\nfunction generateGotchasSection(): string {\n return `## Common Gotchas\n\n_TODO: Add any gotchas, quirks, or non-obvious behaviors that developers should know about._`;\n}\n\nfunction generateGettingStartedSection(multiTool = false): string {\n const invocationNote = multiTool\n ? '\\n\\nSkill names are shared across tools; only the invocation prefix differs: `/joycraft-*` (Claude Code), `$joycraft-*` (Codex), `/skill:joycraft-*` (Pi).'\n : '';\n return `## Getting Started with Joycraft\n\nThis project uses [Joycraft](https://github.com/maksutovic/joycraft) for AI development workflow. Available skills:\n\n| Skill | Purpose |\n|-------|---------|\n| \\`/joycraft-setup\\` | Start here — the first-run door; sets up and assesses your project |\n| \\`/joycraft-tune\\` | Assess your harness, apply upgrades, see your maturity roadmap |\n| \\`/joycraft-new-feature\\` | Interview -> Feature Brief -> Atomic Specs |\n| \\`/joycraft-interview\\` | Lightweight brainstorm — yap about ideas, get a structured summary |\n| \\`/joycraft-decompose\\` | Break a brief into small, testable specs |\n| \\`/joycraft-session-end\\` | Capture discoveries, verify, commit |\n| \\`/joycraft-implement-level5\\` | Experimental — Level 5 autofix loop, holdout scenarios, scenario evolution |\n\nRun \\`/joycraft-tune\\` to see where your project stands and what to improve next.${invocationNote}`;\n}\n\nexport function generateContextMapSection(): string {\n return `## Context Map\n\nKeep this file lean — link out, don't inline. Long-form reference docs live in \\`docs/context/reference/\\`; this table points to what to read on demand.\n\n| Document | Read it when… |\n|----------|---------------|`;\n}\n\nfunction generateExternalValidationSection(): string {\n return `## External Validation\n\nThis project uses holdout scenario tests in a separate private repo.\n\n### NEVER\n- Access, read, or reference the scenarios repo\n- Mention scenario test names or contents\n- Modify the scenarios dispatch workflow to leak test information\n\nThe scenarios repo is deliberately invisible to you. This is the holdout guarantee — like a validation set in ML.`;\n}\n\nfunction generateAreasSection(): string {\n return `## Areas\n\nThis project organizes some work by area. When working on a specific area, read its README first; check for area-specific boundaries.\n\n- For each area: see \\`docs/areas/<area-name>/README.md\\`\n- Area-level boundaries (when present): \\`docs/areas/<area-name>/boundaries.md\\``;\n}\n\nfunction projectHasAreas(opts?: ImproveOptions): boolean {\n if (!opts?.projectDir) return false;\n return existsSync(join(opts.projectDir, 'docs', 'areas'));\n}\n\nfunction stripAreasSection(content: string): string {\n // Remove an existing \"## Areas\" section (header + body up to next \"## \" header or EOF).\n return content.replace(/\\n##\\s+Areas\\b[\\s\\S]*?(?=\\n##\\s|\\n*$)/, '').trimEnd() + '\\n';\n}\n\nfunction generateProjectToolsSection(existingSkills: string[]): string {\n const MAX_LISTED = 10;\n let skillList: string;\n if (existingSkills.length <= MAX_LISTED) {\n skillList = existingSkills.join(', ');\n } else {\n skillList = existingSkills.slice(0, MAX_LISTED).join(', ') +\n `, and ${existingSkills.length - MAX_LISTED} more — see .claude/skills/`;\n }\n return `## Project Tools\n\nThis project has additional tools beyond Joycraft. Always check \\`.claude/skills/\\` for available skills: ${skillList}`;\n}\n\nexport function improveCLAUDEMd(\n existing: string,\n stack: StackInfo,\n existingSkills: string[] = [],\n opts?: ImproveOptions,\n): string {\n // Areas pointer: idempotent in both directions.\n // Always strip an existing \"## Areas\" section first so we re-evaluate cleanly.\n let working = stripAreasSection(existing);\n // A folder-map block is machine-owned structure: regenerate it in place\n // (human wording preserved) whenever we know the real directory.\n if (opts?.projectDir && working.includes(FOLDER_MAP_OPEN)) {\n working = ensureFolderMapSection(working, opts.projectDir);\n }\n const sections = parseSections(working);\n const additions: string[] = [];\n\n if (!hasSection(sections, /behavioral\\s*boundar/i)) {\n additions.push(generateBoundariesSection());\n }\n\n if (!hasSection(sections, /development\\s*workflow/i) && !hasSection(sections, /workflow/i)) {\n additions.push(generateWorkflowSection(stack));\n }\n\n if (!hasSection(sections, /architecture/i)) {\n additions.push(generateArchitectureSection(opts?.projectDir));\n }\n\n if (!hasSection(sections, /key\\s*files/i)) {\n additions.push(generateKeyFilesSection());\n }\n\n if (!hasSection(sections, /common\\s*gotchas/i) && !hasSection(sections, /gotchas/i)) {\n additions.push(generateGotchasSection());\n }\n\n if (!hasSection(sections, /getting\\s*started.*joycraft/i) && !hasSection(sections, /joycraft.*skills/i)) {\n additions.push(generateGettingStartedSection());\n }\n\n if (!hasSection(sections, /context\\s*map/i)) {\n additions.push(generateContextMapSection());\n }\n\n if (!hasSection(sections, /external\\s*validation/i)) {\n additions.push(generateExternalValidationSection());\n }\n\n // Private-mode setup note: independent of the Getting Started check above so\n // it gets added on a re-run even when Getting Started already exists. Matched\n // on its stable phrase, not a heading, so it's idempotent across upgrades.\n if (opts?.privateProfile && !existing.includes(PRIVATE_SETUP_NOTE_MARKER)) {\n additions.push(generatePrivateSetupNote());\n }\n\n if (!hasSection(sections, PRODUCT_IDENTITY_HEADER_PATTERN)) {\n const identitySection = generateProductIdentitySection(opts?.identity);\n if (identitySection) additions.push(identitySection);\n }\n\n if (existingSkills.length > 0 && !hasSection(sections, /project\\s*tools/i)) {\n additions.push(generateProjectToolsSection(existingSkills));\n }\n\n if (projectHasAreas(opts)) {\n additions.push(generateAreasSection());\n }\n\n if (additions.length === 0) {\n const unchanged = working === existing ? existing : working;\n return ensureExecutionProfileSection(unchanged, opts?.executionProfile);\n }\n\n const trimmed = working.trimEnd();\n const merged = trimmed + '\\n\\n' + additions.join('\\n\\n') + '\\n';\n return ensureExecutionProfileSection(merged, opts?.executionProfile);\n}\n\nexport function generateCLAUDEMd(\n projectName: string,\n stack: StackInfo,\n existingSkills: string[] = [],\n opts?: ImproveOptions,\n): string {\n const frameworkNote = stack.framework ? ` (${stack.framework})` : '';\n const langLabel = stack.language === 'unknown' ? '' : ` | **Stack:** ${stack.language}${frameworkNote}`;\n\n const lines: string[] = [\n `# ${projectName}`,\n '',\n `**Component:** _TODO: describe what this project is_${langLabel}`,\n '',\n '---',\n '',\n generateBoundariesSection(),\n '',\n ];\n\n if (opts?.multiTool) {\n lines.push(generateExternalApiSafetySection(), '');\n }\n\n lines.push(\n generateWorkflowSection(stack),\n '',\n generateArchitectureSection(opts?.projectDir),\n '',\n generateKeyFilesSection(),\n '',\n generateGotchasSection(),\n '',\n generateContextMapSection(),\n '',\n generateGettingStartedSection(opts?.multiTool ?? false),\n '',\n );\n\n const identitySection = generateProductIdentitySection(opts?.identity);\n if (identitySection) {\n lines.push(identitySection, '');\n }\n\n if (opts?.executionProfile) {\n lines.push(renderExecutionProfileSection(opts.executionProfile), '');\n }\n\n if (opts?.privateProfile) {\n lines.push(generatePrivateSetupNote(), '');\n }\n\n if (existingSkills.length > 0) {\n lines.push(generateProjectToolsSection(existingSkills), '');\n }\n\n if (projectHasAreas(opts)) {\n lines.push(generateAreasSection(), '');\n }\n\n return lines.join('\\n');\n}\n","import type { StackInfo } from './detect.js';\nimport { renderFolderMap, ensureFolderMapSection, FOLDER_MAP_OPEN } from './folder-map.js';\nimport {\n ensureExecutionProfileSection,\n renderExecutionProfileSection,\n type ExecutionProfile,\n} from './execution-profile.js';\nimport {\n generateBoundariesSection,\n generateExternalApiSafetySection,\n generatePrivateSetupNote,\n generateProductIdentitySection,\n PRIVATE_SETUP_NOTE_MARKER,\n PRODUCT_IDENTITY_HEADER_PATTERN,\n type ProductIdentity,\n} from './improve-claude-md.js';\n\ninterface Section {\n header: string;\n content: string;\n}\n\nfunction parseSections(markdown: string): Section[] {\n const lines = markdown.split('\\n');\n const sections: Section[] = [];\n let currentHeader = '';\n let currentLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith('## ')) {\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n currentHeader = line;\n currentLines = [];\n } else {\n currentLines.push(line);\n }\n }\n\n if (currentHeader || currentLines.length > 0) {\n sections.push({ header: currentHeader, content: currentLines.join('\\n') });\n }\n\n return sections;\n}\n\nfunction hasSection(sections: Section[], pattern: RegExp): boolean {\n return sections.some(s => pattern.test(s.header));\n}\n\nfunction generateCommandsBlock(stack: StackInfo): string {\n const lines: string[] = ['```bash'];\n if (stack.commands.build) lines.push(stack.commands.build);\n if (stack.commands.test) lines.push(stack.commands.test);\n if (stack.commands.lint) lines.push(stack.commands.lint);\n if (stack.commands.typecheck) lines.push(stack.commands.typecheck);\n if (stack.commands.deploy) lines.push(stack.commands.deploy);\n lines.push('```');\n return lines.join('\\n');\n}\n\nfunction generateDevelopmentSection(stack: StackInfo): string {\n return `## Development\\n\\n${generateCommandsBlock(stack)}\\n\\n**Deferred work → \\`docs/backlog/\\`.** Ideas and follow-ups surfaced mid-sprint that can't be taken on now go to \\`docs/backlog/\\` (one file per item) so the current spec stays focused. Promote an entry to a Feature Brief under \\`docs/features/<slug>/\\` when ready to build it.`;\n}\n\nfunction generateArchitectureSection(projectDir?: string): string {\n // With a real directory, emit the check-shaped folder map (D6) instead of a\n // hand-maintained tree that only drifts.\n if (projectDir) {\n return `## Architecture\\n\\n${renderFolderMap(projectDir)}`;\n }\n return `## Architecture\\n\\n_TODO: Add a compact directory tree and one-paragraph summary._`;\n}\n\nfunction generateKeyFilesSection(): string {\n return `## Key Files\\n\\n| File | Purpose |\\n|------|---------|\\n| _TODO_ | _Add key files_ |`;\n}\n\nexport function generateAgentsMd(\n projectName: string,\n stack: StackInfo,\n privateProfile = false,\n executionProfile?: ExecutionProfile,\n identity?: ProductIdentity,\n projectDir?: string,\n): string {\n const frameworkNote = stack.framework ? ` (${stack.framework})` : '';\n const langLabel = stack.language === 'unknown' ? '' : ` | **Stack:** ${stack.language}${frameworkNote}`;\n\n const lines: string[] = [\n `# ${projectName}`,\n '',\n `**Component:** _TODO: describe what this project is_${langLabel}`,\n '',\n '> Auto-generated by Joycraft.',\n '',\n '---',\n '',\n generateBoundariesSection(),\n generateExternalApiSafetySection(),\n '',\n generateArchitectureSection(projectDir),\n '',\n generateKeyFilesSection(),\n '',\n generateDevelopmentSection(stack),\n '',\n ];\n\n const identitySection = generateProductIdentitySection(identity);\n if (identitySection) {\n lines.push(identitySection, '');\n }\n\n if (executionProfile) {\n lines.push(renderExecutionProfileSection(executionProfile), '');\n }\n\n if (privateProfile) {\n lines.push(generatePrivateSetupNote(), '');\n }\n\n return lines.join('\\n');\n}\n\nexport function improveAgentsMd(\n existing: string,\n stack: StackInfo,\n privateProfile = false,\n executionProfile?: ExecutionProfile,\n identity?: ProductIdentity,\n projectDir?: string,\n): string {\n // A folder-map block is machine-owned structure: regenerate it in place\n // (human wording preserved) whenever we know the real directory.\n let working = existing;\n if (projectDir && working.includes(FOLDER_MAP_OPEN)) {\n working = ensureFolderMapSection(working, projectDir);\n }\n const sections = parseSections(working);\n const additions: string[] = [];\n\n if (!hasSection(sections, /behavioral\\s*boundar/i)) {\n additions.push(generateBoundariesSection());\n }\n\n if (!/external\\s*api\\s*safety/i.test(working)) {\n additions.push(generateExternalApiSafetySection());\n }\n\n if (!hasSection(sections, /architecture/i)) {\n additions.push(generateArchitectureSection(projectDir));\n }\n\n if (!hasSection(sections, /key\\s*files/i)) {\n additions.push(generateKeyFilesSection());\n }\n\n if (!hasSection(sections, /development/i)) {\n additions.push(generateDevelopmentSection(stack));\n }\n\n if (!hasSection(sections, PRODUCT_IDENTITY_HEADER_PATTERN)) {\n const identitySection = generateProductIdentitySection(identity);\n if (identitySection) additions.push(identitySection);\n }\n\n if (privateProfile && !working.includes(PRIVATE_SETUP_NOTE_MARKER)) {\n additions.push(generatePrivateSetupNote());\n }\n\n if (additions.length === 0) {\n // Sentinel-based, not heading-based: an existing profile region is opaque\n // user data and must come back byte-identical.\n return ensureExecutionProfileSection(working, executionProfile);\n }\n\n const trimmed = working.trimEnd();\n const merged = trimmed + '\\n\\n' + additions.join('\\n\\n') + '\\n';\n return ensureExecutionProfileSection(merged, executionProfile);\n}\n","import type { StackInfo } from './detect.js';\n\nexport interface PermissionRules {\n allow: string[];\n deny: string[];\n}\n\nexport function generatePermissions(stack: StackInfo): PermissionRules {\n // Default deny rules for ALL projects\n const deny: string[] = [\n 'Bash(rm -rf *)',\n 'Bash(git push --force *)',\n 'Bash(git push -f *)',\n 'Bash(git reset --hard *)',\n 'Edit(//.env*)',\n 'Edit(//*.pem)',\n 'Edit(//*.key)',\n 'Edit(//.git/**)',\n ];\n\n // Default allow rules\n const allow: string[] = [\n 'Bash(git status)',\n 'Bash(git diff *)',\n 'Bash(git log *)',\n 'Bash(git add *)',\n 'Bash(git commit *)',\n 'Bash(git checkout *)',\n 'Bash(git branch *)',\n ];\n\n // Stack-specific rules\n if (stack.language === 'node') {\n allow.push(`Bash(${stack.packageManager} *)`);\n if (stack.packageManager !== 'npm') deny.push('Bash(npm install *)');\n if (stack.packageManager !== 'yarn') deny.push('Bash(yarn add *)');\n if (stack.packageManager !== 'pnpm') deny.push('Bash(pnpm add *)');\n if (stack.packageManager !== 'bun') deny.push('Bash(bun add *)');\n if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);\n if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);\n if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);\n if (stack.commands.typecheck) allow.push(`Bash(${stack.commands.typecheck})`);\n }\n\n if (stack.language === 'python') {\n allow.push(`Bash(${stack.packageManager} *)`);\n if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);\n if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);\n if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);\n }\n\n if (stack.language === 'rust') {\n allow.push('Bash(cargo *)');\n }\n\n if (stack.language === 'go') {\n allow.push('Bash(go *)');\n }\n\n if (stack.language === 'swift') {\n allow.push('Bash(swift *)');\n allow.push('Bash(xcodebuild *)');\n }\n\n return { allow, deny };\n}\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface SafeguardConfig {\n denyPatterns: string[];\n}\n\n/**\n * Generate default deny patterns from common dangerous operations.\n */\nexport function getDefaultDenyPatterns(): string[] {\n return [\n 'rm\\\\s+-rf\\\\s+/', // rm -rf with absolute path\n 'rm\\\\s+-rf\\\\s+\\\\.', // rm -rf . or ./\n 'git\\\\s+push\\\\s+--force', // force push\n 'git\\\\s+push\\\\s+-f\\\\b', // force push shorthand\n 'git\\\\s+reset\\\\s+--hard', // hard reset\n 'DROP\\\\s+TABLE', // SQL drop\n 'DROP\\\\s+DATABASE', // SQL drop\n 'TRUNCATE', // SQL truncate\n 'chmod\\\\s+777', // wide-open permissions\n 'curl.*\\\\|.*sh', // pipe curl to shell\n 'wget.*\\\\|.*sh', // pipe wget to shell\n ];\n}\n\n/**\n * Generate the hook script that blocks dangerous Bash commands.\n */\nexport function generateHookScript(): string {\n return `#!/bin/bash\n# Joycraft Safeguard — PreToolUse hook\n# Blocks dangerous Bash commands. Exit 2 = block the action.\n# Edit deny-patterns.txt to customize what's blocked.\n\nTOOL_NAME=\"$1\"\n# Read the full tool input from stdin\nINPUT=$(cat)\n\n# Only check Bash commands\nif [ \"$TOOL_NAME\" != \"Bash\" ]; then\n exit 0\nfi\n\n# Extract the command from the JSON input\nCOMMAND=$(echo \"$INPUT\" | grep -o '\"command\":\"[^\"]*\"' | head -1 | sed 's/\"command\":\"//;s/\"$//')\n\nif [ -z \"$COMMAND\" ]; then\n exit 0\nfi\n\nPATTERNS_FILE=\"$(dirname \"$0\")/deny-patterns.txt\"\n\nif [ ! -f \"$PATTERNS_FILE\" ]; then\n exit 0\nfi\n\nwhile IFS= read -r pattern || [ -n \"$pattern\" ]; do\n # Skip empty lines and comments\n [ -z \"$pattern\" ] && continue\n [[ \"$pattern\" == \\\\#* ]] && continue\n\n if echo \"$COMMAND\" | grep -qEi \"$pattern\"; then\n echo \"Blocked by Joycraft Safeguard: command matches deny pattern '$pattern'\"\n echo \"Edit .claude/hooks/joycraft/deny-patterns.txt to modify blocked patterns.\"\n exit 2\n fi\ndone < \"$PATTERNS_FILE\"\n\nexit 0\n`;\n}\n\n/**\n * Generate deny-patterns.txt content from default patterns + custom patterns.\n */\nexport function generateDenyPatternsFile(customPatterns: string[] = []): string {\n const lines = [\n '# Joycraft Safeguard — Deny Patterns',\n '# One regex pattern per line. Lines starting with # are comments.',\n '# Commands matching any pattern will be blocked (exit 2).',\n '# Edit this file to customize what\\'s blocked.',\n '',\n '# Destructive file operations',\n 'rm\\\\s+-rf\\\\s+/',\n 'rm\\\\s+-rf\\\\s+\\\\.',\n '',\n '# Dangerous git operations',\n 'git\\\\s+push\\\\s+--force',\n 'git\\\\s+push\\\\s+-f\\\\b',\n 'git\\\\s+reset\\\\s+--hard',\n '',\n '# SQL destruction',\n 'DROP\\\\s+TABLE',\n 'DROP\\\\s+DATABASE',\n 'TRUNCATE',\n '',\n '# System security',\n 'chmod\\\\s+777',\n 'curl.*\\\\|.*sh',\n 'wget.*\\\\|.*sh',\n ];\n\n if (customPatterns.length > 0) {\n lines.push('');\n lines.push('# Project-specific patterns (from risk interview)');\n for (const p of customPatterns) {\n lines.push(p);\n }\n }\n\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Install safeguard hooks into a project.\n */\nexport function installSafeguardHooks(\n targetDir: string,\n customPatterns: string[] = [],\n force: boolean = false,\n skipSettingsMerge: boolean = false\n): { created: string[]; skipped: string[] } {\n const result = { created: [] as string[], skipped: [] as string[] };\n const hooksDir = join(targetDir, '.claude', 'hooks', 'joycraft');\n\n if (!existsSync(hooksDir)) {\n mkdirSync(hooksDir, { recursive: true });\n }\n\n // Write hook script\n const hookPath = join(hooksDir, 'block-dangerous.sh');\n if (!existsSync(hookPath) || force) {\n writeFileSync(hookPath, generateHookScript(), { mode: 0o755 });\n result.created.push(hookPath);\n } else {\n result.skipped.push(hookPath);\n }\n\n // Write deny patterns\n const patternsPath = join(hooksDir, 'deny-patterns.txt');\n if (!existsSync(patternsPath) || force) {\n writeFileSync(patternsPath, generateDenyPatternsFile(customPatterns));\n result.created.push(patternsPath);\n } else {\n result.skipped.push(patternsPath);\n }\n\n // Register hook in settings.json (skip if caller detected malformed JSON)\n if (!skipSettingsMerge) {\n const settingsPath = join(targetDir, '.claude', 'settings.json');\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n } catch {\n // Don't overwrite — caller should handle the warning\n return result;\n }\n }\n\n if (!settings.hooks) settings.hooks = {};\n const hooks = settings.hooks as Record<string, unknown[]>;\n if (!hooks.PreToolUse) hooks.PreToolUse = [];\n\n const preToolUse = hooks.PreToolUse as Array<Record<string, unknown>>;\n const hasJoycraftHook = preToolUse.some(h => {\n const innerHooks = h.hooks as Array<Record<string, unknown>> | undefined;\n return innerHooks?.some(ih => typeof ih.command === 'string' && ih.command.includes('joycraft'));\n });\n\n if (!hasJoycraftHook) {\n preToolUse.push({\n matcher: 'Bash',\n hooks: [{\n type: 'command',\n command: '.claude/hooks/joycraft/block-dangerous.sh',\n }],\n });\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf-8');\n }\n }\n\n return result;\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Ensure the project's tsconfig.json excludes `.pi/` from the TypeScript program.\n *\n * Why: when Pi is a selected harness, `init` installs `.pi/extensions/joycraft-pipeline.ts`\n * — real Pi runtime code that imports `@earendil-works/pi-coding-agent`, a package\n * the user's project does NOT (and shouldn't) depend on. A default TS toolchain\n * whose `include` globs `**​/*.ts` (e.g. create-next-app) would pull that file into\n * the program and fail `tsc`/`next build` on the missing import. The extension must\n * keep its `.ts` extension (Pi loads it as code), so the fix is to keep it out of\n * the user's program: add `.pi` to `exclude`.\n *\n * Transparency + safety contract (mirrors the \"append over rewrite, surface the\n * change\" principle):\n * - Edits surgically by text insertion, preserving the user's comments and\n * formatting — never round-trips through JSON.stringify (which would strip\n * comments from a JSONC tsconfig).\n * - Idempotent: a tsconfig already excluding `.pi` is left untouched.\n * - Bails (returns a 'skipped' outcome with a reason) rather than risk writing\n * malformed JSON when the file shape is too unusual to edit confidently. The\n * caller surfaces the reason so the user can add the line by hand.\n */\n\nexport type TsconfigExcludeOutcome =\n | { status: 'added'; path: string }\n | { status: 'already-present'; path: string }\n | { status: 'no-tsconfig' }\n | { status: 'skipped'; reason: string };\n\nconst PI_EXCLUDE = '.pi';\n\n/** Strip // and /* *​/ comments for analysis only (never for the written output). */\nfunction stripJsonComments(text: string): string {\n // Remove block comments, then line comments. Good enough to test for an\n // existing `.pi` exclude entry; we never write this stripped form back.\n return text\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/(^|[^:])\\/\\/.*$/gm, '$1');\n}\n\n/** True when the parsed (comment-stripped) config already excludes `.pi`. */\nfunction alreadyExcludesPi(rawText: string): boolean {\n try {\n const parsed = JSON.parse(stripJsonComments(rawText)) as { exclude?: unknown };\n if (!Array.isArray(parsed.exclude)) return false;\n return parsed.exclude.some(\n (e) => typeof e === 'string' && (e === PI_EXCLUDE || e === './.pi' || e === '.pi/**'),\n );\n } catch {\n // Unparseable even after comment-stripping → treat as \"not present\" and let\n // the editor below decide whether it can safely insert.\n return false;\n }\n}\n\n/**\n * Insert `.pi` into an existing top-level `\"exclude\": [ ... ]` array, or add a\n * fresh `exclude` key, by surgical text edit. Returns the new text, or null if\n * the file shape is too ambiguous to edit safely (caller then skips + warns).\n */\nfunction insertPiExclude(rawText: string): string | null {\n // Case A: an existing top-level `exclude` array. Match `\"exclude\"` followed by\n // `:` and the opening `[`, then inject `.pi` as the first element. Anchored to\n // the start of a line (after optional whitespace) so we don't match a nested\n // key named \"exclude\" inside compilerOptions.\n const excludeArrayRe = /(\"exclude\"\\s*:\\s*\\[)(\\s*)/;\n if (excludeArrayRe.test(rawText)) {\n return rawText.replace(excludeArrayRe, (_m, open: string, ws: string) => {\n // Preserve whatever whitespace followed the bracket so formatting survives.\n const sep = ws.includes('\\n') ? ws : ' ';\n return `${open}${sep}\"${PI_EXCLUDE}\",${ws.includes('\\n') ? '' : ' '}`;\n });\n }\n\n // Case B: no `exclude` key. Add one right after the top-level `include` array\n // if present (keeps the two siblings together), else before the final closing\n // brace. Only attempt when there's exactly one top-level object.\n const includeArrayRe = /(\"include\"\\s*:\\s*\\[[^\\]]*\\])/;\n if (includeArrayRe.test(rawText)) {\n return rawText.replace(includeArrayRe, (m) => `${m},\\n \"exclude\": [\"${PI_EXCLUDE}\"]`);\n }\n\n // Case C: fall back to inserting before the last `}` in the file. Guard: there\n // must be a closing brace, and the content before it must end in something we\n // can comma-append to. To stay safe, only do this when the object is non-empty\n // (contains at least one `:`), otherwise bail.\n const lastBrace = rawText.lastIndexOf('}');\n if (lastBrace > 0 && rawText.slice(0, lastBrace).includes(':')) {\n const before = rawText.slice(0, lastBrace).replace(/\\s*$/, '');\n const after = rawText.slice(lastBrace);\n const needsComma = !before.endsWith(',') && !before.endsWith('{');\n return `${before}${needsComma ? ',' : ''}\\n \"exclude\": [\"${PI_EXCLUDE}\"]\\n${after}`;\n }\n\n return null;\n}\n\n/**\n * Add `.pi` to tsconfig.json's `exclude` so a Pi-selected install doesn't break\n * the user's `tsc`/build. No-op when there's no tsconfig, or it already excludes\n * `.pi`. See the module doc for the safety contract.\n */\nexport function ensurePiExcludedFromTsconfig(targetDir: string): TsconfigExcludeOutcome {\n const path = join(targetDir, 'tsconfig.json');\n if (!existsSync(path)) return { status: 'no-tsconfig' };\n\n let rawText: string;\n try {\n rawText = readFileSync(path, 'utf-8');\n } catch {\n return { status: 'skipped', reason: 'tsconfig.json could not be read' };\n }\n\n if (alreadyExcludesPi(rawText)) {\n return { status: 'already-present', path };\n }\n\n const updated = insertPiExclude(rawText);\n if (updated === null || updated === rawText) {\n return {\n status: 'skipped',\n reason:\n 'could not safely edit tsconfig.json — add \".pi\" to its \"exclude\" array manually so the Pi extension stays out of your TypeScript build',\n };\n }\n\n // Sanity gate: the edited text must still parse (after comment-stripping) and\n // must now actually exclude .pi. If either fails, do NOT write — bail and warn.\n if (!alreadyExcludesPi(updated)) {\n return {\n status: 'skipped',\n reason:\n 'tsconfig.json edit could not be verified — add \".pi\" to its \"exclude\" array manually',\n };\n }\n\n try {\n writeFileSync(path, updated, 'utf-8');\n } catch {\n return { status: 'skipped', reason: 'tsconfig.json could not be written' };\n }\n return { status: 'added', path };\n}\n","import { createInterface } from 'node:readline';\n\n/**\n * Claude Code's auto-memory offer (curated-harness WS6).\n *\n * A Joycraft project and Claude Code auto-memory are two homes for the same\n * class of fact — the ONE_HOME condition `/joycraft-optimize` exists to flag.\n * The in-repo curated layer (AGENTS.md, decision log, discoveries + Reaper) is\n * reviewable, versioned and shared; per-machine auto-memory is none of those.\n * So init offers to turn auto-memory off — but only ever:\n *\n * - for THIS project (`./.claude/settings.json`), never `~/.claude/`, so the\n * user's other projects are untouched;\n * - interactively, defaulting to no change — never a silent write;\n * - when the key is absent, so an explicit user value is never clobbered.\n *\n * This module owns the question and the pure answer parser. The guarded write\n * itself lives with init's other `settings.json` merges so the file is read and\n * written once.\n */\n\n/** The Claude Code project-settings key this offer sets. */\nexport const AUTO_MEMORY_KEY = 'autoMemoryEnabled';\n\n/**\n * Parse a yes/no answer. Empty takes the no-change default (`false`); an\n * unrecognized answer returns `null` so the caller re-asks rather than\n * coercing a typo into a config write.\n */\nexport function parseAutoMemoryAnswer(answer: string): boolean | null {\n const normalized = answer.trim().toLowerCase();\n if (normalized === '') return false;\n if (normalized === 'y' || normalized === 'yes') return true;\n if (normalized === 'n' || normalized === 'no') return false;\n return null;\n}\n\n/**\n * Ask the question, following the one-readline-per-prompt idiom used by\n * `harness.ts` and `gitignore.ts`. A stream that has already ended degrades to\n * the default rather than hanging — a configuration question must never abort\n * an init.\n */\nfunction promptAutoMemory(): Promise<boolean> {\n console.log('\\nJoycraft keeps project facts in one home: your repo.');\n console.log(\n ' Claude Code auto-memory is a second, per-machine home for the same facts.'\n );\n console.log(\n ` Disabling it for this project writes \"${AUTO_MEMORY_KEY}\": false to .claude/settings.json.`\n );\n console.log(' Your other projects are unaffected.');\n\n const input = process.stdin;\n if (input.readableEnded === true || input.destroyed === true) {\n return Promise.resolve(false);\n }\n\n return new Promise((resolve) => {\n const rl = createInterface({ input, output: process.stdout });\n let settled = false;\n const done = (value: boolean): void => {\n if (settled) return;\n settled = true;\n rl.close();\n resolve(value);\n };\n rl.once('close', () => done(false));\n const ask = (attempt: number): void => {\n rl.question('Disable auto-memory for this project? [y/N]: ', (answer) => {\n const parsed = parseAutoMemoryAnswer(answer);\n if (parsed !== null) {\n done(parsed);\n return;\n }\n // Repeated unparseable input takes the default rather than looping.\n if (attempt >= 4) {\n done(false);\n return;\n }\n console.log(`Unrecognized answer '${answer.trim()}' — type 'y' or 'n', or press Enter for no change.`);\n ask(attempt + 1);\n });\n };\n ask(0);\n });\n}\n\n/**\n * Resolve whether to disable auto-memory for this project.\n * - interactive (TTY): ask, defaulting to no change\n * - non-interactive: skip entirely — no prompt, no write\n */\nexport async function resolveAutoMemoryOffer(interactive: boolean): Promise<boolean> {\n if (!interactive) return false;\n return promptAutoMemory();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,YAAW,cAAAC,aAAY,iBAAAC,gBAAe,gBAAAC,eAAc,eAAAC,cAAa,UAAU,iBAAiB;AACrG,SAAS,QAAAC,OAAM,UAAU,SAAS,eAAe;;;ACDjD,SAAS,cAAc,YAAY,mBAAmB;AACtD,SAAS,YAAY;AAsBrB,IAAM,iBAAiB,oBAAI,IAAI,CAAC,WAAW,QAAQ,SAAS,SAAS,OAAO,QAAQ,CAAC;AACrF,IAAM,iBAAiB,oBAAI,IAAI,CAAC,WAAW,WAAW,WAAW,UAAU,SAAS,OAAO,SAAS,QAAQ,SAAS,QAAQ,QAAQ,CAAC;AAEtI,SAAS,qBAAqB,UAAwD;AACpF,UAAQ,UAAU;AAAA,IAChB,KAAK;AACH,aAAO,EAAE,UAAU,YAAY,YAAY,QAAQ,CAAC,MAAM,OAAO,SAAS,QAAQ,EAAE;AAAA,IACtF,KAAK;AACH,aAAO,EAAE,UAAU,YAAY,SAAS,QAAQ,CAAC,MAAM,OAAO,SAAS,QAAQ,EAAE;AAAA,IACnF,KAAK;AACH,aAAO,EAAE,UAAU,YAAY,YAAY,QAAQ,CAAC,OAAO,SAAS,QAAQ,EAAE;AAAA,IAChF,KAAK;AACH,aAAO,EAAE,UAAU,YAAY,YAAY,QAAQ,CAAC,SAAS,QAAQ,EAAE;AAAA,EAC3E;AACF;AAEA,SAAS,SAAS,MAA6B;AAC7C,MAAI;AACF,WAAO,aAAa,MAAM,OAAO;AAAA,EACnC,QAAQ;AACN,WAAO;AAAA,EACT;AAC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WAAW,CAAC;AAE1E,UAAQ,IAAI,iBAAiB;AAC7B,UAAQ,IAAI,iHAA4G;AACxH,MAAI,mBAAmB;AACrB,YAAQ,IAAI,oFAAoF;AAAA,EAClG,OAAO;AACL,YAAQ,IAAI,6EAA6E;AAAA,EAC3F;AACA,UAAQ,IAAI,kFAAkF;AAC9F,UAAQ,IAAI,2EAA2E;AACvF,MAAI,qBAAqB,WAAW;AAClC,YAAQ,IAAI,wDAAmD,oBAAoB,0BAA0B;AAC7G,YAAQ,IAAI,6DAA6D,uBAAuB,GAAG;AAAA,EACrG,OAAO;AACL,YAAQ,IAAI,6EAA6E;AAAA,EAC3F;AACA,MAAI,CAAC,MAAM;AACT,YAAQ,IAAI,2EAA2E;AAAA,EACzF;AACA,UAAQ,IAAI,EAAE;AAChB;","names":["mkdirSync","existsSync","writeFileSync","readFileSync","readdirSync","join","existsSync","join","existsSync","join","generateCommandsBlock","generateArchitectureSection","generateKeyFilesSection","existsSync","readFileSync","join","join","existsSync","readFileSync","existsSync","readFileSync","writeFileSync","join","resolve","existsSync","mkdirSync","writeFileSync","join","readdirSync","readFileSync"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/upgrade.ts","../src/migration.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, rmdirSync, readdirSync, chmodSync } from 'node:fs';\nimport { join, dirname, resolve } from 'node:path';\nimport { createInterface } from 'node:readline';\nimport { execFileSync, spawnSync } from 'node:child_process';\nimport { readVersion, writeVersion, hashContent, truncateHash, LEGACY_VERSION_FILE, LEGACY_CLAUDE_STATE_PATH, parseGitignoreProfile } from './version.js';\nimport { ensureFolderMapSection } from './folder-map.js';\nimport { applyGitignoreProfile, resolveGitignoreProfile, validateGitignoreFlag, PRIVATE_PROFILE_IGNORES, PRIVATE_UNTRACK_COMMAND } from './gitignore.js';\nimport { applyGitattributes } from './gitattributes.js';\nimport { SKILLS, TEMPLATES, CODEX_SKILLS, PI_SKILLS, PI_SCRIPTS, PI_EXTENSIONS, PI_AGENTS, COPILOT_SKILLS } from './bundled-files.js';\nimport { getPackageVersion } from './package-version.js';\nimport { planMigration, applyMigration, type MigrationPlan } from './migration.js';\nimport { HARNESSES, sanitizeHarnesses, type Harness } from './harness.js';\nimport { ensureExecutionProfileSection, defaultExecutionProfile } from './execution-profile.js';\n\n/**\n * Read-only check for harness files git is still tracking. Used to decide\n * whether to surface the `git rm --cached` untrack hint on a re-run already on\n * the `private` profile (the easy-to-miss case): only show it when files are\n * actually tracked, so it isn't noise. Never runs a mutating git command, and\n * fails closed to `[]` outside a git repo or when git is unavailable.\n */\nfunction listTrackedHarnessFiles(targetDir: string): string[] {\n const dirs = PRIVATE_PROFILE_IGNORES.map((d) => d.replace(/\\/$/, ''));\n try {\n const out = execFileSync('git', ['ls-files', '-z', '--', ...dirs], {\n cwd: targetDir,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n return out.split('\\0').filter((line) => line.length > 0);\n } catch {\n return [];\n }\n}\n\nfunction isStaleVersion(current: string, latest: string): boolean {\n const currentParts = current.split('.').map(Number);\n const latestParts = latest.split('.').map(Number);\n const len = Math.max(currentParts.length, latestParts.length);\n for (let i = 0; i < len; i++) {\n const c = currentParts[i] ?? 0;\n const l = latestParts[i] ?? 0;\n if (c < l) return true;\n if (c > l) return false;\n }\n return false;\n}\n\nasync function checkCliVersion(): Promise<{ stale: boolean; latest?: string }> {\n try {\n const pkgVersion = getPackageVersion();\n const res = await fetch('https://registry.npmjs.org/joycraft/latest', {\n signal: AbortSignal.timeout(3000)\n });\n if (!res.ok) return { stale: false };\n const data = (await res.json()) as { version: string };\n if (isStaleVersion(pkgVersion, data.version)) {\n return { stale: true, latest: data.version };\n }\n } catch {\n // Silent fallback on network errors or missing version\n }\n return { stale: false };\n}\n\nexport interface UpgradeOptions {\n yes: boolean;\n /** Raw --gitignore value from the CLI, if provided. Validated in upgrade(). */\n gitignore?: string;\n /** Test seam for the stale-CLI re-exec; defaults to child_process.spawnSync. */\n spawnForReexec?: (\n cmd: string,\n args: string[],\n opts: { stdio: 'inherit' }\n ) => { status: number | null; error?: Error };\n}\n\n/**\n * Re-run the upgrade through the latest published CLI. Pinning the exact\n * version bypasses npx's cache, which is what leaves a bare `npx joycraft`\n * stale in the first place. Returns false if the spawn itself failed.\n */\nfunction reexecLatestUpgrade(targetDir: string, opts: UpgradeOptions, latest: string): boolean {\n const args = ['-y', `joycraft@${latest}`, 'upgrade', targetDir];\n if (opts.yes) args.push('--yes');\n if (opts.gitignore !== undefined) args.push('--gitignore', opts.gitignore);\n const spawn = opts.spawnForReexec ?? spawnSync;\n const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx';\n const result = spawn(npx, args, { stdio: 'inherit' });\n if (result.error) return false;\n if (typeof result.status === 'number' && result.status !== 0) {\n process.exitCode = result.status;\n }\n return true;\n}\n\ninterface FileChange {\n relativePath: string;\n absolutePath: string;\n newContent: string;\n kind: 'new' | 'updated' | 'customized';\n}\n\n/**\n * Build the managed-file map for the diff/apply loop, scoped to the installed\n * harnesses. A Codex-only project must not have Claude/Pi files added back on\n * upgrade. `harnesses` comes from persisted state; callers pass all available for\n * back-compat when the project predates harness selection. Templates are\n * harness-agnostic and always included.\n */\nfunction getManagedFiles(harnesses: readonly Harness[]): Record<string, string> {\n const files: Record<string, string> = {};\n const wants = (h: Harness): boolean => harnesses.includes(h);\n\n if (wants('claude')) {\n for (const [name, content] of Object.entries(SKILLS)) {\n const skillName = name.replace(/\\.md$/, '');\n files[join('.claude', 'skills', skillName, 'SKILL.md')] = content;\n }\n }\n for (const [name, content] of Object.entries(TEMPLATES)) {\n files[join('docs', 'templates', name)] = content;\n }\n if (wants('codex')) {\n for (const [name, content] of Object.entries(CODEX_SKILLS)) {\n const skillName = name.replace(/\\.md$/, '');\n files[join('.agents', 'skills', skillName, 'SKILL.md')] = content;\n }\n }\n if (wants('pi')) {\n for (const [name, content] of Object.entries(PI_SKILLS)) {\n const skillName = name.replace(/\\.md$/, '');\n files[join('.pi', 'skills', skillName, 'SKILL.md')] = content;\n }\n for (const [name, content] of Object.entries(PI_SCRIPTS)) {\n files[join('.pi', 'scripts', 'joycraft', name)] = content;\n }\n for (const [name, content] of Object.entries(PI_EXTENSIONS)) {\n files[join('.pi', 'extensions', name)] = content;\n }\n for (const [name, content] of Object.entries(PI_AGENTS)) {\n files[join('.pi', 'agents', name)] = content;\n }\n }\n if (wants('copilot')) {\n for (const [name, content] of Object.entries(COPILOT_SKILLS)) {\n const skillName = name.replace(/\\.md$/, '');\n files[join('.github', 'skills', skillName, 'SKILL.md')] = content;\n }\n }\n return files;\n}\n\n// Deprecated skill names from previous versions of Joycraft.\n// These get removed during upgrade to prevent stale slash commands.\nconst DEPRECATED_SKILL_DIRS = [\n // Pre-rebrand names\n 'joysmith', // pre-rebrand main skill\n 'joysmith-assess', // merged into joycraft-tune\n 'joysmith-upgrade', // merged into joycraft-tune\n // Pre-namespace names (bare names without joycraft- prefix)\n 'tune', // now /joycraft-tune\n 'tune-assess', // merged into joycraft-tune\n 'tune-upgrade', // merged into joycraft-tune\n 'joy', // merged into joycraft-tune\n 'interview', // now /joycraft-interview\n 'new-feature', // now /joycraft-new-feature\n 'decompose', // now /joycraft-decompose\n 'session-end', // now /joycraft-session-end\n];\n\n// Flat .md files from the pre-directory skill format\nconst DEPRECATED_SKILL_FILES = [\n 'tune.md',\n 'joy.md',\n 'joysmith.md',\n 'joysmith-assess.md',\n 'joysmith-upgrade.md',\n 'tune-assess.md',\n 'tune-upgrade.md',\n 'interview.md',\n 'new-feature.md',\n 'decompose.md',\n 'session-end.md',\n];\n\nfunction cleanupDeprecatedSkills(targetDir: string): number {\n const skillsDir = join(targetDir, '.claude', 'skills');\n if (!existsSync(skillsDir)) return 0;\n\n let removed = 0;\n\n // Remove deprecated directories\n for (const name of DEPRECATED_SKILL_DIRS) {\n const dir = join(skillsDir, name);\n if (existsSync(dir)) {\n rmSync(dir, { recursive: true, force: true });\n removed++;\n }\n }\n\n // Remove flat .md files from pre-directory format\n for (const name of DEPRECATED_SKILL_FILES) {\n const file = join(skillsDir, name);\n if (existsSync(file)) {\n rmSync(file);\n removed++;\n }\n }\n\n return removed;\n}\n\n/**\n * Self-heal projects inited by an older Joycraft that wrote state to a now-legacy\n * location, relocating it to the current harness-neutral `docs/.joycraft/state.json`.\n * Two legacy homes are handled, in precedence order:\n * 1. `.claude/.joycraft/state.json` — the interim Claude-nested location.\n * 2. `.joycraft-version` — the original repo-root file.\n * The newer (Claude-nested) source wins when both somehow exist. Returns true\n * if any legacy file was found (and removed), false when there's nothing to do.\n *\n * Beyond moving the data, this also clears the foreign-harness footprint: after\n * migrating away from `.claude/.joycraft/`, the emptied `.joycraft/` (and an\n * emptied `.claude/`) are removed so a Codex/Pi-only project stops carrying a\n * stray `.claude/` it never asked for.\n *\n * Gitignore handling is deliberately NOT done here: the profile isn't resolved\n * yet at this point in upgrade(), and applyGitignoreProfile later in the same\n * run covers the state entry (shared) or the whole harness trees (private) —\n * writing the state entry here would leave a dead line under `private`.\n *\n * Runs BEFORE the managed-file diff so the recorded-original hashes are\n * available at the new location for the same run's 3-way comparison. The hidden\n * state's own write truncates the (possibly full-length legacy) hashes, so the\n * comparison stays consistent — see the truncateHash() call in the diff loop.\n */\nfunction migrateLegacyVersionFile(targetDir: string): boolean {\n // Prefer the newer Claude-nested state, then the original root file.\n const claudeStatePath = join(targetDir, LEGACY_CLAUDE_STATE_PATH);\n const rootStatePath = join(targetDir, LEGACY_VERSION_FILE);\n const legacyPath = existsSync(claudeStatePath)\n ? claudeStatePath\n : existsSync(rootStatePath)\n ? rootStatePath\n : null;\n if (legacyPath === null) return false;\n\n let parsed: { version?: unknown; files?: unknown; gitignoreProfile?: unknown; harnesses?: unknown };\n try {\n parsed = JSON.parse(readFileSync(legacyPath, 'utf-8'));\n } catch {\n // Corrupt legacy file: treat as no usable baseline. Remove it so the old\n // location stops being polluted; upgrade then proceeds with no\n // recorded-original (every changed file becomes \"customized\" — safe, never\n // silently wrong).\n rmSync(legacyPath, { force: true });\n cleanupEmptyClaudeState(targetDir);\n return true;\n }\n\n const version = typeof parsed.version === 'string' ? parsed.version : getPackageVersion();\n const files =\n parsed.files && typeof parsed.files === 'object'\n ? (parsed.files as Record<string, string>)\n : {};\n // Carry forward the profile and harness selection recorded in the legacy\n // state. (The root-file format predates both fields, so they're typically\n // absent there — harmless.) Passing them explicitly matters here: the new\n // docs/ state doesn't exist yet, so writeVersion has nothing to preserve them\n // from. Dropping harnesses would make the later getManagedFiles() fall back to\n // all available and resurrect a .claude/ on a Codex/Pi-only project.\n const profile = parseGitignoreProfile(parsed.gitignoreProfile) ?? undefined;\n const harnesses = sanitizeHarnesses(parsed.harnesses) ?? undefined;\n\n // writeVersion targets the new docs/ path and truncates the hashes.\n writeVersion(targetDir, version, files, profile, harnesses);\n rmSync(legacyPath, { force: true });\n cleanupEmptyClaudeState(targetDir);\n return true;\n}\n\n/**\n * After migrating away from `.claude/.joycraft/state.json`, remove the now-empty\n * `.claude/.joycraft/` directory — and `.claude/` itself if Joycraft's state was\n * the only thing in it (a Codex/Pi-only install that should never have had a\n * `.claude/`). Best-effort: a `.claude/` holding skills, hooks, or settings is\n * left untouched. rmdir on a non-empty dir throws, which we swallow.\n */\nfunction cleanupEmptyClaudeState(targetDir: string): void {\n const joycraftDir = join(targetDir, '.claude', '.joycraft');\n const claudeDir = join(targetDir, '.claude');\n try { rmdirSync(joycraftDir); } catch { /* non-empty or absent — leave it */ }\n try { rmdirSync(claudeDir); } catch { /* non-empty or absent — leave it */ }\n}\n\nfunction countLines(content: string): number {\n return content.split('\\n').length;\n}\n\nfunction ensureScriptExecutable(absolutePath: string): void {\n // Joycraft shell scripts in .pi/scripts/joycraft/ must be executable.\n // README.md is the only file in that directory that should stay 644.\n if (absolutePath.includes('.pi/scripts/joycraft/') && !absolutePath.endsWith('README.md')) {\n try {\n chmodSync(absolutePath, 0o755);\n } catch {\n // non-fatal — permissions may be restricted\n }\n }\n}\n\nasync function askUser(question: string): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n return new Promise((resolve) => {\n rl.question(`${question} [y/N] `, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase() === 'y');\n });\n });\n}\n\nfunction printMigrationSummary(plan: MigrationPlan, projectDir: string): void {\n console.log('');\n console.log('Joycraft is migrating your docs/ to the new per-feature layout:');\n console.log('');\n\n const relTo = (p: string) => (p.startsWith(projectDir) ? p.slice(projectDir.length + 1) : p);\n\n // Group per-feature moves by feature folder for readability.\n // Bugfix-area moves are listed separately below.\n const featureMoves = plan.moves.filter(m => m.kind !== 'bugfix-dir');\n const bugfixMoves = plan.moves.filter(m => m.kind === 'bugfix-dir');\n\n const bySlug = new Map<string, typeof plan.moves>();\n for (const move of featureMoves) {\n const parts = relTo(move.to).split(/[\\\\/]/);\n // docs/features/<slug>/...\n const slug = parts.length >= 3 ? parts[2] : '(root)';\n if (!bySlug.has(slug)) bySlug.set(slug, []);\n bySlug.get(slug)!.push(move);\n }\n for (const [slug, moves] of bySlug) {\n console.log(` ${slug}/`);\n for (const move of moves) {\n console.log(` ${relTo(move.from)} → ${relTo(move.to)}`);\n }\n }\n\n if (bugfixMoves.length > 0) {\n console.log('');\n console.log(' Migrating bugfix areas:');\n for (const move of bugfixMoves) {\n console.log(` ${relTo(move.from)} → ${relTo(move.to)}`);\n }\n }\n console.log('');\n}\n\nfunction printMigrationBanner(): void {\n console.log('');\n console.log('Migration complete. See the README section \"Migration: Flat → Per-Feature Layout\"');\n console.log('for context on what changed and why. If your project is a git repo, run');\n console.log('`git status` to inspect the moves before committing.');\n console.log('');\n}\n\nfunction runForcedMigration(projectDir: string): void {\n const plan = planMigration(projectDir);\n if (plan.moves.length === 0 && plan.orphans.specsDirs.length === 0) {\n return; // No flat layout — silent no-op.\n }\n\n printMigrationSummary(plan, projectDir);\n const result = applyMigration(plan);\n\n // Abort threshold: if more than 50% of attempted moves failed, bail loudly.\n const attempted = result.applied + result.errors.length;\n if (attempted > 0 && result.errors.length / attempted > 0.5) {\n console.error('Migration failed for more than half of attempted moves. Aborting upgrade.');\n for (const e of result.errors) {\n console.error(` ${e.move.from} → ${e.move.to}: ${e.error}`);\n }\n throw new Error('Migration aborted: too many failures');\n }\n\n if (result.errors.length > 0) {\n console.log('Some moves had errors but upgrade will continue:');\n for (const e of result.errors) {\n console.log(` warn: ${e.move.from} → ${e.move.to}: ${e.error}`);\n }\n }\n\n printMigrationBanner();\n}\n\nexport interface UpgradeResult {\n /**\n * True when the stale-CLI guard handled this run (re-exec'd the latest\n * version or printed the manual one-liner). The CLI layer uses this to\n * suppress its postAction update nudge, which would otherwise contradict\n * the upgrade the delegated run just completed.\n */\n cliWasStale: boolean;\n}\n\nexport async function upgrade(dir: string, opts: UpgradeOptions): Promise<UpgradeResult> {\n const targetDir = resolve(dir);\n\n // Validate the --gitignore flag before any side effects (network check,\n // legacy migration, docs migration) so a typo'd value changes nothing.\n if (opts.gitignore !== undefined) validateGitignoreFlag(opts.gitignore);\n\n // Guard: if the CLI itself is out of date, never compare project files\n // against stale bundled content. With --yes or an interactive confirmation,\n // re-exec the pinned latest version via npx so upgrade stays one command;\n // otherwise (or if the spawn fails) tell the user the one-liner.\n const cliCheck = await checkCliVersion();\n if (cliCheck.stale && cliCheck.latest) {\n const pkgVersion = getPackageVersion();\n console.log(`Joycraft CLI is out of date (you have ${pkgVersion}, latest is ${cliCheck.latest}).`);\n const rerun =\n opts.yes ||\n (process.stdin.isTTY === true &&\n (await askUser(`Run joycraft@${cliCheck.latest} via npx now?`)));\n if (rerun && reexecLatestUpgrade(targetDir, opts, cliCheck.latest)) {\n return { cliWasStale: true };\n }\n console.log('Update and re-run in one step with: npx joycraft@latest upgrade');\n return { cliWasStale: true };\n }\n\n // Check if project was initialized. A project is \"initialized\" if it has the\n // hidden state, OR a known skill, OR a legacy root state file (pre-relocation).\n const hasLegacyState =\n existsSync(join(targetDir, LEGACY_VERSION_FILE)) ||\n existsSync(join(targetDir, LEGACY_CLAUDE_STATE_PATH));\n const hasSkill = existsSync(join(targetDir, '.claude', 'skills', 'joycraft-tune', 'SKILL.md'))\n || existsSync(join(targetDir, '.claude', 'skills', 'tune', 'SKILL.md'))\n || existsSync(join(targetDir, '.claude', 'skills', 'joy', 'SKILL.md'))\n || existsSync(join(targetDir, '.claude', 'skills', 'joysmith', 'SKILL.md'));\n\n if (!readVersion(targetDir) && !hasLegacyState && !hasSkill) {\n console.log('This project has not been initialized with Joycraft.');\n console.log('Run `npx joycraft init` first.');\n return { cliWasStale: false };\n }\n\n // Relocate any legacy state (root .joycraft-version or the interim\n // .claude/.joycraft/state.json) → docs/.joycraft/state.json, BEFORE the diff\n // loop so the migrated recorded-original is used on this same run. No-op when\n // no legacy file exists.\n migrateLegacyVersionFile(targetDir);\n\n // Clean up deprecated skill directories/files from older versions\n const deprecatedRemoved = cleanupDeprecatedSkills(targetDir);\n if (deprecatedRemoved > 0) {\n console.log(`Removed ${deprecatedRemoved} deprecated skill(s) from previous Joycraft versions.`);\n }\n\n // Forced migration: flat docs/{briefs,research,designs,specs/<feature>}/\n // → docs/features/<slug>/{brief,research,design,specs/}/\n // Runs before the managed-file diff loop so any new managed files end up\n // correctly placed in an already-migrated tree.\n runForcedMigration(targetDir);\n\n // Get current package version\n const pkgVersion = getPackageVersion();\n\n // If version matches exactly, check if any file content actually changed.\n // Re-read state AFTER migration so a just-migrated project's recorded-original\n // hashes (now at the new path) feed the comparison below.\n const installed = readVersion(targetDir);\n const installedHashes = installed?.files ?? {};\n\n // Scope the upgrade to the harnesses this project installed. State written\n // before harness selection has no `harnesses` field → fall back to all available\n // so existing projects keep getting every harness refreshed (back-compat).\n const harnesses: readonly Harness[] = installed?.harnesses ?? HARNESSES;\n const managedFiles = getManagedFiles(harnesses);\n\n // Resolve the project's gitignore profile.\n // - --gitignore flag: explicit choice — the non-interactive way to set or\n // switch the profile on an existing project.\n // - Already chosen (init, or a prior upgrade): honor it silently.\n // - Never chosen (pre-feature project) + interactive: ask once, then persist\n // so this prompt never recurs. --yes suppresses the prompt — it promises\n // a fully unattended run.\n // - Never chosen + non-interactive: fall back to shared for this run only;\n // decided=false means it is never persisted, so the project stays\n // undecided and will be asked next time someone runs upgrade in a TTY.\n const resolvedProfile = await resolveGitignoreProfile({\n flag: opts.gitignore,\n persisted: installed?.gitignoreProfile,\n interactive: process.stdin.isTTY === true && !opts.yes,\n promptIntro: '\\nJoycraft can now control how much of the harness is tracked in git.',\n });\n const gitignoreProfile = resolvedProfile.profile;\n applyGitignoreProfile(targetDir, gitignoreProfile);\n // Bring pre-existing projects up to the init behavior: collapse\n // workflow-exhaust docs in PR review. Append-only + idempotent.\n applyGitattributes(targetDir);\n\n // Bring pre-profile projects up to the init behavior: insert the\n // sentinel-delimited Execution Profile into AGENTS.md when it has none.\n // Insert-only — a project that already has a profile (hand-edited or not)\n // comes back byte-identical, because the region is user-owned data (D7).\n // Upgrade can't ask questions here (it may be running --yes/non-interactive),\n // so it writes the explicit-no default; /joycraft-tune offers the real\n // questions.\n const agentsMdPath = join(targetDir, 'AGENTS.md');\n if (existsSync(agentsMdPath)) {\n const existingAgents = readFileSync(agentsMdPath, 'utf-8');\n let updatedAgents = ensureExecutionProfileSection(\n existingAgents,\n defaultExecutionProfile(harnesses)\n );\n if (updatedAgents !== existingAgents) {\n console.log(' ~ AGENTS.md (added Execution Profile — run /joycraft-tune to fill it in)');\n }\n // Folder map (D6): regenerate the machine-owned block in place (human\n // wording preserved), or append the section when the doc has no\n // architecture section at all. A hand-written architecture section\n // without markers comes back byte-identical.\n const withMap = ensureFolderMapSection(updatedAgents, targetDir);\n if (withMap !== updatedAgents) {\n updatedAgents = withMap;\n console.log(' ~ AGENTS.md (folder map regenerated from the tree)');\n }\n if (updatedAgents !== existingAgents) {\n writeFileSync(agentsMdPath, updatedAgents, 'utf-8');\n }\n }\n\n // Same regeneration for a full CLAUDE.md (claude-only installs); the\n // multi-tool `@AGENTS.md` pointer file is left alone.\n const claudeMdPath = join(targetDir, 'CLAUDE.md');\n if (existsSync(claudeMdPath)) {\n const existingClaude = readFileSync(claudeMdPath, 'utf-8');\n if (!existingClaude.includes('@AGENTS.md')) {\n const withMap = ensureFolderMapSection(existingClaude, targetDir);\n if (withMap !== existingClaude) {\n writeFileSync(claudeMdPath, withMap, 'utf-8');\n console.log(' ~ CLAUDE.md (folder map regenerated from the tree)');\n }\n }\n }\n\n if (gitignoreProfile === 'private') {\n // On a fresh switch to private, always surface the untrack hint. On a\n // re-run where private is already persisted (the easy-to-miss case), only\n // surface it when harness files are actually still tracked — otherwise it's\n // noise. `git ls-files` is read-only; we never run git for the user.\n const switchingToPrivate = installed?.gitignoreProfile !== 'private';\n const trackedHarnessFiles = switchingToPrivate ? [] : listTrackedHarnessFiles(targetDir);\n if (switchingToPrivate || trackedHarnessFiles.length > 0) {\n console.log('');\n console.log(' ⚠ Private profile: harness dirs are gitignored, but git only stops');\n console.log(' tracking files you untrack. If any harness files were already');\n console.log(` committed${trackedHarnessFiles.length > 0 ? ` (${trackedHarnessFiles.length} still tracked)` : ''}, untrack them with:`);\n console.log('');\n console.log(` ${PRIVATE_UNTRACK_COMMAND}`);\n console.log('');\n console.log(' (advisory — Joycraft never runs git for you)');\n }\n }\n\n const changes: FileChange[] = [];\n let upToDate = 0;\n\n for (const [relPath, newContent] of Object.entries(managedFiles)) {\n const absPath = join(targetDir, relPath);\n const newHash = hashContent(newContent);\n\n if (!existsSync(absPath)) {\n // File doesn't exist locally — new file\n changes.push({ relativePath: relPath, absolutePath: absPath, newContent, kind: 'new' });\n continue;\n }\n\n const currentContent = readFileSync(absPath, 'utf-8');\n const currentHash = hashContent(currentContent);\n\n if (currentHash === newHash) {\n // Already matches the latest version\n upToDate++;\n continue;\n }\n\n // installedHashes are stored truncated; truncate the fresh hash to match.\n const originalHash = installedHashes[relPath];\n\n if (originalHash && truncateHash(currentHash) === originalHash) {\n // User hasn't modified the file — safe to auto-update\n changes.push({ relativePath: relPath, absolutePath: absPath, newContent, kind: 'updated' });\n } else {\n // User has customized this file (or no original hash recorded)\n changes.push({ relativePath: relPath, absolutePath: absPath, newContent, kind: 'customized' });\n }\n }\n\n if (changes.length === 0) {\n // Persist a freshly-decided profile (prompt answer or --gitignore switch)\n // even when no files changed, so the decision sticks. Never persist the\n // non-interactive fallback — an undecided project must stay undecided.\n if (resolvedProfile.decided && installed && installed.gitignoreProfile !== gitignoreProfile) {\n writeVersion(targetDir, installed.version, installedHashes, gitignoreProfile);\n }\n console.log('Already up to date.');\n return { cliWasStale: false };\n }\n\n // Process changes\n let updated = 0;\n let skipped = 0;\n let added = 0;\n\n for (const change of changes) {\n if (change.kind === 'new') {\n // New Joycraft files are always auto-added — no prompt needed\n mkdirSync(dirname(change.absolutePath), { recursive: true });\n writeFileSync(change.absolutePath, change.newContent, 'utf-8');\n ensureScriptExecutable(change.absolutePath);\n added++;\n console.log(` + ${change.relativePath}`);\n } else if (change.kind === 'updated') {\n // Safe to auto-update — user hasn't touched the file\n writeFileSync(change.absolutePath, change.newContent, 'utf-8');\n ensureScriptExecutable(change.absolutePath);\n updated++;\n } else if (change.kind === 'customized') {\n const currentContent = readFileSync(change.absolutePath, 'utf-8');\n const currentLines = countLines(currentContent);\n const newLines = countLines(change.newContent);\n const diff = newLines - currentLines;\n const diffLabel = diff > 0 ? `+${diff} lines` : diff < 0 ? `${diff} lines` : 'same length';\n const label = `Customized: ${change.relativePath} (local: ${currentLines} lines, latest: ${newLines} lines, ${diffLabel})`;\n\n if (opts.yes) {\n writeFileSync(change.absolutePath, change.newContent, 'utf-8');\n updated++;\n } else {\n const accept = await askUser(`${label} — overwrite with latest?`);\n if (accept) {\n writeFileSync(change.absolutePath, change.newContent, 'utf-8');\n ensureScriptExecutable(change.absolutePath);\n updated++;\n } else {\n skipped++;\n }\n }\n }\n }\n\n // Write new version file with updated hashes\n const newHashes: Record<string, string> = {};\n for (const [relPath, content] of Object.entries(managedFiles)) {\n const absPath = join(targetDir, relPath);\n if (existsSync(absPath)) {\n const current = readFileSync(absPath, 'utf-8');\n newHashes[relPath] = hashContent(current);\n }\n }\n // Record the profile only when this run actually decided it; writeVersion\n // preserves an already-persisted profile when the argument is omitted, and an\n // undecided project stays undecided (so the one-time prompt can still fire).\n writeVersion(targetDir, pkgVersion, newHashes, resolvedProfile.decided ? gitignoreProfile : undefined);\n\n // Print summary\n const parts: string[] = [];\n if (updated > 0) parts.push(`Updated ${updated}`);\n if (skipped > 0) parts.push(`skipped ${skipped} (customized)`);\n if (added > 0) parts.push(`added ${added} new`);\n if (upToDate > 0) parts.push(`${upToDate} already up to date`);\n console.log(`\\nUpgrade complete: ${parts.join(', ')}.`);\n return { cliWasStale: false };\n}\n\n","// Migration module — moves flat docs/{briefs,research,designs,specs/<feature>} layouts\n// into per-feature folders at docs/features/<slug>/{brief,research,design,specs/}.\n// Plan-then-apply split so callers can render a summary before mutating the filesystem.\n\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n readdirSync,\n renameSync,\n rmSync,\n statSync,\n} from 'node:fs';\nimport { join } from 'node:path';\n\nexport type MoveKind = 'brief' | 'research' | 'design' | 'specs-dir' | 'bugfix-dir';\n\nexport interface Move {\n from: string;\n to: string;\n kind: MoveKind;\n}\n\nexport interface MigrationPlan {\n moves: Move[];\n slugs: string[];\n orphans: { specsDirs: string[] };\n skipped?: Move[];\n}\n\nexport interface MigrationResult {\n applied: number;\n skipped: number;\n errors: Array<{ move: Move; error: string }>;\n}\n\nconst DATE_PREFIX_RE = /^\\d{4}-\\d{2}-\\d{2}-(.+)$/;\n\nfunction deriveSlug(filename: string): string {\n return filename.replace(/\\.md$/, '');\n}\n\nfunction slugWithoutDate(slug: string): string | null {\n const m = slug.match(DATE_PREFIX_RE);\n return m ? m[1] : null;\n}\n\nfunction listMdFiles(dir: string): string[] {\n if (!existsSync(dir)) return [];\n try {\n return readdirSync(dir).filter(f => f.endsWith('.md'));\n } catch {\n return [];\n }\n}\n\nfunction listSubdirs(dir: string): string[] {\n if (!existsSync(dir)) return [];\n try {\n return readdirSync(dir).filter(name => {\n try {\n return statSync(join(dir, name)).isDirectory();\n } catch {\n return false;\n }\n });\n } catch {\n return [];\n }\n}\n\nexport function planMigration(projectDir: string): MigrationPlan {\n const briefsDir = join(projectDir, 'docs', 'briefs');\n const researchDir = join(projectDir, 'docs', 'research');\n const designsDir = join(projectDir, 'docs', 'designs');\n const specsDir = join(projectDir, 'docs', 'specs');\n\n const moves: Move[] = [];\n const skipped: Move[] = [];\n const slugSet = new Set<string>();\n\n // Briefs\n for (const file of listMdFiles(briefsDir)) {\n const slug = deriveSlug(file);\n slugSet.add(slug);\n const move: Move = {\n from: join(briefsDir, file),\n to: join(projectDir, 'docs', 'features', slug, 'brief.md'),\n kind: 'brief',\n };\n if (existsSync(move.to)) skipped.push(move);\n else moves.push(move);\n }\n\n // Research\n for (const file of listMdFiles(researchDir)) {\n const slug = deriveSlug(file);\n slugSet.add(slug);\n const move: Move = {\n from: join(researchDir, file),\n to: join(projectDir, 'docs', 'features', slug, 'research.md'),\n kind: 'research',\n };\n if (existsSync(move.to)) skipped.push(move);\n else moves.push(move);\n }\n\n // Designs\n for (const file of listMdFiles(designsDir)) {\n const slug = deriveSlug(file);\n slugSet.add(slug);\n const move: Move = {\n from: join(designsDir, file),\n to: join(projectDir, 'docs', 'features', slug, 'design.md'),\n kind: 'design',\n };\n if (existsSync(move.to)) skipped.push(move);\n else moves.push(move);\n }\n\n // Spec dirs — match by exact slug or date-stripped slug\n const briefSlugs = Array.from(slugSet);\n const orphanSpecsDirs: string[] = [];\n\n for (const subdir of listSubdirs(specsDir)) {\n let matchedSlug: string | null = null;\n\n if (briefSlugs.includes(subdir)) {\n matchedSlug = subdir;\n } else {\n // Look for a brief slug whose date-stripped form matches this subdir\n for (const slug of briefSlugs) {\n if (slugWithoutDate(slug) === subdir) {\n matchedSlug = slug;\n break;\n }\n }\n }\n\n if (matchedSlug) {\n const move: Move = {\n from: join(specsDir, subdir),\n to: join(projectDir, 'docs', 'features', matchedSlug, 'specs'),\n kind: 'specs-dir',\n };\n if (existsSync(move.to)) skipped.push(move);\n else moves.push(move);\n } else {\n // No matching brief slug → this is an area-level (bugfix) spec dir.\n // Reclassify it as a forced move into docs/bugfixes/<area>/.\n orphanSpecsDirs.push(subdir);\n const move: Move = {\n from: join(specsDir, subdir),\n to: join(projectDir, 'docs', 'bugfixes', subdir),\n kind: 'bugfix-dir',\n };\n if (existsSync(move.to)) skipped.push(move);\n else moves.push(move);\n }\n }\n\n const plan: MigrationPlan = {\n moves,\n slugs: Array.from(slugSet),\n orphans: { specsDirs: orphanSpecsDirs },\n };\n if (skipped.length > 0) plan.skipped = skipped;\n return plan;\n}\n\nfunction moveFsItem(from: string, to: string): void {\n mkdirSync(join(to, '..'), { recursive: true });\n try {\n renameSync(from, to);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'EXDEV') {\n cpSync(from, to, { recursive: true });\n rmSync(from, { recursive: true, force: true });\n } else {\n throw err;\n }\n }\n}\n\nexport function applyMigration(plan: MigrationPlan): MigrationResult {\n let applied = 0;\n let skipped = (plan.skipped?.length) ?? 0;\n const errors: Array<{ move: Move; error: string }> = [];\n\n for (const move of plan.moves) {\n if (existsSync(move.to)) {\n skipped++;\n continue;\n }\n if (!existsSync(move.from)) {\n errors.push({ move, error: `Source missing: ${move.from}` });\n continue;\n }\n try {\n moveFsItem(move.from, move.to);\n applied++;\n } catch (err) {\n errors.push({ move, error: (err as Error).message });\n }\n }\n\n return { applied, skipped, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,aAAY,cAAc,eAAe,aAAAC,YAAW,UAAAC,SAAQ,WAAwB,iBAAiB;AAC9G,SAAS,QAAAC,OAAM,SAAS,eAAe;AACvC,SAAS,uBAAuB;AAChC,SAAS,cAAc,iBAAiB;;;ACCxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;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