@brucewaynedecoy/make-docs 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/{backup-CM7RL2Q7.js → backup-2OT4A6LR.js} +4 -4
  2. package/dist/{chunk-GERMRLJ2.js → chunk-46MGH32G.js} +6 -4
  3. package/dist/chunk-46MGH32G.js.map +1 -0
  4. package/dist/{chunk-LV3CBXZB.js → chunk-CCYP5NU2.js} +3 -3
  5. package/dist/{chunk-OR5ZVGLG.js → chunk-CLSOY7NV.js} +151 -5
  6. package/dist/chunk-CLSOY7NV.js.map +1 -0
  7. package/dist/{chunk-ADVNSMA7.js → chunk-CMNKQM7L.js} +3 -3
  8. package/dist/{chunk-YVSASZMT.js → chunk-HXWD2EUD.js} +19 -14
  9. package/dist/chunk-HXWD2EUD.js.map +1 -0
  10. package/dist/{chunk-65QWMODG.js → chunk-I4FADOUK.js} +3 -3
  11. package/dist/{chunk-65QWMODG.js.map → chunk-I4FADOUK.js.map} +1 -1
  12. package/dist/{chunk-M7DMFIKU.js → chunk-ISSMVKIA.js} +224 -20
  13. package/dist/chunk-ISSMVKIA.js.map +1 -0
  14. package/dist/{chunk-J5QDGRZ7.js → chunk-UNR4CYVX.js} +116 -37
  15. package/dist/chunk-UNR4CYVX.js.map +1 -0
  16. package/dist/{chunk-7R2PPKTB.js → chunk-VMKG3H4B.js} +2 -2
  17. package/dist/{chunk-52FTNVXS.js → chunk-XDSWX4Y4.js} +8906 -2899
  18. package/dist/chunk-XDSWX4Y4.js.map +1 -0
  19. package/dist/index.js +210 -86
  20. package/dist/index.js.map +1 -1
  21. package/dist/registry-PC5GKAKM.js +50 -0
  22. package/dist/registry-PC5GKAKM.js.map +1 -0
  23. package/dist/{self-36ULRIJ6.js → self-WYVXO23B.js} +10 -10
  24. package/dist/server-BQOG6FTA.js +1113 -0
  25. package/dist/server-BQOG6FTA.js.map +1 -0
  26. package/dist/{setup-system-JI36YJ6D.js → setup-system-KN7FTTLT.js} +263 -40
  27. package/dist/setup-system-KN7FTTLT.js.map +1 -0
  28. package/dist/{skills-command-IGDVLNKY.js → skills-command-KEW7MOEW.js} +17 -7
  29. package/dist/skills-command-KEW7MOEW.js.map +1 -0
  30. package/dist/{uninstall-VBGMQQLA.js → uninstall-45XF4CHD.js} +9 -9
  31. package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js +11 -0
  32. package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js.map +1 -0
  33. package/package.json +5 -5
  34. package/skill-registry.json +24 -8
  35. package/skill-registry.schema.json +2 -1
  36. package/template/.make-docs/system/contracts/system-resource-contract.md +16 -0
  37. package/template/.make-docs/system-resources.catalog.json +415 -0
  38. package/template/.make-docs/system-resources.schema.json +25 -0
  39. package/dist/chunk-52FTNVXS.js.map +0 -1
  40. package/dist/chunk-GERMRLJ2.js.map +0 -1
  41. package/dist/chunk-J5QDGRZ7.js.map +0 -1
  42. package/dist/chunk-M7DMFIKU.js.map +0 -1
  43. package/dist/chunk-OR5ZVGLG.js.map +0 -1
  44. package/dist/chunk-YVSASZMT.js.map +0 -1
  45. package/dist/server-H754TA4Q.js +0 -512
  46. package/dist/server-H754TA4Q.js.map +0 -1
  47. package/dist/setup-system-JI36YJ6D.js.map +0 -1
  48. package/dist/skills-command-IGDVLNKY.js.map +0 -1
  49. package/dist/virtual_make-docs-first-party-skills-H3FC47C2.js +0 -11
  50. package/dist/virtual_make-docs-first-party-skills-H3FC47C2.js.map +0 -1
  51. /package/dist/{backup-CM7RL2Q7.js.map → backup-2OT4A6LR.js.map} +0 -0
  52. /package/dist/{chunk-LV3CBXZB.js.map → chunk-CCYP5NU2.js.map} +0 -0
  53. /package/dist/{chunk-ADVNSMA7.js.map → chunk-CMNKQM7L.js.map} +0 -0
  54. /package/dist/{chunk-7R2PPKTB.js.map → chunk-VMKG3H4B.js.map} +0 -0
  55. /package/dist/{self-36ULRIJ6.js.map → self-WYVXO23B.js.map} +0 -0
  56. /package/dist/{uninstall-VBGMQQLA.js.map → uninstall-45XF4CHD.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/operations/types.ts","../src/store/global-config.ts","../src/store/json-files.ts","../src/store/project-identity.ts","../src/store/harness-integration-receipts.ts","../src/store/harness-system-operations.ts","../src/store/global-manifest.ts","../src/store/compatibility-bridge.ts","../src/store/state-rows.ts","../src/store/lifecycle-runs.ts","../src/store/project-state.ts","../src/store/lifecycle.ts","../src/store/bootstrap.ts"],"sourcesContent":["export type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport class OperationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OperationError\";\n }\n}\n\nexport type OperationDomainName =\n | \"closeout\"\n | \"work\"\n | \"lifecycle\"\n | \"prd\";\n\nexport interface OperationProvenance {\n domain: OperationDomainName;\n operation: string;\n source: \"cli\" | \"mcp\" | \"test\" | \"shared\";\n target?: string;\n}\n\nexport type OperationRenderMode = \"json\" | \"markdown\" | \"text\";\n\n/**\n * One registry operation as surfaced by `listOperationDomains()` (R-REG-2):\n * keyed by its stable registry identifier, with the mutation classification\n * flattened to a boolean and the registry lifecycle status carried through.\n */\nexport interface OperationCommandDescriptor {\n id: string;\n summary: string;\n mutates: boolean;\n status: \"active\" | \"pending\";\n}\n\n/** Registry operations grouped by their identifier's domain segment. */\nexport interface OperationDomainDescriptor {\n name: string;\n commands: OperationCommandDescriptor[];\n}\n\nexport interface OperationResult<TValue = JsonValue> {\n value: TValue;\n provenance: OperationProvenance;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { getGlobalConfigPath } from \"./paths\";\nimport { writeStoreJsonFile } from \"./json-files\";\nimport {\n getFirstPartyHarnessAdapter,\n validateHarnessMethodSelection,\n type HarnessMethodSelection,\n} from \"../harness-access\";\nimport { NO_ACCESS, type OperationAccess } from \"../operations/access\";\n\n/**\n * Global configuration file: machine-level and tool-level settings only\n * (R-STORE-2). This surface is deliberately separate from the project-owned\n * presentation overlay at `<repo>/.make-docs/config.yaml`:\n *\n * - Different location (`~/.make-docs/config.json`, never inside a repository).\n * - Different format (JSON, not YAML) so the two files cannot be mistaken for\n * one another.\n * - Different loader: this module only ever reads the global store root; it\n * never reads a project directory, and no project config loader reads this\n * file. Neither file can override the other (R-KEEP-1).\n */\n\nexport const GLOBAL_CONFIG_SCHEMA_VERSION = 1;\n\n/** Self-update preference for the CLI (machine-level setting). */\nexport type SelfUpdatePreference = \"prompt\" | \"auto\" | \"off\";\n\nexport interface McpConnectionRecord {\n id: string;\n keySha256: string;\n active: boolean;\n method: \"mcp\";\n owner: string;\n}\n\nexport interface GlobalHarnessIntent {\n /** Whether this harness is selected for Make Docs setup on this machine. */\n selected: boolean;\n /** Most permissive adapter method the user approved, or none/null when disabled. */\n maximumMethod: string | null;\n /** Maximum operation access approved for this harness on this machine. */\n accessCeiling: OperationAccess;\n /** Revocable proof for one reviewed MCP connection. The raw key stays in the host entry. */\n mcpConnection?: McpConnectionRecord;\n /** Preserve newer or harness-owned settings during an older CLI round trip. */\n [key: string]: unknown;\n}\n\nexport interface GlobalConfigSettings {\n /** How the CLI handles tool self-updates on this machine. */\n selfUpdate: SelfUpdatePreference;\n /** Opt-in for automatic marketplace registration (default: off). */\n marketplaceAutoRegistration: boolean;\n /** Machine intent only. Live native harness configuration remains authority. */\n harnesses: Record<string, GlobalHarnessIntent>;\n /** Preserve settings owned by a newer CLI. */\n [key: string]: unknown;\n}\n\nexport interface GlobalConfig {\n schemaVersion: number;\n settings: GlobalConfigSettings;\n /** Preserve top-level fields owned by a newer CLI. */\n [key: string]: unknown;\n}\n\nexport interface LoadedGlobalConfig {\n config: GlobalConfig;\n /** Absolute path the config was resolved against. */\n path: string;\n /** True when the file existed and parsed; false when defaults were used. */\n loadedFromDisk: boolean;\n warnings: string[];\n}\n\nexport const DEFAULT_GLOBAL_CONFIG_SETTINGS: GlobalConfigSettings = {\n selfUpdate: \"prompt\",\n marketplaceAutoRegistration: false,\n harnesses: {},\n};\n\nexport const DEFAULT_HARNESS_ACCESS_CEILING: OperationAccess = Object.freeze({\n store: \"write\",\n project: \"write\",\n hostConfig: \"none\",\n});\n\nexport function defaultGlobalConfig(): GlobalConfig {\n return {\n schemaVersion: GLOBAL_CONFIG_SCHEMA_VERSION,\n settings: { ...DEFAULT_GLOBAL_CONFIG_SETTINGS, harnesses: {} },\n };\n}\n\n/**\n * Loads the global config from the store root. Missing or unreadable files\n * degrade to defaults with a warning; the global config is operational state\n * and must never block the CLI (R-DB-4 spirit applies to the whole store).\n */\nexport function loadGlobalConfig(storeRoot: string): LoadedGlobalConfig {\n const configPath = getGlobalConfigPath(storeRoot);\n const warnings: string[] = [];\n if (!existsSync(configPath)) {\n return {\n config: defaultGlobalConfig(),\n path: configPath,\n loadedFromDisk: false,\n warnings,\n };\n }\n\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(configPath, \"utf8\"));\n } catch (error) {\n warnings.push(\n `Global config at ${configPath} is not valid JSON (${toMessage(error)}); using defaults. ` +\n \"This is recoverable operational state, not project data.\",\n );\n return {\n config: defaultGlobalConfig(),\n path: configPath,\n loadedFromDisk: false,\n warnings,\n };\n }\n\n return {\n config: normalizeGlobalConfig(raw, configPath, warnings),\n path: configPath,\n loadedFromDisk: true,\n warnings,\n };\n}\n\n/** Writes the global config file (atomically via temp-file rename). */\nexport function writeGlobalConfig(storeRoot: string, config: GlobalConfig): string {\n const configPath = getGlobalConfigPath(storeRoot);\n writeStoreJsonFile(configPath, config);\n return configPath;\n}\n\nfunction normalizeGlobalConfig(\n raw: unknown,\n configPath: string,\n warnings: string[],\n): GlobalConfig {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n warnings.push(\n `Global config at ${configPath} is not a JSON object; using defaults.`,\n );\n return defaultGlobalConfig();\n }\n\n const record = raw as Record<string, unknown>;\n const settingsRaw =\n typeof record.settings === \"object\" && record.settings !== null && !Array.isArray(record.settings)\n ? (record.settings as Record<string, unknown>)\n : {};\n\n const settings: GlobalConfigSettings = {\n ...settingsRaw,\n ...DEFAULT_GLOBAL_CONFIG_SETTINGS,\n harnesses: {},\n };\n\n const selfUpdate = settingsRaw.selfUpdate;\n if (selfUpdate === \"prompt\" || selfUpdate === \"auto\" || selfUpdate === \"off\") {\n settings.selfUpdate = selfUpdate;\n } else if (selfUpdate !== undefined) {\n warnings.push(\n `Global config setting \"selfUpdate\" has unsupported value ${JSON.stringify(selfUpdate)}; using \"${DEFAULT_GLOBAL_CONFIG_SETTINGS.selfUpdate}\".`,\n );\n }\n\n const marketplaceAutoRegistration = settingsRaw.marketplaceAutoRegistration;\n if (typeof marketplaceAutoRegistration === \"boolean\") {\n settings.marketplaceAutoRegistration = marketplaceAutoRegistration;\n } else if (marketplaceAutoRegistration !== undefined) {\n warnings.push(\n 'Global config setting \"marketplaceAutoRegistration\" must be a boolean; using the default (false).',\n );\n }\n\n const harnesses = settingsRaw.harnesses;\n if (harnesses !== undefined) {\n if (typeof harnesses !== \"object\" || harnesses === null || Array.isArray(harnesses)) {\n warnings.push(\n 'Global config setting \"harnesses\" must be an object; using no selected harnesses.',\n );\n } else {\n for (const [harness, value] of Object.entries(harnesses)) {\n if (!/^[a-z][a-z0-9-]*$/.test(harness)) {\n warnings.push(`Global config harness ${JSON.stringify(harness)} is not a safe identifier; it was ignored.`);\n continue;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n warnings.push(`Global config harness \"${harness}\" must be an object; it was ignored.`);\n continue;\n }\n const intent = value as Record<string, unknown>;\n const selected = intent.selected;\n const maximumMethod = intent.maximumMethod;\n if (typeof selected !== \"boolean\") {\n warnings.push(`Global config harness \"${harness}\" must declare a boolean selected value; it was ignored.`);\n continue;\n }\n if (\n maximumMethod !== null &&\n (typeof maximumMethod !== \"string\" || !/^[a-z][a-z0-9-]*$/.test(maximumMethod))\n ) {\n warnings.push(`Global config harness \"${harness}\" has an unsafe maximumMethod; it was ignored.`);\n continue;\n }\n if (selected && maximumMethod === null) {\n warnings.push(`Global config harness \"${harness}\" is selected but has no maximumMethod; it was ignored.`);\n continue;\n }\n const adapter = getFirstPartyHarnessAdapter(harness);\n if (adapter && maximumMethod !== null) {\n try {\n validateHarnessMethodSelection({\n harnessId: harness,\n method: maximumMethod as HarnessMethodSelection,\n });\n } catch (error) {\n warnings.push(`Global config harness \"${harness}\" has an unsupported maximumMethod (${toMessage(error)}); it was ignored.`);\n continue;\n }\n }\n if (selected && maximumMethod === \"none\") {\n warnings.push(`Global config harness \"${harness}\" is selected but maximumMethod is none; it was ignored.`);\n continue;\n }\n const accessCeiling = normalizeHarnessAccessCeiling(\n intent.accessCeiling,\n selected ? DEFAULT_HARNESS_ACCESS_CEILING : NO_ACCESS,\n configPath,\n harness,\n warnings,\n );\n if (!accessCeiling) continue;\n const mcpConnection = normalizeMcpConnection(intent.mcpConnection, harness);\n settings.harnesses[harness] = {\n ...intent,\n selected,\n maximumMethod,\n accessCeiling,\n ...(mcpConnection ? { mcpConnection } : { mcpConnection: undefined }),\n };\n }\n }\n }\n\n return {\n ...record,\n schemaVersion:\n typeof record.schemaVersion === \"number\"\n ? record.schemaVersion\n : GLOBAL_CONFIG_SCHEMA_VERSION,\n settings,\n };\n}\n\nfunction normalizeMcpConnection(value: unknown, owner: string): McpConnectionRecord | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (\n typeof record.id !== \"string\" || !/^[0-9a-f-]{36}$/.test(record.id) ||\n typeof record.keySha256 !== \"string\" || !/^[a-f0-9]{64}$/.test(record.keySha256) ||\n typeof record.active !== \"boolean\" || record.method !== \"mcp\" || record.owner !== owner\n ) return null;\n return {\n id: record.id,\n keySha256: record.keySha256,\n active: record.active,\n method: \"mcp\",\n owner,\n };\n}\n\nfunction normalizeHarnessAccessCeiling(\n value: unknown,\n fallback: OperationAccess,\n configPath: string,\n harness: string,\n warnings: string[],\n): OperationAccess | null {\n if (value === undefined) return { ...fallback };\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n warnings.push(`Global config harness \"${harness}\" has an invalid accessCeiling at ${configPath}; it was ignored.`);\n return null;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n if (\n keys.join(\",\") !== \"hostConfig,project,store\" ||\n !isAccessLevel(record.store) ||\n !isAccessLevel(record.project) ||\n record.hostConfig !== \"none\"\n ) {\n warnings.push(`Global config harness \"${harness}\" has an invalid accessCeiling at ${configPath}; it was ignored.`);\n return null;\n }\n return {\n store: record.store,\n project: record.project,\n hostConfig: \"none\",\n };\n}\n\nfunction isAccessLevel(value: unknown): value is \"none\" | \"read\" | \"write\" {\n return value === \"none\" || value === \"read\" || value === \"write\";\n}\n\nfunction toMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { platform } from \"../platform\";\n\n/**\n * Writes a JSON file atomically: serialize to a temp sibling, then rename over\n * the destination. The platform layer supplies the supported atomic replacement, so concurrent\n * readers of the global config and manifest never observe a torn write.\n */\nexport function writeStoreJsonFile(filePath: string, value: unknown): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n platform.atomicReplace(tempPath, filePath);\n}\n","import { readDeclarativeProjectId } from \"./installation-state\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { getManifestPath, loadManifest } from \"../manifest\";\n\n/** Read the portable declarative identity without creating or changing project state.\n * Installation ownership is separate and belongs to the Store checkout binding.\n */\nexport type ProjectIdentityResolution =\n | {\n status: \"resolved\";\n /** Stable project identifier from declarative config. */\n projectId: string;\n /** Resolved repo root — secondary lookup/display metadata, never identity. */\n rootPath: string;\n manifestPath: string;\n }\n | { status: \"unminted\"; rootPath: string; manifestPath: string }\n | { status: \"no-manifest\"; rootPath: string; manifestPath: string }\n | { status: \"unreadable\"; rootPath: string; manifestPath: string; reason: string };\n\nexport function resolveProjectIdentity(repoRoot: string): ProjectIdentityResolution {\n const rootPath = path.resolve(repoRoot);\n const manifestPath = getManifestPath(rootPath);\n\n\n try {\n const projectId = readDeclarativeProjectId(rootPath);\n if (projectId) return { status: \"resolved\", projectId, rootPath, manifestPath: path.join(rootPath, \".make-docs/config.yaml\") };\n const manifest = loadManifest(rootPath);\n if (!manifest) {\n return { status: \"no-manifest\", rootPath, manifestPath };\n }\n if (!manifest.projectId) {\n return { status: \"unminted\", rootPath, manifestPath };\n }\n return { status: \"resolved\", projectId: manifest.projectId, rootPath, manifestPath };\n } catch (error) {\n return {\n status: \"unreadable\",\n rootPath,\n manifestPath,\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import path from \"node:path\";\nimport { platform } from \"../platform\";\nimport { isRedactedMcpNativeValue, redactMcpNativeValue } from \"../mcp-connection\";\nimport {\n fingerprintEntry,\n getFirstPartyHarnessAdapter,\n sha256,\n type HarnessAccessReceipt,\n type HarnessAccessState,\n type HarnessConnectionMethod,\n type HarnessId,\n type HarnessReceiptEntry,\n type NativeEntryValue,\n} from \"../harness-access\";\nimport { listMigrationState, readMigrationState, recordMigrationState, withInstallationDatabase } from \"./installation-state\";\n\nexport interface StoredHarnessIntegrationReceipt extends Omit<\n HarnessAccessReceipt,\n \"result\" | \"verificationResult\" | \"driftState\" | \"recoveryStatus\"\n> {\n result: \"verified\" | \"failed\" | \"partial\";\n verificationResult: \"passed\" | \"failed\" | \"blocked\";\n driftState: HarnessAccessState;\n recoveryStatus: \"complete\" | \"incomplete\" | \"recovery-required\";\n}\n\n/** Save an adapter's verified receipt in existing Store records. */\nexport function recordHarnessIntegrationReceipt(\n targetRoot: string,\n storeRoot: string,\n receipt: HarnessAccessReceipt,\n): void {\n assertHarnessIntegrationReceipt(receipt);\n const durableReceipt = redactHarnessIntegrationReceipt(receipt);\n const currentId = currentReceiptRecordId(\n receipt.scope,\n receipt.harnessId,\n receipt.connectionMethod,\n );\n if (receipt.scope === \"project\") {\n recordMigrationState(targetRoot, \"receipt\", receipt.operationId, durableReceipt, storeRoot);\n recordMigrationState(targetRoot, \"receipt\", currentId, durableReceipt, storeRoot);\n return;\n }\n const recordId = machineReceiptRecordId(receipt.operationId);\n withInstallationDatabase(targetRoot, (db) => {\n const write = db.prepare(\n \"INSERT INTO tool_operations (operation_id,operation,status,pid,hostname,metadata_json,started_at,finished_at) VALUES (?,?,'completed',?,?,?,?,?) ON CONFLICT(operation_id) DO UPDATE SET status='completed',metadata_json=excluded.metadata_json,finished_at=excluded.finished_at\",\n );\n write.run(recordId, \"setup.system.receipt\", process.pid, platform.hostname, JSON.stringify(durableReceipt), receipt.verifiedAt, receipt.verifiedAt);\n write.run(currentId, \"setup.system.receipt-current\", process.pid, platform.hostname, JSON.stringify(durableReceipt), receipt.verifiedAt, receipt.verifiedAt);\n }, { storeRoot });\n}\n\nexport function redactHarnessIntegrationReceipt<T extends {\n connectionMethod: HarnessConnectionMethod;\n entries: readonly HarnessReceiptEntry[];\n}>(receipt: T): T {\n if (receipt.connectionMethod !== \"mcp\") return receipt;\n return {\n ...receipt,\n entries: receipt.entries.map(entry => ({\n ...entry,\n beforeValue: redactMcpNativeValue(entry.beforeValue),\n value: redactMcpNativeValue(entry.value),\n })),\n } as T;\n}\n\n/** Retain a later drift or recovery observation without changing current ownership. */\nexport function recordHarnessIntegrationReceiptObservation(\n targetRoot: string,\n storeRoot: string,\n receipt: StoredHarnessIntegrationReceipt,\n): void {\n if (!isStoredHarnessIntegrationReceipt(receipt)) {\n throw new Error(\"Harness receipt observation is malformed or lacks exact ownership evidence.\");\n }\n receipt = redactHarnessIntegrationReceipt(receipt);\n const observationId = `harness-receipt-observation:${sha256(JSON.stringify({\n operationId: receipt.operationId,\n verifiedAt: receipt.verifiedAt,\n driftState: receipt.driftState,\n recoveryStatus: receipt.recoveryStatus,\n })).slice(0, 32)}`;\n if (receipt.scope === \"project\") {\n recordMigrationState(targetRoot, \"receipt\", observationId, receipt, storeRoot);\n return;\n }\n withInstallationDatabase(targetRoot, (db) => {\n db.prepare(\n \"INSERT INTO tool_operations (operation_id,operation,status,pid,hostname,metadata_json,started_at,finished_at) VALUES (?,?,'completed',?,?,?,?,?) ON CONFLICT(operation_id) DO UPDATE SET status='completed',metadata_json=excluded.metadata_json,finished_at=excluded.finished_at\",\n ).run(observationId, \"setup.system.receipt-observation\", process.pid, platform.hostname, JSON.stringify(receipt), receipt.verifiedAt, receipt.verifiedAt);\n }, { storeRoot });\n}\n\nexport function readHarnessIntegrationReceipt(\n targetRoot: string,\n storeRoot: string,\n scope: \"machine\" | \"project\",\n operationId: string,\n): HarnessAccessReceipt | null {\n if (scope === \"project\") {\n const receipt = readMigrationState<unknown>(targetRoot, \"receipt\", operationId, storeRoot);\n return isHarnessIntegrationReceipt(receipt) ? receipt : null;\n }\n return withInstallationDatabase(targetRoot, (db) => {\n const row = db.prepare(\n \"SELECT metadata_json FROM tool_operations WHERE operation_id=? AND operation='setup.system.receipt' AND status='completed'\",\n ).get(machineReceiptRecordId(operationId)) as { metadata_json: string } | undefined;\n if (!row) return null;\n const value = parseJson(row.metadata_json);\n return isHarnessIntegrationReceipt(value) ? value : null;\n }, { storeRoot, readOnly: true });\n}\n\n/** Read the latest exact receipt without knowing its prior operation ID. */\nexport function readCurrentHarnessIntegrationReceipt(\n targetRoot: string,\n storeRoot: string,\n scope: \"machine\" | \"project\",\n harnessId: HarnessId,\n connectionMethod: HarnessConnectionMethod,\n): HarnessAccessReceipt | null {\n const currentId = currentReceiptRecordId(scope, harnessId, connectionMethod);\n if (scope === \"project\") {\n const current = readMigrationState<unknown>(targetRoot, \"receipt\", currentId, storeRoot);\n if (isHarnessIntegrationReceipt(current)) return current;\n return latestReceipt(\n listProjectHarnessIntegrationReceipts(targetRoot, storeRoot)\n .filter((receipt) => receipt.harnessId === harnessId && receipt.connectionMethod === connectionMethod),\n );\n }\n return withInstallationDatabase(targetRoot, (db) => {\n const current = db.prepare(\n \"SELECT metadata_json FROM tool_operations WHERE operation_id=? AND operation='setup.system.receipt-current' AND status='completed'\",\n ).get(currentId) as { metadata_json: string } | undefined;\n const currentValue = current ? parseJson(current.metadata_json) : null;\n if (isHarnessIntegrationReceipt(currentValue)) return currentValue;\n const rows = db.prepare(\n \"SELECT metadata_json FROM tool_operations WHERE operation='setup.system.receipt' AND status='completed' ORDER BY finished_at DESC\",\n ).all() as Array<{ metadata_json: string }>;\n return latestReceipt(rows\n .map((row) => parseJson(row.metadata_json))\n .filter(isHarnessIntegrationReceipt)\n .filter((receipt) => receipt.scope === \"machine\" && receipt.harnessId === harnessId && receipt.connectionMethod === connectionMethod));\n }, { storeRoot, readOnly: true });\n}\n\nfunction machineReceiptRecordId(operationId: string): string {\n return `harness-receipt:${operationId}`;\n}\n\nfunction currentReceiptRecordId(\n scope: \"machine\" | \"project\",\n harnessId: HarnessId,\n connectionMethod: HarnessConnectionMethod,\n): string {\n return `harness-receipt-current:${scope}:${harnessId}:${connectionMethod}`;\n}\n\nexport function listProjectHarnessIntegrationReceipts(\n targetRoot: string,\n storeRoot: string,\n): HarnessAccessReceipt[] {\n return uniqueReceipts(listMigrationState<unknown>(targetRoot, \"receipt\", storeRoot)\n .filter(isHarnessIntegrationReceipt)\n .filter((receipt) => receipt.scope === \"project\"));\n}\n\n/** List applied receipt history without replacing older valid evidence. */\nexport function listHarnessIntegrationReceiptHistory(\n targetRoot: string,\n storeRoot: string,\n scope: \"machine\" | \"project\",\n): StoredHarnessIntegrationReceipt[] {\n if (scope === \"project\") {\n return uniqueStoredReceipts(listMigrationState<unknown>(targetRoot, \"receipt\", storeRoot)\n .filter(isStoredHarnessIntegrationReceipt)\n .filter((receipt) => receipt.scope === \"project\"))\n .sort(compareStoredReceiptNewestFirst);\n }\n return withInstallationDatabase(targetRoot, (db) => {\n const rows = db.prepare(\n \"SELECT metadata_json FROM tool_operations WHERE operation IN ('setup.system.receipt','setup.system.receipt-observation') AND status='completed' ORDER BY finished_at DESC\",\n ).all() as Array<{ metadata_json: string }>;\n return uniqueStoredReceipts(rows\n .map((row) => parseJson(row.metadata_json))\n .filter(isStoredHarnessIntegrationReceipt)\n .filter((receipt) => receipt.scope === \"machine\"));\n }, { storeRoot, readOnly: true });\n}\n\nexport function assertHarnessIntegrationReceipt(value: unknown): asserts value is HarnessAccessReceipt {\n if (!isHarnessIntegrationReceipt(value)) {\n throw new Error(\"Harness access receipt is malformed or lacks exact ownership evidence.\");\n }\n}\n\nexport function isHarnessIntegrationReceipt(value: unknown): value is HarnessAccessReceipt {\n if (!isStoredHarnessIntegrationReceipt(value)) return false;\n const adapter = typeof value.harnessId === \"string\" ? getFirstPartyHarnessAdapter(value.harnessId) : undefined;\n return adapter !== undefined &&\n value.adapterVersion === adapter.version &&\n adapter.methods.some(method => method.id === value.connectionMethod) &&\n value.result === \"verified\" &&\n value.verificationResult === \"passed\" &&\n value.driftState === \"current\" &&\n value.recoveryStatus === \"complete\";\n}\n\nexport function isStoredHarnessIntegrationReceipt(\n value: unknown,\n): value is StoredHarnessIntegrationReceipt {\n if (!isRecord(value)) return false;\n const adapter = typeof value.harnessId === \"string\" ? getFirstPartyHarnessAdapter(value.harnessId) : undefined;\n return (value.schemaVersion === 1 || value.schemaVersion === 2) &&\n isSafeId(value.operationId) &&\n adapter !== undefined &&\n value.adapterId === adapter.id &&\n Number.isSafeInteger(value.adapterVersion) &&\n Number(value.adapterVersion) > 0 &&\n (value.connectionMethod === \"mcp\" || value.connectionMethod === \"command-rules\" || value.connectionMethod === \"permission-rules\") &&\n (value.scope === \"machine\" || value.scope === \"project\") &&\n (value.schemaVersion === 1 ? isExecutable(value.executable) : value.executable === undefined) &&\n isSafeId(value.appliedVersion) &&\n isTimestamp(value.verifiedAt) &&\n Array.isArray(value.entries) &&\n value.entries.length > 0 &&\n value.entries.every(entry => isReceiptEntry(entry, value.connectionMethod)) &&\n (value.result === \"verified\" || value.result === \"failed\" || value.result === \"partial\") &&\n (value.verificationResult === \"passed\" || value.verificationResult === \"failed\" || value.verificationResult === \"blocked\") &&\n (value.driftState === \"current\" || value.driftState === \"missing\" || value.driftState === \"drifted\" || value.driftState === \"unsupported\" || value.driftState === \"blocked\") &&\n (value.recoveryStatus === \"complete\" || value.recoveryStatus === \"incomplete\" || value.recoveryStatus === \"recovery-required\");\n}\n\nfunction isExecutable(value: unknown): boolean {\n if (!isRecord(value)) return false;\n if (\n value.kind !== \"make-docs\" ||\n value.productMarker !== \"@brucewaynedecoy/make-docs:package-bin\" ||\n value.packageName !== \"@brucewaynedecoy/make-docs\" ||\n !isSafeId(value.packageVersion) ||\n !path.isAbsolute(String(value.path)) ||\n !path.isAbsolute(String(value.packageRoot)) ||\n !isSafeRelativePath(value.binRelativePath) ||\n !isSha256(value.sha256) ||\n !Number.isSafeInteger(value.size) ||\n Number(value.size) < 1\n ) return false;\n return platform.samePath(\n String(value.path),\n path.resolve(String(value.packageRoot), String(value.binRelativePath)),\n );\n}\n\nfunction isReceiptEntry(value: unknown, method: unknown): value is HarnessReceiptEntry {\n const matches = (entry: NativeEntryValue, fingerprint: unknown): boolean =>\n fingerprint === fingerprintEntry(entry) ||\n (method === \"mcp\" && isRedactedMcpNativeValue(entry) && isSha256(fingerprint));\n return isRecord(value) && isSafeNativePath(value.path) && isSafeId(value.entryId) &&\n value.ownership === \"make-docs\" && isNullableSha256(value.beforeEntryFingerprint) &&\n isNullableSha256(value.beforeFileFingerprint) && isNativeValueOrNull(value.beforeValue) &&\n isSha256(value.entryFingerprint) && isSha256(value.fileFingerprint) && isNativeValue(value.value) &&\n matches(value.value, value.entryFingerprint) &&\n (value.beforeValue === null\n ? value.beforeEntryFingerprint === null\n : matches(value.beforeValue, value.beforeEntryFingerprint));\n}\n\nfunction isSafeNativePath(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length === 0 || /[\\r\\n\\0]/.test(value)) return false;\n if (value.includes(\"\\\\\") || path.posix.isAbsolute(value) || /^[A-Za-z]:/.test(value)) return false;\n const normalized = path.posix.normalize(value);\n return normalized !== \".\" && normalized === value && normalized !== \"..\" && !normalized.startsWith(\"../\");\n}\n\nfunction isSafeRelativePath(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length === 0 || /[\\r\\n\\0]/.test(value)) return false;\n if (value.includes(\"\\\\\") || path.posix.isAbsolute(value) || /^[A-Za-z]:/.test(value)) return false;\n const normalized = path.posix.normalize(value);\n return normalized !== \".\" && normalized === value && normalized !== \"..\" && !normalized.startsWith(\"../\");\n}\n\nfunction isNativeValueOrNull(value: unknown): value is NativeEntryValue | null {\n return value === null || isNativeValue(value);\n}\n\nfunction isNativeValue(value: unknown): value is NativeEntryValue {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isNativeValue);\n return isRecord(value) && Object.values(value).every(isNativeValue);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isSafeId(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && value.length <= 256 && !/[\\r\\n\\0]/.test(value);\n}\n\nfunction isNullableSha256(value: unknown): boolean {\n return value === null || isSha256(value);\n}\n\nfunction isSha256(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value);\n}\n\nfunction isTimestamp(value: unknown): value is string {\n return typeof value === \"string\" && Number.isFinite(Date.parse(value));\n}\n\nfunction parseJson(value: string): unknown {\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return null;\n }\n}\n\nfunction latestReceipt(receipts: HarnessAccessReceipt[]): HarnessAccessReceipt | null {\n return receipts.sort(compareReceiptNewestFirst)[0] ?? null;\n}\n\nfunction compareReceiptNewestFirst(left: HarnessAccessReceipt, right: HarnessAccessReceipt): number {\n return Date.parse(right.verifiedAt) - Date.parse(left.verifiedAt);\n}\n\nfunction compareStoredReceiptNewestFirst(\n left: StoredHarnessIntegrationReceipt,\n right: StoredHarnessIntegrationReceipt,\n): number {\n return Date.parse(right.verifiedAt) - Date.parse(left.verifiedAt);\n}\n\nfunction uniqueReceipts(receipts: HarnessAccessReceipt[]): HarnessAccessReceipt[] {\n const byOperation = new Map<string, HarnessAccessReceipt>();\n for (const receipt of receipts) {\n const existing = byOperation.get(receipt.operationId);\n if (!existing || Date.parse(receipt.verifiedAt) > Date.parse(existing.verifiedAt)) {\n byOperation.set(receipt.operationId, receipt);\n }\n }\n return [...byOperation.values()];\n}\n\nfunction uniqueStoredReceipts(\n receipts: StoredHarnessIntegrationReceipt[],\n): StoredHarnessIntegrationReceipt[] {\n const unique = new Map<string, StoredHarnessIntegrationReceipt>();\n for (const receipt of receipts) {\n const key = [\n receipt.operationId,\n receipt.verifiedAt,\n receipt.driftState,\n receipt.recoveryStatus,\n ].join(\"\\0\");\n unique.set(key, receipt);\n }\n return [...unique.values()];\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { platform } from \"../platform\";\nimport { isRedactedMcpNativeValue, redactMcpNativeValue } from \"../mcp-connection\";\nimport type {\n HarnessAccessPlan,\n HarnessAccessReceipt,\n HarnessConnectionMethod,\n HarnessId,\n HarnessNativeChange,\n NativeEntryValue,\n} from \"../harness-access\";\nimport { fingerprintEntry } from \"../harness-access\";\nimport { classifyStoreCheckpoint9State, type StoreDatabase } from \"./database\";\nimport { isHarnessIntegrationReceipt, readCurrentHarnessIntegrationReceipt, redactHarnessIntegrationReceipt } from \"./harness-integration-receipts\";\nimport { getStoreDatabasePath } from \"./paths\";\nimport {\n canonicalInstallationPath,\n validateInstallationStoreRoot,\n withInstallationDatabase,\n} from \"./installation-state\";\n\nconst OPERATION = \"setup.system.harness\";\n\nexport interface PrepareHarnessSystemOperationInput {\n targetRoot: string;\n storeRoot: string;\n adapterId: string;\n harnessId: HarnessId;\n plan: HarnessAccessPlan;\n appliedVersion: string;\n verifiedAt: string;\n}\n\nexport interface PendingHarnessSystemOperation {\n schemaVersion: 1;\n kind: typeof OPERATION;\n operationId: string;\n adapterId: string;\n harnessId: HarnessId;\n connectionMethod: HarnessConnectionMethod;\n targetRoot: string;\n plan: HarnessAccessPlan;\n planFingerprint: string;\n appliedVersion: string;\n verifiedAt: string;\n ownershipReceipt: HarnessAccessReceipt | null;\n}\n\nexport interface HarnessSystemOperationFailure {\n reason: string;\n changeOutcome: \"none\" | \"unknown\";\n}\n\n/** Save a redacted copy of the reviewed machine plan before any native write. */\nexport function prepareHarnessSystemOperation(\n input: PrepareHarnessSystemOperationInput,\n): PendingHarnessSystemOperation {\n const targetRoot = canonicalInstallationPath(input.targetRoot);\n const storeRoot = validateInstallationStoreRoot(targetRoot, input.storeRoot);\n const ownershipReceipt = input.plan.state === \"drifted\"\n ? readCurrentHarnessIntegrationReceipt(\n targetRoot,\n storeRoot,\n \"machine\",\n input.harnessId,\n input.plan.connectionMethod,\n )\n : null;\n assertReviewedPlan(input.plan, input.adapterId, input.harnessId, ownershipReceipt);\n const durablePlan = redactHarnessPlan(input.plan);\n if (!input.appliedVersion.trim()) throw new Error(\"Machine setup needs an applied version.\");\n if (!Number.isFinite(Date.parse(input.verifiedAt))) {\n throw new Error(\"Machine setup needs a valid verification time.\");\n }\n const pending: PendingHarnessSystemOperation = {\n schemaVersion: 1,\n kind: OPERATION,\n operationId: randomUUID(),\n adapterId: input.adapterId,\n harnessId: input.harnessId,\n connectionMethod: input.plan.connectionMethod,\n targetRoot,\n plan: durablePlan,\n planFingerprint: fingerprintJson(durablePlan),\n appliedVersion: input.appliedVersion,\n verifiedAt: input.verifiedAt,\n ownershipReceipt: ownershipReceipt ? redactHarnessIntegrationReceipt(ownershipReceipt) : null,\n };\n const savedJson = JSON.stringify(pending);\n withInstallationDatabase(targetRoot, (db) => {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n assertNoOtherStoreWork(db, targetRoot);\n db.prepare(\n \"INSERT INTO tool_operations (operation_id,operation,status,pid,hostname,metadata_json,started_at,finished_at) VALUES (?,?,'pending',?,?,?,?,NULL)\",\n ).run(\n pending.operationId,\n OPERATION,\n process.pid,\n platform.hostname,\n savedJson,\n pending.verifiedAt,\n );\n db.exec(\"COMMIT\");\n } catch (error) {\n db.exec(\"ROLLBACK\");\n throw error;\n }\n }, { storeRoot });\n const saved = readPendingHarnessSystemOperation(targetRoot, storeRoot, pending.operationId);\n if (!saved || JSON.stringify(saved) !== savedJson) {\n throw new Error(\n `Machine setup intent ${pending.operationId} did not pass Store readback. No native file was changed.`,\n );\n }\n return saved;\n}\n\n/** Read one exact pending machine plan for deterministic verify or resume. */\nexport function readPendingHarnessSystemOperation(\n targetRootInput: string,\n storeRootInput: string,\n operationId?: string,\n): PendingHarnessSystemOperation | null {\n const targetRoot = canonicalInstallationPath(targetRootInput);\n const storeRoot = validateInstallationStoreRoot(targetRoot, storeRootInput);\n if (!existsSync(getStoreDatabasePath(storeRoot))) return null;\n // Schema versions 1 and 2 predate tool_operations. A read must not upgrade\n // them or assume the table exists. The reviewed prepare path performs the\n // normal checkpoint upgrade before any native harness write.\n if (classifyStoreCheckpoint9State(storeRoot).state === \"supported-legacy\") return null;\n return withInstallationDatabase(targetRoot, (db) => {\n const row = operationId\n ? db.prepare(\n \"SELECT operation_id,metadata_json FROM tool_operations WHERE operation_id=? AND operation=? AND status='pending'\",\n ).get(operationId, OPERATION) as StoredPendingRow | undefined\n : db.prepare(\n \"SELECT operation_id,metadata_json FROM tool_operations WHERE operation=? AND status='pending' ORDER BY started_at,operation_id LIMIT 1\",\n ).get(OPERATION) as StoredPendingRow | undefined;\n if (!row) return null;\n let value: unknown;\n try {\n value = JSON.parse(row.metadata_json);\n } catch {\n throw invalidPending(row.operation_id);\n }\n const pending = validatePending(value, row.operation_id, targetRoot);\n assertDurableOwnershipReceipt(db, pending);\n return pending;\n }, { storeRoot, readOnly: true });\n}\n\n/** Complete only the unchanged plan after its exact verified receipt is in Store. */\nexport function completeHarnessSystemOperation(\n targetRootInput: string,\n storeRootInput: string,\n pending: PendingHarnessSystemOperation,\n receipt: HarnessAccessReceipt,\n): void {\n const targetRoot = canonicalInstallationPath(targetRootInput);\n const storeRoot = validateInstallationStoreRoot(targetRoot, storeRootInput);\n const exact = validatePending(pending, pending.operationId, targetRoot);\n const durableReceipt = redactHarnessIntegrationReceipt(receipt);\n assertReceiptMatchesPlan(durableReceipt, exact);\n const pendingJson = JSON.stringify(exact);\n withInstallationDatabase(targetRoot, (db) => {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n assertNoOtherStoreWork(db, targetRoot, exact.operationId);\n const storedReceipt = db.prepare(\n \"SELECT metadata_json FROM tool_operations WHERE operation_id=? AND operation='setup.system.receipt' AND status='completed'\",\n ).get(`harness-receipt:${exact.operationId}`) as { metadata_json: string } | undefined;\n if (!storedReceipt || storedReceipt.metadata_json !== JSON.stringify(durableReceipt)) {\n throw new Error(\n `Machine setup ${exact.operationId} has no exact verified Store receipt. Keep it pending for recovery.`,\n );\n }\n const result = db.prepare(\n \"UPDATE tool_operations SET status='completed',metadata_json=?,finished_at=? WHERE operation_id=? AND operation=? AND status='pending' AND metadata_json=?\",\n ).run(\n JSON.stringify({ ...exact, receiptOperationId: durableReceipt.operationId }),\n receipt.verifiedAt,\n exact.operationId,\n OPERATION,\n pendingJson,\n );\n if (result.changes !== 1) throw changedPending(exact.operationId);\n db.exec(\"COMMIT\");\n } catch (error) {\n db.exec(\"ROLLBACK\");\n throw error;\n }\n }, { storeRoot });\n}\n\n/** Mark a reviewed operation failed only when the caller knows its change outcome. */\nexport function failHarnessSystemOperation(\n targetRootInput: string,\n storeRootInput: string,\n pending: PendingHarnessSystemOperation,\n failure: HarnessSystemOperationFailure,\n): void {\n if (\n !failure.reason.trim() ||\n (failure.changeOutcome !== \"none\" && failure.changeOutcome !== \"unknown\")\n ) {\n throw new Error(\"Machine setup failure needs a reason and a known change outcome.\");\n }\n const targetRoot = canonicalInstallationPath(targetRootInput);\n const storeRoot = validateInstallationStoreRoot(targetRoot, storeRootInput);\n const exact = validatePending(pending, pending.operationId, targetRoot);\n const pendingJson = JSON.stringify(exact);\n withInstallationDatabase(targetRoot, (db) => {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n assertNoOtherStoreWork(db, targetRoot, exact.operationId);\n const finishedAt = new Date().toISOString();\n const result = db.prepare(\n \"UPDATE tool_operations SET status='failed',metadata_json=?,finished_at=? WHERE operation_id=? AND operation=? AND status='pending' AND metadata_json=?\",\n ).run(\n JSON.stringify({ ...exact, failure: { ...failure, failedAt: finishedAt } }),\n finishedAt,\n exact.operationId,\n OPERATION,\n pendingJson,\n );\n if (result.changes !== 1) throw changedPending(exact.operationId);\n db.exec(\"COMMIT\");\n } catch (error) {\n db.exec(\"ROLLBACK\");\n throw error;\n }\n }, { storeRoot });\n}\n\ninterface StoredPendingRow {\n operation_id: string;\n metadata_json: string;\n}\n\nfunction validatePending(\n value: unknown,\n rowOperationId: string,\n expectedTargetRoot: string,\n): PendingHarnessSystemOperation {\n if (!value || typeof value !== \"object\") throw invalidPending(rowOperationId);\n const pending = value as Partial<PendingHarnessSystemOperation>;\n if (\n pending.schemaVersion !== 1 ||\n pending.kind !== OPERATION ||\n pending.operationId !== rowOperationId ||\n typeof pending.adapterId !== \"string\" ||\n (pending.harnessId !== \"codex\" && pending.harnessId !== \"claude-code\" && pending.harnessId !== \"github-copilot\") ||\n typeof pending.targetRoot !== \"string\" ||\n canonicalInstallationPath(pending.targetRoot) !== expectedTargetRoot ||\n !pending.plan ||\n typeof pending.plan !== \"object\" ||\n typeof pending.planFingerprint !== \"string\" ||\n typeof pending.appliedVersion !== \"string\" ||\n !pending.appliedVersion.trim() ||\n typeof pending.verifiedAt !== \"string\" ||\n !Number.isFinite(Date.parse(pending.verifiedAt))\n ) {\n throw invalidPending(rowOperationId);\n }\n if (pending.ownershipReceipt !== null && typeof pending.ownershipReceipt !== \"object\") {\n throw invalidPending(rowOperationId);\n }\n assertReviewedPlan(\n pending.plan,\n pending.adapterId,\n pending.harnessId,\n pending.ownershipReceipt ?? null,\n );\n if (\n pending.connectionMethod !== pending.plan.connectionMethod ||\n pending.planFingerprint !== fingerprintJson(pending.plan)\n ) {\n throw invalidPending(rowOperationId);\n }\n return pending as PendingHarnessSystemOperation;\n}\n\nfunction assertReviewedPlan(\n plan: HarnessAccessPlan,\n adapterId: string,\n harnessId: HarnessId,\n ownershipReceipt: HarnessAccessReceipt | null,\n): void {\n if (\n plan.schemaVersion !== 1 ||\n plan.kind !== \"apply\" ||\n plan.adapterId !== adapterId ||\n plan.harnessId !== harnessId ||\n plan.scope !== \"machine\" ||\n !path.isAbsolute(plan.root) ||\n path.normalize(plan.root) !== plan.root ||\n !/^[0-9a-f]{64}$/.test(plan.reviewFingerprint) ||\n plan.state === \"blocked\" ||\n plan.state === \"unsupported\" ||\n !Array.isArray(plan.changes) ||\n plan.changes.length === 0\n ) {\n throw new Error(\"Machine setup needs one exact reviewed machine harness plan.\");\n }\n for (const change of plan.changes) assertReviewedChange(plan.root, change, plan.connectionMethod);\n if (plan.state === \"drifted\") {\n assertReceiptOwnedDrift(plan, ownershipReceipt);\n } else if (ownershipReceipt !== null) {\n throw new Error(\"Only a reviewed drift repair can carry an ownership receipt.\");\n }\n}\n\nfunction assertReceiptOwnedDrift(\n plan: HarnessAccessPlan,\n receipt: HarnessAccessReceipt | null,\n): void {\n if (\n !receipt ||\n (receipt.schemaVersion !== 1 && receipt.schemaVersion !== 2) ||\n receipt.adapterId !== plan.adapterId ||\n receipt.adapterVersion !== plan.adapterVersion ||\n receipt.harnessId !== plan.harnessId ||\n receipt.connectionMethod !== plan.connectionMethod ||\n receipt.scope !== \"machine\" ||\n receipt.result !== \"verified\" ||\n receipt.verificationResult !== \"passed\" ||\n receipt.driftState !== \"current\" ||\n receipt.recoveryStatus !== \"complete\" ||\n receipt.entries.length !== plan.changes.length\n ) {\n throw new Error(\"A drift repair needs the exact current Make Docs ownership receipt.\");\n }\n for (let index = 0; index < plan.changes.length; index++) {\n const change = plan.changes[index];\n const entry = receipt.entries[index];\n if (\n change.action !== \"update\" ||\n change.ownership !== \"make-docs-owned\" ||\n change.blockedReason ||\n entry.ownership !== \"make-docs\" ||\n entry.path !== change.path ||\n entry.entryId !== change.entryId ||\n entry.entryFingerprint !== change.beforeEntryFingerprint ||\n JSON.stringify(redactMcpNativeValue(entry.value)) !==\n JSON.stringify(redactMcpNativeValue(change.beforeEntryValue)) ||\n !entryMatches(entry.value, entry.entryFingerprint, plan.connectionMethod)\n ) {\n throw new Error(\n `Drift repair target ${change.path} is not the exact receipt-owned native entry.`,\n );\n }\n }\n}\n\nfunction assertDurableOwnershipReceipt(\n db: StoreDatabase,\n pending: PendingHarnessSystemOperation,\n): void {\n const receipt = pending.ownershipReceipt;\n if (!receipt) return;\n const row = db.prepare(\n \"SELECT metadata_json FROM tool_operations WHERE operation_id=? AND operation='setup.system.receipt' AND status='completed'\",\n ).get(`harness-receipt:${receipt.operationId}`) as { metadata_json: string } | undefined;\n let savedReceipt: unknown = null;\n if (row) {\n try { savedReceipt = JSON.parse(row.metadata_json); } catch { savedReceipt = null; }\n }\n if (!isHarnessIntegrationReceipt(savedReceipt) ||\n JSON.stringify(redactHarnessIntegrationReceipt(savedReceipt)) !== JSON.stringify(receipt)) {\n throw new Error(\n `Pending machine setup ${pending.operationId} lost its exact ownership receipt. Preserve it for manual recovery.`,\n );\n }\n}\n\nfunction assertReviewedChange(root: string, change: HarnessNativeChange, method: HarnessConnectionMethod): void {\n const resolved = path.resolve(root, change.path);\n if (\n !change.path ||\n path.isAbsolute(change.path) ||\n (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) ||\n !new Set([\"create\", \"update\", \"remove\", \"none\"]).has(change.action) ||\n !new Set([\"missing\", \"make-docs-owned\", \"unverified\"]).has(change.ownership) ||\n change.blockedReason ||\n !isFingerprint(change.beforeFileFingerprint, true) ||\n !isFingerprint(change.afterFileFingerprint, false) ||\n !entryMatches(change.beforeEntryValue, change.beforeEntryFingerprint, method) ||\n change.afterEntryValue === null ||\n !entryMatches(change.afterEntryValue, change.afterEntryFingerprint, method)\n ) {\n throw new Error(`Machine setup has an unsafe or incomplete reviewed change: ${change.path}.`);\n }\n}\n\nfunction assertReceiptMatchesPlan(\n receipt: HarnessAccessReceipt,\n pending: PendingHarnessSystemOperation,\n): void {\n const plan = pending.plan;\n if (\n receipt.schemaVersion !== 2 ||\n receipt.operationId !== pending.operationId ||\n receipt.adapterId !== pending.adapterId ||\n receipt.adapterVersion !== plan.adapterVersion ||\n receipt.harnessId !== pending.harnessId ||\n receipt.connectionMethod !== pending.connectionMethod ||\n receipt.scope !== \"machine\" ||\n receipt.appliedVersion !== pending.appliedVersion ||\n receipt.verifiedAt !== pending.verifiedAt ||\n receipt.result !== \"verified\" ||\n receipt.verificationResult !== \"passed\" ||\n receipt.driftState !== \"current\" ||\n receipt.recoveryStatus !== \"complete\" ||\n receipt.entries.length !== plan.changes.length\n ) {\n throw new Error(`Machine setup receipt does not match pending plan ${pending.operationId}.`);\n }\n for (let index = 0; index < plan.changes.length; index++) {\n const change = plan.changes[index];\n const entry = receipt.entries[index];\n if (\n entry.path !== change.path ||\n entry.entryId !== change.entryId ||\n entry.ownership !== \"make-docs\" ||\n entry.beforeEntryFingerprint !== change.beforeEntryFingerprint ||\n entry.beforeFileFingerprint !== change.beforeFileFingerprint ||\n JSON.stringify(entry.beforeValue) !== JSON.stringify(change.beforeEntryValue) ||\n entry.entryFingerprint !== change.afterEntryFingerprint ||\n entry.fileFingerprint !== change.afterFileFingerprint ||\n JSON.stringify(entry.value) !== JSON.stringify(change.afterEntryValue) ||\n !entryMatches(entry.value, entry.entryFingerprint, pending.connectionMethod)\n ) {\n throw new Error(`Machine setup receipt changed reviewed target ${change.path}.`);\n }\n }\n}\n\nfunction assertNoOtherStoreWork(\n db: StoreDatabase,\n targetRoot: string,\n ownOperationId?: string,\n): void {\n const tool = db.prepare(\n `SELECT operation_id FROM tool_operations WHERE status='pending'${ownOperationId ? \" AND operation_id<>?\" : \"\"} LIMIT 1`,\n ).get(...(ownOperationId ? [ownOperationId] : [])) as { operation_id: string } | undefined;\n const project = db.prepare(\n `SELECT operations.operation_id\n FROM installation_operations AS operations\n JOIN installation_checkouts AS checkouts\n ON checkouts.checkout_id=operations.checkout_id\n WHERE operations.status='pending' AND checkouts.root_path=?\n LIMIT 1`,\n ).get(targetRoot) as { operation_id: string } | undefined;\n const writer = db.prepare(\n \"SELECT root_path FROM installation_locks WHERE root_path=? LIMIT 1\",\n ).get(targetRoot) as\n | { root_path: string }\n | undefined;\n if (tool || project || writer) {\n throw new Error(\n `A Store operation is already pending (${tool?.operation_id ?? project?.operation_id ?? writer?.root_path}). Resolve it before machine setup. No native file was changed.`,\n );\n }\n}\n\nfunction entryMatches(\n value: NativeEntryValue | null,\n fingerprint: string | null,\n method: HarnessConnectionMethod,\n): boolean {\n return value === null ? fingerprint === null :\n fingerprint === fingerprintEntry(value) ||\n (method === \"mcp\" && isRedactedMcpNativeValue(value) && isFingerprint(fingerprint, false));\n}\n\nfunction redactHarnessPlan(plan: HarnessAccessPlan): HarnessAccessPlan {\n if (plan.connectionMethod !== \"mcp\") return plan;\n return {\n ...plan,\n changes: plan.changes.map(change => ({\n ...change,\n beforeEntryValue: redactMcpNativeValue(change.beforeEntryValue),\n afterEntryValue: redactMcpNativeValue(change.afterEntryValue),\n })),\n };\n}\n\nfunction isFingerprint(value: string | null, allowNull: boolean): boolean {\n return (allowNull && value === null) || (typeof value === \"string\" && /^[0-9a-f]{64}$/.test(value));\n}\n\nfunction fingerprintJson(value: unknown): string {\n return createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nfunction invalidPending(operationId: string): Error {\n return new Error(\n `Pending machine setup ${operationId} has invalid Store evidence. Preserve it for manual recovery.`,\n );\n}\n\nfunction changedPending(operationId: string): Error {\n return new Error(\n `Pending machine setup ${operationId} changed before completion. Preserve it for Store recovery.`,\n );\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { getGlobalManifestPath, STORE_DATABASE_FILE } from \"./paths\";\nimport { writeStoreJsonFile } from \"./json-files\";\n\n/**\n * Global manifest: tool-level state for the machine-level store (R-STORE-1).\n * It records what bootstrapped the store and the operational status of the\n * SQLite database. It is not the project install manifest — each project's\n * `<repo>/.make-docs/manifest.json` remains the canonical install record\n * (R-MIR-1); this file carries only tool-level state.\n */\n\nexport const GLOBAL_MANIFEST_SCHEMA_VERSION = 1;\n\nexport type StoreDatabaseStatus =\n | \"ready\"\n | \"created\"\n | \"recovered\"\n | \"schema-newer\"\n | \"unavailable\";\n\nexport interface GlobalManifestBootstrapRecord {\n packageName: string;\n packageVersion: string;\n nodeVersion: string;\n at: string;\n}\n\nexport interface GlobalManifestDatabaseRecord {\n file: string;\n schemaVersion: number | null;\n status: StoreDatabaseStatus;\n}\n\nexport interface GlobalManifest {\n schemaVersion: number;\n createdAt: string;\n updatedAt: string;\n lastBootstrap: GlobalManifestBootstrapRecord | null;\n database: GlobalManifestDatabaseRecord;\n}\n\nexport function defaultGlobalManifest(now: string): GlobalManifest {\n return {\n schemaVersion: GLOBAL_MANIFEST_SCHEMA_VERSION,\n createdAt: now,\n updatedAt: now,\n lastBootstrap: null,\n database: {\n file: STORE_DATABASE_FILE,\n schemaVersion: null,\n status: \"unavailable\",\n },\n };\n}\n\n/**\n * Loads the global manifest, tolerating a missing or unreadable file by\n * returning null; callers recreate it, because it is recoverable operational\n * state rather than project knowledge.\n */\nexport function loadGlobalManifest(storeRoot: string): GlobalManifest | null {\n const manifestPath = getGlobalManifestPath(storeRoot);\n if (!existsSync(manifestPath)) {\n return null;\n }\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n } catch {\n return null;\n }\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const nowFallback = new Date().toISOString();\n const database =\n typeof record.database === \"object\" && record.database !== null && !Array.isArray(record.database)\n ? (record.database as Record<string, unknown>)\n : {};\n return {\n schemaVersion:\n typeof record.schemaVersion === \"number\"\n ? record.schemaVersion\n : GLOBAL_MANIFEST_SCHEMA_VERSION,\n createdAt: typeof record.createdAt === \"string\" ? record.createdAt : nowFallback,\n updatedAt: typeof record.updatedAt === \"string\" ? record.updatedAt : nowFallback,\n lastBootstrap: normalizeBootstrapRecord(record.lastBootstrap),\n database: {\n file: typeof database.file === \"string\" ? database.file : STORE_DATABASE_FILE,\n schemaVersion:\n typeof database.schemaVersion === \"number\" ? database.schemaVersion : null,\n status: normalizeDatabaseStatus(database.status),\n },\n };\n}\n\nexport function writeGlobalManifest(storeRoot: string, manifest: GlobalManifest): string {\n const manifestPath = getGlobalManifestPath(storeRoot);\n writeStoreJsonFile(manifestPath, manifest);\n return manifestPath;\n}\n\nfunction normalizeBootstrapRecord(value: unknown): GlobalManifestBootstrapRecord | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n if (\n typeof record.packageName !== \"string\" ||\n typeof record.packageVersion !== \"string\" ||\n typeof record.nodeVersion !== \"string\" ||\n typeof record.at !== \"string\"\n ) {\n return null;\n }\n return {\n packageName: record.packageName,\n packageVersion: record.packageVersion,\n nodeVersion: record.nodeVersion,\n at: record.at,\n };\n}\n\nfunction normalizeDatabaseStatus(value: unknown): StoreDatabaseStatus {\n if (\n value === \"ready\" ||\n value === \"created\" ||\n value === \"recovered\" ||\n value === \"schema-newer\" ||\n value === \"unavailable\"\n ) {\n return value;\n }\n return \"unavailable\";\n}\n","import { acquireStoreAccess, classifyStoreCheckpoint9State, CURRENT_STORE_SCHEMA_VERSION, openStoreSqliteConnection, type StoreDatabase } from \"./database\";\n\nexport type StoreBridgeDisposition =\n | \"convert\"\n | \"retain-history\"\n | \"rebuild\"\n | \"quarantine\"\n | \"unsupported\"\n | \"removable-after-proof\";\n\nexport interface StoreBridgeRegisterEntry {\n bridgeId: string;\n oldForm: string;\n targetForm: string;\n firstBridgeVersion: string;\n owner: string;\n oldWritesStoppedProof: string;\n remainingStateCheck: string;\n endCondition: string;\n removalPhaseOrRelease: string;\n requiredTests: readonly string[];\n retentionAndExportRule: string;\n separateDeletionApproval: true;\n}\n\nexport interface StoreBridgeRecordClassification {\n bridgeId: string;\n disposition: StoreBridgeDisposition;\n count: number;\n reason: string;\n}\n\nexport interface StoreCompatibilityBridgePreview {\n schemaVersion: 1;\n readOnly: true;\n databasePath: string;\n storeState: ReturnType<typeof classifyStoreCheckpoint9State>[\"state\"];\n sourceSchemaVersion: number | null;\n targetSchemaVersion: number;\n disposition: StoreBridgeDisposition;\n records: StoreBridgeRecordClassification[];\n changes: {\n store: string[];\n project: string[];\n native: string[];\n };\n blockers: string[];\n nextAction: string;\n}\n\n/**\n * The bounded W22 P5 bridge register required by PRD 18 R-BRIDGE-4.\n * Entries stay data-only so status and tests can inspect the same contract.\n */\nexport const STORE_COMPATIBILITY_BRIDGE_REGISTER: readonly StoreBridgeRegisterEntry[] = Object.freeze([\n {\n bridgeId: \"w22-p5-store-schema-v1-v4\",\n oldForm: \"Store schemas 1 through 4\",\n targetForm: \"Store schema 5\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Store compatibility owner\",\n oldWritesStoppedProof: \"openStoreDatabase rejects schemas below 5 outside the reviewed migration path.\",\n remainingStateCheck: \"PRAGMA user_version is below 5.\",\n endCondition: \"No supported installation remains below schema 5.\",\n removalPhaseOrRelease: \"A later owner-approved release after P6 installed-package proof\",\n requiredTests: [\"schemas 1-4\", \"repeat\", \"interruption\", \"newer\", \"corrupt\"],\n retentionAndExportRule: \"Keep the verified pre-conversion Store backup until separate cleanup approval.\",\n separateDeletionApproval: true,\n },\n {\n bridgeId: \"w22-p5-checkout-object-numbers\",\n oldForm: \"installation_checkouts.root_device and root_inode\",\n targetForm: \"checkout id, platform path key, and bounded live verification evidence\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Store identity owner\",\n oldWritesStoppedProof: \"The schema-5 checkout writer omits both fields and schema 5 has no such columns.\",\n remainingStateCheck: \"Schema below 5 has either legacy column.\",\n endCondition: \"All supported Stores are schema 5 and archived values remain history only.\",\n removalPhaseOrRelease: \"W22 P5 field retirement; history cleanup needs later approval\",\n requiredTests: [\"moved checkout\", \"clone\", \"repeat\", \"rollback\", \"all core platforms\"],\n retentionAndExportRule: \"Archive exact strings as legacy-import evidence. Do not use them as identity.\",\n separateDeletionApproval: true,\n },\n {\n bridgeId: \"w22-p5-checkpoint-receipts\",\n oldForm: \"store_checkpoint_journal rows\",\n targetForm: \"store_migration_receipts history\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Store migration owner\",\n oldWritesStoppedProof: \"Checkpoint 9 writes store_migration_receipts after schema-5 cutover.\",\n remainingStateCheck: \"Count rows present only in store_checkpoint_journal.\",\n endCondition: \"Every old receipt has a byte-equivalent target history row.\",\n removalPhaseOrRelease: \"Later compatibility cleanup after export and owner approval\",\n requiredTests: [\"receipt copy\", \"readback\", \"projection retry\", \"repeat\"],\n retentionAndExportRule: \"Preserve old rows as private local history until separately approved export or deletion.\",\n separateDeletionApproval: true,\n },\n {\n bridgeId: \"w22-p5-installation-transfers\",\n oldForm: \"installation_transfers rows\",\n targetForm: \"legacy-import migration record source evidence\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Installation migration owner\",\n oldWritesStoppedProof: \"Legacy import writes source evidence only to installation_migration_records.\",\n remainingStateCheck: \"Count installation_transfers rows.\",\n endCondition: \"Supported local-state transfer is complete and retained source evidence is readable.\",\n removalPhaseOrRelease: \"Later transfer-bridge cleanup after owner approval\",\n requiredTests: [\"legacy import\", \"repeat\", \"interruption\", \"source readback\"],\n retentionAndExportRule: \"Retain existing transfer rows as private history. Do not delete source evidence in P5.\",\n separateDeletionApproval: true,\n },\n {\n bridgeId: \"w22-p5-installation-ledger\",\n oldForm: \"installation ledger records with legacy projection mirrors\",\n targetForm: \"versioned installation ledger with minimum applied projection ownership\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Installation state owner\",\n oldWritesStoppedProof: \"P4 target writers omit projection selection and provider mirrors.\",\n remainingStateCheck: \"Parse ledgers and count legacy resourceProjection.selectedTypes, provider, or legacy resource fields.\",\n endCondition: \"Every active ledger has the target projection form or is retained as opaque history.\",\n removalPhaseOrRelease: \"P5 conversion; broad-history cleanup needs later approval\",\n requiredTests: [\"legacy ledger\", \"current ledger\", \"malformed ledger\", \"repeat\"],\n retentionAndExportRule: \"Preserve the source Store backup and never delete project content during conversion.\",\n separateDeletionApproval: true,\n },\n {\n bridgeId: \"w22-p5-harness-receipt-v1\",\n oldForm: \"Harness receipt schema 1 executable proof\",\n targetForm: \"Schema 2 receipt history plus call-time executable verification\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Harness trust owner\",\n oldWritesStoppedProof: \"P4 receipt writers emit schema 2 and omit executable proof.\",\n remainingStateCheck: \"Count schemaVersion 1 receipt JSON in migration records and tool-operation history.\",\n endCondition: \"All active receipt writes are schema 2 and schema 1 remains history only.\",\n removalPhaseOrRelease: \"Later receipt-history cleanup after export and owner approval\",\n requiredTests: [\"schema 1 read\", \"schema 2 write\", \"package update\", \"moved launch\"],\n retentionAndExportRule: \"Retain valid schema 1 receipts as private history. Never use them for current access.\",\n separateDeletionApproval: true,\n },\n {\n bridgeId: \"w22-p5-pending-operations\",\n oldForm: \"Supported pending installation operation and step rows\",\n targetForm: \"The same shared operation journal with target checkout and ledger readers\",\n firstBridgeVersion: \"2.0.0-rc\",\n owner: \"Installation recovery owner\",\n oldWritesStoppedProof: \"No second recovery table or project-local marker is introduced.\",\n remainingStateCheck: \"Count installation_operations with status pending and inspect plan_complete plus saved steps.\",\n endCondition: \"Each pending operation reaches completed or rolled-back through the shared journal.\",\n removalPhaseOrRelease: \"Normal operation retention, not bridge deletion\",\n requiredTests: [\"complete plan resume\", \"incomplete rollback\", \"conflict stop\", \"restart\"],\n retentionAndExportRule: \"Keep exact recovery evidence until the operation reaches a verified terminal state.\",\n separateDeletionApproval: true,\n },\n]);\n\n/** Read and classify the full Store bridge without creating or changing state. */\nexport function previewStoreCompatibilityBridge(storeRoot: string): StoreCompatibilityBridgePreview {\n const classification = classifyStoreCheckpoint9State(storeRoot);\n const base = {\n schemaVersion: 1 as const,\n readOnly: true as const,\n databasePath: classification.databasePath,\n storeState: classification.state,\n sourceSchemaVersion: classification.schemaVersion,\n targetSchemaVersion: CURRENT_STORE_SCHEMA_VERSION,\n };\n if (classification.state === \"absent\") {\n return {\n ...base,\n disposition: \"rebuild\",\n records: [],\n changes: {\n store: [`Create a fresh schema-${CURRENT_STORE_SCHEMA_VERSION} Store.`],\n project: [],\n native: [],\n },\n blockers: [],\n nextAction: \"Review setup. Setup can create the Store without a compatibility conversion.\",\n };\n }\n if (classification.state === \"newer-unknown\") {\n return unsafePreview(base, \"unsupported\", classification.reason, \"Update Make Docs to a version that supports this Store.\");\n }\n if (classification.state === \"corrupt\" || classification.state === \"unknown\" || classification.state === \"indeterminate\") {\n return unsafePreview(base, \"quarantine\", classification.reason, \"Repair or restore this preserved Store before Store-backed work.\");\n }\n\n const release = acquireStoreAccess(storeRoot);\n let db: StoreDatabase | null = null;\n try {\n db = openStoreSqliteConnection(classification.databasePath, { readOnly: true }, \"preview Store compatibility bridge\");\n const version = classification.schemaVersion;\n const tables = new Set((db.prepare(\"SELECT name FROM sqlite_schema WHERE type='table'\").all() as Array<{ name: string }>).map((row) => row.name));\n const records: StoreBridgeRecordClassification[] = [];\n const changes: string[] = [];\n const blockers: string[] = [];\n\n if (version < 5) {\n records.push(record(\"w22-p5-store-schema-v1-v4\", \"convert\", 1, `Schema ${version} has a supported conversion to schema ${CURRENT_STORE_SCHEMA_VERSION}.`));\n }\n if (version < 6) {\n records.push(record(\n \"w23-r0-p5-backlog-review-cache\",\n \"convert\",\n 1,\n `Schema ${version} can add the optional rebuildable backlog review cache.`,\n ));\n }\n if (version < CURRENT_STORE_SCHEMA_VERSION) {\n changes.push(`Create and verify one Store backup before converting schema ${version} to schema ${CURRENT_STORE_SCHEMA_VERSION}.`);\n }\n if (version >= 3 && tables.has(\"installation_checkouts\")) {\n const bridgeCollisions = Number((db.prepare(\"SELECT COUNT(*) AS count FROM installation_migration_records WHERE kind='legacy-import' AND record_id IN ('w22-p5:checkout-object-numbers:v4','w22-p5:installation-ledger-projection:v4')\").get() as { count: number | bigint }).count);\n if (version < 5 && bridgeCollisions) blockers.push(`${bridgeCollisions} reserved P5 bridge record(s) already exist in an older schema.`);\n const activeLocks = Number((db.prepare(\"SELECT COUNT(*) AS count FROM installation_locks\").get() as { count: number | bigint }).count);\n if (activeLocks) blockers.push(`${activeLocks} active installation lock(s) must finish before conversion.`);\n const pendingToolOperations = Number((db.prepare(\"SELECT COUNT(*) AS count FROM tool_operations WHERE status='pending'\").get() as { count: number | bigint }).count);\n if (pendingToolOperations) blockers.push(`${pendingToolOperations} pending tool operation(s) require recovery before conversion.`);\n const columns = new Set((db.prepare(\"PRAGMA table_info(installation_checkouts)\").all() as Array<{ name: string }>).map((row) => row.name));\n if (columns.has(\"root_device\") || columns.has(\"root_inode\")) {\n const count = countRows(db, \"installation_checkouts\");\n records.push(record(\"w22-p5-checkout-object-numbers\", \"convert\", count, \"Archive legacy values as evidence, then remove the active identity columns.\"));\n changes.push(`Archive device and inode strings for ${count} checkout row(s), then remove both active columns.`);\n } else {\n const count = countRecordId(db, \"w22-p5:checkout-object-numbers:v4\");\n records.push(record(\"w22-p5-checkout-object-numbers\", \"retain-history\", count, \"Object numbers are no longer active fields.\"));\n }\n\n const ledgerRows = db.prepare(\"SELECT checkout_id, manifest_json FROM installation_ledgers ORDER BY checkout_id\").all() as Array<{ checkout_id: string; manifest_json: string }>;\n let legacyLedgers = 0;\n for (const row of ledgerRows) {\n const value = parseObject(row.manifest_json);\n if (!value) {\n blockers.push(`Installation ledger ${row.checkout_id} is malformed or unsupported.`);\n continue;\n }\n if (hasLegacyProjection(value)) legacyLedgers++;\n }\n records.push(record(\"w22-p5-installation-ledger\", legacyLedgers ? \"convert\" : \"retain-history\", ledgerRows.length, legacyLedgers ? `${legacyLedgers} ledger(s) use legacy projection mirrors.` : \"All readable ledgers use the accepted projection form.\"));\n if (legacyLedgers) changes.push(`Convert legacy projection mirrors in ${legacyLedgers} installation ledger(s) through the versioned reader and target writer.`);\n\n const transfers = countRows(db, \"installation_transfers\");\n records.push(record(\"w22-p5-installation-transfers\", transfers ? \"retain-history\" : \"removable-after-proof\", transfers, transfers ? \"Existing rows remain private history. New imports use migration records.\" : \"No legacy transfer rows remain.\"));\n\n const pending = Number((db.prepare(\"SELECT COUNT(*) AS count FROM installation_operations WHERE status='pending'\").get() as { count: number | bigint }).count);\n records.push(record(\"w22-p5-pending-operations\", \"retain-history\", pending, pending ? \"Pending work remains in the shared recovery journal.\" : \"No pending installation operation exists.\"));\n\n const receiptVersions = countHarnessReceiptVersions(db);\n records.push(record(\"w22-p5-harness-receipt-v1\", \"retain-history\", receiptVersions.legacy, `${receiptVersions.legacy} schema-1 receipt(s) remain readable history; ${receiptVersions.current} schema-2 receipt(s) use current form.`));\n }\n\n if (tables.has(\"store_checkpoint_journal\")) {\n const oldReceipts = countRows(db, \"store_checkpoint_journal\");\n const targetReceipts = tables.has(\"store_migration_receipts\") ? countRows(db, \"store_migration_receipts\") : 0;\n records.push(record(\"w22-p5-checkpoint-receipts\", version < CURRENT_STORE_SCHEMA_VERSION && oldReceipts ? \"convert\" : \"retain-history\", oldReceipts, `${targetReceipts} target receipt(s) and ${oldReceipts} retained checkpoint receipt(s) are present.`));\n if (version < CURRENT_STORE_SCHEMA_VERSION && oldReceipts) changes.push(`Copy ${oldReceipts} checkpoint receipt row(s) to target receipt history and verify readback.`);\n }\n\n const disposition: StoreBridgeDisposition = blockers.length\n ? \"quarantine\"\n : version < CURRENT_STORE_SCHEMA_VERSION || records.some((entry) => entry.disposition === \"convert\")\n ? \"convert\"\n : \"retain-history\";\n return {\n ...base,\n disposition,\n records,\n changes: { store: changes, project: [], native: [] },\n blockers,\n nextAction: blockers.length\n ? \"Keep the Store unchanged. Repair the listed record, then preview setup again.\"\n : disposition === \"convert\"\n ? \"Review this exact Store plan, then run setup to apply it.\"\n : \"No compatibility conversion is required.\",\n };\n } finally {\n db?.close();\n release();\n }\n}\n\nfunction unsafePreview(\n base: Pick<StoreCompatibilityBridgePreview, \"schemaVersion\" | \"readOnly\" | \"databasePath\" | \"storeState\" | \"sourceSchemaVersion\" | \"targetSchemaVersion\">,\n disposition: \"quarantine\" | \"unsupported\",\n reason: string,\n nextAction: string,\n): StoreCompatibilityBridgePreview {\n return { ...base, disposition, records: [], changes: { store: [], project: [], native: [] }, blockers: [reason], nextAction };\n}\n\nfunction record(bridgeId: string, disposition: StoreBridgeDisposition, count: number, reason: string): StoreBridgeRecordClassification {\n return { bridgeId, disposition, count, reason };\n}\n\nfunction countRows(db: StoreDatabase, table: \"installation_checkouts\" | \"installation_transfers\" | \"store_checkpoint_journal\" | \"store_migration_receipts\"): number {\n return Number((db.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get() as { count: number | bigint }).count);\n}\n\nfunction countRecordId(db: StoreDatabase, recordId: string): number {\n return Number((db.prepare(\"SELECT COUNT(*) AS count FROM installation_migration_records WHERE record_id=?\").get(recordId) as { count: number | bigint }).count);\n}\n\nfunction parseObject(value: string): Record<string, unknown> | null {\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;\n } catch {\n return null;\n }\n}\n\nfunction hasLegacyProjection(manifest: Record<string, unknown>): boolean {\n const projection = manifest.resourceProjection;\n if (!projection || typeof projection !== \"object\" || Array.isArray(projection)) return false;\n const value = projection as Record<string, unknown>;\n if (\"selectedTypes\" in value || \"provider\" in value) return true;\n const resources = value.resources;\n if (!resources || typeof resources !== \"object\" || Array.isArray(resources)) return false;\n const legacy = new Set([\"type\", \"resourcePath\", \"provenanceState\", \"providerPackage\", \"providerVersion\", \"providerImmutableRef\", \"materializationMode\", \"sourceDigest\", \"adoptionReceipt\", \"selectionTrigger\", \"operationLineage\", \"provenanceEvidence\", \"competingClaims\"]);\n return Object.values(resources as Record<string, unknown>).some((entry) => entry && typeof entry === \"object\" && !Array.isArray(entry) && Object.keys(entry as Record<string, unknown>).some((key) => legacy.has(key)));\n}\n\nfunction countHarnessReceiptVersions(db: StoreDatabase): { legacy: number; current: number } {\n let legacy = 0;\n let current = 0;\n const values: string[] = [];\n values.push(...(db.prepare(\"SELECT record_json FROM installation_migration_records WHERE kind='receipt'\").all() as Array<{ record_json: string }>).map((row) => row.record_json));\n values.push(...(db.prepare(\"SELECT metadata_json FROM tool_operations WHERE operation LIKE 'setup.system.receipt%'\").all() as Array<{ metadata_json: string }>).map((row) => row.metadata_json));\n for (const value of values) {\n const parsed = parseObject(value);\n if (parsed?.schemaVersion === 1) legacy++;\n if (parsed?.schemaVersion === 2) current++;\n }\n return { legacy, current };\n}\n","import type { JsonValue } from \"../operations/types\";\nimport type { StoreDatabase } from \"./database\";\n\n/**\n * Row-level primitives over the operational schema. This is the storage seam\n * consumed by later phases and by downstream lineages: the stable-project-\n * identity phase (W18 R10 P2), the unified project-state model (P3), the\n * W18 R7 runner's run-state storage, and the retained work-execution evidence\n * operations (W18 R11).\n *\n * Every project-scoped row is keyed by the manifest-minted project identifier\n * supplied by the caller (R-ID-1); this module never derives identity from a\n * path (R-ID-2) and stores run records and evidence payloads as opaque JSON so\n * the record shapes stay owned by their own lineages (R-SCOPE-1).\n */\n\nexport interface ProjectRegistryEntry {\n projectId: string;\n rootPath: string;\n packageName: string | null;\n packageVersion: string | null;\n registeredAt: string;\n lastSeenAt: string;\n}\n\nexport interface PlaybookRunRow {\n projectId: string;\n runId: string;\n record: JsonValue;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface WorkEvidenceRow {\n projectId: string;\n waveSlug: string;\n phasePath: string;\n evidenceKind: string;\n payload: JsonValue;\n repoRoot: string | null;\n recordedAt: string;\n}\n\n/**\n * Inserts or refreshes an install-registry mirror row (R-MIR-1). The\n * canonical install record remains the project's `.make-docs/manifest.json`.\n */\nexport function upsertProjectRegistryEntry(\n db: StoreDatabase,\n entry: {\n projectId: string;\n rootPath: string;\n packageName?: string | null;\n packageVersion?: string | null;\n now?: string;\n },\n): void {\n const now = entry.now ?? new Date().toISOString();\n db.prepare(\n `INSERT INTO projects (project_id, root_path, package_name, package_version, registered_at, last_seen_at)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id) DO UPDATE SET\n root_path = excluded.root_path,\n package_name = excluded.package_name,\n package_version = excluded.package_version,\n last_seen_at = excluded.last_seen_at`,\n ).run(\n entry.projectId,\n entry.rootPath,\n entry.packageName ?? null,\n entry.packageVersion ?? null,\n now,\n now,\n );\n}\n\nexport function readProjectRegistryEntry(\n db: StoreDatabase,\n projectId: string,\n): ProjectRegistryEntry | null {\n const row = db\n .prepare(\n `SELECT project_id, root_path, package_name, package_version, registered_at, last_seen_at\n FROM projects WHERE project_id = ?`,\n )\n .get(projectId) as Record<string, unknown> | undefined;\n return row ? toProjectRegistryEntry(row) : null;\n}\n\nexport function listProjectRegistryEntries(db: StoreDatabase): ProjectRegistryEntry[] {\n const rows = db\n .prepare(\n `SELECT project_id, root_path, package_name, package_version, registered_at, last_seen_at\n FROM projects ORDER BY project_id`,\n )\n .all() as Array<Record<string, unknown>>;\n return rows.map(toProjectRegistryEntry);\n}\n\n/** Thrown when `createPlaybookRunRecord` collides with an existing run row. */\nexport class PlaybookRunExistsError extends Error {\n constructor(projectId: string, runId: string) {\n super(\n `A Playbook run record already exists for project ${projectId} and run ${runId}. ` +\n \"Use transitionPlaybookRunRecord to update an existing run.\",\n );\n this.name = \"PlaybookRunExistsError\";\n }\n}\n\n/** Thrown when `transitionPlaybookRunRecord` targets a run row that does not exist. */\nexport class PlaybookRunNotFoundError extends Error {\n constructor(projectId: string, runId: string) {\n super(\n `No Playbook run record exists for project ${projectId} and run ${runId}. ` +\n \"Use createPlaybookRunRecord to create a run before transitioning it.\",\n );\n this.name = \"PlaybookRunNotFoundError\";\n }\n}\n\n/**\n * Creates a Playbook run-state record (W18 R10 P3, t2). This is the create\n * half of the storage seam PRD 35's R-STORE-1/R-STORE-2 consume: keyed by\n * (project identifier, run identifier), record stored as opaque JSON. The\n * record shape and progression semantics stay owned by the W18 R7 lineage\n * (R-SCOPE-1); this seam only guarantees create-versus-transition integrity\n * at the storage level. Fails explicitly when the run already exists.\n */\nexport function createPlaybookRunRecord(\n db: StoreDatabase,\n input: { projectId: string; runId: string; record: JsonValue; now?: string },\n): void {\n const now = input.now ?? new Date().toISOString();\n try {\n db.prepare(\n `INSERT INTO playbook_runs (project_id, run_id, record, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?)`,\n ).run(input.projectId, input.runId, JSON.stringify(input.record), now, now);\n } catch (error) {\n if (error instanceof Error && /UNIQUE constraint failed/i.test(error.message)) {\n throw new PlaybookRunExistsError(input.projectId, input.runId);\n }\n throw error;\n }\n}\n\n/**\n * Transitions (replaces) an existing Playbook run-state record. The new\n * record is opaque to the store — what a valid transition IS (statuses,\n * cursors, gates) is the W18 R7 runner's business; storage only guarantees\n * the run exists and the write is atomic. Fails explicitly when the run does\n * not exist so a transition can never silently create state.\n */\nexport function transitionPlaybookRunRecord(\n db: StoreDatabase,\n input: { projectId: string; runId: string; record: JsonValue; now?: string },\n): void {\n const now = input.now ?? new Date().toISOString();\n const result = db\n .prepare(\n `UPDATE playbook_runs SET record = ?, updated_at = ?\n WHERE project_id = ? AND run_id = ?`,\n )\n .run(JSON.stringify(input.record), now, input.projectId, input.runId);\n if (Number(result.changes) === 0) {\n throw new PlaybookRunNotFoundError(input.projectId, input.runId);\n }\n}\n\n/** Lists a project's Playbook run-state records (records stay opaque JSON). */\nexport function listPlaybookRunRecords(\n db: StoreDatabase,\n projectId: string,\n): PlaybookRunRow[] {\n const rows = db\n .prepare(\n `SELECT project_id, run_id, record, created_at, updated_at\n FROM playbook_runs WHERE project_id = ? ORDER BY run_id`,\n )\n .all(projectId) as Array<Record<string, unknown>>;\n return rows.map((row) => ({\n projectId: String(row.project_id),\n runId: String(row.run_id),\n record: JSON.parse(String(row.record)) as JsonValue,\n createdAt: String(row.created_at),\n updatedAt: String(row.updated_at),\n }));\n}\n\n/** Writes a Playbook run-state record (opaque JSON payload; shape owned by W18 R7). */\nexport function upsertPlaybookRunRecord(\n db: StoreDatabase,\n input: { projectId: string; runId: string; record: JsonValue; now?: string },\n): void {\n const now = input.now ?? new Date().toISOString();\n db.prepare(\n `INSERT INTO playbook_runs (project_id, run_id, record, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT (project_id, run_id) DO UPDATE SET\n record = excluded.record,\n updated_at = excluded.updated_at`,\n ).run(input.projectId, input.runId, JSON.stringify(input.record), now, now);\n}\n\nexport function readPlaybookRunRecord(\n db: StoreDatabase,\n projectId: string,\n runId: string,\n): PlaybookRunRow | null {\n const row = db\n .prepare(\n `SELECT project_id, run_id, record, created_at, updated_at\n FROM playbook_runs WHERE project_id = ? AND run_id = ?`,\n )\n .get(projectId, runId) as Record<string, unknown> | undefined;\n if (!row) {\n return null;\n }\n return {\n projectId: String(row.project_id),\n runId: String(row.run_id),\n record: JSON.parse(String(row.record)) as JsonValue,\n createdAt: String(row.created_at),\n updatedAt: String(row.updated_at),\n };\n}\n\n/**\n * Records a work-execution evidence entry against the canonical work-item\n * identity components supplied by the caller (R-PS-3).\n */\nexport function upsertWorkEvidence(\n db: StoreDatabase,\n input: {\n projectId: string;\n waveSlug: string;\n phasePath: string;\n evidenceKind: string;\n payload: JsonValue;\n repoRoot?: string | null;\n now?: string;\n },\n): void {\n const now = input.now ?? new Date().toISOString();\n db.prepare(\n `INSERT INTO work_evidence (project_id, wave_slug, phase_path, evidence_kind, payload, repo_root, recorded_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, wave_slug, phase_path, evidence_kind) DO UPDATE SET\n payload = excluded.payload,\n repo_root = excluded.repo_root,\n recorded_at = excluded.recorded_at`,\n ).run(\n input.projectId,\n input.waveSlug,\n input.phasePath,\n input.evidenceKind,\n JSON.stringify(input.payload),\n input.repoRoot ?? null,\n now,\n );\n}\n\nexport function listWorkEvidence(\n db: StoreDatabase,\n filter: { projectId: string; waveSlug?: string; phasePath?: string },\n): WorkEvidenceRow[] {\n const clauses = [\"project_id = ?\"];\n const params: string[] = [filter.projectId];\n if (filter.waveSlug !== undefined) {\n clauses.push(\"wave_slug = ?\");\n params.push(filter.waveSlug);\n }\n if (filter.phasePath !== undefined) {\n clauses.push(\"phase_path = ?\");\n params.push(filter.phasePath);\n }\n const rows = db\n .prepare(\n `SELECT project_id, wave_slug, phase_path, evidence_kind, payload, repo_root, recorded_at\n FROM work_evidence WHERE ${clauses.join(\" AND \")}\n ORDER BY wave_slug, phase_path, evidence_kind`,\n )\n .all(...params) as Array<Record<string, unknown>>;\n return rows.map((row) => ({\n projectId: String(row.project_id),\n waveSlug: String(row.wave_slug),\n phasePath: String(row.phase_path),\n evidenceKind: String(row.evidence_kind),\n payload: JSON.parse(String(row.payload)) as JsonValue,\n repoRoot: row.repo_root === null ? null : String(row.repo_root),\n recordedAt: String(row.recorded_at),\n }));\n}\n\n/**\n * Removes current rows keyed by the given project identifier inside one\n * transaction. Opaque legacy `playbook_runs` rows are deliberately excluded\n * from this current-state pruning seam (PRD 38 R-PS-6 / R-LIFE-2).\n */\nexport function deleteProjectRows(db: StoreDatabase, projectId: string): void {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n db.prepare(\"DELETE FROM run_evidence WHERE project_id = ?\").run(projectId);\n db.prepare(\"DELETE FROM runs WHERE project_id = ?\").run(projectId);\n db.prepare(\"DELETE FROM work_evidence WHERE project_id = ?\").run(projectId);\n db.prepare(\"DELETE FROM playbook_runs WHERE project_id = ?\").run(projectId);\n db.prepare(\"DELETE FROM projects WHERE project_id = ?\").run(projectId);\n db.exec(\"COMMIT\");\n } catch (error) {\n try {\n db.exec(\"ROLLBACK\");\n } catch {\n // The transaction may already be rolled back.\n }\n throw error;\n }\n}\n\nfunction toProjectRegistryEntry(row: Record<string, unknown>): ProjectRegistryEntry {\n return {\n projectId: String(row.project_id),\n rootPath: String(row.root_path),\n packageName: row.package_name === null ? null : String(row.package_name),\n packageVersion: row.package_version === null ? null : String(row.package_version),\n registeredAt: String(row.registered_at),\n lastSeenAt: String(row.last_seen_at),\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { OperationError, type JsonValue } from \"../operations/types\";\nimport {\n CURRENT_STORE_SCHEMA_VERSION,\n type StoreDatabase,\n} from \"./database\";\n\nexport const LIFECYCLE_RUN_TYPES = [\"lifecycle\"] as const;\nexport type LifecycleRunType = (typeof LIFECYCLE_RUN_TYPES)[number];\n\nexport const LIFECYCLE_STAGES = [\n \"design\",\n \"plan\",\n \"prd\",\n \"work\",\n \"implementation\",\n \"release\",\n \"archive\",\n \"retrospective\",\n] as const;\nexport type LifecycleStage = (typeof LIFECYCLE_STAGES)[number];\n\nexport const LIFECYCLE_STATUSES = [\n \"active\",\n \"paused\",\n \"completed\",\n \"failed\",\n \"abandoned\",\n] as const;\nexport type LifecycleStatus = (typeof LIFECYCLE_STATUSES)[number];\n\nexport const LIFECYCLE_MUTATION_OPERATIONS = [\n \"lifecycle.start\",\n \"lifecycle.checkpoint\",\n \"lifecycle.pause\",\n \"lifecycle.resume\",\n \"lifecycle.attach-evidence\",\n \"lifecycle.complete\",\n \"lifecycle.fail\",\n \"lifecycle.abandon\",\n] as const;\nexport type LifecycleMutationOperation =\n (typeof LIFECYCLE_MUTATION_OPERATIONS)[number];\n\nexport type LifecycleMetadataValue = string | number | boolean | null;\nexport type LifecycleMetadata = Record<string, LifecycleMetadataValue>;\n\nexport interface LifecycleRunRow {\n projectId: string;\n runId: string;\n runType: LifecycleRunType;\n lifecycleStage: LifecycleStage;\n status: LifecycleStatus;\n checkpoint: string | null;\n version: number;\n metadata: LifecycleMetadata;\n startedAt: string;\n updatedAt: string;\n finishedAt: string | null;\n}\n\nexport interface LifecycleEvidenceRow {\n projectId: string;\n runId: string;\n evidenceId: string;\n evidenceKind: string;\n referenceType: \"project-path\" | \"external\";\n reference: string;\n digest: string | null;\n recordedAt: string;\n}\n\n/** Exact minimal receipt accepted for W19 R1 P6. */\nexport interface LifecycleStoreMutationReceipt {\n schemaVersion: 1;\n receiptId: string;\n operation: LifecycleMutationOperation;\n projectId: string;\n runId: string;\n storeSchemaVersion: number;\n resultingVersion: number;\n committedAt: string;\n}\n\nexport interface LifecycleStoreMutationResult {\n status: \"captured\";\n run: LifecycleRunRow;\n receipt: LifecycleStoreMutationReceipt;\n}\n\nexport class LifecycleRunNotFoundError extends OperationError {\n readonly code = \"lifecycle-run-not-found\";\n\n constructor(projectId: string, runId: string) {\n super(`No lifecycle run \\`${runId}\\` exists for project \\`${projectId}\\`.`);\n this.name = \"LifecycleRunNotFoundError\";\n }\n}\n\nexport class LifecycleRunExistsError extends OperationError {\n readonly code = \"lifecycle-run-exists\";\n\n constructor(projectId: string, runId: string) {\n super(`Lifecycle run \\`${runId}\\` already exists for project \\`${projectId}\\`.`);\n this.name = \"LifecycleRunExistsError\";\n }\n}\n\nexport class LifecycleVersionConflictError extends OperationError {\n readonly code = \"lifecycle-version-conflict\";\n\n constructor(runId: string, expectedVersion: number, actualVersion: number) {\n super(\n `Lifecycle run \\`${runId}\\` is at version ${actualVersion}, not expected version ${expectedVersion}. ` +\n \"Read the current run and retry with its explicit version.\",\n );\n this.name = \"LifecycleVersionConflictError\";\n }\n}\n\nexport function createLifecycleRun(\n db: StoreDatabase,\n input: {\n projectId: string;\n runId: string;\n lifecycleStage: LifecycleStage;\n checkpoint?: string | null;\n metadata?: LifecycleMetadata;\n committedAt: string;\n },\n): LifecycleStoreMutationResult {\n return immediateTransaction(db, () => {\n try {\n db.prepare(\n `INSERT INTO runs (\n project_id, run_id, run_type, lifecycle_stage, status, checkpoint,\n version, metadata, started_at, updated_at, finished_at\n ) VALUES (?, ?, 'lifecycle', ?, 'active', ?, 1, ?, ?, ?, NULL)`,\n ).run(\n input.projectId,\n input.runId,\n input.lifecycleStage,\n input.checkpoint ?? null,\n JSON.stringify(input.metadata ?? {}),\n input.committedAt,\n input.committedAt,\n );\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new LifecycleRunExistsError(input.projectId, input.runId);\n }\n throw error;\n }\n const run = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n return {\n status: \"captured\",\n run,\n receipt: createLifecycleStoreMutationReceipt({\n operation: \"lifecycle.start\",\n projectId: input.projectId,\n runId: input.runId,\n resultingVersion: run.version,\n committedAt: input.committedAt,\n }),\n };\n });\n}\n\nexport function readLifecycleRun(\n db: StoreDatabase,\n projectId: string,\n runId: string,\n): LifecycleRunRow | null {\n const row = db\n .prepare(\n `SELECT project_id, run_id, run_type, lifecycle_stage, status, checkpoint,\n version, metadata, started_at, updated_at, finished_at\n FROM runs WHERE project_id = ? AND run_id = ?`,\n )\n .get(projectId, runId) as Record<string, unknown> | undefined;\n return row ? toLifecycleRunRow(row) : null;\n}\n\nexport function listLifecycleRuns(\n db: StoreDatabase,\n projectId: string,\n): LifecycleRunRow[] {\n const rows = db\n .prepare(\n `SELECT project_id, run_id, run_type, lifecycle_stage, status, checkpoint,\n version, metadata, started_at, updated_at, finished_at\n FROM runs WHERE project_id = ? ORDER BY started_at, run_id`,\n )\n .all(projectId) as Array<Record<string, unknown>>;\n return rows.map(toLifecycleRunRow);\n}\n\n/**\n * Applies one caller-authorized state change with explicit optimistic\n * concurrency. The caller owns the legal transition matrix.\n */\nexport function transitionLifecycleRun(\n db: StoreDatabase,\n input: {\n operation: Exclude<LifecycleMutationOperation, \"lifecycle.start\" | \"lifecycle.attach-evidence\">;\n projectId: string;\n runId: string;\n expectedVersion: number;\n nextStatus: LifecycleStatus;\n lifecycleStage?: LifecycleStage;\n checkpoint?: string | null;\n metadata?: LifecycleMetadata;\n committedAt: string;\n },\n): LifecycleStoreMutationResult {\n return immediateTransaction(db, () => {\n const current = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n assertExpectedVersion(current, input.expectedVersion);\n const resultingVersion = current.version + 1;\n const finishedAt = isTerminalStatus(input.nextStatus) ? input.committedAt : null;\n const result = db.prepare(\n `UPDATE runs SET\n lifecycle_stage = ?, status = ?, checkpoint = ?, version = ?,\n metadata = ?, updated_at = ?, finished_at = ?\n WHERE project_id = ? AND run_id = ? AND version = ?`,\n ).run(\n input.lifecycleStage ?? current.lifecycleStage,\n input.nextStatus,\n input.checkpoint === undefined ? current.checkpoint : input.checkpoint,\n resultingVersion,\n JSON.stringify(input.metadata ?? current.metadata),\n input.committedAt,\n finishedAt,\n input.projectId,\n input.runId,\n input.expectedVersion,\n );\n if (Number(result.changes) !== 1) {\n const latest = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n throw new LifecycleVersionConflictError(\n input.runId,\n input.expectedVersion,\n latest.version,\n );\n }\n const run = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n return {\n status: \"captured\",\n run,\n receipt: createLifecycleStoreMutationReceipt({\n operation: input.operation,\n projectId: input.projectId,\n runId: input.runId,\n resultingVersion,\n committedAt: input.committedAt,\n }),\n };\n });\n}\n\nexport function attachLifecycleEvidence(\n db: StoreDatabase,\n input: {\n projectId: string;\n runId: string;\n expectedVersion: number;\n evidenceId: string;\n evidenceKind: string;\n referenceType: \"project-path\" | \"external\";\n reference: string;\n digest?: string | null;\n committedAt: string;\n },\n): LifecycleStoreMutationResult & { evidence: LifecycleEvidenceRow } {\n return immediateTransaction(db, () => {\n const current = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n assertExpectedVersion(current, input.expectedVersion);\n try {\n db.prepare(\n `INSERT INTO run_evidence (\n project_id, run_id, evidence_id, evidence_kind, reference_type,\n reference_value, digest, recorded_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n input.projectId,\n input.runId,\n input.evidenceId,\n input.evidenceKind,\n input.referenceType,\n input.reference,\n input.digest ?? null,\n input.committedAt,\n );\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new OperationError(\n `Evidence \\`${input.evidenceId}\\` already exists for lifecycle run \\`${input.runId}\\`.`,\n );\n }\n throw error;\n }\n const resultingVersion = current.version + 1;\n const updated = db.prepare(\n `UPDATE runs SET version = ?, updated_at = ?\n WHERE project_id = ? AND run_id = ? AND version = ?`,\n ).run(\n resultingVersion,\n input.committedAt,\n input.projectId,\n input.runId,\n input.expectedVersion,\n );\n if (Number(updated.changes) !== 1) {\n const latest = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n throw new LifecycleVersionConflictError(\n input.runId,\n input.expectedVersion,\n latest.version,\n );\n }\n const run = readLifecycleRunOrThrow(db, input.projectId, input.runId);\n const evidence = readLifecycleEvidenceOrThrow(\n db,\n input.projectId,\n input.runId,\n input.evidenceId,\n );\n return {\n status: \"captured\",\n run,\n evidence,\n receipt: createLifecycleStoreMutationReceipt({\n operation: \"lifecycle.attach-evidence\",\n projectId: input.projectId,\n runId: input.runId,\n resultingVersion,\n committedAt: input.committedAt,\n }),\n };\n });\n}\n\nexport function listLifecycleEvidence(\n db: StoreDatabase,\n projectId: string,\n runId: string,\n): LifecycleEvidenceRow[] {\n const rows = db.prepare(\n `SELECT project_id, run_id, evidence_id, evidence_kind, reference_type,\n reference_value, digest, recorded_at\n FROM run_evidence WHERE project_id = ? AND run_id = ?\n ORDER BY recorded_at, evidence_id`,\n ).all(projectId, runId) as Array<Record<string, unknown>>;\n return rows.map(toLifecycleEvidenceRow);\n}\n\nexport function createLifecycleStoreMutationReceipt(input: {\n operation: LifecycleMutationOperation;\n projectId: string;\n runId: string;\n resultingVersion: number;\n committedAt: string;\n}): LifecycleStoreMutationReceipt {\n const subject = {\n schemaVersion: 1 as const,\n operation: input.operation,\n projectId: input.projectId,\n runId: input.runId,\n storeSchemaVersion: CURRENT_STORE_SCHEMA_VERSION,\n resultingVersion: input.resultingVersion,\n committedAt: input.committedAt,\n };\n return {\n schemaVersion: subject.schemaVersion,\n receiptId: `sha256:${createHash(\"sha256\").update(stableJson(subject)).digest(\"hex\")}`,\n operation: subject.operation,\n projectId: subject.projectId,\n runId: subject.runId,\n storeSchemaVersion: subject.storeSchemaVersion,\n resultingVersion: subject.resultingVersion,\n committedAt: subject.committedAt,\n };\n}\n\nfunction immediateTransaction<T>(db: StoreDatabase, apply: () => T): T {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = apply();\n db.exec(\"COMMIT\");\n return result;\n } catch (error) {\n try {\n db.exec(\"ROLLBACK\");\n } catch {\n // SQLite can roll back an interrupted transaction before this handler runs.\n }\n throw error;\n }\n}\n\nfunction readLifecycleRunOrThrow(\n db: StoreDatabase,\n projectId: string,\n runId: string,\n): LifecycleRunRow {\n const run = readLifecycleRun(db, projectId, runId);\n if (!run) throw new LifecycleRunNotFoundError(projectId, runId);\n return run;\n}\n\nfunction readLifecycleEvidenceOrThrow(\n db: StoreDatabase,\n projectId: string,\n runId: string,\n evidenceId: string,\n): LifecycleEvidenceRow {\n const row = db.prepare(\n `SELECT project_id, run_id, evidence_id, evidence_kind, reference_type,\n reference_value, digest, recorded_at\n FROM run_evidence\n WHERE project_id = ? AND run_id = ? AND evidence_id = ?`,\n ).get(projectId, runId, evidenceId) as Record<string, unknown> | undefined;\n if (!row) {\n throw new OperationError(\n `Evidence \\`${evidenceId}\\` was not recorded for lifecycle run \\`${runId}\\`.`,\n );\n }\n return toLifecycleEvidenceRow(row);\n}\n\nfunction assertExpectedVersion(run: LifecycleRunRow, expectedVersion: number): void {\n if (run.version !== expectedVersion) {\n throw new LifecycleVersionConflictError(run.runId, expectedVersion, run.version);\n }\n}\n\nfunction toLifecycleRunRow(row: Record<string, unknown>): LifecycleRunRow {\n return {\n projectId: String(row.project_id),\n runId: String(row.run_id),\n runType: String(row.run_type) as LifecycleRunType,\n lifecycleStage: String(row.lifecycle_stage) as LifecycleStage,\n status: String(row.status) as LifecycleStatus,\n checkpoint: row.checkpoint === null ? null : String(row.checkpoint),\n version: Number(row.version),\n metadata: JSON.parse(String(row.metadata)) as LifecycleMetadata,\n startedAt: String(row.started_at),\n updatedAt: String(row.updated_at),\n finishedAt: row.finished_at === null ? null : String(row.finished_at),\n };\n}\n\nfunction toLifecycleEvidenceRow(row: Record<string, unknown>): LifecycleEvidenceRow {\n return {\n projectId: String(row.project_id),\n runId: String(row.run_id),\n evidenceId: String(row.evidence_id),\n evidenceKind: String(row.evidence_kind),\n referenceType: String(row.reference_type) as LifecycleEvidenceRow[\"referenceType\"],\n reference: String(row.reference_value),\n digest: row.digest === null ? null : String(row.digest),\n recordedAt: String(row.recorded_at),\n };\n}\n\nfunction isTerminalStatus(status: LifecycleStatus): boolean {\n return status === \"completed\" || status === \"failed\" || status === \"abandoned\";\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n return error instanceof Error && /UNIQUE constraint failed/i.test(error.message);\n}\n\nfunction stableJson(value: JsonValue | Record<string, unknown>): string {\n return JSON.stringify(sortJson(value));\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortJson);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, item]) => [key, sortJson(item)]),\n );\n }\n return value;\n}\n","import type { JsonValue } from \"../operations/types\";\nimport type { StoreDatabase } from \"./database\";\nimport {\n listWorkEvidence,\n upsertWorkEvidence,\n type WorkEvidenceRow,\n} from \"./state-rows\";\n\n/**\n * The unified project-state model (W18 R10 P3; PRD 38 R-PS-1 through R-PS-3).\n *\n * Project state is ONE model with TWO facets, both recorded decisions and\n * evidence for a unit of work, keyed by the manifest-minted project\n * identifier:\n *\n * - Playbook run-state (`playbook_runs`): the run records defined by the\n * W18 R7 lineage. The storage seam is create / read / transition keyed by\n * (project_id, run_id) — see `createPlaybookRunRecord`,\n * `readPlaybookRunRecord`, and `transitionPlaybookRunRecord` in\n * `state-rows.ts`. The record itself is opaque JSON: its shape, status\n * vocabulary, and progression semantics are owned by PRD 35 and must not\n * be defined here (R-SCOPE-1).\n * - Work-execution evidence (`work_evidence`): recorded sign-offs and\n * decisions that cannot be re-derived from the repository or git,\n * keyed to the canonical work-item identity below.\n *\n * Both facets live in the same SQLite database, on the same schema version\n * (`PRAGMA user_version`), behind the same append-only migration list\n * (`STORE_MIGRATIONS`), with the same identifier keying discipline. There is\n * deliberately no second store, second version counter, or parallel\n * vocabulary for either facet (R-PS-2).\n */\n\n/**\n * Mirror-versus-relocated roles of the project-state tables (R-MIR-1,\n * R-MIR-2). This is the model-level encoding of the distinction:\n *\n * - `mirror`: the row is an index/cache of data whose canonical source lives\n * in the repository (the project's `.make-docs/manifest.json`). Losing or\n * rebuilding it loses nothing; authoritative reads must resolve to the\n * manifest (see `registry-mirror.ts`).\n * - `relocated-canonical`: the row IS the data. Run-state and work-execution\n * evidence have no in-repo copy anywhere; the store is their only home.\n */\nexport const PROJECT_STATE_TABLE_ROLES = {\n projects: \"mirror\",\n playbook_runs: \"relocated-canonical\",\n work_evidence: \"relocated-canonical\",\n} as const;\n\nexport type ProjectStateTableRole =\n (typeof PROJECT_STATE_TABLE_ROLES)[keyof typeof PROJECT_STATE_TABLE_ROLES];\n\n/**\n * Canonical work-item identity (R-PS-3): resolved repo root, wave slug, and\n * repo-relative phase path, exactly as produced by the retained work-item\n * identity resolver (`resolveWaveTarget` in the work operations domain; its\n * CLI surfacing is owned by the W18 R11 reorganization lineage). The store\n * records evidence AGAINST this identity and never re-derives it — these\n * functions accept the tuple verbatim and store it verbatim.\n *\n * `repoRoot` is carried as secondary lookup metadata only; the row key is the\n * project identifier plus (waveSlug, phasePath) (R-ID-2).\n */\nexport interface WorkItemIdentity {\n /** Resolved repository root (secondary metadata, never part of the key). */\n repoRoot: string;\n /** Wave directory slug under `docs/work/`. */\n waveSlug: string;\n /** Repo-relative phase document path. */\n phasePath: string;\n}\n\n/**\n * Records one work-execution evidence entry against a caller-supplied\n * canonical work-item identity. The evidence kind and payload are the\n * caller's vocabulary (the lifecycle checkpoint mapping lives with the\n * lifecycle operations); the store treats the payload as opaque JSON.\n */\nexport function recordWorkEvidence(\n db: StoreDatabase,\n input: {\n projectId: string;\n identity: WorkItemIdentity;\n evidenceKind: string;\n payload: JsonValue;\n now?: string;\n },\n): void {\n upsertWorkEvidence(db, {\n projectId: input.projectId,\n waveSlug: input.identity.waveSlug,\n phasePath: input.identity.phasePath,\n evidenceKind: input.evidenceKind,\n payload: input.payload,\n repoRoot: input.identity.repoRoot,\n now: input.now,\n });\n}\n\n/** Reads every evidence row recorded against one canonical work-item identity. */\nexport function readWorkItemEvidence(\n db: StoreDatabase,\n input: { projectId: string; identity: Pick<WorkItemIdentity, \"waveSlug\" | \"phasePath\"> },\n): WorkEvidenceRow[] {\n return listWorkEvidence(db, {\n projectId: input.projectId,\n waveSlug: input.identity.waveSlug,\n phasePath: input.identity.phasePath,\n });\n}\n\n/** Reads every evidence row recorded for one wave of a project. */\nexport function listWaveEvidence(\n db: StoreDatabase,\n input: { projectId: string; waveSlug: string },\n): WorkEvidenceRow[] {\n return listWorkEvidence(db, {\n projectId: input.projectId,\n waveSlug: input.waveSlug,\n });\n}\n","import { existsSync, readdirSync, rmdirSync, statSync, unlinkSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { withStoreDatabase } from \"./database\";\nimport {\n GLOBAL_CONFIG_FILE,\n GLOBAL_MANIFEST_FILE,\n STORE_DATABASE_FILE,\n getStoreDatabasePath,\n resolveStoreRoot,\n type ResolveStoreRootOptions,\n} from \"./paths\";\nimport { resolveProjectIdentity } from \"./project-identity\";\nimport { deleteProjectRows, listProjectRegistryEntries } from \"./state-rows\";\n\n/**\n * Store lifecycle behavior (W18 R10 P4; PRD 38 R-LIFE-1, R-LIFE-2).\n *\n * Two seams live here:\n *\n * - {@link pruneProjectFromStore} — project removal. Deletes exactly one\n * project's rows, keyed by the manifest-minted project identifier, leaving\n * every other project's rows untouched (R-LIFE-2). Today's repo-level\n * `make-docs setup remove` calls it; the W18 R11 CLI reorganization's\n * `setup remove` surfaces the same function.\n *\n * - {@link removeGlobalStore} — machine-level store removal. The behavior the\n * tool-level `uninstall` self-management command (W18 R11 lineage) calls\n * when the CLI itself is removed, so the store is removed or the user is\n * informed — never silently orphaned (R-LIFE-1).\n *\n * Repository content is never deleted by either seam, by construction:\n * pruning writes only inside the store database, and store removal unlinks\n * only the fixed, known store filenames under the resolved store root and\n * refuses directories that look like a project `.make-docs/` directory.\n * Neither function throws; every failure degrades to an explicit result,\n * because the store holds recoverable operational state, not project\n * knowledge (R-DB-4).\n */\n\nexport interface PruneProjectFromStoreOptions extends ResolveStoreRootOptions {\n /** Repository root whose project rows should be pruned. */\n repoRoot: string;\n /**\n * Pre-resolved project identifier. Callers that must capture identity\n * before the project manifest disappears (the uninstall flow removes\n * `.make-docs/manifest.json`) resolve it first and pass it here; when\n * omitted, identity is resolved from the repository manifest.\n */\n projectId?: string;\n}\n\nexport type PruneProjectFromStoreResult =\n | {\n status: \"pruned\";\n storeRoot: string;\n projectId: string;\n /** Registry-mirror rows left for other projects after the prune. */\n remainingProjects: number;\n }\n | { status: \"no-store\"; storeRoot: string }\n | {\n status: \"no-identity\";\n storeRoot: string;\n identityStatus: \"unminted\" | \"no-manifest\" | \"unreadable\";\n }\n | { status: \"store-unavailable\"; storeRoot: string; reason: string };\n\n/**\n * Prunes one project's rows from the global store, keyed by the\n * manifest-minted project identifier (R-LIFE-2). All three project-scoped\n * tables are cleared in one transaction via {@link deleteProjectRows}; rows\n * of every other project are untouched. Never creates a store database and\n * never throws.\n */\nexport function pruneProjectFromStore(\n options: PruneProjectFromStoreOptions,\n): PruneProjectFromStoreResult {\n const storeRoot = resolveStoreRoot(options);\n\n let projectId = options.projectId;\n if (!projectId) {\n const identity = resolveProjectIdentity(options.repoRoot);\n if (identity.status !== \"resolved\") {\n return { status: \"no-identity\", storeRoot, identityStatus: identity.status };\n }\n projectId = identity.projectId;\n }\n const resolvedProjectId = projectId;\n\n if (!existsSync(getStoreDatabasePath(storeRoot))) {\n return { status: \"no-store\", storeRoot };\n }\n\n try {\n return withStoreDatabase(storeRoot, (db) => {\n deleteProjectRows(db, resolvedProjectId);\n return {\n status: \"pruned\" as const,\n storeRoot,\n projectId: resolvedProjectId,\n remainingProjects: listProjectRegistryEntries(db).length,\n };\n });\n } catch (error) {\n return {\n status: \"store-unavailable\",\n storeRoot,\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/** Quarantine files created by database recovery are store-owned too. */\nconst STORE_QUARANTINE_FILE_PREFIX = `${STORE_DATABASE_FILE}.corrupt-`;\n\n/** The complete set of files the store ever writes under its root. */\nconst KNOWN_STORE_FILES = new Set([\n GLOBAL_CONFIG_FILE,\n GLOBAL_MANIFEST_FILE,\n STORE_DATABASE_FILE,\n `${STORE_DATABASE_FILE}-wal`,\n `${STORE_DATABASE_FILE}-shm`,\n]);\n\n/**\n * Entries whose presence marks a project `.make-docs/` directory rather than\n * the machine-level store. If the resolved store root contains any of these\n * (for example through a misconfigured `MAKE_DOCS_HOME`), removal refuses to\n * touch anything: repository content is never deleted by store handling.\n */\nconst PROJECT_MAKE_DOCS_MARKERS = [\n \"config.yaml\",\n \"contracts\",\n \"references\",\n \"templates\",\n \"scripts\",\n \"agentics\",\n \"backup\",\n \"conflicts\",\n \"runs\",\n];\n\nexport interface RemoveGlobalStoreOptions extends ResolveStoreRootOptions {}\n\nexport interface RemoveGlobalStoreResult {\n status: \"removed\" | \"not-found\" | \"retained\" | \"refused\";\n storeRoot: string;\n /** Store root-relative names of the files that were removed. */\n removedFiles: string[];\n /** Store root-relative names of entries that were kept. */\n retainedEntries: string[];\n warnings: string[];\n}\n\n/**\n * Removes the machine-level global store (R-LIFE-1). This is the removal\n * behavior tool-level `uninstall` invokes so the store is never silently\n * orphaned when the CLI itself is removed.\n *\n * Structural safety: only the fixed, known store filenames (and database\n * quarantine files) are ever unlinked, non-recursively, directly under the\n * resolved store root; the root directory itself is removed only when it is\n * empty afterwards. Anything unexpected is retained and reported, and a root\n * that looks like a project `.make-docs/` directory is refused outright —\n * repository content cannot be deleted by this function. Never throws.\n */\nexport function removeGlobalStore(\n options: RemoveGlobalStoreOptions = {},\n): RemoveGlobalStoreResult {\n const storeRoot = resolveStoreRoot(options);\n const result: RemoveGlobalStoreResult = {\n status: \"not-found\",\n storeRoot,\n removedFiles: [],\n retainedEntries: [],\n warnings: [],\n };\n\n let entries: string[];\n try {\n if (!existsSync(storeRoot) || !statSync(storeRoot).isDirectory()) {\n return result;\n }\n entries = readdirSync(storeRoot).sort();\n } catch (error) {\n result.status = \"retained\";\n result.warnings.push(\n `Could not read the make-docs global store at ${storeRoot} (${toMessage(error)}); nothing was removed.`,\n );\n return result;\n }\n\n const projectMarkers = entries.filter((entry) =>\n PROJECT_MAKE_DOCS_MARKERS.includes(entry),\n );\n if (projectMarkers.length > 0) {\n result.status = \"refused\";\n result.retainedEntries = entries;\n result.warnings.push(\n `Refusing to remove ${storeRoot}: it contains ${projectMarkers.join(\", \")}, ` +\n \"which marks a project .make-docs/ directory, not the machine-level store. \" +\n \"No files were removed; repository content is never deleted by store handling.\",\n );\n return result;\n }\n\n for (const entry of entries) {\n const isStoreFile =\n KNOWN_STORE_FILES.has(entry) || entry.startsWith(STORE_QUARANTINE_FILE_PREFIX);\n if (!isStoreFile) {\n result.retainedEntries.push(entry);\n continue;\n }\n try {\n unlinkSync(path.join(storeRoot, entry));\n result.removedFiles.push(entry);\n } catch (error) {\n result.retainedEntries.push(entry);\n result.warnings.push(\n `Could not remove ${path.join(storeRoot, entry)} (${toMessage(error)}).`,\n );\n }\n }\n\n if (result.retainedEntries.length === 0) {\n try {\n rmdirSync(storeRoot);\n result.status = \"removed\";\n return result;\n } catch (error) {\n result.warnings.push(\n `Could not remove the store directory ${storeRoot} (${toMessage(error)}).`,\n );\n }\n } else {\n result.warnings.push(\n `The store directory ${storeRoot} was kept because it contains entries the store does not own: ` +\n `${result.retainedEntries.join(\", \")}.`,\n );\n }\n\n result.status = \"retained\";\n return result;\n}\n\nfunction toMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { existsSync, mkdirSync } from \"node:fs\";\nimport {\n CURRENT_STORE_SCHEMA_VERSION,\n openStoreDatabase,\n StoreSchemaNewerError,\n StoreUnavailableError,\n} from \"./database\";\nimport { defaultGlobalConfig, writeGlobalConfig } from \"./global-config\";\nimport {\n defaultGlobalManifest,\n loadGlobalManifest,\n writeGlobalManifest,\n type StoreDatabaseStatus,\n} from \"./global-manifest\";\nimport {\n getGlobalConfigPath,\n getGlobalManifestPath,\n getStoreDatabasePath,\n resolveStoreRoot,\n type ResolveStoreRootOptions,\n} from \"./paths\";\n\n/**\n * Global-store bootstrap (R-STORE-1): when Make Docs is installed on a\n * system, ensure `~/.make-docs/` exists with the global config, the global\n * manifest, and the SQLite database, and apply any pending schema migrations.\n *\n * The bootstrap is strictly additive to the machine-level store: it never\n * reads from or writes to the target repository, so local repository\n * bootstrap behavior is byte-identical with and without the store\n * (R-STORE-3). It also never throws — every failure becomes a warning,\n * because the store holds recoverable operational state, not project\n * knowledge (R-DB-4).\n */\n\nexport interface StoreBootstrapOptions extends ResolveStoreRootOptions {\n packageMeta?: { name: string; version: string };\n now?: () => Date;\n}\n\nexport interface StoreBootstrapReport {\n storeRoot: string;\n configPath: string;\n configCreated: boolean;\n manifestPath: string;\n manifestCreated: boolean;\n databasePath: string;\n databaseStatus: StoreDatabaseStatus;\n /** Schema version recorded in the database, when it is usable. */\n schemaVersion: number | null;\n warnings: string[];\n}\n\nexport function bootstrapGlobalStore(\n options: StoreBootstrapOptions = {},\n): StoreBootstrapReport {\n const storeRoot = resolveStoreRoot(options);\n const now = (options.now ?? (() => new Date()))().toISOString();\n const report: StoreBootstrapReport = {\n storeRoot,\n configPath: getGlobalConfigPath(storeRoot),\n configCreated: false,\n manifestPath: getGlobalManifestPath(storeRoot),\n manifestCreated: false,\n databasePath: getStoreDatabasePath(storeRoot),\n databaseStatus: \"unavailable\",\n schemaVersion: null,\n warnings: [],\n };\n\n try {\n mkdirSync(storeRoot, { recursive: true, mode: 0o700 });\n } catch (error) {\n report.warnings.push(\n `Could not create the make-docs global store at ${storeRoot} (${toMessage(error)}). ` +\n \"Operational state will not be recorded; repository content is unaffected.\",\n );\n return report;\n }\n\n // Global config: create with defaults when missing; never overwrite an\n // existing file, because it carries user-set machine-level settings.\n try {\n if (!existsSync(report.configPath)) {\n writeGlobalConfig(storeRoot, defaultGlobalConfig());\n report.configCreated = true;\n }\n } catch (error) {\n report.warnings.push(\n `Could not write the global config at ${report.configPath} (${toMessage(error)}).`,\n );\n }\n\n // SQLite database: create, verify, and migrate. Failures degrade.\n try {\n const open = openStoreDatabase(storeRoot);\n try {\n report.schemaVersion = open.schemaVersion;\n if (open.recovered) {\n report.databaseStatus = \"recovered\";\n report.warnings.push(\n `The make-docs store database at ${open.databasePath} was unreadable and has been recreated ` +\n `(the old file was kept at ${open.quarantinedPath ?? \"a quarantine path\"}). ` +\n \"This is recoverable operational-state loss (run state and recorded sign-offs); \" +\n \"no project knowledge or repository content was lost, and state can be re-established.\",\n );\n } else {\n report.databaseStatus = open.created ? \"created\" : \"ready\";\n }\n } finally {\n open.db.close();\n }\n } catch (error) {\n if (error instanceof StoreSchemaNewerError) {\n report.databaseStatus = \"schema-newer\";\n report.schemaVersion = error.databaseSchemaVersion;\n report.warnings.push(error.message);\n } else if (error instanceof StoreUnavailableError) {\n report.databaseStatus = \"unavailable\";\n report.warnings.push(error.message);\n } else {\n report.databaseStatus = \"unavailable\";\n report.warnings.push(\n `Could not open the make-docs store database at ${report.databasePath} (${toMessage(error)}). ` +\n \"Repository operations are unaffected.\",\n );\n }\n }\n\n // Global manifest: create or refresh tool-level state last so it reflects\n // the database outcome of this bootstrap.\n try {\n const existing = loadGlobalManifest(storeRoot);\n const manifest = existing ?? defaultGlobalManifest(now);\n report.manifestCreated = existing === null;\n manifest.updatedAt = now;\n manifest.lastBootstrap = {\n packageName: options.packageMeta?.name ?? \"make-docs\",\n packageVersion: options.packageMeta?.version ?? \"unknown\",\n nodeVersion: process.version,\n at: now,\n };\n manifest.database = {\n file: \"store.db\",\n schemaVersion:\n report.databaseStatus === \"unavailable\" ? manifest.database.schemaVersion : report.schemaVersion,\n status: report.databaseStatus,\n };\n writeGlobalManifest(storeRoot, manifest);\n } catch (error) {\n report.warnings.push(\n `Could not write the global manifest at ${report.manifestPath} (${toMessage(error)}).`,\n );\n }\n\n return report;\n}\n\n/** Convenience re-export so callers can assert the expected schema version. */\nexport { CURRENT_STORE_SCHEMA_VERSION };\n\nfunction toMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACbA,SAAS,YAAY,oBAAoB;;;ACAzC,SAAS,WAAW,qBAAqB;AACzC,OAAO,UAAU;AAQV,SAAS,mBAAmB,UAAkB,OAAsB;AACzE,YAAU,KAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AACrD,QAAM,WAAW,GAAG,QAAQ,QAAQ,QAAQ,GAAG,IAAI,KAAK,IAAI,CAAC;AAC7D,gBAAc,UAAU,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,GAAM,MAAM;AACrE,WAAS,cAAc,UAAU,QAAQ;AAC3C;;;ADSO,IAAM,+BAA+B;AAqDrC,IAAM,iCAAuD;AAAA,EAClE,YAAY;AAAA,EACZ,6BAA6B;AAAA,EAC7B,WAAW,CAAC;AACd;AAEO,IAAM,iCAAkD,OAAO,OAAO;AAAA,EAC3E,OAAO;AAAA,EACP,SAAS;AAAA,EACT,YAAY;AACd,CAAC;AAEM,SAAS,sBAAoC;AAClD,SAAO;AAAA,IACL,eAAe;AAAA,IACf,UAAU,EAAE,GAAG,gCAAgC,WAAW,CAAC,EAAE;AAAA,EAC/D;AACF;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AAoB,WAAW,QAAQ;AAAA,EACzC,SAAS,OAAO;AACd,WAAO,SAAS;AAAA,MACd,0CAA0C,OAAO,YAAY,KAAKA,WAAU,KAAK,CAAC;AAAA,IACpF;AAAA,EACF;AAEA,SAAO;AACT;AAKA,SAASE,WAAU,OAAwB;AACzC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;","names":["record","path","path","path","path","existsSync","path","existsSync","path","existsSync","readFileSync","existsSync","readFileSync","record","createHash","createHash","existsSync","path","existsSync","toMessage","path","existsSync","mkdirSync","mkdirSync","toMessage","existsSync","toMessage"]}
@@ -4,7 +4,7 @@ import {
4
4
  preparePlannedFileChange,
5
5
  recordPlannedFileChange,
6
6
  relativePathToTarget
7
- } from "./chunk-YVSASZMT.js";
7
+ } from "./chunk-HXWD2EUD.js";
8
8
 
9
9
  // src/installation-files.ts
10
10
  import { lstatSync, readdirSync, rmdirSync, unlinkSync } from "fs";
@@ -201,4 +201,4 @@ export {
201
201
  assertLifecyclePlanSnapshotCurrent,
202
202
  createLifecycleMutationReceipt
203
203
  };
204
- //# sourceMappingURL=chunk-7R2PPKTB.js.map
204
+ //# sourceMappingURL=chunk-VMKG3H4B.js.map