joycraft 0.7.16 → 0.7.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{chunk-GTP7Z52K.js → chunk-YLWBDXF4.js} +72 -15
- package/dist/chunk-YLWBDXF4.js.map +1 -0
- package/dist/cli.js +5 -5
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/{init-MUB5CC6L.js → init-O2QC5X57.js} +2 -2
- package/dist/joycraft-release.json +1 -1
- package/dist/{update-LFLQTPUA.js → update-LYHS4FBH.js} +4 -2
- package/dist/{upgrade-L5WERK4X.js → upgrade-GMP6JQ52.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-GTP7Z52K.js.map +0 -1
- /package/dist/{init-MUB5CC6L.js.map → init-O2QC5X57.js.map} +0 -0
- /package/dist/{update-LFLQTPUA.js.map → update-LYHS4FBH.js.map} +0 -0
- /package/dist/{upgrade-L5WERK4X.js.map → upgrade-GMP6JQ52.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/update.ts","../src/detect.ts","../src/safeguard.ts","../src/claude-session-start.ts","../src/model-profile.ts","../src/bundle-inventory.ts","../src/update-patches.ts","../src/update-plan.ts","../src/update-transaction.ts","../src/package-version.ts","../src/gitattributes.ts","../src/auto-memory.ts","../src/execution-profile.ts","../src/update-inventory.ts","../src/folder-map.ts","../src/improve-claude-md.ts","../src/agents-md.ts","../src/permissions.ts","../src/tsconfig.ts","../src/auto-safe-update.ts"],"sourcesContent":["import {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n} from 'node:fs';\nimport { execFileSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { join, resolve, dirname } from 'node:path';\n\nimport { detectStack } from './detect.js';\nimport { getBundleInventory, type BundleInventoryEntry } from './bundle-inventory.js';\nimport {\n adoptLegacyInstallation,\n manifestDigest,\n normalizeManifestPath,\n rawFileHash,\n readInstallationManifestInfo,\n type InstallationManifest,\n type LocalInstallationSettings,\n} from './install-manifest.js';\nimport { createUpdatePlan, type PlannedUpdateAction, type UpdatePlan, type UpdateSnapshot } from './update-plan.js';\nimport {\n applyUpdatePlan,\n recoverInterruptedUpdate,\n rollbackLastSuccessfulUpdate,\n type TransactionResult,\n type AuthorityTransition,\n type LocalTransactionOperation,\n} from './update-transaction.js';\nimport { getPackageVersion } from './package-version.js';\nimport { HARNESSES, parseHarnessSelection, resolveHarnesses, sanitizeHarnesses, type Harness } from './harness.js';\nimport {\n DEFAULT_GITIGNORE_PROFILE,\n LEGACY_CLAUDE_STATE_PATH,\n LEGACY_VERSION_FILE,\n STATE_PATH,\n parseGitignoreProfile,\n readVersion,\n type GitignoreProfile,\n} from './version.js';\nimport { planGitignoreProfile, sharedManifestIgnoreWarning } from './gitignore.js';\nimport { planGitattributes } from './gitattributes.js';\nimport { resolveUpdatePath } from './update-paths.js';\nimport { resolveAutoMemoryOffer } from './auto-memory.js';\nimport { defaultExecutionProfile, resolveExecutionProfile, type ExecutionProfile } from './execution-profile.js';\nimport { resolveGitignoreProfile } from './gitignore.js';\nimport { materializeFreshInstallInventory, type InventoryPatchOperation } from './update-inventory.js';\nimport {\n evaluateAutoSafeEligibility,\n} from './auto-safe-update.js';\nimport { readUpdatePolicy } from './update-check.js';\nimport type { ReleaseDescriptor, VerifiedReleaseArtifact } from './release-artifact.js';\n\n/** A bundle already selected by the launcher or supplied by a local test/artifact. */\nexport interface ExecutingBundle {\n version: string;\n /** Canonical outer-package SHA-512 integrity. Empty means unknown for a local bundle. */\n integrity?: string;\n /** Parsed descriptor shipped with the bundle that is actually executing. */\n descriptor?: ReleaseDescriptor;\n /** Inventory from the executing package. Supplying it avoids any package lookup. */\n inventory?: readonly BundleInventoryEntry[];\n}\n\nexport interface UpdateOptions {\n /** Explicit harness selection. Required for a fresh unattended `update`. */\n harnesses?: readonly Harness[] | string;\n /** Apply only safe actions; customized files remain conflicts. */\n yes?: boolean;\n nonInteractive?: boolean;\n /** Explicit paths whose customized bytes may be replaced. */\n replaceCustomized?: readonly string[];\n /** Repair explicitly deleted, verified files. */\n repair?: readonly string[];\n /** Init compatibility behavior: all harnesses in a fresh non-TTY run. */\n legacyInit?: boolean;\n /** `init --force` is scoped to known generator/inventory paths. */\n force?: boolean;\n gitignore?: string;\n json?: boolean;\n /** An exact bundle selected by the launcher. No registry work is performed here. */\n bundle?: ExecutingBundle;\n /** Recovery commands are intentionally explicit and share the same output contract. */\n recovery?: 'recover' | 'rollback';\n /** Optional profile captured by the init boundary's interactive setup. */\n executionProfile?: ExecutionProfile;\n /** Optional project-local auto-memory choice captured by init. */\n disableAutoMemory?: boolean;\n /** Return the complete read-only plan without applying it. */\n preview?: boolean;\n /** Apply only after the complete automatic safety gate passes. */\n automatic?: boolean;\n /** Verifier-issued proof for the exact candidate artifact. */\n verifiedArtifact?: VerifiedReleaseArtifact;\n}\n\nexport type UpdateStatus =\n | 'applied'\n | 'noop'\n | 'preserved'\n | 'conflict'\n | 'invalid'\n | 'attention'\n | 'failed';\n\nexport interface UpdateOutcome {\n status: UpdateStatus;\n exitCode: number;\n targetVersion?: string;\n installedVersion?: string;\n profile?: GitignoreProfile;\n harnesses?: Harness[];\n applied: string[];\n preserved: string[];\n conflicts: string[];\n diagnostics: string[];\n registry: 'unknown' | 'available' | 'unavailable' | 'not-requested';\n transaction?: TransactionResult;\n /** Local settings are kept separate from the tracked manifest during adoption. */\n localSettings?: LocalInstallationSettings;\n /** Existing non-Joycraft skills found while preparing a fresh init. */\n existingSkills?: string[];\n /** The read-only plan is exposed for agent review and test seams. */\n plan?: UpdatePlan;\n}\n\nexport function updateStatusExitCode(status: UpdateStatus): number {\n switch (status) {\n case 'applied':\n case 'noop':\n case 'preserved':\n return 0;\n case 'conflict':\n return 2;\n case 'attention':\n return 3;\n case 'invalid':\n case 'failed':\n return 1;\n default: {\n const exhaustive: never = status;\n throw new Error(`Unknown update status: ${String(exhaustive)}`);\n }\n }\n}\n\nfunction outcome(status: UpdateStatus, fields: Partial<UpdateOutcome> = {}): UpdateOutcome {\n return {\n status,\n exitCode: updateStatusExitCode(status),\n applied: [],\n preserved: [],\n conflicts: [],\n diagnostics: [],\n registry: 'not-requested',\n ...fields,\n };\n}\n\nfunction parseSelection(value: UpdateOptions['harnesses']): Harness[] | null {\n if (typeof value === 'string') return parseHarnessSelection(value);\n if (value === undefined) return null;\n if (value.some((entry) => typeof entry !== 'string' || !HARNESSES.includes(entry.trim().toLowerCase() as Harness))) return null;\n return sanitizeHarnesses(value);\n}\n\nfunction interactive(options: UpdateOptions): boolean {\n return options.nonInteractive !== true && options.yes !== true && process.stdin.isTTY === true;\n}\n\nfunction profileFromAuthorities(root: string, requested: string | undefined): {\n profile: GitignoreProfile;\n manifestInfo: ReturnType<typeof readInstallationManifestInfo>;\n sourceProfile?: GitignoreProfile;\n sourceManifestInfo?: ReturnType<typeof readInstallationManifestInfo>;\n diagnostic?: string;\n} {\n const explicit = requested === undefined ? undefined : parseGitignoreProfile(requested);\n if (requested !== undefined && explicit === null) {\n return {\n profile: DEFAULT_GITIGNORE_PROFILE,\n manifestInfo: readInstallationManifestInfo(root, DEFAULT_GITIGNORE_PROFILE),\n diagnostic: `Invalid gitignore profile '${requested}'. Choose shared or private.`,\n };\n }\n if (explicit) {\n const selected = readInstallationManifestInfo(root, explicit);\n const otherProfile: GitignoreProfile = explicit === 'shared' ? 'private' : 'shared';\n const other = readInstallationManifestInfo(root, otherProfile);\n if ((selected.status !== 'missing' && selected.status !== 'valid') || (other.status !== 'missing' && other.status !== 'valid')) {\n const bad = selected.status !== 'missing' && selected.status !== 'valid' ? selected : other;\n return { profile: explicit, manifestInfo: selected, diagnostic: `The ${bad.status} installation manifest needs attention.` };\n }\n if (selected.status === 'valid' && other.status === 'valid') {\n return { profile: explicit, manifestInfo: selected, diagnostic: 'Both shared and private installation manifests are valid; choose one authority before updating.' };\n }\n if (selected.status === 'missing' && other.status === 'valid') {\n return { profile: explicit, manifestInfo: selected, sourceProfile: otherProfile, sourceManifestInfo: other };\n }\n return { profile: explicit, manifestInfo: selected };\n }\n\n const shared = readInstallationManifestInfo(root, 'shared');\n const privateManifest = readInstallationManifestInfo(root, 'private');\n if ((shared.status !== 'missing' && shared.status !== 'valid') || (privateManifest.status !== 'missing' && privateManifest.status !== 'valid')) {\n const bad = shared.status !== 'missing' && shared.status !== 'valid' ? shared : privateManifest;\n return { profile: 'shared', manifestInfo: shared, diagnostic: `The ${bad.status} installation manifest needs attention.` };\n }\n if (shared.status === 'valid' && privateManifest.status === 'valid') {\n return { profile: 'shared', manifestInfo: shared, diagnostic: 'Both shared and private installation manifests are valid; choose one authority before updating.' };\n }\n if (shared.status === 'valid') return { profile: 'shared', manifestInfo: shared };\n if (privateManifest.status === 'valid') return { profile: 'private', manifestInfo: privateManifest };\n const legacy = readVersion(root);\n return {\n profile: legacy?.gitignoreProfile ?? DEFAULT_GITIGNORE_PROFILE,\n manifestInfo: readInstallationManifestInfo(root, legacy?.gitignoreProfile ?? DEFAULT_GITIGNORE_PROFILE),\n };\n}\n\nfunction regularFile(root: string, relative: string): boolean {\n try {\n return lstatSync(join(root, ...relative.split('/'))).isFile();\n } catch {\n return false;\n }\n}\n\nfunction snapshotFor(root: string, paths: Iterable<string>): UpdateSnapshot {\n const files: Record<string, { content: Buffer; mode?: number }> = {};\n for (const relative of paths) {\n if (!regularFile(root, relative)) continue;\n const absolute = join(root, ...relative.split('/'));\n const stat = lstatSync(absolute);\n files[relative] = { content: readFileSync(absolute), mode: stat.mode & 0o7777 };\n }\n return { files };\n}\n\nfunction executingBundle(options: UpdateOptions): ExecutingBundle {\n const supplied = options.bundle;\n if (supplied) return { ...supplied, integrity: supplied.integrity ?? '' };\n let descriptor: ReleaseDescriptor | undefined;\n try {\n descriptor = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'joycraft-release.json'), 'utf8')) as ReleaseDescriptor;\n } catch {\n descriptor = undefined;\n }\n return { version: getPackageVersion(), integrity: '', descriptor };\n}\n\nfunction legacyStateExists(root: string): boolean {\n return existsSync(join(root, STATE_PATH))\n || existsSync(join(root, LEGACY_VERSION_FILE))\n || existsSync(join(root, LEGACY_CLAUDE_STATE_PATH));\n}\n\nfunction legacyHarnesses(root: string): Harness[] | undefined {\n for (const relative of [STATE_PATH, LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE]) {\n if (!regularFile(root, relative)) continue;\n try {\n const parsed = JSON.parse(readFileSync(join(root, ...relative.split('/')), 'utf8')) as Record<string, unknown>;\n if (Array.isArray(parsed.harnesses)) return sanitizeHarnesses(parsed.harnesses) ?? undefined;\n } catch {\n // The migration below preserves malformed state bytes; selection falls\n // back to inspecting known Joycraft artifacts.\n }\n }\n return undefined;\n}\n\n/**\n * True when an entry belongs to a harness's own tree. A harness-gated template\n * under docs/templates/ carries a harness owner but is shared documentation,\n * so it never identifies which harness a project uses.\n */\nfunction harnessTreeEntry(entry: BundleInventoryEntry, harness: Harness): boolean {\n return entry.harness === harness && entry.content !== undefined && !entry.path.startsWith('docs/templates/');\n}\n\nfunction recognizedHarnesses(root: string): Harness[] {\n const inventory = getBundleInventory(HARNESSES);\n return HARNESSES.filter((harness) => inventory.some((entry) => harnessTreeEntry(entry, harness) && regularFile(root, entry.path)));\n}\n\nfunction legacyMigrationOperations(root: string, localSettings?: LocalInstallationSettings): LocalTransactionOperation[] {\n const sources = [STATE_PATH, LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE];\n const found: Array<{ path: string; content: Buffer }> = [];\n for (const relative of sources) {\n if (!regularFile(root, relative)) continue;\n found.push({ path: relative, content: readFileSync(join(root, ...relative.split('/'))) });\n }\n const operations: LocalTransactionOperation[] = [];\n const settingsPath = 'docs/.joycraft/local/settings.json';\n if (localSettings && Object.keys(localSettings).length > 0) {\n let settings: LocalInstallationSettings | undefined = localSettings;\n const existingSettings = regularFile(root, settingsPath)\n ? readFileSync(join(root, ...settingsPath.split('/')))\n : undefined;\n if (existingSettings) {\n try {\n const parsed = JSON.parse(existingSettings.toString('utf8'));\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n // A user's existing local preferences are authoritative. Legacy\n // values fill only keys that are not already present locally.\n settings = { ...localSettings, ...(parsed as Record<string, unknown>) };\n } else {\n settings = undefined;\n }\n } catch {\n // Leave an invalid user settings file untouched rather than replacing\n // it while migrating unrelated legacy state.\n settings = undefined;\n }\n }\n if (settings) {\n operations.push({\n path: settingsPath,\n kind: 'write',\n content: Buffer.from(JSON.stringify(settings, null, 2) + '\\n'),\n currentPresent: existingSettings !== undefined,\n ...(existingSettings ? { rawPrecondition: rawFileHash(existingSettings) } : {}),\n });\n }\n }\n if (!found.length || regularFile(root, 'docs/.joycraft/local/legacy-state-backup.json')) return operations;\n const backup = Buffer.from(JSON.stringify(Object.fromEntries(found.map((entry) => [entry.path, entry.content.toString('base64')]))));\n operations.push({\n path: 'docs/.joycraft/local/legacy-state-backup.json',\n kind: 'write',\n content: backup,\n currentPresent: false,\n });\n for (const entry of found) {\n operations.push({\n path: entry.path,\n kind: 'delete',\n currentPresent: true,\n rawPrecondition: rawFileHash(entry.content),\n });\n }\n return operations;\n}\n\nfunction hasRecognizedHarness(root: string): boolean {\n return recognizedHarnesses(root).length > 0;\n}\n\ninterface RecordedSelection {\n present: boolean;\n harnesses?: Harness[];\n profile?: GitignoreProfile;\n}\n\nconst RECORDED_SELECTION_PATHS = [STATE_PATH, LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE];\n\n/** Read only the facts needed to decide whether a fresh interview is needed. */\nfunction readRecordedSelection(root: string): RecordedSelection {\n const recorded: RecordedSelection = { present: false };\n for (const profile of ['shared', 'private'] as const) {\n const info = readInstallationManifestInfo(root, profile);\n if (info.status !== 'missing') recorded.present = true;\n if (info.manifest) {\n recorded.harnesses ??= [...info.manifest.harnesses];\n recorded.profile ??= info.manifest.profile;\n }\n }\n for (const relative of RECORDED_SELECTION_PATHS) {\n const path = join(root, ...relative.split('/'));\n if (!existsSync(path)) continue;\n recorded.present = true;\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n if (!recorded.harnesses && Array.isArray(parsed.harnesses)) {\n recorded.harnesses = sanitizeHarnesses(parsed.harnesses) ?? undefined;\n }\n recorded.profile ??= parseGitignoreProfile(parsed.gitignoreProfile) ?? undefined;\n } catch {\n // update() performs the authoritative malformed-state diagnosis later.\n }\n }\n if (!recorded.present) recorded.present = hasRecognizedHarness(root);\n return recorded;\n}\n\nfunction emptyHarnessSelection(value: UpdateOptions['harnesses']): boolean {\n if (Array.isArray(value)) return value.length === 0;\n return typeof value === 'string' && parseHarnessSelection(value)?.length === 0;\n}\n\nfunction invalidExplicitHarnessSelection(value: UpdateOptions['harnesses']): boolean {\n if (typeof value === 'string') return parseHarnessSelection(value) === null;\n if (value === undefined) return false;\n return value.some((entry) => (\n typeof entry !== 'string'\n || !HARNESSES.includes(entry.trim().toLowerCase() as Harness)\n ));\n}\n\ninterface InteractiveSelectionResult {\n options: UpdateOptions;\n emptySelection: boolean;\n}\n\n/**\n * Shared init/update boundary. It only captures choices; update() remains the\n * sole owner of snapshotting, planning, and filesystem mutation.\n */\nasync function resolveInteractiveInitOptions(root: string, input: UpdateOptions): Promise<InteractiveSelectionResult> {\n const recorded = readRecordedSelection(root);\n const prompting = process.stdin.isTTY === true\n && input.yes !== true\n && input.nonInteractive !== true\n && input.json !== true\n && input.recovery === undefined\n && input.automatic !== true\n && !recorded.present;\n let options = { ...input };\n\n if (prompting && options.harnesses === undefined) {\n options.harnesses = await resolveHarnesses(true);\n } else if (!prompting && options.harnesses === undefined && recorded.harnesses !== undefined) {\n options.harnesses = [...recorded.harnesses];\n }\n if (emptyHarnessSelection(options.harnesses)) {\n return { options, emptySelection: true };\n }\n if (invalidExplicitHarnessSelection(options.harnesses)) {\n return { options, emptySelection: false };\n }\n\n const selected = typeof options.harnesses === 'string'\n ? parseHarnessSelection(options.harnesses)\n : options.harnesses === undefined\n ? recorded.harnesses\n : sanitizeHarnesses(options.harnesses);\n const profileHarnesses = selected ?? [...HARNESSES];\n if (prompting && options.executionProfile === undefined) {\n options.executionProfile = await resolveExecutionProfile(profileHarnesses, true);\n }\n if (prompting && options.gitignore === undefined) {\n options.gitignore = (await resolveGitignoreProfile({\n persisted: recorded.profile,\n interactive: true,\n promptIntro: '\\nHow should Joycraft files be tracked in git?',\n })).profile;\n } else if (options.gitignore === undefined && recorded.profile !== undefined) {\n // Legacy state has no manifest authority for profileFromAuthorities() to\n // discover, so carry its recorded choice through migration explicitly.\n options.gitignore = recorded.profile;\n }\n if (prompting && options.disableAutoMemory === undefined && profileHarnesses.includes('claude')) {\n options.disableAutoMemory = await resolveAutoMemoryOffer(true);\n }\n return { options, emptySelection: false };\n}\n\nfunction chosenHarnesses(root: string, options: UpdateOptions, manifest: InstallationManifest | undefined): Harness[] | null {\n const explicit = parseSelection(options.harnesses);\n if (explicit !== null) return explicit;\n if (manifest?.harnesses?.length) return [...manifest.harnesses];\n const legacy = legacyHarnesses(root);\n if (legacy !== undefined && legacy.length > 0) return legacy;\n const recognized = recognizedHarnesses(root);\n if (recognized.length > 0) return recognized;\n if (legacyStateExists(root)) return [...HARNESSES];\n if (options.legacyInit) return [...HARNESSES];\n if (!interactive(options)) return null;\n return null;\n}\n\nfunction localSettingsFromAdoption(root: string, entries: readonly BundleInventoryEntry[], bundle: ExecutingBundle, profile: GitignoreProfile): {\n manifest: InstallationManifest;\n localSettings?: LocalInstallationSettings;\n conflicts: string[];\n} {\n const adopted = adoptLegacyInstallation(root, {\n inventory: entries,\n candidateContent: Object.fromEntries(entries.filter((entry) => entry.content !== undefined).map((entry) => [entry.path, { content: entry.content, vendorVersion: bundle.version }])),\n targetVersion: bundle.version,\n bundleIntegrity: bundle.integrity ?? '',\n profile,\n });\n return { manifest: adopted.manifest, localSettings: adopted.localSettings, conflicts: adopted.conflicts };\n}\n\nfunction pathsForOutcome(plan: UpdatePlan): { applied: string[]; preserved: string[]; conflicts: string[] } {\n const applied = plan.actions\n .filter((action) => action.selected && ['replace', 'create', 'repair', 'delete', 'conflict'].includes(action.kind))\n .map((action) => action.path);\n const resolved = new Set(plan.actions\n .filter((action) => action.kind === 'conflict' && action.selected && action.resolution === 'replace')\n .map((action) => action.path));\n const preserved = plan.preserved\n .filter((entry) => !resolved.has(entry.path))\n .filter((entry) => !plan.actions.some((action) => action.path === entry.path && action.nonActionable === true))\n .map((entry) => entry.path);\n const conflicts = plan.conflicts.filter((action) => !resolved.has(action.path)).map((action) => action.path);\n return { applied: [...new Set(applied)], preserved: [...new Set(preserved)], conflicts: [...new Set(conflicts)] };\n}\n\nfunction setupPatchAction(operation: InventoryPatchOperation): PlannedUpdateAction {\n return {\n path: operation.path,\n kind: 'replace',\n selected: true,\n reason: operation.reason,\n content: operation.content,\n rawPrecondition: operation.rawPrecondition,\n rawTargetHash: rawFileHash(operation.content),\n currentPresent: operation.currentPresent,\n targetPresent: true,\n };\n}\n\nfunction profileBookkeepingActions(root: string, profile: GitignoreProfile): PlannedUpdateAction[] {\n const paths = ['.gitignore', '.gitattributes'];\n const resolved = paths.map((path) => ({ path, absolute: resolveUpdatePath(root, path) }));\n const actions: PlannedUpdateAction[] = [];\n for (const target of resolved) {\n const current = regularFile(root, target.path) ? readFileSync(target.absolute) : undefined;\n const currentText = current?.toString('utf8') ?? '';\n const planned = target.path === '.gitignore' ? planGitignoreProfile(currentText, profile) : planGitattributes(currentText);\n if (planned.added.length === 0) continue;\n const stat = current ? lstatSync(target.absolute) : undefined;\n actions.push({\n path: target.path,\n kind: 'replace',\n selected: true,\n reason: `Append Joycraft ${target.path} entries while preserving existing project lines.`,\n content: planned.content,\n rawTargetHash: rawFileHash(planned.content),\n currentPresent: current !== undefined,\n targetPresent: true,\n ...(current ? { rawPrecondition: rawFileHash(current) } : {}),\n ...(stat ? { mode: stat.mode & 0o7777 } : {}),\n });\n }\n return actions;\n}\n\n/**\n * Explain when a selected shared harness is hidden by the project's effective\n * Git ignore rules. This is advisory and read-only; the profile planner still\n * owns all .gitignore writes.\n */\nfunction selectedHarnessIgnoreWarning(root: string, harnesses: readonly Harness[]): string[] {\n const warnings: string[] = [];\n for (const harness of harnesses) {\n const candidate = getBundleInventory([harness]).find((entry) => harnessTreeEntry(entry, harness))?.path;\n if (!candidate) continue;\n const top = candidate.split('/')[0];\n let localBroadIgnore = false;\n let localUnignore = false;\n try {\n const localRules = readFileSync(join(root, '.gitignore'), 'utf8')\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'));\n localBroadIgnore = localRules.some((line) => line === top || line === `${top}/` || line === `${top}/*` || line === `${top}/**`);\n localUnignore = localRules.some((line) => line === `!${top}/skills/` || line === `!${top}/skills/**` || line === `!${candidate}`);\n } catch {\n // A missing .gitignore is normal on a fresh project.\n }\n if (localBroadIgnore && !localUnignore) {\n const hint = harness === 'claude' ? ' Add !.claude/skills/ (and its parent directory exceptions) if teammates should receive those skills.' : '';\n warnings.push(`Selected ${harness} harness path ${candidate} is hidden by .gitignore.${hint}`);\n continue;\n }\n try {\n execFileSync('git', ['check-ignore', '--no-index', '-q', '--', candidate], {\n cwd: root,\n stdio: ['ignore', 'ignore', 'ignore'],\n });\n const hint = harness === 'claude' ? ' Add !.claude/skills/ (and its parent directory exceptions) if teammates should receive those skills.' : '';\n warnings.push(`Selected ${harness} harness path ${candidate} is hidden by the effective Git ignore rules.${hint}`);\n } catch {\n // Exit status 1 means the path is visible; other failures mean this is\n // not a Git worktree or Git is unavailable. Both are silent here.\n }\n }\n return warnings;\n}\n\nfunction transactionStatus(plan: UpdatePlan, result: TransactionResult, authorityTransition = false, localOperations = false): UpdateStatus {\n if (result.status === 'attention') return 'attention';\n if (result.status === 'failed') return 'failed';\n const unresolvedConflicts = pathsForOutcome(plan).conflicts;\n if (result.status === 'conflict' || unresolvedConflicts.length > 0) return 'conflict';\n if (pathsForOutcome(plan).preserved.length > 0 && pathsForOutcome(plan).applied.length === 0 && !authorityTransition && !localOperations) return 'preserved';\n if (result.status === 'noop' || (result.status === 'applied' && pathsForOutcome(plan).applied.length === 0 && !authorityTransition && !localOperations)) return 'noop';\n return 'applied';\n}\n\nfunction recoveryOutcomeStatus(status: TransactionResult['status']): UpdateStatus {\n if (status === 'conflict') return 'conflict';\n if (status === 'attention') return 'attention';\n if (status === 'none') return 'invalid';\n if (status === 'failed') return 'failed';\n return 'applied';\n}\n\n/**\n * Plan and apply one already-selected Joycraft bundle. This function never\n * resolves `latest` and never performs a registry request: the launcher owns\n * exact release selection, while this engine consumes the executing bundle.\n */\nexport async function update(dir: string, options: UpdateOptions = {}): Promise<UpdateOutcome> {\n const root = resolve(dir);\n const bundle = executingBundle(options);\n if (!/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(bundle.version)) {\n return outcome('invalid', { diagnostics: [`Invalid executing bundle version '${bundle.version}'.`] });\n }\n // Automatic mode is a narrow agent boundary. Reject explicit setup,\n // recovery, and repair choices before those branches can perform work.\n if (options.automatic && (\n options.recovery !== undefined\n || options.legacyInit === true\n || options.force === true\n || (options.replaceCustomized?.length ?? 0) > 0\n || (options.repair?.length ?? 0) > 0\n || options.executionProfile !== undefined\n || options.disableAutoMemory !== undefined\n || options.gitignore !== undefined\n || options.harnesses !== undefined\n )) {\n return outcome('invalid', { diagnostics: ['Automatic updates cannot include recovery, setup, repair, replacement, migration, or profile options.'] });\n }\n if (options.preview && options.recovery !== undefined) {\n return outcome('invalid', { diagnostics: ['A preview cannot run a recovery or rollback operation.'] });\n }\n if (options.force && !options.legacyInit) {\n return outcome('invalid', { diagnostics: ['--force is supported only by the init alias.'] });\n }\n for (const requestedPath of [...(options.replaceCustomized ?? []), ...(options.repair ?? [])]) {\n try {\n normalizeManifestPath(requestedPath);\n } catch (error) {\n return outcome('invalid', { diagnostics: [error instanceof Error ? error.message : String(error)] });\n }\n }\n const interactiveSelection = await resolveInteractiveInitOptions(root, options);\n options = interactiveSelection.options;\n if (interactiveSelection.emptySelection) {\n return outcome('noop', {\n targetVersion: bundle.version,\n harnesses: [],\n diagnostics: [\n 'No harness selected — Joycraft will not install any skills.',\n `Please run init again and select at least one harness (${HARNESSES.join(', ')}).`,\n ],\n registry: 'unknown',\n });\n }\n const requestedProfile = options.gitignore;\n const authority = profileFromAuthorities(root, requestedProfile);\n if (authority.diagnostic) {\n const invalidProfile = options.gitignore !== undefined && parseGitignoreProfile(options.gitignore) === null;\n return outcome(invalidProfile ? 'invalid' : 'attention', { diagnostics: [authority.diagnostic], profile: authority.profile });\n }\n if (options.harnesses !== undefined && parseSelection(options.harnesses) === null) {\n return outcome('invalid', { profile: authority.profile, diagnostics: ['Invalid harness selection. Choose from claude, codex, pi, copilot, or omp.'] });\n }\n\n if (options.recovery === 'recover') {\n const transaction = recoverInterruptedUpdate(root, { profile: authority.profile });\n const status = recoveryOutcomeStatus(transaction.status);\n return outcome(status, { profile: authority.profile, transaction, diagnostics: transaction.diagnostics, conflicts: transaction.conflicts });\n }\n if (options.recovery === 'rollback') {\n const transaction = rollbackLastSuccessfulUpdate(root, { profile: authority.profile });\n const status = recoveryOutcomeStatus(transaction.status);\n return outcome(status, { profile: authority.profile, transaction, diagnostics: transaction.diagnostics, conflicts: transaction.conflicts });\n }\n\n const existingManifest = authority.manifestInfo.manifest ?? authority.sourceManifestInfo?.manifest;\n const legacyProject = legacyStateExists(root) || hasRecognizedHarness(root);\n let harnesses = chosenHarnesses(root, options, existingManifest);\n if (harnesses === null) {\n if (options.legacyInit && !interactive(options)) {\n harnesses = [...HARNESSES];\n } else {\n return outcome('invalid', {\n profile: authority.profile,\n diagnostics: ['Fresh unattended update requires explicit harness selection via --harnesses.'],\n });\n }\n }\n if (harnesses.length === 0) return outcome('invalid', { profile: authority.profile, diagnostics: ['Select at least one harness.'] });\n if (options.legacyInit && options.nonInteractive === true && options.harnesses === undefined) {\n // Compatibility notice is deliberately emitted by the CLI only when human output is requested.\n }\n\n const baseEntries = bundle.inventory ? [...bundle.inventory] : getBundleInventory(harnesses);\n let manifest: InstallationManifest;\n let localSettings: LocalInstallationSettings | undefined;\n if (existingManifest) {\n manifest = { ...existingManifest, harnesses: [...harnesses], profile: authority.profile };\n } else if (legacyProject) {\n const adopted = localSettingsFromAdoption(root, baseEntries, bundle, authority.profile);\n manifest = { ...adopted.manifest, harnesses: [...harnesses], profile: authority.profile };\n localSettings = adopted.localSettings;\n } else {\n manifest = {\n schemaVersion: 1,\n targetVersion: bundle.version,\n bundleIntegrity: bundle.integrity ?? '',\n harnesses: [...harnesses],\n profile: authority.profile,\n files: {},\n };\n }\n\n const stack = await detectStack(root);\n const canonicalInventory = !bundle.inventory\n || (baseEntries.some((entry) => entry.path === 'CLAUDE.md' && entry.kind === 'create-once')\n && baseEntries.some((entry) => entry.path.startsWith('docs/templates/')));\n const materialized = materializeFreshInstallInventory({\n root,\n entries: baseEntries,\n manifest,\n harnesses,\n profile: authority.profile,\n stack,\n executionProfile: options.executionProfile ?? defaultExecutionProfile(harnesses),\n disableAutoMemory: options.disableAutoMemory,\n freshInstall: !existingManifest && !legacyProject && canonicalInventory,\n // The init alias is the explicit setup boundary. It may merge the\n // allowlisted Claude settings fragments on an established installation;\n // ordinary update/upgrade must leave that user configuration alone.\n configureClaude: options.legacyInit === true,\n force: options.legacyInit === true && options.force === true,\n });\n const entries = materialized.entries;\n const setupPatches = materialized.setup.patchOperations;\n let profileActions: PlannedUpdateAction[];\n try {\n for (const directory of materialized.setup.directories) resolveUpdatePath(root, directory);\n profileActions = profileBookkeepingActions(root, authority.profile);\n } catch (error) {\n return outcome('attention', {\n targetVersion: bundle.version,\n profile: authority.profile,\n harnesses,\n diagnostics: [`Profile bookkeeping path needs attention: ${error instanceof Error ? error.message : String(error)}`],\n registry: 'unknown',\n });\n }\n const paths = new Set<string>([\n ...entries.map((entry) => entry.path),\n ...Object.keys(manifest.files),\n ]);\n const snapshot = snapshotFor(root, paths);\n const replaceCustomized = [...(options.replaceCustomized ?? [])];\n const forceCustomized: string[] = [];\n if (options.legacyInit && options.force) {\n // Init --force is an explicit replacement request for paths declared by\n // the executing inventory. It never discovers or overwrites arbitrary\n // project files outside that inventory.\n for (const entry of entries) {\n if (entry.content !== undefined && (entry.kind === 'vendor' || entry.kind === 'create-once')) {\n replaceCustomized.push(entry.path);\n forceCustomized.push(entry.path);\n }\n }\n }\n const plan = createUpdatePlan({\n snapshot,\n manifest,\n inventory: entries,\n options: {\n targetVersion: bundle.version,\n bundleIntegrity: bundle.integrity ?? '',\n safeUnattended: options.yes === true || options.nonInteractive === true || process.stdin.isTTY !== true,\n replaceCustomized: [...new Set(replaceCustomized)],\n forceCustomized: [...new Set(forceCustomized)],\n repair: options.repair,\n baseManifestDigest: existingManifest ? undefined : null,\n },\n });\n plan.diagnostics.push(...materialized.diagnostics.map((diagnostic) => (\n /settings\\.json is malformed/i.test(diagnostic) && !/fix the json/i.test(diagnostic)\n ? `${diagnostic} Fix the JSON before retrying.`\n : diagnostic\n )));\n for (const operation of setupPatches) plan.actions.push(setupPatchAction(operation));\n plan.actions.push(...profileActions);\n // The authority digest must describe the bytes read from disk. The planner's\n // manifest is intentionally cloned with the requested harness/profile before\n // planning, so its synthetic digest cannot be used for transaction authority.\n plan.baseManifestDigest = existingManifest ? manifestDigest(existingManifest) : null;\n const selected = pathsForOutcome(plan);\n // Baselines can intentionally lag after a preserved local-only edit. Record\n // actual unresolved vendor changes so discovery does not mistake that for a conflict.\n plan.nextManifest.pendingConflicts = selected.conflicts;\n const authorityTransition: AuthorityTransition | undefined = authority.sourceProfile && existingManifest\n ? {\n oldAuthority: {\n profile: authority.sourceProfile,\n digest: manifestDigest(existingManifest),\n ...(authority.sourceManifestInfo?.raw !== undefined ? { raw: authority.sourceManifestInfo.raw } : {}),\n },\n newAuthority: { profile: authority.profile, digest: null },\n }\n : undefined;\n const localOperations = legacyMigrationOperations(root, localSettings);\n if (options.automatic) {\n const eligibility = evaluateAutoSafeEligibility({\n policy: readUpdatePolicy(root),\n candidate: options.verifiedArtifact,\n executingVersion: bundle.version,\n executingIntegrity: bundle.integrity || undefined,\n executingDescriptor: bundle.descriptor,\n manifestSchema: manifest.schemaVersion,\n plan,\n existingManifest,\n replaceCustomized,\n repair: options.repair,\n migration: localOperations.length > 0,\n legacyBridge: !existingManifest && legacyProject,\n setupChanges: setupPatches.length > 0,\n // Profile bookkeeping is project configuration. An idempotent profile\n // has no action; any append belongs to an explicit reviewed update.\n profileChanges: profileActions.some((action) => action.selected),\n localOperations: localOperations.length > 0,\n authorityTransition: authorityTransition !== undefined,\n });\n if (!eligibility.eligible) {\n return outcome(selected.conflicts.length > 0 ? 'conflict' : 'invalid', {\n targetVersion: bundle.version,\n profile: authority.profile,\n harnesses,\n preserved: selected.preserved,\n conflicts: selected.conflicts,\n diagnostics: [...plan.diagnostics, ...eligibility.diagnostics],\n plan,\n localSettings,\n registry: 'unknown',\n });\n }\n // Verification supplies the outer package digest; a package cannot embed\n // its own tarball digest without introducing a circular hash.\n plan.nextManifest.bundleIntegrity = options.verifiedArtifact!.release.integrity;\n }\n if (options.preview) {\n const previewStatus: UpdateStatus = selected.conflicts.length > 0\n ? 'conflict'\n : selected.preserved.length > 0 && selected.applied.length === 0\n ? 'preserved'\n : selected.applied.length > 0 ? 'applied' : 'noop';\n return outcome(previewStatus, {\n targetVersion: bundle.version,\n profile: authority.profile,\n harnesses,\n applied: [],\n preserved: selected.preserved,\n conflicts: selected.conflicts,\n diagnostics: plan.diagnostics,\n plan,\n localSettings,\n registry: 'unknown',\n });\n }\n let transaction: TransactionResult;\n try {\n transaction = applyUpdatePlan(root, plan, {\n profile: authority.profile,\n ...(authorityTransition ? { authorityTransition } : {}),\n ...(localOperations.length ? { localOperations } : {}),\n });\n } catch (error) {\n return outcome('failed', {\n targetVersion: bundle.version,\n profile: authority.profile,\n harnesses,\n applied: [],\n preserved: selected.preserved,\n conflicts: selected.conflicts,\n diagnostics: [error instanceof Error ? error.message : String(error)],\n plan,\n localSettings,\n registry: 'unknown',\n });\n }\n const status = transactionStatus(plan, transaction, authorityTransition !== undefined, localOperations.length > 0);\n const actualApplied = transaction.status === 'applied' ? selected.applied : [];\n if (transaction.status === 'applied' || transaction.status === 'noop') {\n try {\n for (const directory of materialized.setup.directories) {\n resolveUpdatePath(root, directory);\n mkdirSync(join(root, ...directory.split('/')), { recursive: true });\n }\n } catch (error) {\n return outcome('attention', {\n targetVersion: bundle.version,\n profile: authority.profile,\n harnesses,\n applied: actualApplied,\n preserved: selected.preserved,\n conflicts: selected.conflicts,\n diagnostics: [`Update applied but profile bookkeeping needs attention: ${String(error)}`],\n transaction,\n plan,\n localSettings,\n registry: 'unknown',\n });\n }\n }\n const diagnostics = [...plan.diagnostics, ...transaction.diagnostics];\n if (transaction.status === 'applied' && authority.profile === 'shared') {\n const manifestWarning = sharedManifestIgnoreWarning(root);\n if (manifestWarning) diagnostics.push(manifestWarning);\n diagnostics.push(...selectedHarnessIgnoreWarning(root, harnesses));\n }\n return outcome(status, {\n targetVersion: bundle.version,\n installedVersion: transaction.status === 'applied' || transaction.status === 'noop'\n ? plan.nextManifest.targetVersion\n : existingManifest?.targetVersion,\n profile: authority.profile,\n harnesses,\n applied: actualApplied,\n preserved: selected.preserved,\n conflicts: [...new Set([...selected.conflicts, ...transaction.conflicts])],\n diagnostics,\n transaction,\n plan,\n localSettings,\n existingSkills: materialized.setup.existingSkills,\n registry: 'unknown',\n });\n}\n\nexport function formatUpdateOutcome(result: UpdateOutcome, json = false): string {\n if (json) {\n return JSON.stringify({\n status: result.status,\n exitCode: result.exitCode,\n targetVersion: result.targetVersion,\n installedVersion: result.installedVersion,\n profile: result.profile,\n harnesses: result.harnesses,\n applied: result.applied,\n preserved: result.preserved,\n conflicts: result.conflicts,\n diagnostics: result.diagnostics,\n registry: result.registry,\n existingSkills: result.existingSkills,\n transaction: result.transaction,\n });\n }\n const lines = [`Joycraft update: ${result.status}.`];\n if (result.targetVersion) lines.push(` Target: ${result.targetVersion}`);\n if (result.applied.length) lines.push(` Applied: ${result.applied.length}`);\n if (result.preserved.length) lines.push(` Preserved customizations: ${result.preserved.join(', ')}`);\n if (result.conflicts.length) lines.push(` Pending conflicts: ${result.conflicts.join(', ')}`);\n for (const diagnostic of result.diagnostics) lines.push(` ⚠ ${diagnostic}`);\n return lines.join('\\n');\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, 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#\n# Claude Code passes no arguments: the hook payload arrives as JSON on stdin\n# ({\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"...\"},...}). The reason for a\n# block goes to stderr, which is what the model sees on exit 2.\n\nINPUT=$(cat)\n\nif command -v jq >/dev/null 2>&1; then\n TOOL_NAME=$(printf '%s' \"$INPUT\" | jq -r '.tool_name // empty' 2>/dev/null)\n COMMAND=$(printf '%s' \"$INPUT\" | jq -r '.tool_input.command // .command // empty' 2>/dev/null)\nelse\n # Fallback without jq: tolerate spaces around the colon and escaped quotes.\n TOOL_NAME=$(printf '%s' \"$INPUT\" | grep -o '\"tool_name\"[[:space:]]*:[[:space:]]*\"[^\"]*\"' | head -1 | sed 's/^\"tool_name\"[[:space:]]*:[[:space:]]*\"//;s/\"$//')\n COMMAND=$(printf '%s' \"$INPUT\" | grep -o '\"command\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]\\\\|\\\\\\\\.\\\\)*\"' | head -1 | sed 's/^\"command\"[[:space:]]*:[[:space:]]*\"//;s/\"$//;s/\\\\\\\\\"/\"/g;s/\\\\\\\\\\\\\\\\/\\\\\\\\/g')\nfi\n\n# Only check Bash commands (the settings matcher already limits this hook to\n# Bash; a payload that names another tool is passed through untouched).\nif [ -n \"$TOOL_NAME\" ] && [ \"$TOOL_NAME\" != \"Bash\" ]; then\n exit 0\nfi\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 printf '%s' \"$COMMAND\" | grep -qEi \"$pattern\"; then\n echo \"Blocked by Joycraft Safeguard: command matches deny pattern '$pattern'\" >&2\n echo \"Edit .claude/hooks/joycraft/deny-patterns.txt to modify blocked patterns.\" >&2\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","/**\n * Source for the Claude SessionStart adapter installed beside the existing\n * Joycraft hook path. It delegates all policy, cache, and registry work to the\n * shared checker and keeps hook failures non-blocking.\n */\nexport function generateClaudeSessionStartAdapter(): string {\n return `// Joycraft update discovery adapter — runs on Claude Code session start\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { appendFileSync } from 'node:fs';\n\nconst root = join(dirname(fileURLToPath(import.meta.url)), '..', '..');\n\nasync function readHookEvent() {\n if (process.stdin.isTTY) return {};\n return new Promise((resolve) => {\n let raw = '';\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n process.stdin.off('data', onData);\n process.stdin.off('end', finish);\n process.stdin.off('error', finish);\n process.stdin.pause();\n try {\n const parsed = JSON.parse(raw);\n resolve(parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {});\n } catch {\n resolve({});\n }\n };\n const onData = (chunk) => {\n raw += chunk;\n // Claude sends one compact JSON event. Parsing immediately avoids\n // waiting on a pipe that a host may keep open for the hook lifetime.\n try { JSON.parse(raw); finish(); } catch { /* wait for more bytes */ }\n };\n const timer = setTimeout(finish, 250);\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', onData);\n process.stdin.on('end', finish);\n process.stdin.on('error', finish);\n process.stdin.resume();\n });\n}\n\ntry {\n const event = await readHookEvent();\n const eventSession = typeof event.session_id === 'string' ? event.session_id : undefined;\n const session = eventSession\n ?? process.env.JOYCRAFT_SESSION_ID\n ?? \\`parent-\\${process.ppid}\\`;\n // Claude documents this append-only environment handoff for SessionStart:\n // https://code.claude.com/docs/en/hooks#persist-environment-variables\n if (process.env.CLAUDE_ENV_FILE) {\n const assignment = \"export JOYCRAFT_SESSION_ID='\" + session.replaceAll(\"'\", ${JSON.stringify(\"'\\\"'\\\"'\")}) + \"'\\\\n\";\n try { appendFileSync(process.env.CLAUDE_ENV_FILE, assignment, { mode: 0o600 }); } catch { /* continue without environment persistence */ }\n }\n const checker = await import(pathToFileURL(join(root, 'docs', '.joycraft', 'check.mjs')).href);\n const result = await checker.checkForUpdate(root, { sessionId: session });\n if (result?.display && result.availableVersion) {\n console.log(\\`Joycraft \\${result.availableVersion} available (you have \\${result.installedVersion ?? 'unknown'}). Finish the active skill, then run the update and restart or reinvoke the skill.\\`);\n checker.acknowledgeUpdate(root, { release: result.availableVersion, session });\n }\n} catch {\n // Discovery must never block Claude's requested work.\n}\n`;\n}\n","import type { Harness } from './harness.js';\n\n/**\n * The Fable 5.1 model profile: one reference doc (D1), installed only for the\n * harnesses that run Claude models (D6), and pointed at by one Context Map row\n * in the project's memory file.\n *\n * This module is the single home of the eligible-harness list. The template\n * gate in `bundle-inventory.ts` and the memory-file row gate both read it, so a\n * project never points at a doc it did not receive.\n */\n\n/** `TEMPLATES` key (path relative to `src/templates/`). */\nexport const MODEL_PROFILE_TEMPLATE_KEY = 'reference/model-profile-claude-fable-5-1.md';\n\n/** Installed project-relative path. */\nexport const MODEL_PROFILE_PATH = `docs/templates/${MODEL_PROFILE_TEMPLATE_KEY}`;\n\n/** D6: keyed to the model, not the harness. Pi and omp run Claude models; Codex and Copilot do not. */\nexport const MODEL_PROFILE_HARNESSES: readonly Harness[] = Object.freeze(['claude', 'pi', 'omp'] as const);\n\n/** The one Context Map row. A pointer only; no profile text is copied. */\nexport const MODEL_PROFILE_CONTEXT_MAP_ROW =\n `| \\`${MODEL_PROFILE_PATH}\\` | Working with Claude Fable 5.1 — finishing whole tasks, scope, progress updates, prose |`;\n\n/** True when the selection includes a harness that receives the profile doc. */\nexport function selectsModelProfile(harnesses: readonly Harness[]): boolean {\n return harnesses.some((harness) => MODEL_PROFILE_HARNESSES.includes(harness));\n}\n","import {\n CODEX_SKILLS,\n COPILOT_SKILLS,\n OMP_SKILLS,\n PI_AGENTS,\n PI_EXTENSIONS,\n PI_SCRIPTS,\n PI_SKILLS,\n SKILLS,\n TEMPLATES,\n CHECKER_SOURCE,\n} from './bundled-files.js';\nimport { HARNESSES, sanitizeHarnesses, type Harness } from './harness.js';\nimport { generateDenyPatternsFile, generateHookScript } from './safeguard.js';\nimport { generateClaudeSessionStartAdapter } from './claude-session-start.js';\nimport { MODEL_PROFILE_HARNESSES, MODEL_PROFILE_TEMPLATE_KEY } from './model-profile.js';\n\nexport type BundleEntryKind = 'vendor' | 'create-once' | 'config-patch';\nexport type BundleEntryHarness = Harness | 'shared';\n\n/**\n * One declared artifact in the Joycraft bundle.\n *\n * `active`/`installable` deliberately distinguish a known future artifact\n * from content that this package can safely install today. Inactive entries\n * carry ownership and path information for the planner without shipping a\n * placeholder implementation.\n */\nexport interface BundleInventoryEntry {\n path: string;\n harness: BundleEntryHarness;\n kind: BundleEntryKind;\n ownership: 'managed';\n active: boolean;\n installable: boolean;\n content?: string;\n executable?: boolean;\n mode?: number;\n ownedKey?: string;\n ownedRegion?: string;\n}\n\nconst vendor = (\n path: string,\n harness: BundleEntryHarness,\n content: string,\n options: Pick<BundleInventoryEntry, 'executable' | 'mode'> = {},\n): BundleInventoryEntry => ({\n path,\n harness,\n kind: 'vendor',\n ownership: 'managed',\n active: true,\n installable: true,\n content,\n ...options,\n});\n\nconst createOnce = (path: string): BundleInventoryEntry => ({\n path,\n harness: 'shared',\n kind: 'create-once',\n ownership: 'managed',\n active: true,\n installable: false,\n});\n\nconst patch = (\n path: string,\n harness: Harness,\n ownedKey?: string,\n ownedRegion?: string,\n): BundleInventoryEntry => ({\n path,\n harness,\n kind: 'config-patch',\n ownership: 'managed',\n active: true,\n installable: false,\n ...(ownedKey ? { ownedKey } : {}),\n ...(ownedRegion ? { ownedRegion } : {}),\n});\n\nconst deferred = (path: string, harness: BundleEntryHarness, ownedRegion?: string): BundleInventoryEntry => ({\n path,\n harness,\n kind: 'vendor',\n ownership: 'managed',\n active: false,\n installable: false,\n ...(ownedRegion ? { ownedRegion } : {}),\n});\n\n/**\n * Per-template harness gates, keyed by `TEMPLATES` key (the path relative to\n * `src/templates/`). A listed template installs only when the selection\n * includes at least one of its harnesses. Keys absent from this table stay\n * `'shared'` and install for every selection. A key with no matching template\n * is inert: this table filters the bundled record and never supplies paths.\n */\nexport const TEMPLATE_HARNESS_GATES: Readonly<Record<string, readonly Harness[]>> = {\n // D6: keyed to the model, not the harness. The list lives in model-profile.ts\n // so the memory-file pointer row is gated on exactly the same harnesses.\n [MODEL_PROFILE_TEMPLATE_KEY]: MODEL_PROFILE_HARNESSES,\n};\n\n/**\n * Map bundled templates to `docs/templates/` vendor entries for a selection.\n * An ungated template yields one `'shared'` entry. A gated template yields one\n * entry owned by the first eligible selected harness in canonical order, or\n * nothing when no eligible harness is selected.\n */\nexport function templateEntries(\n templates: Readonly<Record<string, string>>,\n selected: readonly Harness[],\n gates: Readonly<Record<string, readonly Harness[]>> = TEMPLATE_HARNESS_GATES,\n): BundleInventoryEntry[] {\n return Object.entries(templates).flatMap(([path, content]) => {\n const gate = Object.prototype.hasOwnProperty.call(gates, path) ? gates[path] : undefined;\n if (!gate) return [vendor(`docs/templates/${path}`, 'shared', content)];\n const owner = HARNESSES.find((harness) => gate.includes(harness) && selected.includes(harness));\n return owner ? [vendor(`docs/templates/${path}`, owner, content)] : [];\n });\n}\n\nfunction mapVendorFiles(\n harness: Harness,\n root: string,\n files: Record<string, string>,\n options: Pick<BundleInventoryEntry, 'executable' | 'mode'> | undefined = undefined,\n): BundleInventoryEntry[] {\n return Object.entries(files).map(([name, content]) => {\n const relative = name.endsWith('.md') && root.endsWith('/skills')\n ? `${name.slice(0, -3)}/SKILL.md`\n : name;\n return vendor(`${root}/${relative}`, harness, content, options ?? (root.endsWith('/scripts/joycraft') && !name.endsWith('README.md')\n ? { executable: true, mode: 0o755 }\n : root.endsWith('/scripts/joycraft')\n ? { executable: false }\n : {}));\n });\n}\n\n/**\n * Return the canonical managed bundle inventory for the selected harnesses.\n * Unknown array members are sanitized using the same canonical harness list as\n * init and persisted installation state. A non-array selection is treated as\n * no recorded selection and therefore includes every harness for compatibility.\n */\nexport function getBundleInventory(selection: readonly Harness[] | unknown = HARNESSES): BundleInventoryEntry[] {\n const selected = sanitizeHarnesses(selection) ?? [...HARNESSES];\n const wants = (harness: Harness): boolean => selected.includes(harness);\n const entries: BundleInventoryEntry[] = [\n ...templateEntries(TEMPLATES, selected),\n createOnce('CLAUDE.md'),\n createOnce('AGENTS.md'),\n vendor('docs/.joycraft/check.mjs', 'shared', CHECKER_SOURCE, { executable: true, mode: 0o755 }),\n ];\n\n if (wants('claude')) {\n entries.push(...mapVendorFiles('claude', '.claude/skills', SKILLS));\n entries.push(\n vendor('.claude/hooks/joycraft/block-dangerous.sh', 'claude', generateHookScript(), { executable: true, mode: 0o755 }),\n vendor('.claude/hooks/joycraft/deny-patterns.txt', 'claude', generateDenyPatternsFile(), { executable: false }),\n vendor('.claude/hooks/joycraft-version-check.mjs', 'claude', generateClaudeSessionStartAdapter(), { executable: true, mode: 0o755 }),\n patch('.claude/settings.json', 'claude', undefined, 'hooks.SessionStart[command=node .claude/hooks/joycraft-version-check.mjs]'),\n patch('.claude/settings.json', 'claude', undefined, 'hooks.PreToolUse[command=.claude/hooks/joycraft/block-dangerous.sh]'),\n patch('.claude/settings.json', 'claude', 'env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS'),\n patch('.claude/settings.json', 'claude', undefined, 'permissions.allow[joycraft-generated]'),\n patch('.claude/settings.json', 'claude', undefined, 'permissions.deny[joycraft-generated]'),\n patch('.claude/settings.json', 'claude', 'autoMemoryEnabled'),\n );\n }\n if (wants('codex')) entries.push(...mapVendorFiles('codex', '.agents/skills', CODEX_SKILLS));\n if (wants('pi')) {\n entries.push(...mapVendorFiles('pi', '.pi/skills', PI_SKILLS));\n entries.push(...mapVendorFiles('pi', '.pi/scripts/joycraft', PI_SCRIPTS));\n entries.push(...mapVendorFiles('pi', '.pi/extensions', PI_EXTENSIONS));\n entries.push(...mapVendorFiles('pi', '.pi/agents', PI_AGENTS));\n }\n if (wants('copilot')) entries.push(...mapVendorFiles('copilot', '.github/skills', COPILOT_SKILLS));\n if (wants('omp')) entries.push(...mapVendorFiles('omp', '.omp/skills', OMP_SKILLS));\n\n return entries;\n}\n","/** The one fragment of a file that an update is allowed to replace. */\nexport interface PatchSelector {\n /** A dotted path through JSON objects, such as `env.generated`. */\n ownedKey?: string;\n /** An exact marker identifier, such as `joycraft:managed`. */\n ownedRegion?: string;\n}\n\nexport type OwnedContentResult =\n | { status: 'present'; content: string }\n | { status: 'missing' }\n | { status: 'invalid'; reason: string };\n\nexport type OwnedContentApplication =\n | { ok: true; content: string }\n | { ok: false; reason: string };\n\ntype SelectorKind =\n | { kind: 'key'; value: string }\n | { kind: 'region'; value: string }\n | { kind: 'invalid'; reason: string };\n\nconst FORBIDDEN_JSON_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\nconst REGION_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;\n\nfunction selectorKind(selector: PatchSelector | null | undefined): SelectorKind {\n if (!selector || typeof selector !== 'object') {\n return { kind: 'invalid', reason: 'Patch selector must be an object' };\n }\n\n const hasKey = selector.ownedKey !== undefined;\n const hasRegion = selector.ownedRegion !== undefined;\n if (hasKey === hasRegion) {\n return { kind: 'invalid', reason: 'Patch selector must contain exactly one ownedKey or ownedRegion' };\n }\n\n if (hasKey) {\n if (typeof selector.ownedKey !== 'string') {\n return { kind: 'invalid', reason: 'ownedKey must be a string' };\n }\n const parts = selector.ownedKey.split('.');\n if (parts.length === 0 || parts.some((part) => part.length === 0 || FORBIDDEN_JSON_KEYS.has(part))) {\n return { kind: 'invalid', reason: 'ownedKey contains an empty or prototype key segment' };\n }\n return { kind: 'key', value: selector.ownedKey };\n }\n\n if (typeof selector.ownedRegion !== 'string' || !REGION_IDENTIFIER.test(selector.ownedRegion)) {\n return { kind: 'invalid', reason: 'ownedRegion is not a valid marker identifier' };\n }\n return { kind: 'region', value: selector.ownedRegion };\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(content: string): { value: Record<string, unknown> } | { reason: string } {\n let value: unknown;\n try {\n value = JSON.parse(content) as unknown;\n } catch {\n return { reason: 'Current content is not valid JSON' };\n }\n if (!isJsonObject(value)) {\n return { reason: 'JSON patch paths require an object at the root' };\n }\n return { value };\n}\n\nfunction own(value: Record<string, unknown>, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, key);\n}\n\nfunction readJsonValue(root: Record<string, unknown>, path: string): OwnedContentResult {\n const parts = path.split('.');\n let parent: unknown = root;\n for (let index = 0; index < parts.length - 1; index += 1) {\n if (!isJsonObject(parent)) {\n return { status: 'invalid', reason: `JSON path parent is not an object at ${parts[index]}` };\n }\n const part = parts[index];\n if (!own(parent, part)) return { status: 'missing' };\n parent = parent[part];\n }\n\n if (!isJsonObject(parent)) {\n return { status: 'invalid', reason: 'JSON path parent is not an object' };\n }\n const finalPart = parts[parts.length - 1];\n if (!own(parent, finalPart)) return { status: 'missing' };\n const serialized = JSON.stringify(parent[finalPart]);\n // A parsed JSON value cannot be undefined, but retain a defensive guard if\n // this helper is ever reused with a non-JSON object.\n return serialized === undefined\n ? { status: 'invalid', reason: 'Owned JSON value cannot be serialized' }\n : { status: 'present', content: serialized };\n}\n\nfunction newlineOf(content: string): '\\n' | '\\r\\n' {\n return content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n}\n\nfunction hasFinalNewline(content: string): boolean {\n return content.endsWith('\\n') || content.endsWith('\\r');\n}\n\nfunction normalizeNewlines(content: string, newline: '\\n' | '\\r\\n'): string {\n return content.replace(/\\r\\n?|\\n/g, newline);\n}\n\nfunction jsonIndent(content: string): string | undefined {\n // The first indented JSON line establishes the existing document style.\n // Passing a string to JSON.stringify preserves tabs as well as spaces.\n const match = content.match(/(?:^|\\r?\\n)([ \\t]+)(?=[\"}\\]])/);\n return match?.[1];\n}\n\nfunction serializePatchedJson(\n value: Record<string, unknown>,\n current: string,\n): string {\n const indentation = jsonIndent(current);\n const serialized = JSON.stringify(value, null, indentation);\n const newline = newlineOf(current);\n const withNewlines = normalizeNewlines(serialized, newline);\n return hasFinalNewline(current) ? `${withNewlines}${newline}` : withNewlines;\n}\n\nfunction parseTarget(target: string): { value: unknown } | { reason: string } {\n try {\n return { value: JSON.parse(target) as unknown };\n } catch {\n return { reason: 'Target content is not valid JSON' };\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\ninterface MarkerBounds {\n openEnd: number;\n closeStart: number;\n body: string;\n newline: '\\n' | '\\r\\n';\n hasLeadingBoundary: boolean;\n hasTrailingBoundary: boolean;\n}\n\nfunction markerBounds(current: string, identifier: string): MarkerBounds | { status: 'missing' } | { status: 'invalid'; reason: string } {\n const opening = `<!-- ${identifier} -->`;\n const closing = `<!-- /${identifier} -->`;\n const openCount = countOccurrences(current, opening);\n const closeCount = countOccurrences(current, closing);\n const mentionPattern = new RegExp(`<!--\\\\s*/?\\\\s*${escapeRegExp(identifier)}\\\\s*-->`, 'g');\n const mentions = current.match(mentionPattern) ?? [];\n\n if (mentions.length === 0) return { status: 'missing' };\n if (openCount !== 1 || closeCount !== 1 || mentions.length !== 2) {\n return { status: 'invalid', reason: 'Owned region markers are duplicated or malformed' };\n }\n\n const openEnd = current.indexOf(opening) + opening.length;\n const closeStart = current.indexOf(closing);\n if (closeStart <= openEnd) {\n return { status: 'invalid', reason: 'Owned region markers are in the wrong order' };\n }\n\n const newline = newlineOf(current);\n const body = current.slice(openEnd, closeStart);\n const hasLeadingBoundary = body.startsWith(newline);\n const withoutLeading = hasLeadingBoundary ? body.slice(newline.length) : body;\n const hasTrailingBoundary = withoutLeading.endsWith(newline);\n return {\n openEnd,\n closeStart,\n body: withoutLeading,\n newline,\n hasLeadingBoundary,\n hasTrailingBoundary,\n };\n}\n\nfunction countOccurrences(content: string, needle: string): number {\n let count = 0;\n let offset = 0;\n while (true) {\n const found = content.indexOf(needle, offset);\n if (found < 0) return count;\n count += 1;\n offset = found + needle.length;\n }\n}\n\nexport function readOwnedContent(current: string, selector: PatchSelector): OwnedContentResult {\n const selected = selectorKind(selector);\n if (selected.kind === 'invalid') return { status: 'invalid', reason: selected.reason };\n\n if (selected.kind === 'key') {\n const parsed = parseJsonObject(current);\n if ('reason' in parsed) return { status: 'invalid', reason: parsed.reason };\n return readJsonValue(parsed.value, selected.value);\n }\n\n const markers = markerBounds(current, selected.value);\n if ('status' in markers) {\n return markers.status === 'missing'\n ? { status: 'missing' }\n : { status: 'invalid', reason: markers.reason };\n }\n return { status: 'present', content: markers.body };\n}\n\nexport function applyOwnedContent(\n current: string | undefined,\n selector: PatchSelector,\n target: string,\n): OwnedContentApplication {\n const selected = selectorKind(selector);\n if (selected.kind === 'invalid') return { ok: false, reason: selected.reason };\n if (current === undefined) return { ok: false, reason: 'Current content is missing' };\n\n if (selected.kind === 'key') {\n const parsed = parseJsonObject(current);\n if ('reason' in parsed) return { ok: false, reason: parsed.reason };\n const parsedTarget = parseTarget(target);\n if ('reason' in parsedTarget) return { ok: false, reason: parsedTarget.reason };\n\n const parts = selected.value.split('.');\n let parent: unknown = parsed.value;\n for (let index = 0; index < parts.length - 1; index += 1) {\n if (!isJsonObject(parent)) {\n return { ok: false, reason: `JSON path parent is not an object at ${parts[index]}` };\n }\n const part = parts[index];\n if (!own(parent, part)) return { ok: false, reason: `JSON path does not exist: ${selected.value}` };\n parent = parent[part];\n }\n if (!isJsonObject(parent)) return { ok: false, reason: 'JSON path parent is not an object' };\n parent[parts[parts.length - 1]] = parsedTarget.value;\n return { ok: true, content: serializePatchedJson(parsed.value, current) };\n }\n\n const markers = markerBounds(current, selected.value);\n if ('status' in markers) {\n return {\n ok: false,\n reason: markers.status === 'missing' ? 'Owned region markers are missing' : markers.reason,\n };\n }\n\n const markerPattern = new RegExp(`<!--\\\\s*/?\\\\s*${escapeRegExp(selected.value)}\\\\s*-->`);\n if (markerPattern.test(target)) {\n return { ok: false, reason: 'Target content contains an owned region marker' };\n }\n\n let normalizedTarget = normalizeNewlines(target, markers.newline);\n if (markers.hasLeadingBoundary && normalizedTarget.startsWith(markers.newline)) {\n normalizedTarget = normalizedTarget.slice(markers.newline.length);\n }\n if (markers.hasTrailingBoundary && !normalizedTarget.endsWith(markers.newline)) {\n normalizedTarget += markers.newline;\n }\n const content = `${current.slice(0, markers.openEnd)}${markers.hasLeadingBoundary ? markers.newline : ''}${normalizedTarget}${current.slice(markers.closeStart)}`;\n return { ok: true, content };\n}\n","import {\n normalizedVendorHash,\n manifestDigest,\n rawFileHash,\n type InstallationManifest,\n type VendorCatalogueEntry,\n} from './install-manifest.js';\nimport type { BundleInventoryEntry } from './bundle-inventory.js';\nimport { applyOwnedContent, readOwnedContent } from './update-patches.js';\n\nexport type SnapshotContent = string | Buffer;\n\nexport interface SnapshotFile {\n content: SnapshotContent;\n mode?: number;\n}\n\nexport interface UpdateSnapshot {\n files: Readonly<Record<string, SnapshotFile | SnapshotContent>>;\n}\n\nexport interface UpdatePlanOptions {\n targetVersion?: string;\n bundleIntegrity?: string;\n /** Authority digest supplied by the orchestration boundary. `null` means no authority existed. */\n baseManifestDigest?: string | null;\n /** Safe unattended mode selects only actions that cannot overwrite user edits. */\n safeUnattended?: boolean;\n replaceCustomized?: readonly string[];\n /** Init --force may explicitly replace known create-once/vendor paths. */\n forceCustomized?: readonly string[];\n repair?: readonly string[];\n /** Optional trusted historical vendor hashes used for bridge adoption. */\n catalogue?: readonly VendorCatalogueEntry[];\n}\n\nexport type UpdateActionKind =\n | 'reconcile'\n | 'replace'\n | 'preserve'\n | 'conflict'\n | 'repair'\n | 'create'\n | 'adopt'\n | 'delete'\n | 'orphan';\n\nexport interface PlannedUpdateAction {\n path: string;\n kind: UpdateActionKind;\n selected: boolean;\n resolution?: 'replace' | 'repair' | 'preserve';\n reason: string;\n content?: SnapshotContent;\n preservedContent?: SnapshotContent;\n diff?: string;\n rawPrecondition?: string;\n rawTargetHash?: string;\n mode?: number;\n currentPresent: boolean;\n targetPresent: boolean;\n /** For config patches, identifies the fragments calculated in content. */\n patch?: { ownedKey?: string; ownedRegion?: string };\n /** A preserved known document that needs no user-facing action or status. */\n nonActionable?: boolean;\n}\n\nexport interface UpdatePlan {\n actions: PlannedUpdateAction[];\n /** Convenience view of all preserved current bytes, including conflicts. */\n preserved: Array<{ path: string; content: SnapshotContent; reason: string }>;\n conflicts: PlannedUpdateAction[];\n diagnostics: string[];\n nextManifest: InstallationManifest;\n /** Digest of the authority read during planning; null explicitly requires a missing authority. */\n baseManifestDigest?: string | null;\n}\n\ninterface TargetGroup {\n path: string;\n entries: BundleInventoryEntry[];\n invalidDefinition: boolean;\n}\n\nfunction bytes(value: SnapshotContent): SnapshotContent {\n return Buffer.isBuffer(value) ? Buffer.from(value) : value;\n}\n\nfunction text(value: SnapshotContent): string {\n return Buffer.isBuffer(value) ? value.toString('utf8') : value;\n}\n\nfunction contentOf(value: SnapshotFile | SnapshotContent): SnapshotContent {\n return typeof value === 'object' && value !== null && 'content' in value\n ? bytes((value as SnapshotFile).content)\n : bytes(value as SnapshotContent);\n}\n\nfunction cloneManifest(manifest: InstallationManifest): InstallationManifest {\n return {\n ...manifest,\n files: Object.fromEntries(Object.entries(manifest.files).map(([path, file]) => [path, { ...file }])),\n };\n}\n\nfunction normalized(value: SnapshotContent): string {\n return normalizedVendorHash(text(value));\n}\n\nfunction newlineStyle(value: string): '\\r\\n' | '\\n' {\n return value.includes('\\r\\n') ? '\\r\\n' : '\\n';\n}\n\nfunction preserveNewlines(target: SnapshotContent, current: SnapshotContent | undefined, executable: boolean | undefined): SnapshotContent {\n if (!current || executable || Buffer.isBuffer(target) || Buffer.isBuffer(current)) return bytes(target);\n const style = newlineStyle(text(current));\n if (style === '\\n') return target;\n return text(target).replace(/\\r\\n?/g, '\\n').replace(/\\n/g, '\\r\\n');\n}\n\nfunction diff(path: string, current: SnapshotContent, target: SnapshotContent): string {\n const oldLines = text(current).replace(/\\r\\n?/g, '\\n').split('\\n');\n const newLines = text(target).replace(/\\r\\n?/g, '\\n').split('\\n');\n const lines = [`--- ${path}`, `+++ ${path}`];\n const size = Math.max(oldLines.length, newLines.length);\n for (let i = 0; i < size; i += 1) {\n if (oldLines[i] === newLines[i]) lines.push(` ${oldLines[i] ?? ''}`);\n else {\n if (oldLines[i] !== undefined) lines.push(`-${oldLines[i]}`);\n if (newLines[i] !== undefined) lines.push(`+${newLines[i]}`);\n }\n }\n return lines.join('\\n');\n}\n\nfunction selected(options: UpdatePlanOptions, path: string, kind: UpdateActionKind): boolean {\n if (kind === 'replace' || kind === 'create' || kind === 'adopt' || kind === 'delete' || kind === 'reconcile') return true;\n if (kind === 'repair') return (options.repair ?? []).includes(path);\n return false;\n}\n\nfunction explicitReplacement(options: UpdatePlanOptions, path: string): boolean {\n return (options.replaceCustomized ?? []).includes(path);\n}\n\nfunction targetPayload(entry: BundleInventoryEntry): SnapshotContent | undefined {\n return entry.content;\n}\n\nfunction patchOutput(\n current: SnapshotContent,\n entries: readonly BundleInventoryEntry[],\n): { content?: SnapshotContent; fragment?: string; reason?: string } {\n const entry = entries[0];\n if (entry.content === undefined) return { reason: 'Config patch has no installable payload.' };\n const selector = { ...(entry.ownedKey ? { ownedKey: entry.ownedKey } : {}), ...(entry.ownedRegion ? { ownedRegion: entry.ownedRegion } : {}) };\n const result = applyOwnedContent(text(current), selector, text(entry.content));\n if (!result.ok) return { reason: result.reason };\n const fragment = readOwnedContent(result.content, selector);\n if (fragment.status !== 'present') return { reason: fragment.status === 'invalid' ? fragment.reason : 'Patched owned content is missing.' };\n return { content: result.content, fragment: fragment.content };\n}\n\nfunction trustedHash(path: string, options: UpdatePlanOptions): string | undefined {\n const catalogue = options.catalogue?.find((entry) => entry.path === path);\n return catalogue?.vendorHash;\n}\n\nfunction addFile(next: InstallationManifest, path: string, entry: BundleInventoryEntry, hash: string, version: string): void {\n next.files[path] = {\n ...(next.files[path] ?? {}),\n vendorVersion: version,\n vendorHash: hash,\n kind: entry.kind,\n ownership: 'verified',\n ...(entry.ownedKey ? { ownedKey: entry.ownedKey } : {}),\n ...(entry.ownedRegion ? { ownedRegion: entry.ownedRegion } : {}),\n };\n}\n\nfunction actionBase(path: string, kind: UpdateActionKind, reason: string, current: SnapshotContent | undefined, target: SnapshotContent | undefined, mode: number | undefined): PlannedUpdateAction {\n const currentPresent = current !== undefined;\n const targetPresent = target !== undefined;\n const result: PlannedUpdateAction = {\n path, kind, selected: false, reason, currentPresent, targetPresent,\n ...(current !== undefined ? { preservedContent: bytes(current) } : {}),\n ...(target !== undefined ? { rawTargetHash: rawFileHash(target) } : {}),\n ...(mode === undefined ? {} : { mode }),\n };\n if (current !== undefined) result.rawPrecondition = rawFileHash(current);\n return result;\n}\n\n/**\n * Compare an explicit snapshot, manifest, and bundle inventory without any I/O,\n * prompting, mutation, or network access. The returned actions are sufficient\n * for a later transaction to recheck raw preconditions and apply reviewed bytes.\n */\nexport function createUpdatePlan(input: {\n snapshot: UpdateSnapshot;\n manifest: InstallationManifest;\n inventory: readonly BundleInventoryEntry[];\n options?: UpdatePlanOptions;\n}): UpdatePlan {\n const options = input.options ?? {};\n const snapshotFiles = input.snapshot.files;\n const current = new Map<string, SnapshotContent>();\n for (const [path, value] of Object.entries(snapshotFiles)) current.set(path, contentOf(value));\n const nextManifest = cloneManifest(input.manifest);\n if (options.targetVersion !== undefined) nextManifest.targetVersion = options.targetVersion;\n if (options.bundleIntegrity !== undefined) nextManifest.bundleIntegrity = options.bundleIntegrity;\n const diagnostics: string[] = [];\n const actions: PlannedUpdateAction[] = [];\n const groups = new Map<string, TargetGroup>();\n const knownPaths = new Set<string>();\n\n for (const entry of input.inventory) {\n knownPaths.add(entry.path);\n // Create-once documents and inactive/non-installable declarations carry\n // ownership metadata only. They must never become a write target here.\n if ((entry.kind === 'create-once' && entry.content === undefined) || !entry.active || !entry.installable || (entry.kind === 'vendor' && entry.content === undefined)) continue;\n let group = groups.get(entry.path);\n if (!group) {\n group = { path: entry.path, entries: [], invalidDefinition: false };\n groups.set(entry.path, group);\n }\n if (group.entries.some((prior) => prior.kind !== entry.kind || prior.harness !== entry.harness)) group.invalidDefinition = true;\n group.entries.push(entry);\n }\n\n const add = (action: PlannedUpdateAction): void => {\n actions.push(action);\n if (action.kind === 'conflict' || action.kind === 'orphan') {\n if (action.preservedContent !== undefined) diagnostics.push(`${action.path}: ${action.reason}`);\n }\n };\n\n for (const group of groups.values()) {\n const manifestEntry = input.manifest.files[group.path];\n const currentContent = current.get(group.path);\n if (group.invalidDefinition) {\n const action = actionBase(group.path, 'conflict', 'Conflicting inventory definitions for one path.', currentContent, undefined, undefined);\n action.selected = false;\n add(action);\n continue;\n }\n const first = group.entries[0];\n let target: SnapshotContent | undefined;\n let targetFragment: SnapshotContent | undefined;\n let fragmentHash = false;\n if (first.kind === 'config-patch') {\n const patchDefinitions = group.entries.map((entry) => `${entry.ownedKey ?? ''}\\0${entry.ownedRegion ?? ''}`);\n for (let i = 0; i < group.entries.length; i += 1) {\n for (let j = i + 1; j < group.entries.length; j += 1) {\n if (patchDefinitions[i] === patchDefinitions[j]) {\n const left = targetPayload(group.entries[i]);\n const right = targetPayload(group.entries[j]);\n if ((left === undefined) !== (right === undefined) || (left !== undefined && right !== undefined && normalized(left) !== normalized(right))) {\n group.invalidDefinition = true;\n }\n }\n }\n }\n if (new Set(patchDefinitions).size > 1) {\n const action = actionBase(group.path, 'conflict', 'Multiple owned patch selectors share one path; refusing ambiguous composition.', currentContent, undefined, first.mode);\n add(action);\n continue;\n }\n if (group.invalidDefinition) {\n const action = actionBase(group.path, 'conflict', 'Conflicting inventory definitions for one path.', currentContent, undefined, undefined);\n add(action);\n continue;\n }\n if (currentContent === undefined) continue;\n const result = patchOutput(currentContent, group.entries);\n if (!result.content) {\n const action = actionBase(group.path, 'conflict', result.reason ?? 'Unable to calculate config patch.', currentContent, undefined, first.mode);\n action.selected = false;\n add(action);\n continue;\n }\n target = result.content;\n targetFragment = result.fragment;\n fragmentHash = true;\n } else {\n const payloads = group.entries.map((entry) => targetPayload(entry)).filter((value): value is SnapshotContent => value !== undefined);\n if (!payloads.length) continue;\n if (payloads.some((value) => normalized(value) !== normalized(payloads[0]))) {\n const action = actionBase(group.path, 'conflict', 'Duplicate inventory entries have conflicting payloads.', currentContent, undefined, first.mode);\n add(action);\n continue;\n }\n target = preserveNewlines(payloads[0], currentContent, first.executable);\n }\n const old = manifestEntry;\n const verified = old?.ownership === 'verified' && !!old.vendorHash;\n const currentHash = currentContent === undefined\n ? undefined\n : fragmentHash && targetFragment !== undefined\n ? (() => {\n const selector = { ...(first.ownedKey ? { ownedKey: first.ownedKey } : {}), ...(first.ownedRegion ? { ownedRegion: first.ownedRegion } : {}) };\n const fragment = readOwnedContent(text(currentContent), selector);\n return fragment.status === 'present' ? normalized(fragment.content) : undefined;\n })()\n : normalized(currentContent);\n const targetHash = fragmentHash && targetFragment !== undefined ? normalized(targetFragment) : normalized(target);\n const baselineHash = verified ? old!.vendorHash : trustedHash(group.path, options);\n const currentEqualsTarget = currentHash !== undefined && currentHash === targetHash;\n const currentEqualsBase = currentHash !== undefined && baselineHash !== undefined && currentHash === baselineHash;\n const targetEqualsBase = baselineHash !== undefined && targetHash === baselineHash;\n let kind: UpdateActionKind;\n let reason: string;\n if (currentContent === undefined) {\n if (verified) { kind = 'preserve'; reason = 'Local deletion is preserved; repair requires explicit selection.'; }\n else if (old) { kind = 'preserve'; reason = 'Prior ownership is unverified; preserve the local deletion.'; }\n else {\n kind = first.kind === 'vendor' || (first.kind === 'create-once' && first.content !== undefined) ? 'create' : 'preserve';\n reason = kind === 'create' ? 'New selected file.' : 'Config patch has no current file.';\n }\n } else if (old?.kind === 'create-once' && !explicitReplacement(options, group.path)) {\n kind = 'preserve'; reason = 'Create-once document is user-owned after its first creation; preserve local content.';\n } else if (currentEqualsTarget) {\n kind = old && verified ? 'reconcile' : 'adopt';\n reason = kind === 'reconcile' ? 'Current bytes already equal target; reconcile manifest metadata.' : 'Exact trusted target match establishes vendor ownership.';\n } else if (currentEqualsBase) {\n kind = 'replace'; reason = 'Current bytes equal the verified vendor base; safe replacement.';\n } else if ((options.forceCustomized ?? []).includes(group.path)) {\n kind = 'replace'; reason = 'Scoped init force selected this known customized path.';\n } else if (targetEqualsBase) {\n kind = 'preserve'; reason = 'Vendor target is unchanged; preserve the local-only edit.';\n } else if (verified) {\n kind = 'conflict'; reason = 'Current customization and target vendor content both differ from the verified base.';\n } else {\n kind = 'conflict'; reason = 'Ownership is unverified; preserve current content until trusted evidence or explicit review.';\n }\n // A local-only edit is normally preserved because the vendor target has\n // not changed. An explicit replacement path is the user's reviewed\n // authorization to replace those bytes as well; keep the ordinary\n // conflict shape for both-changed files so review metadata remains clear.\n if (kind === 'preserve' && explicitReplacement(options, group.path) && currentContent !== undefined && target !== undefined) {\n kind = 'replace';\n reason = 'Explicit replacement selected for this customized path.';\n }\n const action = actionBase(group.path, kind, reason, currentContent, target, first.mode);\n if (target !== undefined && ['replace', 'create', 'adopt', 'conflict'].includes(kind)) action.content = bytes(target);\n action.selected = selected(options, group.path, kind);\n if (kind === 'preserve' && currentContent === undefined && verified && options.repair?.includes(group.path)) {\n action.kind = 'repair'; action.resolution = 'repair'; action.selected = true;\n if (target !== undefined) action.content = bytes(target);\n } else if (kind === 'conflict' && explicitReplacement(options, group.path)) {\n action.resolution = 'replace'; action.selected = true;\n }\n if (kind === 'conflict' && currentContent !== undefined && target !== undefined) action.diff = diff(group.path, currentContent, target);\n if (first.kind === 'config-patch') action.patch = { ...(first.ownedKey ? { ownedKey: first.ownedKey } : {}), ...(first.ownedRegion ? { ownedRegion: first.ownedRegion } : {}) };\n add(action);\n if (action.selected && ['replace', 'create', 'adopt', 'repair', 'reconcile'].includes(action.kind)) addFile(nextManifest, group.path, first, targetHash, options.targetVersion ?? input.manifest.targetVersion);\n if (action.selected && action.kind === 'conflict' && action.resolution === 'replace') addFile(nextManifest, group.path, first, targetHash, options.targetVersion ?? input.manifest.targetVersion);\n }\n\n for (const [path, old] of Object.entries(input.manifest.files)) {\n if (knownPaths.has(path)) continue;\n const currentContent = current.get(path);\n if (currentContent === undefined) {\n const action = actionBase(path, 'preserve', 'Previously managed file is absent; preserve local deletion.', undefined, undefined, undefined);\n add(action);\n continue;\n }\n if (old.kind !== 'vendor') {\n const unchangedCreateOnce = old.kind === 'create-once' && old.vendorHash !== '' && normalized(currentContent) === old.vendorHash;\n const action = actionBase(\n path,\n 'preserve',\n unchangedCreateOnce\n ? 'Create-once document is unchanged; leave the existing file in place.'\n : 'Target no longer declares a patch/document; preserve the whole user file.',\n currentContent,\n undefined,\n undefined,\n );\n if (unchangedCreateOnce) action.nonActionable = true;\n action.selected = false;\n add(action);\n continue;\n }\n if (old.ownership !== 'verified' || !old.vendorHash) {\n const action = actionBase(path, 'orphan', 'Target no longer declares this file and ownership is unverified; preserve it.', currentContent, undefined, undefined);\n action.selected = false;\n add(action);\n delete nextManifest.files[path];\n continue;\n }\n const currentHash = normalized(currentContent);\n if (currentHash === old.vendorHash) {\n const action = actionBase(path, 'delete', 'Target no longer includes an owned file; delete only the verified file.', currentContent, undefined, undefined);\n action.selected = true;\n add(action);\n delete nextManifest.files[path];\n } else {\n const action = actionBase(path, 'orphan', 'Target no longer includes customized content; preserve it as an orphaned customization.', currentContent, undefined, undefined);\n action.selected = false;\n add(action);\n delete nextManifest.files[path];\n }\n }\n\n const preserved = actions\n .filter((action) => action.preservedContent !== undefined && ['preserve', 'conflict', 'orphan'].includes(action.kind))\n .map((action) => ({ path: action.path, content: bytes(action.preservedContent!), reason: action.reason }));\n const conflicts = actions.filter((action) => action.kind === 'conflict');\n return {\n actions,\n preserved,\n conflicts,\n diagnostics,\n nextManifest,\n baseManifestDigest: options.baseManifestDigest !== undefined\n ? options.baseManifestDigest\n : manifestDigest(input.manifest),\n };\n}\n","import {\n chmodSync,\n closeSync,\n existsSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n rmdirSync,\n rmSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport * as fs from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { randomUUID } from 'node:crypto';\n\nimport {\n manifestDigest,\n manifestPath,\n parseInstallationManifest,\n rawFileHash,\n readInstallationManifestInfo,\n validateManifest,\n type InstallationManifest,\n} from './install-manifest.js';\nimport { resolveUpdatePath } from './update-paths.js';\nimport type { PlannedUpdateAction, SnapshotContent, UpdatePlan } from './update-plan.js';\nimport type { GitignoreProfile } from './version.js';\nimport { LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE, STATE_PATH } from './version.js';\n\nconst LOCAL_DIR = 'docs/.joycraft/local';\nconst LOCK_RELATIVE = `${LOCAL_DIR}/update.lock`;\nconst JOURNAL_RELATIVE = `${LOCAL_DIR}/update-journal.json`;\nconst BACKUPS_RELATIVE = `${LOCAL_DIR}/backups`;\nconst LAST_SUCCESSFUL_RELATIVE = `${LOCAL_DIR}/last-successful.json`;\n\nexport type TransactionPhase =\n | 'lock-acquired'\n | 'journal-written'\n | 'backups-written'\n | 'staged'\n | 'files-applied'\n | 'files-verified'\n | 'manifest-renamed'\n | 'journal-bookkept'\n | 'cleanup'\n | 'complete';\n\nexport interface TransactionPhaseInfo {\n operationId: string;\n journalPath: string;\n}\n\nexport interface TransactionOptions {\n profile?: GitignoreProfile;\n operationId?: string;\n /**\n * Move manifest authority as part of this transaction. The source and\n * destination are explicit so a profile change cannot accidentally publish\n * to the destination while leaving the source authoritative.\n */\n authorityTransition?: AuthorityTransition;\n /** Narrow, planner-owned writes for legacy migration and local preferences. */\n localOperations?: readonly LocalTransactionOperation[];\n /** Throw after the selected real phase, leaving the journal for recovery. */\n failureAt?: TransactionPhase;\n onPhase?: (phase: TransactionPhase, info: TransactionPhaseInfo) => void;\n}\n\nexport interface AuthorityReference {\n profile: GitignoreProfile;\n /** Optional while callers use the canonical profile path. */\n path?: string;\n /** Digest expected at this authority before the transaction starts. */\n digest?: string | null;\n /** Optional raw preimage supplied by the planner. */\n raw?: SnapshotContent;\n}\n\n/** The old and new manifest authorities for a shared/private profile switch. */\nexport interface AuthorityTransition {\n oldAuthority: AuthorityReference;\n newAuthority: AuthorityReference;\n}\n\nexport type LocalTransactionOperationKind = 'write' | 'delete';\n\nexport interface LocalTransactionOperation {\n path: string;\n kind: LocalTransactionOperationKind;\n content?: SnapshotContent;\n currentPresent: boolean;\n rawPrecondition?: string;\n mode?: number;\n}\n\nexport interface TransactionResult {\n status: 'applied' | 'noop' | 'attention' | 'failed' | 'conflict' | 'rolled-back' | 'committed' | 'none';\n operationId?: string;\n phase?: TransactionPhase;\n journalPath?: string;\n backupPath?: string;\n diagnostics: string[];\n conflicts: string[];\n}\n\ninterface EncodedBytes {\n encoding: 'base64';\n data: string;\n}\n\ninterface Image {\n present: boolean;\n bytes?: EncodedBytes;\n hash?: string;\n mode?: number;\n}\n\ninterface JournalOperation {\n path: string;\n kind: 'write' | 'delete';\n before: Image;\n after: Image;\n stageRelative?: string;\n backupRelative?: string;\n /** Manifest authority operations are validated against journal authorities. */\n authority?: boolean;\n /** Planner-approved state/preferences migration operation. */\n localMigration?: boolean;\n}\n\ninterface JournalAuthority {\n profile: GitignoreProfile;\n path: string;\n /** Digest of the authority bytes in this journal (old preimage or new commit). */\n digest: string | null;\n bytes?: EncodedBytes;\n /** Digest required at the destination before publishing (normally null). */\n preconditionDigest?: string | null;\n}\n\ninterface TransactionJournal {\n schemaVersion: 1;\n operationId: string;\n profile: GitignoreProfile;\n phase: TransactionPhase;\n oldManifestDigest: string | null;\n newManifestDigest: string;\n oldManifest?: EncodedBytes;\n newManifest: EncodedBytes;\n plan: unknown;\n operations: JournalOperation[];\n backupRelative: string;\n oldAuthority?: JournalAuthority;\n newAuthority?: JournalAuthority;\n}\n\ninterface SuccessfulBackup {\n schemaVersion: 1;\n operationId: string;\n profile: GitignoreProfile;\n oldManifestDigest: string | null;\n newManifestDigest: string;\n oldManifest?: EncodedBytes;\n newManifest: EncodedBytes;\n operations: JournalOperation[];\n backupRelative: string;\n oldAuthority?: JournalAuthority;\n newAuthority?: JournalAuthority;\n}\n\ninterface LockHandle {\n path: string;\n ownerPath: string;\n operationId: string;\n acquired: boolean;\n}\n\nclass TransactionConflictError extends Error {\n readonly conflictPath?: string;\n\n constructor(message: string, conflictPath?: string) {\n super(message);\n this.name = 'TransactionConflictError';\n this.conflictPath = conflictPath;\n }\n}\n\nfunction encode(value: unknown): unknown {\n if (Buffer.isBuffer(value)) return { __joycraftBuffer: value.toString('base64') };\n if (Array.isArray(value)) return value.map(encode);\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encode(item)]));\n }\n return value;\n}\n\nfunction decode(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(decode);\n if (value && typeof value === 'object') {\n const object = value as Record<string, unknown>;\n if (typeof object.__joycraftBuffer === 'string' && Object.keys(object).length === 1) {\n return Buffer.from(object.__joycraftBuffer, 'base64');\n }\n return Object.fromEntries(Object.entries(object).map(([key, item]) => [key, decode(item)]));\n }\n return value;\n}\n\nfunction bytes(value: SnapshotContent): Buffer {\n return Buffer.isBuffer(value) ? Buffer.from(value) : Buffer.from(value);\n}\n\nfunction imageBytes(image: Image): Buffer | undefined {\n return image.present && image.bytes ? Buffer.from(image.bytes.data, 'base64') : undefined;\n}\n\nfunction imageOf(content: Buffer | undefined, mode: number | undefined): Image {\n if (!content) return { present: false };\n return { present: true, bytes: { encoding: 'base64', data: content.toString('base64') }, hash: rawFileHash(content), ...(mode === undefined ? {} : { mode }) };\n}\n\nfunction modeOf(path: string): number | undefined {\n try { return statSync(path).mode & 0o7777; } catch { return undefined; }\n}\n\nfunction hitPhase(options: TransactionOptions, phase: TransactionPhase, info: TransactionPhaseInfo): void {\n options.onPhase?.(phase, info);\n if (options.failureAt === phase) {\n throw new Error(`Injected transaction failure after ${phase}.`);\n }\n}\n\nfunction localPath(root: string, relativePath: string): string {\n return resolveUpdatePath(root, relativePath);\n}\n\nfunction ensureDirectory(root: string, relativePath: string): string {\n const path = localPath(root, relativePath);\n mkdirSync(path, { recursive: true });\n // Recheck after mkdir to catch a replacement by a symlink or file.\n return localPath(root, relativePath);\n}\n\nfunction durableWrite(path: string, data: Buffer | string, mode?: number): void {\n mkdirSync(dirname(path), { recursive: true });\n // Windows requires write access on the handle used to flush file buffers.\n const fd = openSync(path, 'w');\n try {\n writeFileSync(fd, data);\n fsyncSync(fd);\n } finally { closeFd(fd); }\n if (mode !== undefined) chmodSync(path, mode);\n}\n\nfunction closeFd(fd: number): void {\n closeSync(fd);\n}\n\nfunction readJournal(root: string): TransactionJournal | null {\n const path = localPath(root, JOURNAL_RELATIVE);\n if (!existsSync(path)) return null;\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<TransactionJournal>;\n if (parsed.schemaVersion !== 1 || typeof parsed.operationId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(parsed.operationId) || !Array.isArray(parsed.operations)\n || typeof parsed.newManifestDigest !== 'string' || !parsed.newManifest || typeof parsed.backupRelative !== 'string') {\n throw new Error('Invalid Joycraft update journal; refusing recovery.');\n }\n return parsed as TransactionJournal;\n}\n\nfunction writeJournal(root: string, journal: TransactionJournal): string {\n const path = localPath(root, JOURNAL_RELATIVE);\n const tempRelative = `${JOURNAL_RELATIVE}.tmp-${journal.operationId}`;\n const temp = localPath(root, tempRelative);\n durableWrite(temp, JSON.stringify(encode(journal), null, 2) + '\\n');\n fs.renameSync(temp, path);\n return path;\n}\n\nfunction lock(root: string, operationId: string): LockHandle | null {\n ensureDirectory(root, LOCAL_DIR);\n const path = localPath(root, LOCK_RELATIVE);\n try {\n mkdirSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') return null;\n throw error;\n }\n const ownerPath = localPath(root, `${LOCK_RELATIVE}/owner.json`);\n try {\n durableWrite(ownerPath, JSON.stringify({ operationId, pid: process.pid, startedAt: new Date().toISOString() }) + '\\n');\n } catch (error) {\n try {\n if (lstatSync(path).isDirectory() && readdirSync(path).length === 0) rmdirSync(path);\n } catch { /* preserve a lock that may have been replaced concurrently */ }\n throw error;\n }\n return { path, ownerPath, operationId, acquired: true };\n}\n\nfunction recoveryLock(root: string, operationId: string): LockHandle | null {\n const acquired = lock(root, operationId);\n if (acquired) return acquired;\n const ownerPath = localPath(root, `${LOCK_RELATIVE}/owner.json`);\n try {\n if (!lstatSync(ownerPath).isFile()) return null;\n const owner = JSON.parse(readFileSync(ownerPath, 'utf8')) as { operationId?: unknown; pid?: unknown };\n if (owner.operationId !== operationId || typeof owner.pid !== 'number' || !Number.isInteger(owner.pid) || owner.pid <= 0) return null;\n try { process.kill(owner.pid, 0); return null; } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') return null;\n }\n // Re-check identity immediately before reclaiming the dead owner's lock.\n const check = JSON.parse(readFileSync(ownerPath, 'utf8')) as { operationId?: unknown; pid?: unknown };\n if (check.operationId !== operationId || check.pid !== owner.pid) return null;\n unlinkSync(ownerPath);\n rmdirSync(localPath(root, LOCK_RELATIVE));\n return lock(root, operationId);\n } catch {\n return null;\n }\n}\n\nfunction unlock(handle: LockHandle): void {\n if (!handle.acquired) return;\n try {\n if (!lstatSync(handle.path).isDirectory() || !lstatSync(handle.ownerPath).isFile()) return;\n const owner = JSON.parse(readFileSync(handle.ownerPath, 'utf8')) as { operationId?: unknown };\n if (owner.operationId !== handle.operationId) return;\n unlinkSync(handle.ownerPath);\n rmdirSync(handle.path);\n } catch { /* never remove another process lock */ }\n handle.acquired = false;\n}\n\nfunction profileFor(plan: UpdatePlan, options: TransactionOptions): GitignoreProfile {\n if (options.authorityTransition) {\n if (options.authorityTransition.newAuthority.profile !== plan.nextManifest.profile) {\n throw new Error(`Transaction profile '${options.authorityTransition.newAuthority.profile}' does not match manifest profile '${plan.nextManifest.profile}'.`);\n }\n return options.authorityTransition.newAuthority.profile;\n }\n if (options.profile && options.profile !== plan.nextManifest.profile) {\n throw new Error(`Transaction profile '${options.profile}' does not match manifest profile '${plan.nextManifest.profile}'.`);\n }\n return plan.nextManifest.profile;\n}\n\nfunction isControlPath(relativePath: string, profile: GitignoreProfile): boolean {\n const controls = [\n // Both authority locations are transaction control paths regardless of\n // the destination profile. A private transaction must not be able to\n // smuggle a write to the tracked shared authority through its plan.\n manifestPath('shared'),\n manifestPath('private'),\n LOCAL_DIR,\n LOCK_RELATIVE,\n JOURNAL_RELATIVE,\n `${LOCAL_DIR}/staging`,\n BACKUPS_RELATIVE,\n LAST_SUCCESSFUL_RELATIVE,\n ];\n return controls.some((control) => relativePath === control || relativePath.startsWith(`${control}/`));\n}\n\n// These are the only project-local state files that the update planner may\n// migrate. In particular, callers cannot turn localOperations into a control\n// path escape by supplying an arbitrary path beneath docs/.joycraft/local.\nconst APPROVED_LOCAL_MIGRATION_PATHS = new Set([\n STATE_PATH,\n LEGACY_VERSION_FILE,\n LEGACY_CLAUDE_STATE_PATH,\n `${LOCAL_DIR}/settings.json`,\n `${LOCAL_DIR}/preferences.json`,\n `${LOCAL_DIR}/legacy-state-backup.json`,\n]);\n\nfunction validateLocalMigrationPath(root: string, relativePath: string): void {\n localPath(root, relativePath);\n if (!APPROVED_LOCAL_MIGRATION_PATHS.has(relativePath)) {\n throw new Error(`Local migration action is not allowlisted: '${relativePath}'.`);\n }\n}\n\nfunction validateManagedPath(root: string, relativePath: string, profile: GitignoreProfile): void {\n localPath(root, relativePath);\n if (isControlPath(relativePath, profile)) {\n throw new Error(`Update action cannot target Joycraft transaction state: '${relativePath}'.`);\n }\n}\n\nfunction operationFromInput(\n input: {\n path: string;\n kind: 'write' | 'delete';\n content?: SnapshotContent;\n currentPresent: boolean;\n rawPrecondition?: string;\n mode?: number;\n },\n root: string,\n): JournalOperation {\n const path = localPath(root, input.path);\n let current: Buffer | undefined;\n let mode: number | undefined;\n try {\n const stat = lstatSync(path);\n if (!stat.isFile()) throw new Error(`Planned update path is not a regular file: '${input.path}'.`);\n current = readFileSync(path);\n mode = stat.mode & 0o7777;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (input.currentPresent !== (current !== undefined)) {\n throw new TransactionConflictError(`Raw precondition failed for '${input.path}'.`, input.path);\n }\n if (input.rawPrecondition !== undefined && rawFileHash(current ?? Buffer.alloc(0)) !== input.rawPrecondition) {\n if (!(current === undefined && input.rawPrecondition === '')) {\n throw new TransactionConflictError(`Raw precondition failed for '${input.path}'.`, input.path);\n }\n }\n if (input.kind === 'delete') {\n return { path: input.path, kind: 'delete', before: imageOf(current, mode), after: { present: false }, localMigration: true };\n }\n if (input.content === undefined) throw new Error(`Selected local migration has no content: '${input.path}'.`);\n const target = bytes(input.content);\n return {\n path: input.path,\n kind: 'write',\n before: imageOf(current, mode),\n after: imageOf(target, input.mode ?? mode ?? 0o644),\n localMigration: true,\n };\n}\n\nfunction authorityPath(root: string, reference: AuthorityReference): string {\n const expected = manifestPath(reference.profile);\n if (reference.path !== undefined && reference.path !== expected) {\n throw new Error(`Authority path '${reference.path}' does not match profile '${reference.profile}'.`);\n }\n return localPath(root, expected);\n}\n\nfunction digestOfAuthorityInfo(info: ReturnType<typeof readInstallationManifestInfo>): string | null {\n return info.manifest ? manifestDigest(info.manifest) : null;\n}\n\nfunction validateAuthorityReference(\n root: string,\n reference: AuthorityReference,\n info: ReturnType<typeof readInstallationManifestInfo>,\n label: string,\n): void {\n authorityPath(root, reference);\n if (info.status !== 'valid' && info.status !== 'missing') {\n throw new TransactionConflictError(`Cannot transition while the ${label} authority is ${info.status}.`, manifestPath(reference.profile));\n }\n const actual = digestOfAuthorityInfo(info);\n if (reference.digest !== undefined && reference.digest !== actual) {\n throw new TransactionConflictError(`${label} manifest authority changed after planning.`, manifestPath(reference.profile));\n }\n if (reference.raw !== undefined) {\n const raw = info.raw;\n if (raw === undefined || raw !== (Buffer.isBuffer(reference.raw) ? reference.raw.toString('utf8') : reference.raw)) {\n throw new TransactionConflictError(`${label} manifest authority bytes changed after planning.`, manifestPath(reference.profile));\n }\n }\n}\n\nfunction authorityReferenceForTransition(\n root: string,\n transition: AuthorityTransition,\n): { old: AuthorityReference; next: AuthorityReference; oldInfo: ReturnType<typeof readInstallationManifestInfo>; nextInfo: ReturnType<typeof readInstallationManifestInfo> } {\n if (transition.oldAuthority.profile === transition.newAuthority.profile) {\n throw new Error('Authority transition requires distinct shared and private profiles.');\n }\n authorityPath(root, transition.oldAuthority);\n authorityPath(root, transition.newAuthority);\n const oldInfo = readInstallationManifestInfo(root, transition.oldAuthority.profile);\n const nextInfo = readInstallationManifestInfo(root, transition.newAuthority.profile);\n validateAuthorityReference(root, transition.oldAuthority, oldInfo, 'old');\n // A destination authority is never silently replaced. The destination\n // precondition may explicitly describe absence, but any existing authority\n // is still a conflict that preserves its bytes.\n if (nextInfo.status !== 'missing') {\n throw new TransactionConflictError('The target manifest authority already exists; preserving it.', manifestPath(transition.newAuthority.profile));\n }\n if (transition.newAuthority.digest !== undefined && transition.newAuthority.digest !== null) {\n throw new TransactionConflictError('The target manifest authority precondition must be missing.', manifestPath(transition.newAuthority.profile));\n }\n return { old: transition.oldAuthority, next: transition.newAuthority, oldInfo, nextInfo };\n}\n\nfunction authorityOperation(\n root: string,\n path: string,\n kind: 'write' | 'delete',\n content?: Buffer,\n before?: Image,\n): JournalOperation {\n const current = currentImage(root, path);\n const expected = before ?? current;\n if (!sameImage(current, expected)) throw new TransactionConflictError(`Raw precondition failed for '${path}'.`, path);\n if (kind === 'delete') return { path, kind, before: expected, after: { present: false }, authority: true };\n if (!content) throw new Error(`Authority write has no manifest bytes: '${path}'.`);\n return { path, kind, before: expected, after: imageOf(content, 0o644), authority: true };\n}\n\nfunction siblingStagePath(relativePath: string, operationId: string, index: number): string {\n const slash = relativePath.lastIndexOf('/');\n const parent = slash < 0 ? '' : relativePath.slice(0, slash);\n const name = `.joycraft-${operationId}-${index}.stage`;\n return parent ? `${parent}/${name}` : name;\n}\n\nfunction operationFor(action: PlannedUpdateAction, root: string): JournalOperation | null {\n if (!action.selected || action.kind === 'reconcile' || action.kind === 'adopt' || action.kind === 'preserve' || action.kind === 'orphan') return null;\n const path = localPath(root, action.path);\n let current: Buffer | undefined;\n let mode: number | undefined;\n try {\n const stat = lstatSync(path);\n if (!stat.isFile()) throw new Error(`Planned update path is not a regular file: '${action.path}'.`);\n current = readFileSync(path);\n mode = stat.mode & 0o7777;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (action.currentPresent !== (current !== undefined)) {\n throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);\n }\n if (action.rawPrecondition !== undefined && rawFileHash(current ?? Buffer.alloc(0)) !== action.rawPrecondition) {\n if (!(current === undefined && action.rawPrecondition === '')) {\n throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);\n }\n }\n if (action.kind === 'delete') {\n return { path: action.path, kind: 'delete', before: imageOf(current, mode), after: { present: false } };\n }\n if (action.content === undefined) throw new Error(`Selected update action has no content: '${action.path}'.`);\n const target = bytes(action.content);\n const targetMode = action.mode ?? mode ?? 0o644;\n return {\n path: action.path,\n kind: 'write',\n before: imageOf(current, mode),\n after: imageOf(target, targetMode),\n };\n}\n\nfunction validateMetadataPrecondition(action: PlannedUpdateAction, root: string): void {\n if (!action.selected || (action.kind !== 'reconcile' && action.kind !== 'adopt')) return;\n const current = currentImage(root, action.path);\n if (action.currentPresent !== current.present) throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);\n if (action.rawPrecondition !== undefined) {\n const content = imageBytes(current);\n if (!content || rawFileHash(content) !== action.rawPrecondition) {\n throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);\n }\n }\n}\n\nfunction currentImage(root: string, relativePath: string): Image {\n const path = localPath(root, relativePath);\n try {\n const stat = lstatSync(path);\n if (!stat.isFile()) throw new Error(`Transaction path is not a regular file: '${relativePath}'.`);\n const content = readFileSync(path);\n return imageOf(content, stat.mode & 0o7777);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { present: false };\n throw error;\n }\n}\n\nfunction sameImage(left: Image, right: Image): boolean {\n if (left.present !== right.present) return false;\n if (!left.present) return true;\n const leftBytes = imageBytes(left);\n const rightBytes = imageBytes(right);\n return !!leftBytes && !!rightBytes && rawFileHash(leftBytes) === rawFileHash(rightBytes)\n && (right.mode === undefined || (left.mode !== undefined && (\n // Windows chmod exposes writability, not Unix owner/group/execute bits.\n process.platform === 'win32'\n ? (left.mode & 0o200) === (right.mode & 0o200)\n : left.mode === right.mode\n )));\n}\n\nfunction writeImage(root: string, relativePath: string, image: Image): void {\n const path = localPath(root, relativePath);\n if (!image.present) {\n try { unlinkSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }\n return;\n }\n const content = imageBytes(image);\n if (!content) throw new Error(`Missing preimage bytes for '${relativePath}'.`);\n mkdirSync(dirname(path), { recursive: true });\n localPath(root, relativePath);\n const slash = relativePath.lastIndexOf('/');\n const parent = slash < 0 ? '' : relativePath.slice(0, slash);\n const tempRelative = `${parent ? `${parent}/` : ''}.joycraft-rollback-${randomUUID()}.stage`;\n const temp = localPath(root, tempRelative);\n durableWrite(temp, content, image.mode);\n fs.renameSync(temp, path);\n}\n\nfunction manifestBytes(manifest: InstallationManifest): Buffer {\n return Buffer.from(JSON.stringify(manifest, null, 2) + '\\n');\n}\n\nfunction withTransactionMarker(manifest: InstallationManifest, operationId: string): InstallationManifest {\n return { ...manifest, __joycraftTransactionId: operationId };\n}\n\nfunction withoutTransactionMarker(manifest: InstallationManifest): InstallationManifest {\n const copy = { ...manifest } as Record<string, unknown>;\n delete copy.__joycraftTransactionId;\n return copy as InstallationManifest;\n}\n\nfunction cleanupKnown(root: string, journal: TransactionJournal): void {\n for (const operation of journal.operations) {\n if (!operation.stageRelative) continue;\n const staged = localPath(root, operation.stageRelative);\n if (existsSync(staged)) unlinkSync(staged);\n }\n const journalPath = localPath(root, JOURNAL_RELATIVE);\n if (existsSync(journalPath)) unlinkSync(journalPath);\n const tempPath = localPath(root, `${JOURNAL_RELATIVE}.tmp-${journal.operationId}`);\n if (existsSync(tempPath)) unlinkSync(tempPath);\n const manifestTemp = localPath(root, `${manifestPath(journal.profile)}.tmp-${journal.operationId}`);\n if (existsSync(manifestTemp)) unlinkSync(manifestTemp);\n}\n\nfunction successfulFromJournal(journal: TransactionJournal): SuccessfulBackup {\n return {\n schemaVersion: 1,\n operationId: journal.operationId,\n profile: journal.profile,\n oldManifestDigest: journal.oldManifestDigest,\n newManifestDigest: journal.newManifestDigest,\n ...(journal.oldManifest ? { oldManifest: journal.oldManifest } : {}),\n newManifest: journal.newManifest,\n operations: journal.operations,\n backupRelative: journal.backupRelative,\n ...(journal.oldAuthority ? { oldAuthority: journal.oldAuthority } : {}),\n ...(journal.newAuthority ? { newAuthority: journal.newAuthority } : {}),\n };\n}\n\nfunction retainSuccessfulBackup(root: string, journal: TransactionJournal): void {\n const target = localPath(root, LAST_SUCCESSFUL_RELATIVE);\n const temp = localPath(root, `${LAST_SUCCESSFUL_RELATIVE}.tmp-${journal.operationId}`);\n durableWrite(temp, JSON.stringify(encode(successfulFromJournal(journal)), null, 2) + '\\n');\n fs.renameSync(temp, target);\n}\n\nfunction attention(message: string, operationId?: string, journalPath?: string): TransactionResult {\n return { status: 'attention', ...(operationId ? { operationId } : {}), ...(journalPath ? { journalPath } : {}), diagnostics: [message], conflicts: [] };\n}\n\n/** Apply the selected, already-reviewed actions through a recoverable transaction. */\nexport function applyUpdatePlan(root: string, plan: UpdatePlan, options: TransactionOptions = {}): TransactionResult {\n const operationId = options.operationId ?? randomUUID();\n const profile = profileFor(plan, options);\n let transitionAuthorities: ReturnType<typeof authorityReferenceForTransition> | null = null;\n // Validate every authority and transaction-state path before any selected\n // project file can be changed. The manifest reader itself intentionally\n // remains diagnostic, so this boundary must reject a symlinked authority.\n localPath(root, manifestPath(profile));\n localPath(root, LOCAL_DIR);\n localPath(root, LOCK_RELATIVE);\n localPath(root, JOURNAL_RELATIVE);\n const journalPath = localPath(root, JOURNAL_RELATIVE);\n const info = { operationId, journalPath };\n if (existsSync(journalPath)) {\n return attention('An interrupted update is awaiting recovery; recover it before applying a new plan.', operationId, journalPath);\n }\n if (options.authorityTransition) {\n try {\n transitionAuthorities = authorityReferenceForTransition(root, options.authorityTransition);\n } catch (error) {\n if (error instanceof TransactionConflictError) {\n return { status: 'conflict', operationId, journalPath, diagnostics: [error.message], conflicts: error.conflictPath ? [error.conflictPath] : [] };\n }\n throw error;\n }\n localPath(root, manifestPath(transitionAuthorities.old.profile));\n }\n // Validate all managed paths before taking the lock or creating local state.\n for (const action of plan.actions) if (action.selected) validateManagedPath(root, action.path, profile);\n for (const operation of options.localOperations ?? []) validateLocalMigrationPath(root, operation.path);\n const manifestProfile = transitionAuthorities?.old.profile ?? profile;\n const manifestInfo = readInstallationManifestInfo(root, manifestProfile);\n if (manifestInfo.status !== 'valid' && manifestInfo.status !== 'missing') {\n return attention(`Cannot apply update while the ${manifestInfo.status} installation manifest needs attention.`);\n }\n const currentManifest = manifestInfo.manifest;\n const currentDigest = currentManifest ? manifestDigest(currentManifest) : null;\n const expectedBaseDigest = transitionAuthorities?.old.digest ?? plan.baseManifestDigest;\n if (expectedBaseDigest !== undefined && expectedBaseDigest !== currentDigest) {\n return { status: 'conflict', operationId, journalPath, diagnostics: ['The installation manifest changed after this plan was created; re-plan before applying.'], conflicts: [manifestPath(manifestProfile)] };\n }\n const markedNext = withTransactionMarker(plan.nextManifest, operationId);\n if (!validateManifest(markedNext)) throw new Error('Refusing to publish an invalid transaction manifest.');\n if (!transitionAuthorities && !(options.localOperations?.length) && currentManifest && manifestDigest(withoutTransactionMarker(markedNext)) === manifestDigest(withoutTransactionMarker(currentManifest))\n && plan.actions.every((action) => !action.selected || action.kind === 'reconcile' || action.kind === 'adopt')) {\n try {\n for (const action of plan.actions) validateMetadataPrecondition(action, root);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/'([^']+)'/);\n return { status: 'conflict', operationId, journalPath, diagnostics: [message], conflicts: match ? [match[1]] : [] };\n }\n return { status: 'noop', diagnostics: [], conflicts: [] };\n }\n const handle = lock(root, operationId);\n if (!handle) return attention('Another Joycraft updater holds the project lock.', operationId, journalPath);\n try {\n hitPhase(options, 'lock-acquired', info);\n if (existsSync(journalPath)) return attention('An interrupted update appeared while acquiring the project lock; recover it before applying a new plan.', operationId, journalPath);\n // Re-read after lock acquisition to close the plan-to-lock race.\n const lockedInfo = readInstallationManifestInfo(root, manifestProfile);\n if (lockedInfo.status !== 'valid' && lockedInfo.status !== 'missing') return attention(`Cannot apply update while the ${lockedInfo.status} installation manifest needs attention.`, operationId, journalPath);\n const lockedDigest = lockedInfo.manifest ? manifestDigest(lockedInfo.manifest) : null;\n if (expectedBaseDigest !== undefined && expectedBaseDigest !== lockedDigest) return { status: 'conflict', operationId, journalPath, diagnostics: ['The installation manifest changed while the update lock was acquired; re-plan before applying.'], conflicts: [manifestPath(manifestProfile)] };\n if (transitionAuthorities) {\n try {\n const lockedAuthorities = authorityReferenceForTransition(root, options.authorityTransition!);\n transitionAuthorities = lockedAuthorities;\n } catch (error) {\n if (error instanceof TransactionConflictError) return { status: 'conflict', operationId, journalPath, diagnostics: [error.message], conflicts: error.conflictPath ? [error.conflictPath] : [] };\n return attention(String(error), operationId, journalPath);\n }\n }\n try {\n for (const action of plan.actions) validateMetadataPrecondition(action, root);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/'([^']+)'/);\n return { status: 'conflict', operationId, journalPath, diagnostics: [message], conflicts: match ? [match[1]] : [] };\n }\n let operations: JournalOperation[];\n try {\n operations = plan.actions.map((action) => operationFor(action, root)).filter((item): item is JournalOperation => item !== null);\n for (const migration of options.localOperations ?? []) operations.push(operationFromInput(migration, root));\n if (transitionAuthorities) {\n const oldPath = manifestPath(transitionAuthorities.old.profile);\n const nextPath = manifestPath(transitionAuthorities.next.profile);\n const oldImage = currentImage(root, oldPath);\n const nextImage = currentImage(root, nextPath);\n operations.push(authorityOperation(root, oldPath, 'delete', undefined, oldImage));\n operations.push(authorityOperation(root, nextPath, 'write', manifestBytes(markedNext), nextImage));\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/'([^']+)'/);\n return { status: 'conflict', operationId, journalPath, diagnostics: [message], conflicts: match ? [match[1]] : [] };\n }\n const backupRelative = `${BACKUPS_RELATIVE}/${operationId}`;\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index];\n operation.backupRelative = `${backupRelative}/${index}.bin`;\n if (operation.kind === 'write') {\n operation.stageRelative = siblingStagePath(operation.path, operationId, index);\n if (existsSync(localPath(root, operation.stageRelative))) {\n throw new Error(`Transaction staging path already exists: '${operation.stageRelative}'.`);\n }\n }\n }\n const journal: TransactionJournal = {\n schemaVersion: 1,\n operationId,\n profile,\n phase: 'lock-acquired',\n oldManifestDigest: lockedInfo.manifest ? manifestDigest(lockedInfo.manifest) : null,\n newManifestDigest: manifestDigest(markedNext),\n ...(!transitionAuthorities && lockedInfo.raw ? { oldManifest: { encoding: 'base64', data: Buffer.from(lockedInfo.raw).toString('base64') } } : {}),\n newManifest: { encoding: 'base64', data: manifestBytes(markedNext).toString('base64') },\n plan: encode(plan),\n operations,\n backupRelative,\n ...(transitionAuthorities ? {\n oldAuthority: {\n profile: transitionAuthorities.old.profile,\n path: manifestPath(transitionAuthorities.old.profile),\n digest: lockedInfo.manifest ? manifestDigest(lockedInfo.manifest) : null,\n ...(lockedInfo.raw ? { bytes: { encoding: 'base64' as const, data: Buffer.from(lockedInfo.raw).toString('base64') } } : {}),\n },\n newAuthority: {\n profile: transitionAuthorities.next.profile,\n path: manifestPath(transitionAuthorities.next.profile),\n digest: manifestDigest(markedNext),\n preconditionDigest: transitionAuthorities.nextInfo.manifest ? manifestDigest(transitionAuthorities.nextInfo.manifest) : null,\n bytes: { encoding: 'base64' as const, data: manifestBytes(markedNext).toString('base64') },\n },\n } : {}),\n };\n journal.phase = 'journal-written';\n writeJournal(root, journal);\n hitPhase(options, 'journal-written', info);\n\n ensureDirectory(root, `${backupRelative}`);\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index];\n const before = imageBytes(operation.before);\n if (before) durableWrite(localPath(root, operation.backupRelative!), before, operation.before.mode);\n }\n journal.phase = 'backups-written';\n writeJournal(root, journal);\n hitPhase(options, 'backups-written', info);\n\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index];\n if (operation.kind !== 'write') continue;\n const targetPath = localPath(root, operation.path);\n mkdirSync(dirname(targetPath), { recursive: true });\n localPath(root, operation.path);\n const stagePath = localPath(root, operation.stageRelative!);\n if (existsSync(stagePath)) throw new Error(`Transaction staging path already exists: '${operation.stageRelative}'.`);\n const content = imageBytes(operation.after)!;\n durableWrite(stagePath, content, operation.after.mode);\n const staged = currentImage(root, operation.stageRelative!);\n if (!sameImage(staged, operation.after)) throw new Error(`Staged bytes or mode failed validation for '${operation.path}'.`);\n }\n journal.phase = 'staged';\n writeJournal(root, journal);\n hitPhase(options, 'staged', info);\n\n for (const operation of operations) {\n // Revalidate containment and the raw current image directly before each\n // rename/unlink. This also catches a symlink inserted after staging.\n const target = localPath(root, operation.path);\n mkdirSync(dirname(target), { recursive: true });\n localPath(root, operation.path);\n const current = currentImage(root, operation.path);\n if (!sameImage(current, operation.before)) throw new Error(`Raw precondition failed immediately before writing '${operation.path}'.`);\n if (operation.kind === 'delete') {\n if (current.present) unlinkSync(target);\n }\n else fs.renameSync(localPath(root, operation.stageRelative!), target);\n }\n journal.phase = 'files-applied';\n writeJournal(root, journal);\n hitPhase(options, 'files-applied', info);\n for (const operation of operations) {\n if (!sameImage(currentImage(root, operation.path), operation.after)) throw new Error(`Published bytes or mode failed validation for '${operation.path}'.`);\n }\n journal.phase = 'files-verified';\n writeJournal(root, journal);\n hitPhase(options, 'files-verified', info);\n\n // The plan's manifest and metadata preconditions remain authoritative until\n // the last publication step. A late edit leaves the journal recoverable.\n const beforeManifest = readInstallationManifestInfo(root, manifestProfile);\n if (!transitionAuthorities && beforeManifest.status !== 'valid' && beforeManifest.status !== 'missing') throw new TransactionConflictError('Installation manifest changed before publication.', manifestPath(manifestProfile));\n const beforeDigest = beforeManifest.manifest ? manifestDigest(beforeManifest.manifest) : null;\n if (!transitionAuthorities && beforeDigest !== journal.oldManifestDigest) throw new TransactionConflictError('Installation manifest changed before publication.', manifestPath(manifestProfile));\n if (transitionAuthorities) {\n const oldAfter = readInstallationManifestInfo(root, transitionAuthorities.old.profile);\n const nextAfter = readInstallationManifestInfo(root, transitionAuthorities.next.profile);\n if (oldAfter.status !== 'missing' || nextAfter.status !== 'valid' || !nextAfter.manifest\n || manifestDigest(nextAfter.manifest) !== journal.newManifestDigest) {\n throw new TransactionConflictError('Manifest authority changed before transition commit.', manifestPath(transitionAuthorities.next.profile));\n }\n }\n for (const action of plan.actions) validateMetadataPrecondition(action, root);\n for (const operation of operations) if (!sameImage(currentImage(root, operation.path), operation.after)) throw new TransactionConflictError(`Published bytes changed before manifest publication for '${operation.path}'.`, operation.path);\n\n if (!transitionAuthorities) {\n const manifestRel = manifestPath(profile);\n const manifestAbs = localPath(root, manifestRel);\n const manifestTemp = localPath(root, `${manifestRel}.tmp-${operationId}`);\n durableWrite(manifestTemp, manifestBytes(markedNext));\n parseInstallationManifest(readFileSync(manifestTemp, 'utf8'));\n fs.renameSync(manifestTemp, manifestAbs);\n }\n // Record rollback material before exposing the manifest-renamed phase. If\n // the process stops immediately after the rename, recovery can still\n // retain the same backup for an explicit guarded rollback.\n retainSuccessfulBackup(root, journal);\n journal.phase = 'manifest-renamed';\n writeJournal(root, journal);\n hitPhase(options, 'manifest-renamed', info);\n journal.phase = 'journal-bookkept';\n writeJournal(root, journal);\n hitPhase(options, 'journal-bookkept', info);\n journal.phase = 'cleanup';\n hitPhase(options, 'cleanup', info);\n cleanupKnown(root, journal);\n hitPhase(options, 'complete', info);\n return { status: 'applied', operationId, backupPath: localPath(root, backupRelative), diagnostics: [], conflicts: [] };\n } catch (error) {\n if (error instanceof TransactionConflictError) {\n return { status: 'conflict', operationId, journalPath, diagnostics: [error.message], conflicts: error.conflictPath ? [error.conflictPath] : [] };\n }\n throw error;\n } finally {\n unlock(handle);\n }\n}\n\nfunction decodeJournal(value: TransactionJournal): TransactionJournal {\n return decode(value) as TransactionJournal;\n}\n\nfunction verifiedJournalBytes(value: EncodedBytes): Buffer {\n if (!value || value.encoding !== 'base64' || typeof value.data !== 'string') {\n throw new Error('Invalid journal byte encoding.');\n }\n const decoded = Buffer.from(value.data, 'base64');\n if (decoded.toString('base64') !== value.data) throw new Error('Invalid journal base64 payload.');\n return decoded;\n}\n\nfunction validateJournalImage(image: Image): void {\n if (!image || typeof image.present !== 'boolean') throw new Error('Invalid journal file image.');\n if (!image.present) {\n if (image.bytes !== undefined || image.hash !== undefined) throw new Error('Absent journal file has content.');\n return;\n }\n if (!image.bytes || rawFileHash(verifiedJournalBytes(image.bytes)) !== image.hash) {\n throw new Error('Journal preimage or target bytes do not match their recorded digest.');\n }\n if (image.mode !== undefined && (!Number.isInteger(image.mode) || image.mode < 0 || image.mode > 0o7777)) {\n throw new Error('Invalid journal file mode.');\n }\n}\n\nfunction validateJournalAuthority(root: string, authority: JournalAuthority, label: string): void {\n if (!authority || (authority.profile !== 'shared' && authority.profile !== 'private')\n || authority.path !== manifestPath(authority.profile)\n || (authority.digest !== null && !/^[0-9a-f]{64}$/i.test(authority.digest))) {\n throw new Error(`Invalid ${label} manifest authority descriptor.`);\n }\n authorityPath(root, authority);\n if (authority.bytes) {\n const parsed = parseInstallationManifest(verifiedJournalBytes(authority.bytes).toString('utf8'));\n if (manifestDigest(parsed) !== authority.digest || parsed.profile !== authority.profile) {\n throw new Error(`Invalid ${label} manifest authority digest.`);\n }\n } else if (authority.digest !== null) {\n throw new Error(`Missing ${label} manifest authority preimage.`);\n }\n if (authority.preconditionDigest !== undefined\n && authority.preconditionDigest !== null\n && !/^[0-9a-f]{64}$/i.test(authority.preconditionDigest)) {\n throw new Error(`Invalid ${label} authority precondition digest.`);\n }\n}\n\nfunction authorityImageMatches(image: Image, authority: JournalAuthority): boolean {\n if (authority.digest === null) return !image.present;\n if (!image.present || !image.bytes || !authority.bytes) return false;\n return rawFileHash(imageBytes(image)!) === rawFileHash(verifiedJournalBytes(authority.bytes));\n}\n\nfunction validateJournal(root: string, journal: TransactionJournal): void {\n if (journal.schemaVersion !== 1 || !/^[A-Za-z0-9_-]+$/.test(journal.operationId) || !Array.isArray(journal.operations)) {\n throw new Error('Invalid update journal identity.');\n }\n if (journal.profile !== 'shared' && journal.profile !== 'private') throw new Error('Invalid update journal profile.');\n const next = parseInstallationManifest(verifiedJournalBytes(journal.newManifest).toString('utf8'));\n if (manifestDigest(next) !== journal.newManifestDigest || next.profile !== journal.profile || next.__joycraftTransactionId !== journal.operationId) {\n throw new Error('Journal commit marker does not match its recorded manifest.');\n }\n if (journal.oldManifest) {\n const previous = parseInstallationManifest(verifiedJournalBytes(journal.oldManifest).toString('utf8'));\n if (manifestDigest(previous) !== journal.oldManifestDigest || previous.profile !== journal.profile) throw new Error('Journal manifest preimage digest is invalid.');\n } else if (journal.oldManifestDigest !== null && !journal.oldAuthority) throw new Error('Journal is missing its manifest preimage.');\n if (journal.backupRelative !== `${BACKUPS_RELATIVE}/${journal.operationId}`) throw new Error('Update journal backup path is not transaction-owned.');\n localPath(root, journal.backupRelative);\n if ((journal.oldAuthority === undefined) !== (journal.newAuthority === undefined)) {\n throw new Error('Update journal must contain both authority descriptors.');\n }\n if (journal.oldAuthority && journal.newAuthority) {\n validateJournalAuthority(root, journal.oldAuthority, 'old');\n validateJournalAuthority(root, journal.newAuthority, 'new');\n if (journal.oldAuthority.profile === journal.newAuthority.profile || journal.oldAuthority.path === journal.newAuthority.path) {\n throw new Error('Update journal authority descriptors must be distinct.');\n }\n if (journal.newAuthority.digest !== journal.newManifestDigest) throw new Error('New authority digest does not match the transaction manifest.');\n const authorityOperations = journal.operations.filter((operation) => operation.authority);\n const oldDeletes = authorityOperations.filter((operation) => operation.path === journal.oldAuthority!.path && operation.kind === 'delete');\n const newWrites = authorityOperations.filter((operation) => operation.path === journal.newAuthority!.path && operation.kind === 'write');\n if (authorityOperations.length !== 2 || oldDeletes.length !== 1 || newWrites.length !== 1\n || !authorityImageMatches(oldDeletes[0].before, journal.oldAuthority)\n || oldDeletes[0].after.present\n || newWrites[0].before.present\n || !authorityImageMatches(newWrites[0].after, journal.newAuthority)) {\n throw new Error('Update journal authority operations do not match their recorded transition.');\n }\n } else if (journal.operations.some((operation) => operation.authority)) {\n throw new Error('Update journal contains authority operations without an authority transition.');\n }\n for (let index = 0; index < journal.operations.length; index += 1) {\n const operation = journal.operations[index];\n if (operation.kind !== 'write' && operation.kind !== 'delete') throw new Error('Invalid journal operation kind.');\n validateJournalImage(operation.before);\n validateJournalImage(operation.after);\n if (operation.authority) {\n if (!journal.oldAuthority || !journal.newAuthority || (operation.path !== journal.oldAuthority.path && operation.path !== journal.newAuthority.path)) {\n throw new Error('Update journal authority operation is not transaction-owned.');\n }\n } else if (operation.localMigration) {\n validateLocalMigrationPath(root, operation.path);\n } else {\n validateManagedPath(root, operation.path, journal.profile);\n }\n const expectedStage = operation.kind === 'write' ? siblingStagePath(operation.path, journal.operationId, index) : undefined;\n const stageRequired = ['staged', 'files-applied', 'files-verified', 'manifest-renamed', 'journal-bookkept', 'cleanup', 'complete'].includes(journal.phase);\n if ((stageRequired && operation.stageRelative !== expectedStage) || (operation.stageRelative !== undefined && operation.stageRelative !== expectedStage)) throw new Error('Update journal staging path is not transaction-owned.');\n if (operation.backupRelative && !operation.backupRelative.startsWith(`${journal.backupRelative}/`)) throw new Error('Update journal backup file is not transaction-owned.');\n }\n}\n\nfunction recoveryResult(status: TransactionResult['status'], journal: TransactionJournal, conflicts: string[] = [], diagnostics: string[] = []): TransactionResult {\n return { status, operationId: journal.operationId, journalPath: JOURNAL_RELATIVE, diagnostics, conflicts };\n}\n\nfunction transitionAuthorityState(root: string, journal: TransactionJournal): { oldState: boolean; newState: boolean } | TransactionResult {\n if (!journal.oldAuthority || !journal.newAuthority) return { oldState: false, newState: false };\n const oldInfo = readInstallationManifestInfo(root, journal.oldAuthority.profile);\n const newInfo = readInstallationManifestInfo(root, journal.newAuthority.profile);\n if (oldInfo.status !== 'valid' && oldInfo.status !== 'missing') {\n return recoveryResult('attention', journal, [], [`Cannot recover while the old manifest authority is ${oldInfo.status}.`]);\n }\n if (newInfo.status !== 'valid' && newInfo.status !== 'missing') {\n return recoveryResult('attention', journal, [], [`Cannot recover while the new manifest authority is ${newInfo.status}.`]);\n }\n const oldDigest = digestOfAuthorityInfo(oldInfo);\n const newDigest = digestOfAuthorityInfo(newInfo);\n const oldMatches = oldDigest === journal.oldAuthority.digest;\n const newMatches = newDigest === journal.newAuthority.digest;\n // The old authority is deleted before the new one is renamed. Missing both\n // therefore means an interrupted pre-commit interval and must roll back.\n if (oldMatches && newMatches) return recoveryResult('attention', journal, [journal.oldAuthority.path, journal.newAuthority.path], ['Both manifest authorities are present; transition state is ambiguous.']);\n if (newMatches && !oldInfo.manifest) return { oldState: false, newState: true };\n if (oldMatches && !newInfo.manifest) return { oldState: true, newState: false };\n if (!oldInfo.manifest && !newInfo.manifest) return { oldState: true, newState: false };\n return recoveryResult('attention', journal, [journal.oldAuthority.path, journal.newAuthority.path], ['Manifest authority matches neither the interrupted preimage nor its commit marker.']);\n}\n\n/** Recover the one known interrupted transaction, preserving any user edits. */\nexport function recoverInterruptedUpdate(root: string, options: TransactionOptions = {}): TransactionResult {\n let journal: TransactionJournal | null;\n try { journal = decodeJournal(readJournal(root)!); } catch (error) {\n return attention(`Unable to read the interrupted update journal: ${String(error)}`);\n }\n if (!journal) return { status: 'none', diagnostics: [], conflicts: [] };\n try {\n validateJournal(root, journal);\n } catch (error) {\n return attention(`Unable to recover the interrupted update safely: ${String(error)}`, journal.operationId, localPath(root, JOURNAL_RELATIVE));\n }\n const handle = recoveryLock(root, journal.operationId);\n if (!handle) return recoveryResult('attention', journal, [], ['Another Joycraft updater holds the project lock.']);\n try {\n const lockedJournalRaw = readJournal(root);\n if (!lockedJournalRaw || lockedJournalRaw.operationId !== journal.operationId || lockedJournalRaw.newManifestDigest !== journal.newManifestDigest) {\n return recoveryResult('attention', journal, [], ['The interrupted journal changed while recovery was acquiring the lock.']);\n }\n journal = decodeJournal(lockedJournalRaw);\n validateJournal(root, journal);\n const authorityState = transitionAuthorityState(root, journal);\n if ('status' in authorityState) return authorityState;\n let oldState: boolean;\n let newState: boolean;\n if (journal.oldAuthority && journal.newAuthority) {\n oldState = authorityState.oldState;\n newState = authorityState.newState;\n } else {\n const info = readInstallationManifestInfo(root, journal.profile);\n if (info.status !== 'valid' && info.status !== 'missing') return recoveryResult('attention', journal, [], [`Cannot recover while the ${info.status} installation manifest needs attention.`]);\n const digest = info.manifest ? manifestDigest(info.manifest) : null;\n oldState = digest === journal.oldManifestDigest;\n newState = digest === journal.newManifestDigest;\n if (!oldState && !newState) return recoveryResult('attention', journal, [], ['Current manifest matches neither the interrupted update preimage nor its commit marker.']);\n }\n const conflicts: string[] = [];\n for (const operation of journal.operations) {\n const current = currentImage(root, operation.path);\n if (newState ? !sameImage(current, operation.after) : (!sameImage(current, operation.before) && !sameImage(current, operation.after))) conflicts.push(operation.path);\n }\n if (conflicts.length) return recoveryResult('conflict', journal, conflicts, ['Recovery found intervening user edits; backup material was retained.']);\n if (newState) {\n retainSuccessfulBackup(root, journal);\n cleanupKnown(root, journal);\n hitPhase(options, 'complete', { operationId: journal.operationId, journalPath: localPath(root, JOURNAL_RELATIVE) });\n return recoveryResult('committed', journal);\n }\n for (const operation of [...journal.operations].reverse()) {\n const current = currentImage(root, operation.path);\n if (sameImage(current, operation.before)) continue;\n writeImage(root, operation.path, operation.before);\n }\n if (journal.oldAuthority && journal.newAuthority) {\n // Authority preimages are ordinary journal operations. Reversing them\n // above deletes the new authority and restores the old one in a\n // recoverable order; no second manifest write is needed here.\n } else if (journal.oldManifest) {\n const oldManifest = Buffer.from(journal.oldManifest.data, 'base64');\n const manifestRel = manifestPath(journal.profile);\n const temp = localPath(root, `${manifestRel}.recovery-${journal.operationId}`);\n durableWrite(temp, oldManifest);\n parseInstallationManifest(readFileSync(temp, 'utf8'));\n fs.renameSync(temp, localPath(root, manifestRel));\n } else {\n const manifest = localPath(root, manifestPath(journal.profile));\n if (existsSync(manifest)) unlinkSync(manifest);\n }\n cleanupKnown(root, journal);\n hitPhase(options, 'complete', { operationId: journal.operationId, journalPath: localPath(root, JOURNAL_RELATIVE) });\n return recoveryResult('rolled-back', journal);\n } finally {\n unlock(handle);\n }\n}\n\n/** Restore the retained last-successful backup after checking every precondition. */\nexport function rollbackLastSuccessfulUpdate(root: string, options: TransactionOptions = {}): TransactionResult {\n const descriptorPath = localPath(root, LAST_SUCCESSFUL_RELATIVE);\n if (!existsSync(descriptorPath)) return { status: 'none', diagnostics: [], conflicts: [] };\n let backup: SuccessfulBackup;\n try { backup = decode(JSON.parse(readFileSync(descriptorPath, 'utf8'))) as SuccessfulBackup; } catch (error) {\n return attention(`Unable to read the retained successful backup: ${String(error)}`);\n }\n try {\n validateJournal(root, backup as unknown as TransactionJournal);\n } catch (error) {\n return attention(`Unable to use the retained successful backup safely: ${String(error)}`);\n }\n const handle = lock(root, backup.operationId);\n if (!handle) return attention('Another Joycraft updater holds the project lock.');\n try {\n let lockedBackup: SuccessfulBackup;\n try { lockedBackup = decode(JSON.parse(readFileSync(descriptorPath, 'utf8'))) as SuccessfulBackup; } catch (error) {\n return attention(`Unable to re-read the retained successful backup safely: ${String(error)}`);\n }\n if (lockedBackup.operationId !== backup.operationId || lockedBackup.newManifestDigest !== backup.newManifestDigest) {\n return attention('The retained successful backup changed while acquiring the project lock.');\n }\n backup = lockedBackup;\n validateJournal(root, backup as unknown as TransactionJournal);\n if (backup.oldAuthority && backup.newAuthority) {\n const oldInfo = readInstallationManifestInfo(root, backup.oldAuthority.profile);\n const newInfo = readInstallationManifestInfo(root, backup.newAuthority.profile);\n if (oldInfo.status !== 'missing' || newInfo.status !== 'valid' || !newInfo.manifest || manifestDigest(newInfo.manifest) !== backup.newManifestDigest) {\n return { status: 'conflict', operationId: backup.operationId, diagnostics: ['Current manifest authority no longer matches the successful update; rollback is guarded.'], conflicts: [manifestPath(backup.newAuthority.profile)] };\n }\n } else {\n const info = readInstallationManifestInfo(root, backup.profile);\n if (info.status !== 'valid' || !info.manifest || manifestDigest(info.manifest) !== backup.newManifestDigest) {\n return { status: 'conflict', operationId: backup.operationId, diagnostics: ['Current manifest no longer matches the successful update; rollback is guarded.'], conflicts: [manifestPath(backup.profile)] };\n }\n }\n const conflicts: string[] = [];\n for (const operation of backup.operations) if (!sameImage(currentImage(root, operation.path), operation.after)) conflicts.push(operation.path);\n if (conflicts.length) return { status: 'conflict', operationId: backup.operationId, diagnostics: ['Current files changed after the successful update; rollback left them untouched.'], conflicts };\n for (const operation of [...backup.operations].reverse()) writeImage(root, operation.path, operation.before);\n if (backup.oldAuthority && backup.newAuthority) {\n // Manifest authority is restored by the journaled authority operations\n // above. Their reverse order also prevents a window with two owners.\n } else if (backup.oldManifest) {\n const manifestRel = manifestPath(backup.profile);\n const temp = localPath(root, `${manifestRel}.rollback-${backup.operationId}`);\n durableWrite(temp, Buffer.from(backup.oldManifest.data, 'base64'));\n parseInstallationManifest(readFileSync(temp, 'utf8'));\n fs.renameSync(temp, localPath(root, manifestRel));\n } else {\n const manifestRel = manifestPath(backup.profile);\n if (existsSync(localPath(root, manifestRel))) unlinkSync(localPath(root, manifestRel));\n }\n hitPhase(options, 'complete', { operationId: backup.operationId, journalPath: descriptorPath });\n return { status: 'rolled-back', operationId: backup.operationId, backupPath: localPath(root, backup.backupRelative), diagnostics: [], conflicts: [] };\n } finally {\n unlock(handle);\n }\n}\n","import { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nexport function getPackageVersion(): string {\n const pkgPath = join(__dirname, '..', 'package.json');\n const raw = readFileSync(pkgPath, 'utf-8');\n const pkg = JSON.parse(raw) as { version?: unknown };\n if (typeof pkg.version !== 'string' || pkg.version.length === 0) {\n throw new Error(`Joycraft package.json at ${pkgPath} is missing a version field`);\n }\n return pkg.version;\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Paths Joycraft marks `linguist-generated=true` so GitHub collapses them in\n * PR review and drops them from diff stats. These are workflow exhaust —\n * briefs, specs, discoveries, installed templates — historical artifacts by\n * the time a PR is opened (the spec was reviewed conversationally when it was\n * written). Reviewers can still expand any of them with one click.\n *\n * Deliberately NOT listed (durable knowledge that deserves review eyes):\n * CLAUDE.md, AGENTS.md, docs/context/ (steers every future agent run), and\n * docs/backlog/ (human-authored idea capture).\n */\nexport const GITATTRIBUTES_COMMENT =\n '# Joycraft: collapse generated workflow docs in PR review (expand with one click)';\n\nexport const GITATTRIBUTES_ENTRIES = [\n 'docs/features/** linguist-generated=true',\n 'docs/bugfixes/** linguist-generated=true',\n 'docs/discoveries/** linguist-generated=true',\n 'docs/templates/** linguist-generated=true',\n];\n\nexport interface GitattributesPlan {\n content: string;\n added: string[];\n}\n\n/** Plan append-only generated-file attributes without filesystem access. */\nexport function planGitattributes(current: string): GitattributesPlan {\n const present = new Set(current.split('\\n').map((line) => line.trim()));\n const missing = GITATTRIBUTES_ENTRIES.filter((entry) => !present.has(entry.trim()));\n if (missing.length === 0) return { content: current, added: [] };\n const lines = present.has(GITATTRIBUTES_COMMENT) ? missing : [GITATTRIBUTES_COMMENT, ...missing];\n const separator = current.length > 0 && !current.endsWith('\\n') ? '\\n' : '';\n return { content: current + separator + lines.join('\\n') + '\\n', added: missing };\n}\n\n/**\n * Append-only, create-if-absent, idempotent .gitattributes writer — the same\n * contract as ensureGitignoreEntries: never rewrites, reorders, or removes\n * existing lines; only appends entries not already present (matched exactly,\n * after trimming). The comment header is only added when at least one entry\n * is missing, so a fully-applied file is never touched. Returns the entries\n * actually added (empty when everything was already present).\n */\nexport function applyGitattributes(targetDir: string): string[] {\n const gitattributesPath = join(targetDir, '.gitattributes');\n const current = existsSync(gitattributesPath) ? readFileSync(gitattributesPath, 'utf-8') : '';\n const planned = planGitattributes(current);\n if (planned.added.length > 0) writeFileSync(gitattributesPath, planned.content, 'utf-8');\n return planned.added;\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","import { createInterface } from 'node:readline';\nimport type { Harness } from './harness.js';\n\n/**\n * The per-project **Execution Profile** (decision D6 of the succinct-gates\n * feature): which harness agents may fan out into swarms, and which model +\n * effort those agents should run at.\n *\n * It lives in exactly one home — a sentinel-delimited `## Execution Profile`\n * section in AGENTS.md. No state.json mirror: the profile is team-shared data\n * the human owns and hand-edits, and two homes for one fact violate ONE_HOME.\n *\n * It is **data only**. Nothing here recommends a model, ranks tiers, or routes\n * a stage to an agent — opinionated defaults stay in the backlogged\n * model-tiering feature (`docs/backlog/2026-07-20-model-tiering.md`, D7).\n * That is also why model and effort are free text: model names age faster than\n * Joycraft releases, so an enum here would be wrong within a minor version.\n */\n\n/** Opening sentinel — the only machine contract; everything inside is user-owned. */\nexport const EXECUTION_PROFILE_OPEN = '<!-- joycraft:execution-profile -->';\n/** Closing sentinel. */\nexport const EXECUTION_PROFILE_CLOSE = '<!-- /joycraft:execution-profile -->';\n\n/** The markdown heading the section is written under. */\nexport const EXECUTION_PROFILE_HEADING = '## Execution Profile';\n\n/**\n * The value written for model/effort when nobody was asked (non-interactive\n * init). Deliberately not a model name — it tells downstream skills \"use\n * whatever the session is already running\", which is the only answer that\n * can't go stale.\n */\nexport const SESSION_DEFAULT = 'session default';\n\nexport interface ExecutionProfileEntry {\n harness: Harness;\n /** Fan out to a swarm of subagents during `/joycraft-decompose`? */\n swarmDecompose: boolean;\n /** Fan out to a swarm of subagents during `/joycraft-implement`? */\n swarmImplement: boolean;\n /** Free-text model name, or SESSION_DEFAULT. Never validated against a list. */\n model: string;\n /** Free-text reasoning effort, or SESSION_DEFAULT. */\n effort: string;\n}\n\nexport interface ExecutionProfile {\n entries: ExecutionProfileEntry[];\n}\n\n/**\n * The profile written when nobody could be asked: skipping is first-class, so\n * the section is still written — with explicit \"no\" answers — rather than being\n * omitted. Downstream skills then read an explicit answer, never an absence.\n */\nexport function defaultExecutionProfile(harnesses: readonly Harness[]): ExecutionProfile {\n return {\n entries: harnesses.map((harness) => ({\n harness,\n swarmDecompose: false,\n swarmImplement: false,\n model: SESSION_DEFAULT,\n effort: SESSION_DEFAULT,\n })),\n };\n}\n\nfunction yn(value: boolean): string {\n return value ? 'yes' : 'no';\n}\n\n/** True when the document already carries a profile region (matched on the sentinel, not the heading). */\nexport function hasExecutionProfile(content: string): boolean {\n return content.includes(EXECUTION_PROFILE_OPEN);\n}\n\n/**\n * Render the section. One line per selected harness, so a single-harness\n * project never sees rows it didn't ask for.\n */\nexport function renderExecutionProfileSection(profile: ExecutionProfile): string {\n const lines: string[] = [EXECUTION_PROFILE_HEADING, '', EXECUTION_PROFILE_OPEN];\n for (const e of profile.entries) {\n lines.push(\n `- ${e.harness}: Swarms: decompose ${yn(e.swarmDecompose)} · implement ${yn(e.swarmImplement)} · model ${e.model} · effort ${e.effort}`\n );\n }\n lines.push(EXECUTION_PROFILE_CLOSE);\n return lines.join('\\n');\n}\n\n/**\n * Insert the section into an existing document when absent; return the document\n * untouched when a profile is already there. The sentinels make the region\n * opaque — a hand-edit inside them (even a malformed one) is preserved verbatim,\n * because the content is the user's data, not our schema (D7).\n */\nexport function ensureExecutionProfileSection(\n existing: string,\n profile: ExecutionProfile | undefined\n): string {\n if (!profile || hasExecutionProfile(existing)) return existing;\n return existing.trimEnd() + '\\n\\n' + renderExecutionProfileSection(profile) + '\\n';\n}\n\n/**\n * Ask one question, following the one-interface-per-prompt idiom the rest of\n * the CLI uses (`harness.ts`, `gitignore.ts`): open readline, ask, close.\n *\n * EOF matters more here than for those one-shot prompts, because this\n * interview asks several questions in a row: a stdin that runs out mid-way\n * (piped input, a redirect, Ctrl-D) must degrade every remaining question to\n * its stated default rather than hang or throw. Configuration questions never\n * abort an init.\n */\nfunction ask(question: string): Promise<string> {\n return new Promise((resolve) => {\n const input = process.stdin;\n // A stream that already ended emits no further 'close' on a *new* readline\n // interface, so the close-guard below never fires and the question hangs\n // forever. Detect the spent stream up front instead: this is the path a\n // short piped answer list takes once it runs out, and every remaining\n // question must degrade to its default rather than block the init.\n if (input.readableEnded === true || input.destroyed === true) {\n resolve('');\n return;\n }\n const rl = createInterface({ input, output: process.stdout });\n let settled = false;\n const done = (value: string): void => {\n if (settled) return;\n settled = true;\n rl.close();\n resolve(value);\n };\n rl.once('close', () => done(''));\n try {\n rl.question(question, (answer) => done(answer.trim()));\n } catch {\n done('');\n }\n });\n}\n\nasync function askYesNo(question: string): Promise<boolean> {\n for (let attempt = 0; attempt < 5; attempt++) {\n const answer = (await ask(`${question} [y/N]: `)).toLowerCase();\n if (answer === '' || answer === 'n' || answer === 'no') return false;\n if (answer === 'y' || answer === 'yes') return true;\n console.log(\"Please answer 'y' or 'n'.\");\n }\n // Repeated unparseable input (or a closed stream): take the default rather\n // than looping forever.\n return false;\n}\n\n/**\n * Interactive capture, one small block per selected harness. Follows the\n * harness-selection idiom in `harness.ts`: same readline interface, empty\n * answer means the stated default, unrecognized input re-asks.\n */\nasync function promptExecutionProfileInteractive(\n harnesses: readonly Harness[]\n): Promise<ExecutionProfile> {\n console.log('\\nExecution profile — how should agents run on this project?');\n console.log(' (Recorded in AGENTS.md as data. Press Enter to accept the default.)');\n const entries: ExecutionProfileEntry[] = [];\n for (const harness of harnesses) {\n console.log(`\\n ${harness}:`);\n const swarmDecompose = await askYesNo(' Use swarms for decompose?');\n const swarmImplement = await askYesNo(' Use swarms for implement?');\n const model = (await ask(` Model (${SESSION_DEFAULT}): `)) || SESSION_DEFAULT;\n const effort = (await ask(` Effort (${SESSION_DEFAULT}): `)) || SESSION_DEFAULT;\n entries.push({ harness, swarmDecompose, swarmImplement, model, effort });\n }\n return { entries };\n}\n\n/**\n * Resolve the profile for an init run:\n * - interactive (TTY): ask per selected harness\n * - non-interactive: the explicit-no default — never blocks a scripted run\n */\nexport async function resolveExecutionProfile(\n harnesses: readonly Harness[],\n interactive: boolean\n): Promise<ExecutionProfile> {\n if (harnesses.length === 0) return { entries: [] };\n if (interactive) return promptExecutionProfileInteractive(harnesses);\n return defaultExecutionProfile(harnesses);\n}\n","import {\n existsSync,\n lstatSync,\n readFileSync,\n readdirSync,\n statSync,\n} from 'node:fs';\nimport { basename, join } from 'node:path';\n\nimport type { StackInfo } from './detect.js';\nimport type { ExecutionProfile } from './execution-profile.js';\nimport { generateAgentsMd } from './agents-md.js';\nimport {\n generateCLAUDEMd,\n generateClaudeMdPointer,\n insertModelProfilePointer,\n} from './improve-claude-md.js';\nimport { selectsModelProfile } from './model-profile.js';\nimport { generatePermissions } from './permissions.js';\nimport { planPiExcludedFromTsconfig } from './tsconfig.js';\nimport type { Harness } from './harness.js';\nimport {\n rawFileHash,\n type InstallationManifest,\n} from './install-manifest.js';\nimport type { BundleInventoryEntry } from './bundle-inventory.js';\nimport type { GitignoreProfile } from './version.js';\n\n/** The exact first-run backlog stub retained from the legacy init flow. */\nexport const 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\n/**\n * The first-run intent inbox README. Editable source of truth:\n * `src/templates/intent/README.md` (a test asserts the two are identical).\n */\nexport const INTENT_README = `# Intent inbox\n\nAn intent is a short note that describes a need before anyone commits to\nbuilding it: a customer bug, a product idea, a ticket from another system, or\nan alert. Put intents here, one file per intent. Nothing needs to decide on a\nfeature name first.\n\n- One file per intent: \\`docs/intent/YYYY-MM-DD-<short-name>.md\\`.\n- Use the shape in \\`docs/templates/INTENT_TEMPLATE.md\\`: Author, Status,\n \\`source\\`, Problem, Proposed outcome, Affected users and systems,\n Constraints, Open questions.\n- A new intent starts with \\`Status: untriaged\\`. Joycraft skills update that\n line when they triage or consume the intent. The file stays here afterwards.\n- \\`source:\\` records where the intent came from, for example \\`human\\`,\n \\`interview\\`, \\`linear:<id>\\`, or \\`alert:<name>\\`. It is free text.\n\n## How intents map to Joycraft artifacts\n\nAnthropic's AI-native development playbook names a chain of artifacts. Joycraft\nalready has most of them under its own names. Nothing is renamed. Use the\nJoycraft names below.\n\n| Playbook term | Joycraft artifact | Where it lives |\n|---------------|-------------------|----------------|\n| intent | intent | \\`docs/intent/<name>.md\\` |\n| spec | brief | \\`docs/features/<slug>/brief.md\\` |\n| plan | design + atomic specs | \\`docs/features/<slug>/design.md\\` and \\`docs/features/<slug>/specs/\\` |\n\nAn intent becomes a brief through \\`/joycraft-new-feature\\`, or a bugfix spec\nthrough \\`/joycraft-bugfix\\`. The brief, design, and specs keep their current\nnames and folders.\n`;\n\nexport interface InventoryPatchOperation {\n path: string;\n kind: 'write';\n content: string;\n currentPresent: boolean;\n rawPrecondition?: string;\n reason: string;\n}\n\nexport interface InventorySetup {\n /** Empty directories the transaction should create after successful apply. */\n directories: string[];\n /** Existing non-Joycraft Claude skill directory names for the generators. */\n existingSkills: string[];\n /** Settings/tsconfig writes that must be converted into transaction actions. */\n patchOperations: InventoryPatchOperation[];\n}\n\nexport interface FreshInventoryInput {\n root: string;\n entries: readonly BundleInventoryEntry[];\n manifest: InstallationManifest;\n harnesses: readonly Harness[];\n profile: GitignoreProfile;\n stack: StackInfo;\n executionProfile?: ExecutionProfile;\n disableAutoMemory?: boolean;\n /** True only for the fresh-install/setup path. */\n freshInstall?: boolean;\n /** Explicit init/setup request to configure an existing Claude settings file. */\n configureClaude?: boolean;\n /** Explicit legacy init force; only known generated documents are eligible. */\n force?: boolean;\n /** Optional bridge behavior; the unified command may own this action itself. */\n retireLegacyChecker?: boolean;\n}\n\nexport interface MaterializedInventory {\n entries: BundleInventoryEntry[];\n setup: InventorySetup;\n diagnostics: string[];\n}\n\nconst CLAUDE_SETTINGS = '.claude/settings.json';\nconst TS_CONFIG = 'tsconfig.json';\nconst KNOWN_GENERATED_DOCUMENTS = new Set(['CLAUDE.md', 'AGENTS.md']);\nconst SAFE_GUARD_HOOK = '.claude/hooks/joycraft/block-dangerous.sh';\nconst UPDATE_CHECK_HOOK = 'node .claude/hooks/joycraft-version-check.mjs';\n\nfunction regularFile(root: string, relative: string): boolean {\n try {\n return lstatSync(join(root, ...relative.split('/'))).isFile();\n } catch {\n return false;\n }\n}\n\nfunction isDirectory(root: string, relative: string): boolean {\n try {\n return lstatSync(join(root, ...relative.split('/'))).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction existingPath(root: string, relative: string): boolean {\n try {\n lstatSync(join(root, ...relative.split('/')));\n return true;\n } catch {\n return false;\n }\n}\n\nfunction projectName(root: string): string {\n return (root.split(/[\\\\/]/).filter(Boolean).pop() ?? basename(root)) || 'project';\n}\n\nfunction existingClaudeSkills(root: string, selected: readonly Harness[]): string[] {\n if (!selected.includes('claude')) return [];\n const directory = join(root, '.claude', 'skills');\n try {\n return readdirSync(directory, { withFileTypes: true })\n .filter((entry) => !entry.name.startsWith('joycraft-') && !entry.name.startsWith('.'))\n .filter((entry) => {\n try {\n return statSync(join(directory, entry.name)).isDirectory();\n } catch {\n return false;\n }\n })\n .map((entry) => entry.name);\n } catch {\n return [];\n }\n}\n\n/**\n * Any non-Claude harness makes AGENTS.md the shared memory file and CLAUDE.md\n * an `@AGENTS.md` import pointer; a Claude-only selection keeps CLAUDE.md.\n */\nfunction sharesAgentsMd(harnesses: readonly Harness[]): boolean {\n return harnesses.some((harness) => harness !== 'claude');\n}\n\n/** The one memory file this selection designates (see generatorContent). */\nfunction memoryFilePath(harnesses: readonly Harness[]): 'CLAUDE.md' | 'AGENTS.md' {\n return sharesAgentsMd(harnesses) ? 'AGENTS.md' : 'CLAUDE.md';\n}\n\nfunction generatorContent(\n root: string,\n path: string,\n harnesses: readonly Harness[],\n profile: GitignoreProfile,\n stack: StackInfo,\n existingSkills: string[],\n executionProfile: ExecutionProfile | undefined,\n): string | undefined {\n const multiTool = sharesAgentsMd(harnesses);\n const modelProfilePointer = selectsModelProfile(harnesses);\n if (path === 'CLAUDE.md') {\n return multiTool\n ? generateClaudeMdPointer()\n : generateCLAUDEMd(projectName(root), stack, existingSkills, {\n privateProfile: profile === 'private',\n projectDir: root,\n modelProfilePointer,\n });\n }\n if (path === 'AGENTS.md') {\n // Claude-only: CLAUDE.md is the memory file and carries the pointer, so the\n // companion AGENTS.md stays without it (one pointer per project).\n return multiTool\n ? generateCLAUDEMd(projectName(root), stack, existingSkills, {\n privateProfile: profile === 'private',\n multiTool: true,\n executionProfile,\n projectDir: root,\n modelProfilePointer,\n })\n : generateAgentsMd(projectName(root), stack, profile === 'private', executionProfile, undefined, root);\n }\n return undefined;\n}\n\nfunction materializeDocuments(\n input: FreshInventoryInput,\n existingSkills: string[],\n): BundleInventoryEntry[] {\n return input.entries.flatMap((entry) => {\n // Config patches for settings are converted into one transaction operation\n // below. Keeping them out of the planner avoids ambiguous same-path\n // selector composition while preserving the rest of the supplied bundle.\n if (entry.path === CLAUDE_SETTINGS && entry.kind === 'config-patch') return [];\n if (entry.kind !== 'create-once') return [entry];\n\n const exists = regularFile(input.root, entry.path);\n const recorded = input.manifest.files[entry.path] !== undefined;\n const forceKnown = input.force === true && KNOWN_GENERATED_DOCUMENTS.has(entry.path);\n\n if (entry.content !== undefined) {\n if (!exists || forceKnown) return [entry];\n return [];\n }\n\n const content = generatorContent(\n input.root,\n entry.path,\n input.harnesses,\n input.profile,\n input.stack,\n existingSkills,\n input.executionProfile,\n );\n if (content === undefined) return [];\n // Preserve a previously-created document, including a local deletion. A\n // force run can review only the two generated boundary documents.\n if ((!exists && !recorded) || forceKnown) {\n return [{ ...entry, installable: true, content }];\n }\n return [];\n });\n}\n\nfunction freshSettingsEntry(input: FreshInventoryInput): BundleInventoryEntry | undefined {\n if (!input.freshInstall || !input.harnesses.includes('claude') || existingPath(input.root, CLAUDE_SETTINGS)) return undefined;\n const permissions = generatePermissions(input.stack);\n const settings: Record<string, unknown> = {\n env: { CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1' },\n hooks: {\n SessionStart: [{\n matcher: '',\n hooks: [{ type: 'command', command: UPDATE_CHECK_HOOK }],\n }],\n PreToolUse: [{\n matcher: 'Bash',\n hooks: [{ type: 'command', command: SAFE_GUARD_HOOK }],\n }],\n },\n permissions,\n };\n if (input.disableAutoMemory === true) settings.autoMemoryEnabled = false;\n return {\n path: CLAUDE_SETTINGS,\n harness: 'claude',\n kind: 'create-once',\n ownership: 'managed',\n active: true,\n installable: true,\n content: JSON.stringify(settings, null, 2) + '\\n',\n };\n}\n\nfunction freshBacklogEntry(input: FreshInventoryInput): BundleInventoryEntry | undefined {\n if (!input.freshInstall || regularFile(input.root, 'docs/backlog/README.md')) return undefined;\n if (existingPath(input.root, 'docs/backlog/README.md')) return undefined;\n return {\n path: 'docs/backlog/README.md',\n harness: 'shared',\n kind: 'create-once',\n ownership: 'managed',\n active: true,\n installable: true,\n content: BACKLOG_README,\n };\n}\n\nfunction freshIntentEntry(input: FreshInventoryInput): BundleInventoryEntry | undefined {\n if (!input.freshInstall) return undefined;\n // Never write into a docs/intent that is a regular file or any other non-directory.\n if (existingPath(input.root, 'docs/intent') && !isDirectory(input.root, 'docs/intent')) return undefined;\n if (existingPath(input.root, 'docs/intent/README.md')) return undefined;\n return {\n path: 'docs/intent/README.md',\n harness: 'shared',\n kind: 'create-once',\n ownership: 'managed',\n active: true,\n installable: true,\n content: INTENT_README,\n };\n}\n\nfunction parseSettings(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw);\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction arraySetting(value: unknown): string[] | undefined {\n if (value === undefined) return [];\n if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) return undefined;\n return [...value] as string[];\n}\n\nfunction addIfMissing(target: string[], values: readonly string[]): boolean {\n let changed = false;\n for (const value of values) {\n if (!target.includes(value)) {\n target.push(value);\n changed = true;\n }\n }\n return changed;\n}\n\nfunction safeguardHookPresent(value: unknown): boolean {\n if (!Array.isArray(value)) return false;\n return value.some((record) => {\n if (!record || typeof record !== 'object' || Array.isArray(record)) return false;\n const hooks = (record as Record<string, unknown>).hooks;\n return Array.isArray(hooks) && hooks.some((hook) =>\n hook && typeof hook === 'object' && !Array.isArray(hook)\n && (hook as Record<string, unknown>).command === SAFE_GUARD_HOOK,\n );\n });\n}\n\nfunction updateCheckHookPresent(value: unknown): boolean {\n if (!Array.isArray(value)) return false;\n return value.some((record) => {\n if (!record || typeof record !== 'object' || Array.isArray(record)) return false;\n const hooks = (record as Record<string, unknown>).hooks;\n return Array.isArray(hooks) && hooks.some((hook) =>\n hook && typeof hook === 'object' && !Array.isArray(hook)\n && (hook as Record<string, unknown>).command === UPDATE_CHECK_HOOK,\n );\n });\n}\n\nfunction mergeOwnedSettings(\n raw: string,\n input: FreshInventoryInput,\n allowGenerated: boolean,\n diagnostics: string[],\n): string | undefined {\n const settings = parseSettings(raw);\n if (!settings) {\n diagnostics.push('settings.json is malformed or not an object; preserving it without generated setup changes.');\n return undefined;\n }\n let changed = false;\n\n if (allowGenerated) {\n const env = settings.env === undefined\n ? (settings.env = {}, settings.env as Record<string, unknown>)\n : settings.env && typeof settings.env === 'object' && !Array.isArray(settings.env)\n ? settings.env as Record<string, unknown>\n : undefined;\n if (!env) {\n diagnostics.push('settings.json has a non-object env value; preserving it without generated setup changes.');\n return undefined;\n }\n if (!Object.prototype.hasOwnProperty.call(env, 'CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS')) {\n env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = '1';\n changed = true;\n }\n\n const permissions = settings.permissions === undefined\n ? (settings.permissions = {}, settings.permissions as Record<string, unknown>)\n : settings.permissions && typeof settings.permissions === 'object' && !Array.isArray(settings.permissions)\n ? settings.permissions as Record<string, unknown>\n : undefined;\n if (!permissions) {\n diagnostics.push('settings.json has a non-object permissions value; preserving it without generated setup changes.');\n return undefined;\n }\n const allow = arraySetting(permissions.allow);\n const deny = arraySetting(permissions.deny);\n if (!allow || !deny) {\n diagnostics.push('settings.json has a non-array permissions list; preserving it without generated setup changes.');\n return undefined;\n }\n changed = addIfMissing(allow, generatePermissions(input.stack).allow) || changed;\n changed = addIfMissing(deny, generatePermissions(input.stack).deny) || changed;\n permissions.allow = allow;\n permissions.deny = deny;\n\n const hooks = settings.hooks === undefined\n ? (settings.hooks = {}, settings.hooks as Record<string, unknown>)\n : settings.hooks && typeof settings.hooks === 'object' && !Array.isArray(settings.hooks)\n ? settings.hooks as Record<string, unknown>\n : undefined;\n if (!hooks) {\n diagnostics.push('settings.json has a non-object hooks value; preserving it without generated setup changes.');\n return undefined;\n }\n const preToolUse = hooks.PreToolUse === undefined\n ? (hooks.PreToolUse = [], hooks.PreToolUse as unknown[])\n : hooks.PreToolUse;\n if (!Array.isArray(preToolUse)) {\n diagnostics.push('settings.json has a non-array hooks.PreToolUse value; preserving it without generated setup changes.');\n return undefined;\n }\n if (!safeguardHookPresent(preToolUse)) {\n preToolUse.push({ matcher: 'Bash', hooks: [{ type: 'command', command: SAFE_GUARD_HOOK }] });\n changed = true;\n }\n\n const sessionStart = hooks.SessionStart === undefined\n ? (hooks.SessionStart = [], hooks.SessionStart as unknown[])\n : hooks.SessionStart;\n if (!Array.isArray(sessionStart)) {\n diagnostics.push('settings.json has a non-array hooks.SessionStart value; preserving it without generated setup changes.');\n return undefined;\n }\n if (!updateCheckHookPresent(sessionStart)) {\n sessionStart.push({ matcher: '', hooks: [{ type: 'command', command: UPDATE_CHECK_HOOK }] });\n changed = true;\n }\n }\n\n if (input.disableAutoMemory === true && !Object.prototype.hasOwnProperty.call(settings, 'autoMemoryEnabled')) {\n settings.autoMemoryEnabled = false;\n changed = true;\n }\n if (!changed) return undefined;\n const newline = raw.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const serialized = JSON.stringify(settings, null, 2).replace(/\\r?\\n/g, newline);\n return raw.endsWith('\\n') || raw.endsWith('\\r') ? serialized + newline : serialized;\n}\n\nfunction retireLegacyChecker(raw: string, diagnostics: string[]): string | undefined {\n const settings = parseSettings(raw);\n if (!settings) {\n diagnostics.push('settings.json is malformed or not an object; preserving it without legacy checker retirement.');\n return undefined;\n }\n const hooks = settings.hooks;\n if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return undefined;\n const sessionStart = (hooks as Record<string, unknown>).SessionStart;\n if (!Array.isArray(sessionStart)) return undefined;\n const checker = 'node .claude/hooks/joycraft-version-check.mjs';\n let found = false;\n const nextSessionStart = sessionStart.flatMap((entry) => {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return [entry];\n const record = entry as Record<string, unknown>;\n if (!Array.isArray(record.hooks)) return [entry];\n const nextHooks = record.hooks.filter((hook) => {\n const command = hook && typeof hook === 'object' && !Array.isArray(hook)\n ? (hook as Record<string, unknown>).command\n : undefined;\n if (command === checker) {\n found = true;\n return false;\n }\n return true;\n });\n return nextHooks.length ? [{ ...record, hooks: nextHooks }] : [];\n });\n if (!found) return undefined;\n const nextSettings = { ...settings, hooks: { ...(hooks as Record<string, unknown>), SessionStart: nextSessionStart } };\n const newline = raw.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const serialized = JSON.stringify(nextSettings, null, 2).replace(/\\r?\\n/g, newline);\n return raw.endsWith('\\n') || raw.endsWith('\\r') ? serialized + newline : serialized;\n}\n\nfunction settingsPatch(input: FreshInventoryInput, diagnostics: string[]): InventoryPatchOperation | undefined {\n if (!input.harnesses.includes('claude') || !regularFile(input.root, CLAUDE_SETTINGS)) return undefined;\n const path = join(input.root, ...CLAUDE_SETTINGS.split('/'));\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n diagnostics.push('settings.json could not be read; preserving it without generated setup changes.');\n return undefined;\n }\n const allowGenerated = input.freshInstall === true || input.configureClaude === true;\n let next = mergeOwnedSettings(raw, input, allowGenerated, diagnostics);\n if (next === undefined) next = raw;\n if (input.retireLegacyChecker === true) {\n const retired = retireLegacyChecker(next, diagnostics);\n if (retired !== undefined) next = retired;\n }\n if (next === raw) return undefined;\n return {\n path: CLAUDE_SETTINGS,\n kind: 'write',\n content: next,\n currentPresent: true,\n rawPrecondition: rawFileHash(raw),\n reason: allowGenerated\n ? 'Apply the selected initial Claude setup while preserving unrelated settings.'\n : 'Apply the explicitly selected auto-memory preference while preserving unrelated Claude settings.',\n };\n}\n\nfunction tsconfigPatch(input: FreshInventoryInput, diagnostics: string[]): InventoryPatchOperation | undefined {\n if (!input.freshInstall || !input.harnesses.includes('pi') || !regularFile(input.root, TS_CONFIG)) return undefined;\n const path = join(input.root, TS_CONFIG);\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n diagnostics.push('tsconfig.json could not be read; add \".pi\" to its exclude array manually.');\n return undefined;\n }\n const planned = planPiExcludedFromTsconfig(raw);\n if (planned.status === 'already-present') return undefined;\n if (planned.status === 'skipped') {\n diagnostics.push(planned.reason);\n return undefined;\n }\n return {\n path: TS_CONFIG,\n kind: 'write',\n content: planned.content,\n currentPresent: true,\n rawPrecondition: rawFileHash(raw),\n reason: 'Exclude the installed Pi runtime from the project TypeScript program while preserving the existing tsconfig bytes.',\n };\n}\n\n/**\n * Insert the one model-profile Context Map row into an existing memory file\n * (D14). Only the selection's designated file is read; the operation exists\n * only when the bytes would change, so a second run reports nothing. It never\n * creates or resurrects the file, and never removes a row (D14 keeps cleanup\n * advisory).\n */\nfunction contextMapPointerPatch(\n input: FreshInventoryInput,\n entries: readonly BundleInventoryEntry[],\n diagnostics: string[],\n): InventoryPatchOperation | undefined {\n if (!selectsModelProfile(input.harnesses)) return undefined;\n const memory = memoryFilePath(input.harnesses);\n if (!regularFile(input.root, memory)) return undefined;\n // A generated document written in this same run already carries the row.\n if (entries.some((entry) => entry.path === memory && entry.content !== undefined)) return undefined;\n let raw: string;\n try {\n raw = readFileSync(join(input.root, memory), 'utf8');\n } catch {\n diagnostics.push(`${memory} could not be read; add the model profile row to its Context Map manually.`);\n return undefined;\n }\n const next = insertModelProfilePointer(raw);\n if (next === raw) return undefined;\n return {\n path: memory,\n kind: 'write',\n content: next,\n currentPresent: true,\n rawPrecondition: rawFileHash(raw),\n reason: 'Add one Context Map row pointing at the Claude Fable 5.1 model profile; every other byte is preserved.',\n };\n}\n\n/**\n * Read current project bytes and turn fresh-install setup into inventory\n * entries plus transaction-ready operations. This function performs no writes,\n * prompts, registry access, or mutation of the supplied inventory/manifest.\n */\nexport function materializeFreshInstallInventory(input: FreshInventoryInput): MaterializedInventory {\n const diagnostics: string[] = [];\n const existingSkills = existingClaudeSkills(input.root, input.harnesses);\n const entries = materializeDocuments(input, existingSkills);\n const known = new Set(entries.map((entry) => entry.path));\n const backlog = freshBacklogEntry(input);\n if (backlog && !known.has(backlog.path)) entries.push(backlog);\n const intent = freshIntentEntry(input);\n if (intent && !known.has(intent.path)) entries.push(intent);\n const settings = freshSettingsEntry(input);\n if (settings && !known.has(settings.path)) entries.push(settings);\n\n const directories: string[] = [];\n if (input.freshInstall) {\n for (const relative of ['docs/context', 'docs/backlog', 'docs/intent']) {\n if (!existingPath(input.root, relative)) directories.push(relative);\n else {\n try {\n if (!lstatSync(join(input.root, ...relative.split('/'))).isDirectory()) {\n diagnostics.push(`${relative} exists but is not a directory; preserving it.`);\n }\n } catch {\n diagnostics.push(`${relative} could not be inspected; preserving it.`);\n }\n }\n }\n }\n\n const patchOperations = [\n settingsPatch(input, diagnostics),\n tsconfigPatch(input, diagnostics),\n contextMapPointerPatch(input, entries, diagnostics),\n ]\n .filter((operation): operation is InventoryPatchOperation => operation !== undefined);\n return {\n entries,\n setup: { directories, existingSkills, patchOperations },\n diagnostics,\n };\n}\n","// Check-shaped folder map (D6).\n//\n// The generated architecture section is derived from the real filesystem\n// instead of a hand-maintained tree: a pure walk emits top-level folders (plus\n// key subfolders) with one-line descriptions inside sentinel markers, so init\n// and upgrade can regenerate structure while preserving human wording, and\n// tune can diff the doc against the tree and report drift instead of letting a\n// stale map mislead an agent.\n\nimport { readdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport const FOLDER_MAP_OPEN = '<!-- joycraft:folder-map -->';\nexport const FOLDER_MAP_CLOSE = '<!-- /joycraft:folder-map -->';\nexport const FOLDER_MAP_PLACEHOLDER = '_TODO: one line on what lives here_';\n\n/** Row cap — past this scale the answer is nested instruction files, not a bigger map. */\nconst MAX_ROWS = 30;\n\n/** Dirs that are dependency, build-output, VCS, or cache noise — never mapped. */\nconst SKIPPED_DIRS = new Set([\n 'node_modules', 'dist', 'build', 'out', 'coverage', 'target', 'vendor',\n '__pycache__', 'venv', '.venv', 'tmp', 'temp',\n]);\n\n/** Top-level dirs whose immediate subfolders are worth a row of their own. */\nconst KEY_PARENTS = new Set(['src', 'docs']);\n\n/** Descriptions the generator can actually know — everything else gets the placeholder. */\nconst KNOWN_DESCRIPTIONS: Record<string, string> = {\n 'src/': 'Source code',\n 'docs/': 'Documentation',\n 'tests/': 'Test suite',\n 'test/': 'Test suite',\n 'scripts/': 'Maintenance and build scripts',\n 'templates/': 'Templates',\n 'public/': 'Static assets served as-is',\n 'assets/': 'Static assets',\n 'examples/': 'Usage examples',\n 'packages/': 'Monorepo packages',\n 'apps/': 'Monorepo applications',\n 'config/': 'Configuration',\n 'docs/context/': 'Knowledge layer — operational fact-docs and reference',\n 'docs/features/': 'Per-feature briefs, designs, and atomic specs',\n 'docs/discoveries/': 'Session surprises worth remembering',\n 'docs/templates/': 'Bundled output and reference templates',\n 'docs/backlog/': 'Deferred work, one file per item',\n 'docs/intent/': 'Intent inbox — incoming work before a feature slug exists',\n 'docs/research/': 'Research notes and findings',\n};\n\nfunction listDirs(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIPPED_DIRS.has(e.name))\n .map((e) => e.name)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** Folder paths (POSIX, trailing slash) the map covers, deterministic for a given tree. */\nexport function walkFolders(dir: string): { folders: string[]; capped: boolean } {\n // Top-level folders first, then key subfolders — so a cap cuts depth, never breadth.\n const tops = listDirs(dir);\n const folders = tops.map((top) => `${top}/`);\n for (const top of tops) {\n if (KEY_PARENTS.has(top)) {\n for (const sub of listDirs(join(dir, top))) {\n folders.push(`${top}/${sub}/`);\n }\n }\n }\n const capped = folders.length > MAX_ROWS;\n return { folders: capped ? folders.slice(0, MAX_ROWS) : folders, capped };\n}\n\nfunction parseRows(block: string): Map<string, string> {\n const rows = new Map<string, string>();\n for (const line of block.split('\\n')) {\n const match = line.match(/^\\| `([^`]+)` \\| (.*) \\|$/);\n if (match) rows.set(match[1], match[2]);\n }\n return rows;\n}\n\n/**\n * The sentinel-delimited map block. When `existingBlock` is given, human\n * descriptions for surviving folders are preserved — the machine owns\n * structure, the human owns wording.\n */\nexport function renderFolderMap(dir: string, existingBlock?: string): string {\n const { folders, capped } = walkFolders(dir);\n const previous = existingBlock ? parseRows(existingBlock) : new Map<string, string>();\n\n const lines = [FOLDER_MAP_OPEN, '| Folder | What lives here |', '|--------|-----------------|'];\n for (const folder of folders) {\n const description = previous.get(folder) ?? KNOWN_DESCRIPTIONS[folder] ?? FOLDER_MAP_PLACEHOLDER;\n lines.push(`| \\`${folder}\\` | ${description} |`);\n }\n if (capped) {\n lines.push('', `_Capped at ${MAX_ROWS} rows — this tree is past root-map scale; use the growth path below._`);\n }\n lines.push(\n '',\n 'Past multi-team scale, replace this root map with nested per-directory instruction files (`joycraft-collaborative-setup`) — never a bigger tree.',\n FOLDER_MAP_CLOSE,\n );\n return lines.join('\\n');\n}\n\nconst BLOCK_RE = new RegExp(`${FOLDER_MAP_OPEN}[\\\\s\\\\S]*?${FOLDER_MAP_CLOSE}`);\n\n/**\n * Regenerate the map block in place (preserving human wording), or append an\n * `## Architecture` section carrying it when the document has none. A\n * hand-written architecture section without markers is user prose — untouched.\n */\nexport function ensureFolderMapSection(markdown: string, dir: string): string {\n const existingBlock = markdown.match(BLOCK_RE)?.[0];\n if (existingBlock) {\n return markdown.replace(BLOCK_RE, renderFolderMap(dir, existingBlock));\n }\n if (/^## .*architecture/im.test(markdown)) return markdown;\n return `${markdown.trimEnd()}\\n\\n## Architecture\\n\\n${renderFolderMap(dir)}\\n`;\n}\n\n/**\n * Structure-only drift between the document's map block and the real tree —\n * description wording (including unfilled placeholders) never counts as drift.\n * Null when the document carries no map block.\n */\nexport function diffFolderMap(markdown: string, dir: string): { added: string[]; removed: string[] } | null {\n const block = markdown.match(BLOCK_RE)?.[0];\n if (!block) return null;\n const documented = new Set(parseRows(block).keys());\n const actual = new Set(walkFolders(dir).folders);\n return {\n added: [...actual].filter((f) => !documented.has(f)),\n removed: [...documented].filter((f) => !actual.has(f)),\n };\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';\nimport { MODEL_PROFILE_CONTEXT_MAP_ROW, MODEL_PROFILE_PATH } from './model-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 * True when the selection includes a harness that receives the Claude Fable\n * 5.1 model profile (see model-profile.ts). The Context Map then carries the\n * one pointer row to it — generated fresh, or inserted into an existing table\n * without touching any other line.\n */\n modelProfilePointer?: boolean;\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\nconst CONTEXT_MAP_TABLE_HEADER = '| Document | Read it when… |\\n|----------|---------------|';\n\nexport function generateContextMapSection(modelProfilePointer = false): string {\n const row = modelProfilePointer ? `\\n${MODEL_PROFILE_CONTEXT_MAP_ROW}` : '';\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${CONTEXT_MAP_TABLE_HEADER}${row}`;\n}\n\ninterface SourceLine {\n /** Line text without its terminator or a trailing CR. */\n text: string;\n start: number;\n /** Offset just past the line terminator (or EOF). */\n end: number;\n}\n\nfunction sourceLines(content: string): SourceLine[] {\n const lines: SourceLine[] = [];\n let offset = 0;\n while (offset < content.length) {\n const newline = content.indexOf('\\n', offset);\n const end = newline === -1 ? content.length : newline + 1;\n const raw = content.slice(offset, newline === -1 ? content.length : newline);\n lines.push({ text: raw.replace(/\\r$/, ''), start: offset, end });\n offset = end;\n }\n return lines;\n}\n\nfunction insertAfterLine(content: string, line: SourceLine, block: string, newline: string): string {\n if (content[line.end - 1] === '\\n') {\n return content.slice(0, line.end) + block + newline + content.slice(line.end);\n }\n // The anchor is the final, unterminated line: keep the file unterminated.\n return content + newline + block;\n}\n\n/**\n * Scoped single-line insertion of the model-profile Context Map row (D14).\n * Returns the input unchanged when the file already names the profile path\n * anywhere. Otherwise appends the row to the end of the first table in the\n * `## Context Map` section (matched case-insensitively), adds a table when the\n * section has none, or appends the section with the row when the file has no\n * Context Map at all. The file's newline style is preserved and no other byte\n * moves.\n */\nexport function insertModelProfilePointer(content: string): string {\n if (content.includes(MODEL_PROFILE_PATH)) return content;\n const newline = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lines = sourceLines(content);\n const header = lines.findIndex((line) => line.text.startsWith('## ') && /context\\s*map/i.test(line.text));\n\n if (header === -1) {\n const section = generateContextMapSection(true).replace(/\\n/g, newline);\n if (content === '') return section + newline;\n const base = content.endsWith('\\n') ? content : content + newline;\n return base + newline + section + newline;\n }\n\n let sectionEnd = lines.length;\n for (let index = header + 1; index < lines.length; index++) {\n if (lines[index].text.startsWith('## ')) {\n sectionEnd = index;\n break;\n }\n }\n const isTableLine = (index: number) => lines[index].text.trim().startsWith('|');\n let tableStart = -1;\n for (let index = header + 1; index < sectionEnd; index++) {\n if (isTableLine(index)) {\n tableStart = index;\n break;\n }\n }\n if (tableStart !== -1) {\n let last = tableStart;\n while (last + 1 < sectionEnd && isTableLine(last + 1)) last++;\n return insertAfterLine(content, lines[last], MODEL_PROFILE_CONTEXT_MAP_ROW, newline);\n }\n\n let lastContent = header;\n for (let index = header + 1; index < sectionEnd; index++) {\n if (lines[index].text.trim() !== '') lastContent = index;\n }\n const table = ['', ...CONTEXT_MAP_TABLE_HEADER.split('\\n'), MODEL_PROFILE_CONTEXT_MAP_ROW].join(newline);\n return insertAfterLine(content, lines[lastContent], table, newline);\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 const hasContextMap = hasSection(sections, /context\\s*map/i);\n const wantsPointer = opts?.modelProfilePointer === true && !working.includes(MODEL_PROFILE_PATH);\n // Scoped step: one row into an existing Context Map, nothing else re-rendered.\n if (wantsPointer && hasContextMap) working = insertModelProfilePointer(working);\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 (!hasContextMap) {\n additions.push(generateContextMapSection(wantsPointer));\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(opts?.modelProfilePointer === true),\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 { MODEL_PROFILE_PATH } from './model-profile.js';\nimport {\n generateBoundariesSection,\n generateContextMapSection,\n generateExternalApiSafetySection,\n insertModelProfilePointer,\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 modelProfilePointer = false,\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 if (modelProfilePointer) {\n lines.push(generateContextMapSection(true), '');\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 modelProfilePointer = false,\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 const hasContextMap = hasSection(sections, /context\\s*map/i);\n const wantsPointer = modelProfilePointer && !working.includes(MODEL_PROFILE_PATH);\n // Scoped step: one row into an existing Context Map, nothing else re-rendered.\n if (wantsPointer && hasContextMap) working = insertModelProfilePointer(working);\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 (wantsPointer && !hasContextMap) {\n additions.push(generateContextMapSection(true));\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 } 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\n/** Read-only result used by update planning before a transaction writes bytes. */\nexport type TsconfigExcludePlan =\n | { status: 'added'; content: string }\n | { status: 'already-present' }\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 const planned = planPiExcludedFromTsconfig(rawText);\n if (planned.status === 'already-present') {\n return { status: 'already-present', path };\n }\n\n if (planned.status === 'skipped') return planned;\n\n try {\n writeFileSync(path, planned.content, 'utf-8');\n } catch {\n return { status: 'skipped', reason: 'tsconfig.json could not be written' };\n }\n return { status: 'added', path };\n}\n\n/**\n * Calculate the minimal `.pi` exclusion without touching the filesystem.\n * The returned bytes are suitable for a transaction operation with a raw\n * precondition supplied by the caller.\n */\nexport function planPiExcludedFromTsconfig(rawText: string): TsconfigExcludePlan {\n if (alreadyExcludesPi(rawText)) return { status: 'already-present' };\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, return no bytes.\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 return { status: 'added', content: updated };\n}\n","import { compareStableVersions, type CheckPolicy } from './update-check.js';\nimport type { InstallationManifest } from './install-manifest.js';\nimport type { UpdatePlan } from './update-plan.js';\nimport {\n isVerifiedReleaseArtifact,\n type VerifiedReleaseArtifact,\n} from './release-artifact.js';\n\nexport interface AutoSafeEligibilityInput {\n /** The policy read from project-local checker state. */\n policy: CheckPolicy;\n /** A verifier-issued proof for the exact candidate package artifact. */\n candidate?: VerifiedReleaseArtifact;\n /** Facts from the bundle that is actually about to execute. */\n executingVersion: string;\n executingIntegrity?: string;\n executingDescriptor?: unknown;\n manifestSchema?: number;\n plan: UpdatePlan;\n existingManifest?: InstallationManifest;\n replaceCustomized?: readonly string[];\n repair?: readonly string[];\n migration?: boolean;\n legacyBridge?: boolean;\n setupChanges?: boolean;\n profileChanges?: boolean;\n localOperations?: boolean;\n authorityTransition?: boolean;\n}\n\nexport interface AutoSafeEligibility {\n eligible: boolean;\n diagnostics: string[];\n}\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined;\n}\n\nfunction descriptorEqual(left: unknown, right: unknown): boolean {\n const a = object(left);\n const b = object(right);\n if (!a || !b) return false;\n return a.schemaVersion === b.schemaVersion\n && a.releaseVersion === b.releaseVersion\n && a.autoSafeEligible === b.autoSafeEligible\n && Array.isArray(a.manifestSchemas)\n && Array.isArray(b.manifestSchemas)\n && JSON.stringify(a.manifestSchemas) === JSON.stringify(b.manifestSchemas);\n}\n\n/**\n * Evaluate the complete automatic-update contract without I/O, prompts, or\n * mutation. A true result requires every independent proof to be present.\n */\nexport function evaluateAutoSafeEligibility(input: AutoSafeEligibilityInput): AutoSafeEligibility {\n const diagnostics: string[] = [];\n const reject = (message: string): void => { diagnostics.push(message); };\n if (input.policy !== 'auto-safe') reject('Automatic updates require the local auto-safe policy.');\n const candidate = input.candidate;\n if (!candidate || !isVerifiedReleaseArtifact(candidate)) {\n reject('Automatic updates require a verifier-issued exact release artifact.');\n }\n\n const release = candidate?.release;\n const descriptor = candidate?.descriptor;\n const descriptorObject = object(descriptor);\n if (candidate && release && release.packageName !== 'joycraft') reject('The verified artifact package is not Joycraft.');\n if (candidate && release && release.version !== input.executingVersion) {\n reject('The verified artifact version does not match the executing bundle.');\n }\n if (candidate && input.executingIntegrity !== undefined && release && release.integrity !== input.executingIntegrity) {\n reject('The verified artifact integrity does not match the executing bundle.');\n }\n if (input.executingDescriptor === undefined) reject('The executing bundle has no verified compatibility descriptor.');\n else if (candidate && !descriptorEqual(descriptor, input.executingDescriptor)) {\n reject('The verified compatibility descriptor does not match the executing bundle.');\n }\n if (!descriptorObject || descriptorObject.schemaVersion !== 1 || descriptorObject.releaseVersion !== release?.version) {\n reject('The verified artifact has no supported compatibility descriptor.');\n }\n if (descriptorObject?.autoSafeEligible !== true) reject('The release is not declared eligible for auto-safe updates.');\n const supportedSchemas = descriptorObject?.manifestSchemas;\n const schema = input.manifestSchema ?? input.plan.nextManifest.schemaVersion;\n if (!Array.isArray(supportedSchemas) || !supportedSchemas.includes(schema)) reject('The release does not support this manifest protocol.');\n\n if (!/^(\\d+)\\.(\\d+)\\.(\\d+)$/.test(input.executingVersion) || !release?.version || !/^(\\d+)\\.(\\d+)\\.(\\d+)$/.test(release.version)) {\n reject('Prerelease and malformed releases require an explicit update.');\n } else if (compareStableVersions(release.version, input.executingVersion) !== 0) {\n reject('Downgrades and version changes require an explicit update.');\n }\n if (!input.existingManifest) reject('Automatic updates require an existing installation manifest.');\n else if (compareStableVersions(release?.version ?? '', input.existingManifest.targetVersion) !== 1) {\n reject('The candidate is not newer than the installed release; use an explicit update.');\n }\n if (input.plan.conflicts.length > 0) reject('The update plan contains unresolved conflicts.');\n if (input.plan.actions.some((action) => action.kind === 'conflict' || action.kind === 'repair')) {\n reject('The update plan contains a conflict or repair action.');\n }\n if (input.plan.actions.some((action) => action.selected\n && (action.patch !== undefined || action.path === '.claude/settings.json')\n && !(action.currentPresent && action.targetPresent && typeof action.rawPrecondition === 'string' && action.rawPrecondition === action.rawTargetHash))) {\n reject('The update plan changes user configuration.');\n }\n if ((input.replaceCustomized?.length ?? 0) > 0) reject('Customized replacements require an explicit update.');\n if ((input.repair?.length ?? 0) > 0) reject('Repairs require an explicit update.');\n if (input.migration) reject('Migrations require an explicit update.');\n if (input.legacyBridge) reject('Legacy bridge adoption requires an explicit update.');\n if (input.setupChanges) reject('Setup and user-configuration changes require an explicit update.');\n if (input.profileChanges) reject('Profile changes require an explicit update.');\n if (input.localOperations) reject('Local state migrations require an explicit update.');\n if (input.authorityTransition) reject('Manifest authority transitions require an explicit update.');\n return { eligible: diagnostics.length === 0, diagnostics };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,cAAAA;AAAA,EACA,aAAAC;AAAA,EACA,aAAAC;AAAA,EACA,gBAAAC;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,QAAAC,QAAM,SAAS,WAAAC,gBAAe;;;ACRvC,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;AAC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,+BAA+B,OAAO,UAAU,KAAK,IAAI,CAAC,EAAE;AACpG,MAAI,OAAO,UAAU,OAAQ,OAAM,KAAK,wBAAwB,OAAO,UAAU,KAAK,IAAI,CAAC,EAAE;AAC7F,aAAW,cAAc,OAAO,YAAa,OAAM,KAAK,YAAO,UAAU,EAAE;AAC3E,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["existsSync","lstatSync","mkdirSync","readFileSync","fileURLToPath","join","dirname","existsSync","readFileSync","join","selected","selected","action","existsSync","mkdirSync","readdirSync","readFileSync","writeFileSync","object","bytes","mkdirSync","writeFileSync","existsSync","readFileSync","readdirSync","bytes","readFileSync","dirname","join","existsSync","readFileSync","writeFileSync","join","normalized","resolve","ask","interactive","createInterface","resolve","createInterface","interactive","lstatSync","readFileSync","readdirSync","statSync","join","readdirSync","join","existsSync","join","existsSync","join","projectName","generateCommandsBlock","generateArchitectureSection","generateKeyFilesSection","projectName","existsSync","readFileSync","writeFileSync","join","text","lstatSync","join","selected","readdirSync","statSync","readFileSync","selected","regularFile","lstatSync","join","readFileSync","dirname","fileURLToPath","existsSync","transaction","status","mkdirSync"]}
|