@mean-weasel/lineage 0.1.21 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/MANUAL_INSTALL_DOGFOOD.md +341 -0
- package/README.md +46 -14
- package/dist/cli/lineage-dev.js +27 -21
- package/dist/cli/lineage-dev.js.map +3 -3
- package/dist/cli/lineage-preview.js +27 -21
- package/dist/cli/lineage-preview.js.map +3 -3
- package/dist/cli/lineage.js +27 -21
- package/dist/cli/lineage.js.map +3 -3
- package/dist/docs-site/404.html +41 -0
- package/dist/docs-site/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js +1 -0
- package/dist/docs-site/_astro/Search.astro_astro_type_script_index_0_lang.x2pVooPA.js +1 -0
- package/dist/docs-site/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js +1 -0
- package/dist/docs-site/_astro/common.DarLW4Vf.css +3 -0
- package/dist/docs-site/_astro/ec.0vx5m.js +3 -0
- package/dist/docs-site/_astro/ec.w36nc.css +1 -0
- package/dist/docs-site/_astro/page.LAbJoB63.js +1 -0
- package/dist/docs-site/_astro/print.ehPL0gv-.css +1 -0
- package/dist/docs-site/_astro/starlight-toc.CTCQXEge.js +1 -0
- package/dist/docs-site/_astro/ui-core.DWIqd25E.js +2 -0
- package/dist/docs-site/concepts/agent-claims-handoffs/index.html +99 -0
- package/dist/docs-site/concepts/attempts-current-version/index.html +86 -0
- package/dist/docs-site/concepts/branches-vs-rerolls/index.html +114 -0
- package/dist/docs-site/concepts/projects-workspaces-assets/index.html +89 -0
- package/dist/docs-site/concepts/selections-next-variations/index.html +86 -0
- package/dist/docs-site/index.html +92 -0
- package/dist/docs-site/integrations/cloud-storage/index.html +92 -0
- package/dist/docs-site/integrations/image-generation/index.html +93 -0
- package/dist/docs-site/integrations/index.html +112 -0
- package/dist/docs-site/integrations/social-scheduling/index.html +89 -0
- package/dist/docs-site/operations/backup-recovery/index.html +87 -0
- package/dist/docs-site/operations/channels/index.html +88 -0
- package/dist/docs-site/operations/local-first-data/index.html +90 -0
- package/dist/docs-site/operations/profiles-database-identity/index.html +90 -0
- package/dist/docs-site/operations/troubleshooting/index.html +89 -0
- package/dist/docs-site/pagefind/fragment/en_1126abb.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_19b3f6c.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_31aa611.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_38817cc.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_4184ad1.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_41db543.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_469f895.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_4db923b.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_56e45b6.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_56fe7ca.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_581a7cb.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_5be5e44.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_603c2be.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_66b3118.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_6a19c31.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_74e9307.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_7c9d5a2.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_818744b.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_8269752.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_88b38c1.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_8c1c735.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_98d9b16.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_a3d636e.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_b15ecf0.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_bcc29c5.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_bfb13e9.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_d0fca9e.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_d49ed00.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_e0786b9.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_e298dee.pf_fragment +0 -0
- package/dist/docs-site/pagefind/fragment/en_f6179a8.pf_fragment +0 -0
- package/dist/docs-site/pagefind/index/en_f279b04.pf_index +0 -0
- package/dist/docs-site/pagefind/pagefind-component-ui.css +1509 -0
- package/dist/docs-site/pagefind/pagefind-component-ui.js +56 -0
- package/dist/docs-site/pagefind/pagefind-entry.json +1 -0
- package/dist/docs-site/pagefind/pagefind-highlight.js +1070 -0
- package/dist/docs-site/pagefind/pagefind-modular-ui.css +214 -0
- package/dist/docs-site/pagefind/pagefind-modular-ui.js +8 -0
- package/dist/docs-site/pagefind/pagefind-ui.css +1 -0
- package/dist/docs-site/pagefind/pagefind-ui.js +2 -0
- package/dist/docs-site/pagefind/pagefind-worker.js +6 -0
- package/dist/docs-site/pagefind/pagefind.en_74951c3ca7.pf_meta +0 -0
- package/dist/docs-site/pagefind/pagefind.js +6 -0
- package/dist/docs-site/pagefind/wasm.en.pagefind +0 -0
- package/dist/docs-site/pagefind/wasm.unknown.pagefind +0 -0
- package/dist/docs-site/reference/cli/index.html +86 -0
- package/dist/docs-site/reference/interface-guide/index.html +86 -0
- package/dist/docs-site/reference/release-notes/index.html +80 -0
- package/dist/docs-site/reference/settings/index.html +86 -0
- package/dist/docs-site/reference/terminology/index.html +94 -0
- package/dist/docs-site/sitemap-0.xml +1 -0
- package/dist/docs-site/sitemap-index.xml +1 -0
- package/dist/docs-site/start-here/example-projects/index.html +88 -0
- package/dist/docs-site/start-here/first-workspace/index.html +91 -0
- package/dist/docs-site/start-here/installation-first-run/index.html +86 -0
- package/dist/docs-site/start-here/what-is-lineage/index.html +96 -0
- package/dist/docs-site/workflows/back-up-approved-assets/index.html +88 -0
- package/dist/docs-site/workflows/content-batches/index.html +88 -0
- package/dist/docs-site/workflows/continue-new-agent-session/index.html +89 -0
- package/dist/docs-site/workflows/create-grow-lineage/index.html +89 -0
- package/dist/docs-site/workflows/generate-import-variations/index.html +92 -0
- package/dist/docs-site/workflows/restore-earlier-attempt/index.html +87 -0
- package/dist/docs-site/workflows/review-approve-assets/index.html +87 -0
- package/dist/pages/.nojekyll +0 -0
- package/dist/pages/assets/agent-shared-state-DOfpTLiw.webp +0 -0
- package/dist/pages/assets/agent-to-canvas-DtIu_cPq.mp4 +0 -0
- package/dist/pages/assets/app-B-fAyNsU.css +1 -0
- package/dist/{web/assets/app-DX744BME.js → pages/assets/app-DdU93vp2.js} +36 -2
- package/dist/pages/assets/attempt-history-D6wdic6n.webp +0 -0
- package/dist/pages/assets/branching-tree-B8I5_S6D.png +0 -0
- package/dist/pages/assets/canvas-cli-DHBacq7r.png +0 -0
- package/dist/pages/assets/hero-agent-sync-D8ibW83E.mp4 +0 -0
- package/dist/pages/assets/hero-agent-sync-poster-zBB3KpbO.png +0 -0
- package/dist/pages/assets/hero-board-DG3ED4AW.webp +0 -0
- package/dist/pages/assets/hero-lineage-growth-Bsl9tiq-.mp4 +0 -0
- package/dist/pages/assets/hero-trace-connections-Bb52ABBc.mp4 +0 -0
- package/dist/pages/assets/human-selection-BdDBDE-I.webp +0 -0
- package/dist/pages/assets/human-to-agent-D1z92ZO9.mp4 +0 -0
- package/dist/pages/assets/jsx-runtime-DAFSxiwi.js +8 -0
- package/dist/pages/assets/landing-MwOFmHoi.js +2 -0
- package/dist/{web/assets/landing-Dmkx4R_N.css → pages/assets/landing-wy4L-yBm.css} +1 -1
- package/dist/pages/assets/reroll-history-DQcEH42R.mp4 +0 -0
- package/dist/pages/docs/404.html +41 -0
- package/dist/pages/docs/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js +1 -0
- package/dist/pages/docs/_astro/Search.astro_astro_type_script_index_0_lang.x2pVooPA.js +1 -0
- package/dist/pages/docs/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js +1 -0
- package/dist/pages/docs/_astro/common.DarLW4Vf.css +3 -0
- package/dist/pages/docs/_astro/ec.0vx5m.js +3 -0
- package/dist/pages/docs/_astro/ec.w36nc.css +1 -0
- package/dist/pages/docs/_astro/page.LAbJoB63.js +1 -0
- package/dist/pages/docs/_astro/print.ehPL0gv-.css +1 -0
- package/dist/pages/docs/_astro/starlight-toc.CTCQXEge.js +1 -0
- package/dist/pages/docs/_astro/ui-core.DWIqd25E.js +2 -0
- package/dist/pages/docs/concepts/agent-claims-handoffs/index.html +99 -0
- package/dist/pages/docs/concepts/attempts-current-version/index.html +86 -0
- package/dist/pages/docs/concepts/branches-vs-rerolls/index.html +114 -0
- package/dist/pages/docs/concepts/projects-workspaces-assets/index.html +89 -0
- package/dist/pages/docs/concepts/selections-next-variations/index.html +86 -0
- package/dist/pages/docs/index.html +92 -0
- package/dist/pages/docs/integrations/cloud-storage/index.html +92 -0
- package/dist/pages/docs/integrations/image-generation/index.html +93 -0
- package/dist/pages/docs/integrations/index.html +112 -0
- package/dist/pages/docs/integrations/social-scheduling/index.html +89 -0
- package/dist/pages/docs/operations/backup-recovery/index.html +87 -0
- package/dist/pages/docs/operations/channels/index.html +88 -0
- package/dist/pages/docs/operations/local-first-data/index.html +90 -0
- package/dist/pages/docs/operations/profiles-database-identity/index.html +90 -0
- package/dist/pages/docs/operations/troubleshooting/index.html +89 -0
- package/dist/pages/docs/pagefind/fragment/en_1126abb.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_19b3f6c.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_31aa611.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_38817cc.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_4184ad1.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_41db543.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_469f895.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_4db923b.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_56e45b6.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_56fe7ca.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_581a7cb.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_5be5e44.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_603c2be.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_66b3118.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_6a19c31.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_74e9307.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_7c9d5a2.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_818744b.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_8269752.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_88b38c1.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_8c1c735.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_98d9b16.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_a3d636e.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_b15ecf0.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_bcc29c5.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_bfb13e9.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_d0fca9e.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_d49ed00.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_e0786b9.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_e298dee.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/fragment/en_f6179a8.pf_fragment +0 -0
- package/dist/pages/docs/pagefind/index/en_f279b04.pf_index +0 -0
- package/dist/pages/docs/pagefind/pagefind-component-ui.css +1509 -0
- package/dist/pages/docs/pagefind/pagefind-component-ui.js +56 -0
- package/dist/pages/docs/pagefind/pagefind-entry.json +1 -0
- package/dist/pages/docs/pagefind/pagefind-highlight.js +1070 -0
- package/dist/pages/docs/pagefind/pagefind-modular-ui.css +214 -0
- package/dist/pages/docs/pagefind/pagefind-modular-ui.js +8 -0
- package/dist/pages/docs/pagefind/pagefind-ui.css +1 -0
- package/dist/pages/docs/pagefind/pagefind-ui.js +2 -0
- package/dist/pages/docs/pagefind/pagefind-worker.js +6 -0
- package/dist/pages/docs/pagefind/pagefind.en_74951c3ca7.pf_meta +0 -0
- package/dist/pages/docs/pagefind/pagefind.js +6 -0
- package/dist/pages/docs/pagefind/wasm.en.pagefind +0 -0
- package/dist/pages/docs/pagefind/wasm.unknown.pagefind +0 -0
- package/dist/pages/docs/reference/cli/index.html +86 -0
- package/dist/pages/docs/reference/interface-guide/index.html +86 -0
- package/dist/pages/docs/reference/release-notes/index.html +80 -0
- package/dist/pages/docs/reference/settings/index.html +86 -0
- package/dist/pages/docs/reference/terminology/index.html +94 -0
- package/dist/pages/docs/sitemap-0.xml +1 -0
- package/dist/pages/docs/sitemap-index.xml +1 -0
- package/dist/pages/docs/start-here/example-projects/index.html +88 -0
- package/dist/pages/docs/start-here/first-workspace/index.html +91 -0
- package/dist/pages/docs/start-here/installation-first-run/index.html +86 -0
- package/dist/pages/docs/start-here/what-is-lineage/index.html +96 -0
- package/dist/pages/docs/workflows/back-up-approved-assets/index.html +88 -0
- package/dist/pages/docs/workflows/content-batches/index.html +88 -0
- package/dist/pages/docs/workflows/continue-new-agent-session/index.html +89 -0
- package/dist/pages/docs/workflows/create-grow-lineage/index.html +89 -0
- package/dist/pages/docs/workflows/generate-import-variations/index.html +92 -0
- package/dist/pages/docs/workflows/restore-earlier-attempt/index.html +87 -0
- package/dist/pages/docs/workflows/review-approve-assets/index.html +87 -0
- package/dist/pages/index.html +42 -0
- package/dist/pages/landing/index.html +42 -0
- package/dist/pages/lineage-showcase-cover-16x9.png +0 -0
- package/dist/runtime-build.json +5 -5
- package/dist/server.js +73 -24
- package/dist/server.js.map +4 -4
- package/dist/web/assets/app-DdU93vp2.js +50 -0
- package/dist/web/assets/landing-MwOFmHoi.js +2 -0
- package/dist/web/assets/landing-wy4L-yBm.css +1 -0
- package/dist/web/index.html +3 -3
- package/dist/web/landing/index.html +26 -3
- package/dist/web/lineage-showcase-cover-16x9.png +0 -0
- package/package.json +11 -2
- package/dist/web/assets/landing-CPZnU7M8.js +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/cli/lineageCli.ts", "../../src/shared/edgeSummary.ts", "../../src/server/agentClaims.ts", "../../src/server/assetLineageDb.ts", "../../src/server/assetCore.ts", "../../src/server/adapters/storage/s3StorageAdapter.ts", "../../src/server/localReview.ts", "../../src/server/profileWriterLease.ts", "../../src/server/lineageProfiles.ts", "../../src/shared/lineageProfileTypes.ts", "../../src/server/nodeSqlite.ts", "../../src/server/assetLineage.ts", "../../src/server/assetLineageSelection.ts", "../../src/server/assetLineageTasks.ts", "../../src/server/assetLineageWorkspaces.ts", "../../src/server/lineageClaimGuards.ts", "../../src/server/lineageRuntimeCommand.ts", "../../src/server/assetLineageHandoff.ts", "../../src/server/generationReceipts.ts", "../../src/shared/generationOutputManifest.ts", "../../src/server/lineageSelectionPacket.ts", "../../src/server/runtimeInfo.ts", "../../src/shared/runtimeInfoTypes.ts", "../../src/server/managedWriterRouting.ts", "../../src/cli/lineage-preview.ts"],
|
|
4
|
-
"sourcesContent": ["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { homedir, platform } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { requireEdgeSummary } from '../shared/edgeSummary';\nimport {\n createAgentClaim,\n heartbeatAgentClaim,\n inspectAgentClaim,\n isAgentClaimError,\n listAgentClaims,\n parseClaimTtl,\n redactAgentClaimTokens,\n releaseAgentClaim,\n revokeAgentClaim,\n transferAgentClaim,\n type AgentClaimScopeType,\n} from '../server/agentClaims';\nimport { defaultProduct, packageRoot as lineagePackageRoot, setLineageAssetRoot } from '../server/assetCore';\nimport {\n clearLineageRerollRequest,\n getLineageNextAsset,\n getLineageSnapshot,\n listLineageRerollRequests,\n markLineageRerollRequest,\n} from '../server/assetLineage';\nimport { getLineageBrief, linkSelectedLineageChild } from '../server/assetLineageHandoff';\nimport {\n addLineageTaskComment,\n cancelLineageTask,\n claimLineageTask,\n getLineageTask,\n listLineageTasks,\n overrideLineageTask,\n startLineageTask,\n updateLineageTaskInstructions,\n} from '../server/assetLineageTasks';\nimport {\n importImageGenerationOutputs,\n importImageRerollOutput,\n inspectImageGeneration,\n planImageGeneration,\n planImageReroll,\n} from '../server/generationReceipts';\nimport { getLineageSelectionPacket } from '../server/lineageSelectionPacket';\nimport { assertLineageCodeOrigin, getLineageCodeIdentity, getLineageRuntimeInfo } from '../server/runtimeInfo';\nimport {\n assertProfileChannel,\n assertUnselectedDatabaseIsUnbound,\n bindLineageProfileDatabase,\n cloneLineageProfileAssets,\n cloneLineageProfileDatabase,\n doctorLineageProfile,\n initializeLineageProfile,\n repinLineageDevelopmentProfileRuntime,\n resolveLineageProfile,\n} from '../server/lineageProfiles';\nimport { executeManagedWriterCommand } from '../server/managedWriterRouting';\nimport { acquireProfileWriterLease, ProfileWriterLeaseConflictError } from '../server/profileWriterLease';\nimport type {\n LineageProfileAssetsCloneResult,\n LineageProfileBindResult,\n LineageProfileCloneResult,\n LineageProfileDoctorResult,\n LineageProfileInitResult,\n LineageProfileRuntimeRepinResult,\n ResolvedLineageProfile,\n} from '../shared/lineageProfileTypes';\nimport type { LineageRuntimeCodeIdentity, LineageRuntimeInfo } from '../shared/runtimeInfoTypes';\n\nexport interface LineageCliConfig {\n binName: 'lineage' | 'lineage-dev' | 'lineage-preview';\n channel: 'stable' | 'preview' | 'dev';\n defaultHost: string;\n defaultPort: number;\n displayName: string;\n}\n\ninterface StartOptions {\n assetRoot: string;\n dbPath: string;\n host: string;\n json: boolean;\n open: boolean;\n port: number;\n profile?: ResolvedLineageProfile;\n}\n\ninterface DataCommandOptions {\n assetId?: string;\n childAssetId?: string;\n claimToken?: string;\n confirmWrite: boolean;\n dbPath?: string;\n json: boolean;\n project: string;\n rootAssetId?: string;\n summary?: string;\n}\n\nconst signalExitCodes: Partial<Record<NodeJS.Signals, number>> = {\n SIGINT: 130,\n SIGTERM: 143,\n};\n\nfunction packageRoot(): string {\n return resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');\n}\n\nfunction packageVersion(): string {\n try {\n const packageInfo = JSON.parse(readFileSync(join(packageRoot(), 'package.json'), 'utf8')) as { version?: string };\n return packageInfo.version || '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nfunction dataRoot(displayName: string): string {\n if (process.env.LINEAGE_HOME) return process.env.LINEAGE_HOME;\n if (platform() === 'darwin') return join(homedir(), 'Library', 'Application Support', displayName);\n if (platform() === 'win32') return join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), displayName);\n return join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), displayName.toLowerCase().replace(/\\s+/g, '-'));\n}\n\nfunction readOption(args: string[], name: string): string | undefined {\n const prefix = `${name}=`;\n const inline = args.find(arg => arg.startsWith(prefix));\n if (inline) return inline.slice(prefix.length);\n const index = args.indexOf(name);\n if (index >= 0) return args[index + 1];\n return undefined;\n}\n\nfunction readOptions(args: string[], name: string): string[] {\n const values: string[] = [];\n const prefix = `${name}=`;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg.startsWith(prefix)) values.push(arg.slice(prefix.length));\n else if (arg === name && args[index + 1] && !args[index + 1].startsWith('--')) {\n values.push(args[index + 1]);\n index += 1;\n }\n }\n return values;\n}\n\nfunction readJsonFile(path: string, label: string): unknown {\n try {\n return JSON.parse(readFileSync(resolve(path), 'utf8')) as unknown;\n } catch (error) {\n throw new Error(`${label} must be a readable JSON file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nfunction parentFilesOption(value: string | undefined): Record<string, string[]> | undefined {\n if (value === undefined) return undefined;\n const mappings: Record<string, string[]> = {};\n for (const rawMapping of value.split(';')) {\n const separator = rawMapping.indexOf('=');\n const parent = separator >= 0 ? rawMapping.slice(0, separator).trim() : '';\n const files = separator >= 0 ? rawMapping.slice(separator + 1).split(',').map(file => file.trim()).filter(Boolean) : [];\n if (!parent || files.length === 0) throw new Error('lineage generate image import --parent-files requires parent=file[,file][;parent=file]');\n if (Object.hasOwn(mappings, parent)) throw new Error(`Duplicate generation parent mapping: ${parent}`);\n mappings[parent] = files;\n }\n return mappings;\n}\n\nexport function resolveStartOptions(config: LineageCliConfig, args: string[]): StartOptions {\n if (!profileSelector(args)) {\n throw new Error('Start requires --profile or LINEAGE_PROFILE. Create one with `profile init --profile <id> --confirm-write`, then start again with that profile');\n }\n const profile = prepareCliProfile(config, args);\n const serviceUrl = profile ? new URL(profile.service_origin) : undefined;\n const rawPort = readOption(args, '--port') || process.env.PORT || serviceUrl?.port || String(config.defaultPort);\n const port = Number(rawPort);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(`Invalid port: ${rawPort}`);\n }\n const host = readOption(args, '--host') || process.env.HOST || serviceUrl?.hostname || config.defaultHost;\n if (profile && serviceUrl && (host !== serviceUrl.hostname || port !== Number(serviceUrl.port || 80))) {\n throw new Error(`Profile ${profile.profile_id} service_origin ${profile.service_origin} conflicts with requested host/port ${host}:${port}`);\n }\n return {\n assetRoot: profile?.asset_root || resolveCliAssetRoot(args),\n dbPath: profile?.database_path || resolveCliDbPath(config, args),\n host,\n json: args.includes('--json'),\n open: args.includes('--open'),\n port,\n profile,\n };\n}\n\nfunction resolveCliAssetRoot(args: string[]): string {\n return resolve(readOption(args, '--asset-root') || process.env.LINEAGE_ASSET_ROOT || lineagePackageRoot);\n}\n\nfunction configureCliAssetRoot(args: string[]): string {\n const assetRoot = resolveCliAssetRoot(args);\n process.env.LINEAGE_ASSET_ROOT = assetRoot;\n return setLineageAssetRoot(assetRoot);\n}\n\nfunction resolveCliDbPath(config: LineageCliConfig, args: string[]): string {\n return readOption(args, '--db') || process.env.LINEAGE_DB || join(dataRoot(config.displayName), `${config.binName}.sqlite`);\n}\n\nfunction hasOption(args: string[], name: string): boolean {\n return args.includes(name) || args.some(arg => arg.startsWith(`${name}=`));\n}\n\nfunction profileSelector(args: string[]): string | undefined {\n const option = readOption(args, '--profile');\n if (option && process.env.LINEAGE_PROFILE && option !== process.env.LINEAGE_PROFILE) {\n throw new Error(`--profile ${option} conflicts with LINEAGE_PROFILE ${process.env.LINEAGE_PROFILE}`);\n }\n return option || process.env.LINEAGE_PROFILE;\n}\n\nfunction doctorFailures(result: LineageProfileDoctorResult): string {\n return result.checks.filter(check => check.status === 'fail').map(check => `${check.id}: ${check.message}`).join('; ');\n}\n\nfunction prepareCliProfile(config: LineageCliConfig, args: string[]): ResolvedLineageProfile | undefined {\n const selector = profileSelector(args);\n if (!selector) {\n assertUnselectedDatabaseIsUnbound(getLineageRuntimeInfo({ channel: config.channel, dbPath: resolveCliDbPath(config, args) }));\n return undefined;\n }\n if (hasOption(args, '--db')) throw new Error('A named profile cannot be combined with --db');\n if (hasOption(args, '--asset-root')) throw new Error('A named profile cannot be combined with --asset-root');\n const profile = resolveLineageProfile(selector);\n if (process.env.LINEAGE_DB && resolve(process.env.LINEAGE_DB) !== profile.database_path) {\n throw new Error(`Profile ${profile.profile_id} database_path conflicts with LINEAGE_DB`);\n }\n if (process.env.LINEAGE_ASSET_ROOT && resolve(process.env.LINEAGE_ASSET_ROOT) !== profile.asset_root) {\n throw new Error(`Profile ${profile.profile_id} asset_root conflicts with LINEAGE_ASSET_ROOT`);\n }\n assertProfileChannel(profile, config.channel);\n const runtime = getLineageRuntimeInfo({ channel: config.channel, dbPath: profile.database_path });\n const doctor = doctorLineageProfile(selector, { channel: config.channel, code: runtime.code, gitSha: runtime.git_sha, version: runtime.version });\n if (!doctor.ok) throw new Error(`Profile ${profile.profile_id} failed doctor: ${doctorFailures(doctor)}`);\n process.env.LINEAGE_ASSET_ROOT = profile.asset_root;\n process.env.LINEAGE_DB = profile.database_path;\n process.env.LINEAGE_PROFILE = selector;\n process.env.LINEAGE_PROFILE_ENVIRONMENT = profile.environment;\n process.env.LINEAGE_PROFILE_FINGERPRINT = profile.profile_fingerprint;\n process.env.LINEAGE_PROFILE_ID = profile.profile_id;\n process.env.LINEAGE_PROFILE_MANIFEST = profile.manifest_path;\n process.env.LINEAGE_PROFILE_SERVICE_ORIGIN = profile.service_origin;\n setLineageAssetRoot(profile.asset_root);\n return profile;\n}\n\nexport function formatLineageHelp(config: LineageCliConfig): string {\n return `${config.binName} ${packageVersion()}\n\nUsage:\n ${config.binName} start --profile <id-or-manifest> [--open] [--json]\n ${config.binName} profile init --profile <new-profile-id> [--service-origin <http-origin>] --confirm-write [--json]\n ${config.binName} profile doctor --profile <id-or-manifest> [--json]\n ${config.binName} profile bind --profile <id-or-manifest> --confirm-write [--json]\n ${config.binName} profile clone --source-db <snapshot-source> --target-profile <id-or-manifest> --confirm-write [--json]\n ${config.binName} profile clone-assets --source-asset-root <path> --target-profile <id-or-manifest> --confirm-write [--json]\n ${config.binName} profile repin-runtime --profile <development-profile> --checkout-root <path> --confirm-write [--json]\n ${config.binName} runtime info [--json]\n ${config.binName} runtime doctor [--json]\n ${config.binName} next [--project <project>] [--root <asset-id>] [--db <path>] [--json]\n ${config.binName} brief [--project <project>] [--root <asset-id>] [--db <path>] [--json]\n ${config.binName} inspect --asset-id <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} selection packet [--project <project>] [--workspace <id-or-root>|--root <asset-id>] [--channel <channel>] [--campaign <campaign>] [--context-notes <text>] [--label <label>] [--schema v2] [--out <path>] [--strict] [--db <path>] [--json]\n ${config.binName} link-child --root <asset-id> --child <asset-id> --summary \"<one-or-two-words>\" [--project <project>] [--claim-token <claim-id.secret>] [--confirm-write] [--db <path>] [--json]\n ${config.binName} generate image plan --prompt <text> --from-lineage-selection [--count <count>|--per-base-count <count>] [--project <project>] [--dry-run] [--db <path>] [--json]\n ${config.binName} generate image inspect --job-id <job-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} generate image import --job-id <job-id> --manifest <json-file> --confirm-write [--project <project>] [--db <path>] [--json]\n ${config.binName} generate image import --job-id <legacy-job-id> (--files <file,file>|--parent-files <parent=file;parent=file>) --confirm-write [--project <project>] [--db <path>] [--json]\n ${config.binName} reroll list --root <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} reroll mark --root <asset-id> --target <asset-id> [--notes <text>] [--requested-by agent|human|system] [--project <project>] [--confirm-write] [--db <path>] [--json]\n ${config.binName} reroll cancel --root <asset-id> --target <asset-id> [--project <project>] [--confirm-write] [--db <path>] [--json]\n ${config.binName} reroll plan --root <asset-id> --target <asset-id> --prompt <text> [--project <project>] [--db <path>] [--json]\n ${config.binName} reroll import --job-id <job-id> --file <scratch-file> --confirm-write [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks list --root <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks inspect --task <task-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks claim --task <task-id> --agent-name <name> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks start --task <task-id> --claim-token <claim-id.secret> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks comment --task <task-id> --message <text> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks cancel --task <task-id> [--confirm-write] [--override] [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks override --task <task-id> --reason <text> [--instructions <text>] [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks instructions --task <task-id> --instructions <text> [--project <project>] [--db <path>] [--json]\n ${config.binName} db info [--db <path>] [--json]\n ${config.binName} agent claim --project <project> --scope <scope> --target <target-id> --agent-name <name> [--channel <channel>] [--ttl 20m] [--json]\n ${config.binName} agent graph --root <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} agent status [--project <project>] [--json]\n ${config.binName} agent inspect --claim <claim-id> [--project <project>] [--json]\n ${config.binName} agent heartbeat --claim-token <claim-id.secret> [--json]\n ${config.binName} agent release --claim-token <claim-id.secret> [--json]\n ${config.binName} agent revoke --claim <claim-id> --project <project> --reason <text> --confirm-write [--json]\n ${config.binName} agent transfer --claim <claim-id> --to-agent-name <name> --confirm-write [--project <project>] [--json]\n ${config.binName} --help\n ${config.binName} --version\n\n${config.displayName} runs the bundled Lineage server for the ${config.channel} channel.\n\nAsset catalogs and local media default to the installed package root. Pass\n--asset-root <path> or LINEAGE_ASSET_ROOT to use an external project root.\n\nAll commands accept --profile <id-or-manifest> or LINEAGE_PROFILE. Named\nprofiles are authoritative for database, asset root, environment, and origin;\nthey cannot be combined with direct --db or --asset-root overrides. Commands\nwithout a profile run in legacy-unbound diagnostic/read-only mode.\n\nOperational commands also require an attested code origin. Stable and preview\nrun from separate lineage-channel install receipts. Dev runs only from a Git\ncheckout/worktree through npm run lineage:dev.\n\nServer startup independently verifies code origin. When --open is requested,\nthe browser opens only after /api/runtime matches the expected code, profile,\ndatabase, and unique service instance.\n\nVariation vs re-roll:\n link-child creates a new visible child variation edge.\n reroll mark -> reroll plan -> reroll import updates the same node with a new attempt.`;\n}\n\nfunction printHelp(config: LineageCliConfig): void {\n console.log(formatLineageHelp(config));\n}\n\nfunction openBrowser(url: string): void {\n const command = platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'cmd' : 'xdg-open';\n const args = platform() === 'win32' ? ['/c', 'start', '', url] : [url];\n const opener = spawn(command, args, { detached: true, stdio: 'ignore' });\n opener.unref();\n}\n\nexport function lineageServiceIdentityErrors(\n runtime: LineageRuntimeInfo,\n expected: {\n channel: LineageRuntimeInfo['channel'];\n code_fingerprint: string;\n database_path: string;\n instance_id: string;\n launcher_pid: number;\n profile?: ResolvedLineageProfile;\n },\n): string[] {\n const errors: string[] = [];\n if (runtime.channel !== expected.channel) errors.push(`channel ${runtime.channel} != ${expected.channel}`);\n if (!runtime.code?.verified) errors.push('service code identity is not verified');\n if (runtime.code?.fingerprint !== expected.code_fingerprint) errors.push(`code fingerprint ${runtime.code?.fingerprint || 'missing'} != ${expected.code_fingerprint}`);\n if (resolve(runtime.database.path) !== resolve(expected.database_path)) errors.push(`database ${runtime.database.path} != ${expected.database_path}`);\n if (runtime.service?.instance_id !== expected.instance_id) errors.push(`service instance ${runtime.service?.instance_id || 'missing'} != ${expected.instance_id}`);\n if (runtime.service?.launcher_pid !== expected.launcher_pid) errors.push(`launcher pid ${runtime.service?.launcher_pid || 'missing'} != ${expected.launcher_pid}`);\n if (expected.profile) {\n if (!runtime.profile.bound) errors.push('service profile is unbound');\n if (runtime.profile.id !== expected.profile.profile_id) errors.push(`profile ${runtime.profile.id} != ${expected.profile.profile_id}`);\n if (runtime.profile.environment !== expected.profile.environment) errors.push(`environment ${runtime.profile.environment} != ${expected.profile.environment}`);\n if (runtime.profile.fingerprint !== expected.profile.profile_fingerprint) errors.push(`profile fingerprint ${runtime.profile.fingerprint || 'missing'} != ${expected.profile.profile_fingerprint}`);\n if (runtime.schema.profile_id !== expected.profile.profile_id) errors.push(`database profile ${runtime.schema.profile_id || 'missing'} != ${expected.profile.profile_id}`);\n if (runtime.schema.profile_fingerprint !== expected.profile.profile_fingerprint) errors.push(`database fingerprint ${runtime.schema.profile_fingerprint || 'missing'} != ${expected.profile.profile_fingerprint}`);\n }\n return errors;\n}\n\nasync function openBrowserAfterReadiness(\n url: string,\n expected: Parameters<typeof lineageServiceIdentityErrors>[1],\n child: ReturnType<typeof spawn>,\n): Promise<void> {\n const deadline = Date.now() + 15_000;\n let lastError = 'service did not respond';\n while (Date.now() < deadline && child.exitCode === null) {\n try {\n const response = await fetch(`${url}/api/runtime`, { signal: AbortSignal.timeout(1_000) });\n if (response.ok) {\n const body = await response.json() as { runtime?: LineageRuntimeInfo };\n if (body.runtime) {\n const errors = lineageServiceIdentityErrors(body.runtime, expected);\n if (errors.length === 0) {\n openBrowser(url);\n return;\n }\n lastError = errors.join('; ');\n }\n } else lastError = `HTTP ${response.status}`;\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n await new Promise(resolveDelay => setTimeout(resolveDelay, 200));\n }\n throw new Error(`Service readiness failed; browser was not opened: ${lastError}`);\n}\n\nfunction positionalArgs(args: string[]): string[] {\n const values: string[] = [];\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg.startsWith('--')) {\n if (!arg.includes('=') && args[index + 1] && !args[index + 1].startsWith('--')) index += 1;\n continue;\n }\n values.push(arg);\n }\n return values;\n}\n\nfunction resolveDataCommandOptions(args: string[]): DataCommandOptions {\n configureCliAssetRoot(args);\n const positions = positionalArgs(args);\n const options = {\n assetId: readOption(args, '--asset-id') || positions[0],\n childAssetId: readOption(args, '--child'),\n claimToken: readOption(args, '--claim-token') || process.env.LINEAGE_CLAIM_TOKEN,\n confirmWrite: args.includes('--confirm-write'),\n dbPath: readOption(args, '--db'),\n json: args.includes('--json'),\n project: readOption(args, '--project') || process.env.LINEAGE_DEFAULT_PRODUCT || defaultProduct,\n rootAssetId: readOption(args, '--root'),\n summary: readOption(args, '--summary'),\n };\n if (options.dbPath) process.env.LINEAGE_DB = options.dbPath;\n return options;\n}\n\nexport function runLineageDataCommand(command: string, args: string[]): unknown {\n const options = resolveDataCommandOptions(args);\n if (command === 'next') return getLineageNextAsset(options.project, options.rootAssetId || options.assetId);\n if (command === 'brief') return getLineageBrief(options.project, options.rootAssetId || options.assetId);\n if (command === 'inspect') {\n if (!options.assetId) throw new Error('lineage inspect requires --asset-id');\n return getLineageSnapshot(options.project, options.assetId);\n }\n if (command === 'selection') {\n const subcommand = positionalArgs(args)[0] || '';\n if (subcommand !== 'packet') throw new Error(`Unknown selection command: ${subcommand}`);\n const schema = readOption(args, '--schema');\n if (schema && schema !== 'v2') throw new Error(`Unsupported selection packet schema: ${schema}. Omit --schema for v1 or pass --schema v2.`);\n const labels = readOptions(args, '--label')\n .flatMap(label => label.split(','))\n .map(label => label.trim())\n .filter(Boolean);\n const packet = getLineageSelectionPacket(options.project, {\n campaign: readOption(args, '--campaign'),\n channel: readOption(args, '--channel'),\n command: 'lineage selection packet',\n contextNotes: readOption(args, '--context-notes') || readOption(args, '--notes'),\n dbPath: options.dbPath,\n labels,\n packageVersion: packageVersion(),\n rootAssetId: options.rootAssetId,\n schema: schema === 'v2' ? 'v2' : undefined,\n strict: args.includes('--strict'),\n workspaceId: readOption(args, '--workspace') || readOption(args, '--workspace-id'),\n });\n const out = readOption(args, '--out');\n if (out) {\n const outPath = resolve(out);\n mkdirSync(dirname(outPath), { recursive: true });\n writeFileSync(outPath, `${JSON.stringify(packet, null, 2)}\\n`);\n }\n return packet;\n }\n if (command === 'link-child') {\n if (!options.childAssetId) throw new Error('lineage link-child requires --child');\n const summary = requireEdgeSummary(options.summary);\n return linkSelectedLineageChild(options.project, {\n childAssetId: options.childAssetId,\n claimToken: options.claimToken,\n confirmWrite: options.confirmWrite,\n rootAssetId: options.rootAssetId || options.assetId,\n summary,\n summaryActor: 'agent',\n });\n }\n if (command === 'generate') {\n const [resource, subcommand] = positionalArgs(args);\n if (resource !== 'image') throw new Error(`Unknown generate command: ${resource}`);\n if (subcommand === 'plan') {\n const prompt = readOption(args, '--prompt');\n const rawCount = readOption(args, '--count');\n const rawPerBaseCount = readOption(args, '--per-base-count');\n if (!prompt) throw new Error('lineage generate image plan requires --prompt');\n return planImageGeneration(options.project, {\n count: rawCount === undefined ? undefined : Number(rawCount),\n dryRun: args.includes('--dry-run'),\n fromLineageSelection: args.includes('--from-lineage-selection'),\n perBaseCount: rawPerBaseCount === undefined ? undefined : Number(rawPerBaseCount),\n prompt,\n });\n }\n if (subcommand === 'inspect') {\n const jobId = readOption(args, '--job-id');\n if (!jobId) throw new Error('lineage generate image inspect requires --job-id');\n return inspectImageGeneration(options.project, jobId);\n }\n if (subcommand === 'import') {\n const jobId = readOption(args, '--job-id');\n const manifestPath = readOption(args, '--manifest');\n const filesValue = readOption(args, '--files');\n const parentFilesValue = readOption(args, '--parent-files');\n if (!jobId) throw new Error('lineage generate image import requires --job-id');\n if (manifestPath !== undefined && (filesValue !== undefined || parentFilesValue !== undefined)) {\n throw new Error('Use --manifest or legacy --files/--parent-files, not both');\n }\n if (filesValue !== undefined && parentFilesValue !== undefined) throw new Error('Use --files or --parent-files, not both');\n return importImageGenerationOutputs(options.project, {\n confirmWrite: options.confirmWrite,\n files: filesValue === undefined ? undefined : filesValue.split(',').map(file => file.trim()).filter(Boolean),\n jobId,\n manifest: manifestPath === undefined ? undefined : readJsonFile(manifestPath, 'Generation output manifest'),\n parentFiles: parentFilesOption(parentFilesValue),\n });\n }\n throw new Error(`Unknown generate image command: ${subcommand}`);\n }\n if (command === 'reroll') {\n const subcommand = positionalArgs(args)[0] || '';\n if (subcommand === 'list') {\n if (!options.rootAssetId) throw new Error('lineage reroll list requires --root');\n return listLineageRerollRequests(options.project, options.rootAssetId);\n }\n if (subcommand === 'mark') {\n const targetAssetId = readOption(args, '--target');\n const requestedBy = rerollRequestedBy(readOption(args, '--requested-by') || 'agent');\n if (!options.rootAssetId) throw new Error('lineage reroll mark requires --root');\n if (!targetAssetId) throw new Error('lineage reroll mark requires --target');\n return markLineageRerollRequest(options.project, {\n rootAssetId: options.rootAssetId,\n nodeAssetId: targetAssetId,\n notes: readOption(args, '--notes'),\n requestedBy,\n confirmWrite: options.confirmWrite,\n });\n }\n if (subcommand === 'cancel') {\n const targetAssetId = readOption(args, '--target');\n if (!options.rootAssetId) throw new Error('lineage reroll cancel requires --root');\n if (!targetAssetId) throw new Error('lineage reroll cancel requires --target');\n return clearLineageRerollRequest(options.project, {\n rootAssetId: options.rootAssetId,\n nodeAssetId: targetAssetId,\n confirmWrite: options.confirmWrite,\n });\n }\n if (subcommand === 'plan') {\n const targetAssetId = readOption(args, '--target');\n const prompt = readOption(args, '--prompt');\n if (!options.rootAssetId) throw new Error('lineage reroll plan requires --root');\n if (!targetAssetId) throw new Error('lineage reroll plan requires --target');\n if (!prompt) throw new Error('lineage reroll plan requires --prompt');\n return planImageReroll(options.project, {\n rootAssetId: options.rootAssetId,\n targetAssetId,\n prompt,\n dryRun: args.includes('--dry-run'),\n });\n }\n if (subcommand === 'import') {\n const jobId = readOption(args, '--job-id');\n const file = readOption(args, '--file');\n if (!jobId) throw new Error('lineage reroll import requires --job-id');\n if (!file) throw new Error('lineage reroll import requires --file');\n return importImageRerollOutput(options.project, { jobId, file, confirmWrite: options.confirmWrite });\n }\n throw new Error(`Unknown reroll command: ${subcommand}`);\n }\n if (command === 'tasks') {\n const subcommand = positionalArgs(args)[0] || '';\n const taskId = readOption(args, '--task');\n if (subcommand === 'list') {\n if (!options.rootAssetId) throw new Error('lineage tasks list requires --root');\n return listLineageTasks(options.project, options.rootAssetId);\n }\n if (subcommand === 'inspect') {\n if (!taskId) throw new Error('lineage tasks inspect requires --task');\n return getLineageTask(options.project, taskId);\n }\n if (subcommand === 'claim') {\n const agentName = readOption(args, '--agent-name');\n if (!taskId) throw new Error('lineage tasks claim requires --task');\n if (!agentName) throw new Error('lineage tasks claim requires --agent-name');\n return claimLineageTask(options.project, { taskId, agentName });\n }\n if (subcommand === 'start') {\n if (!taskId) throw new Error('lineage tasks start requires --task');\n if (!options.claimToken) throw new Error('lineage tasks start requires --claim-token');\n return startLineageTask(options.project, { taskId, claimToken: options.claimToken });\n }\n if (subcommand === 'comment') {\n const message = readOption(args, '--message');\n if (!taskId) throw new Error('lineage tasks comment requires --task');\n if (!message) throw new Error('lineage tasks comment requires --message');\n return addLineageTaskComment(options.project, {\n actor: readOption(args, '--actor') || 'human',\n message,\n taskId,\n });\n }\n if (subcommand === 'cancel') {\n if (!taskId) throw new Error('lineage tasks cancel requires --task');\n return cancelLineageTask(options.project, {\n actor: readOption(args, '--actor') || 'human',\n confirmWrite: options.confirmWrite,\n override: args.includes('--override'),\n taskId,\n });\n }\n if (subcommand === 'override') {\n const reason = readOption(args, '--reason');\n if (!taskId) throw new Error('lineage tasks override requires --task');\n if (!reason) throw new Error('lineage tasks override requires --reason');\n return overrideLineageTask(options.project, {\n actor: readOption(args, '--actor') || 'human',\n instructions: readOption(args, '--instructions'),\n reason,\n taskId,\n });\n }\n if (subcommand === 'instructions') {\n const instructions = readOption(args, '--instructions');\n if (!taskId) throw new Error('lineage tasks instructions requires --task');\n if (instructions === undefined) throw new Error('lineage tasks instructions requires --instructions');\n return updateLineageTaskInstructions(options.project, { instructions, taskId });\n }\n throw new Error(`Unknown tasks command: ${subcommand}`);\n }\n throw new Error(`Unknown command: ${command}`);\n}\n\nfunction rerollRequestedBy(value: string): 'agent' | 'human' | 'system' {\n if (value === 'agent' || value === 'human' || value === 'system') return value;\n throw new Error(`Invalid re-roll requester: ${value}`);\n}\n\nexport function printDataResult(command: string, result: unknown, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (command === 'next' && result && typeof result === 'object' && 'reason' in result) {\n const next = result as { next_asset?: { asset_id: string; title: string } | null; reason: string; root_asset_id: string };\n console.log(next.next_asset ? `${next.next_asset.asset_id}: ${next.next_asset.title}` : `No next asset: ${next.reason}`);\n console.log(`Root: ${next.root_asset_id}`);\n return;\n }\n if (command === 'brief' && result && typeof result === 'object' && 'brief' in result) {\n const brief = result as { brief: { title: string; prompt: string } };\n console.log(brief.brief.title);\n console.log(brief.brief.prompt);\n return;\n }\n if (command === 'inspect' && result && typeof result === 'object' && 'nodes' in result) {\n const snapshot = result as { active_asset_id: string; edges: unknown[]; nodes: unknown[]; root_asset_id: string };\n console.log(`${snapshot.root_asset_id}: ${snapshot.nodes.length} node(s), ${snapshot.edges.length} edge(s)`);\n console.log(`Active: ${snapshot.active_asset_id}`);\n return;\n }\n if (command === 'selection' && result && typeof result === 'object' && 'packet_id' in result) {\n const packet = result as { assets?: unknown[]; packet_id: string; selection?: { count: number }; warnings?: string[]; workspace?: { root_asset_id: string } };\n console.log(`${packet.packet_id}: ${packet.selection?.count || packet.assets?.length || 0} selected asset(s)`);\n if (packet.workspace?.root_asset_id) console.log(`Root: ${packet.workspace.root_asset_id}`);\n for (const warning of packet.warnings || []) console.log(`Warning: ${warning}`);\n return;\n }\n if (command === 'link-child' && result && typeof result === 'object') {\n const link = result as { dryRun?: boolean; edge?: { child_asset_id: string; parent_asset_id: string }; message?: string; warning?: string };\n console.log(link.message || `${link.dryRun ? 'Dry run: ' : ''}Link ${link.edge?.child_asset_id || 'child'} from ${link.edge?.parent_asset_id || 'parent'}`);\n if (link.warning) console.log(`Warning: ${link.warning}`);\n return;\n }\n if (command === 'generate' && result && typeof result === 'object' && 'job' in result) {\n const generation = result as { idempotent?: boolean; imported?: unknown[]; job?: { id: string; status: string } };\n if (generation.imported) {\n console.log(`${generation.idempotent ? 'Already imported' : 'Imported'} ${generation.imported.length} output(s) for ${generation.job?.id || 'job'}`);\n } else {\n console.log(`Generation job ${generation.job?.id || 'job'} ${generation.job?.status || 'unknown'}`);\n }\n return;\n }\n if (command === 'reroll' && result && typeof result === 'object') {\n if ('requests' in result) {\n const listed = result as { requests: Array<{ node_asset_id: string; notes?: string }> };\n console.log(`${listed.requests.length} pending re-roll target(s)`);\n for (const request of listed.requests) console.log(`${request.node_asset_id}${request.notes ? `: ${request.notes}` : ''}`);\n return;\n }\n if ('job' in result) {\n const planned = result as { imported?: unknown[]; job?: { id: string; status: string } };\n console.log(planned.imported ? `Imported re-roll for ${planned.job?.id || 'job'}` : `Planned re-roll ${planned.job?.id || 'job'}`);\n return;\n }\n if ('request' in result) {\n const mutation = result as { dryRun?: boolean; request?: { node_asset_id: string; status: string } };\n console.log(`${mutation.dryRun ? 'Dry run: ' : ''}Re-roll ${mutation.request?.status || 'request'} for ${mutation.request?.node_asset_id || 'target'}`);\n return;\n }\n }\n if (command === 'tasks' && result && typeof result === 'object') {\n if ('tasks' in result) {\n const listed = result as { tasks: Array<{ id: string; status: string; target_asset_id: string; task_type: string }> };\n console.log(`${listed.tasks.length} lineage task(s)`);\n for (const task of listed.tasks) console.log(`${task.id} ${task.task_type} ${task.status} ${task.target_asset_id}`);\n return;\n }\n if ('task' in result) {\n const mutation = result as {\n dryRun?: boolean;\n events?: Array<{ event_type: string }>;\n task?: { id: string; status: string; target_asset_id: string; task_type: string };\n };\n const prefix = mutation.dryRun ? 'Dry run: ' : '';\n console.log(`${prefix}${mutation.task?.id || 'task'} ${mutation.task?.task_type || 'task'} ${mutation.task?.status || 'unknown'} ${mutation.task?.target_asset_id || ''}`.trim());\n if ('claim_token' in mutation && typeof mutation.claim_token === 'string') console.log(`Token: ${mutation.claim_token}`);\n if (mutation.events && mutation.events.length > 0) console.log(`Events: ${mutation.events.map(event => event.event_type).join(', ')}`);\n return;\n }\n }\n console.log(String(result));\n}\n\nexport function runLineageDbCommand(config: LineageCliConfig, command: string, args: string[]): unknown {\n configureCliAssetRoot(args);\n const dbPath = resolveCliDbPath(config, args);\n process.env.LINEAGE_DB = dbPath;\n if (command === 'info') return getLineageRuntimeInfo({ channel: config.channel, dbPath });\n throw new Error(`Unknown db command: ${command}`);\n}\n\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'doctor', args: string[]): LineageProfileDoctorResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'init', args: string[]): LineageProfileInitResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'bind', args: string[]): LineageProfileBindResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'clone', args: string[]): Promise<LineageProfileCloneResult>;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'clone-assets', args: string[]): LineageProfileAssetsCloneResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'repin-runtime', args: string[]): LineageProfileRuntimeRepinResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: string, args: string[]): LineageProfileDoctorResult | LineageProfileInitResult | LineageProfileBindResult | LineageProfileAssetsCloneResult | LineageProfileRuntimeRepinResult | Promise<LineageProfileCloneResult>;\nexport function runLineageProfileCommand(\n config: LineageCliConfig,\n command: string,\n args: string[],\n): LineageProfileDoctorResult | LineageProfileInitResult | LineageProfileBindResult | LineageProfileAssetsCloneResult | LineageProfileRuntimeRepinResult | Promise<LineageProfileCloneResult> {\n const runtime = getLineageRuntimeInfo({ channel: config.channel });\n const runtimeIdentity = { channel: config.channel, code: runtime.code, gitSha: runtime.git_sha, version: runtime.version };\n if (command === 'init') {\n if (hasOption(args, '--db')) throw new Error('Profile init cannot be combined with --db');\n if (hasOption(args, '--asset-root')) throw new Error('Profile init cannot be combined with --asset-root');\n if (!args.includes('--confirm-write')) throw new Error('Profile init requires --confirm-write');\n const profileId = readOption(args, '--profile');\n if (!profileId) throw new Error('lineage profile init requires --profile');\n if (process.env.LINEAGE_PROFILE && process.env.LINEAGE_PROFILE !== profileId) {\n throw new Error('Profile init requires an explicit --profile that does not conflict with LINEAGE_PROFILE');\n }\n const serviceOrigin = readOption(args, '--service-origin') || `http://${config.defaultHost}:${config.defaultPort}`;\n return initializeLineageProfile(profileId, serviceOrigin, runtimeIdentity, true, (profile, initialize) => {\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n try {\n return initialize();\n } finally {\n writerLease.release();\n }\n });\n }\n if (command === 'clone') {\n const source = readOption(args, '--source-db');\n const target = readOption(args, '--target-profile');\n if (!source || !target) throw new Error('lineage profile clone requires --source-db and --target-profile');\n if (hasOption(args, '--profile')) throw new Error('Profile clone uses --target-profile, not --profile');\n if (!args.includes('--confirm-write')) throw new Error('Profile clone requires --confirm-write');\n const targetProfile = resolveLineageProfile(target);\n const writerLease = acquireProfileWriterLease(targetProfile, config.channel, 'cli');\n return cloneLineageProfileDatabase(source, target, runtimeIdentity, true)\n .finally(writerLease.release);\n }\n if (command === 'clone-assets') {\n const source = readOption(args, '--source-asset-root');\n const target = readOption(args, '--target-profile');\n if (!source || !target) throw new Error('lineage profile clone-assets requires --source-asset-root and --target-profile');\n if (hasOption(args, '--profile')) throw new Error('Profile asset clone uses --target-profile, not --profile');\n if (!args.includes('--confirm-write')) throw new Error('Profile asset clone requires --confirm-write');\n const targetProfile = resolveLineageProfile(target);\n const writerLease = acquireProfileWriterLease(targetProfile, config.channel, 'cli');\n try {\n return cloneLineageProfileAssets(source, target, runtimeIdentity, true);\n } finally {\n writerLease.release();\n }\n }\n if (hasOption(args, '--db')) throw new Error(`Profile ${command} cannot be combined with --db`);\n if (hasOption(args, '--asset-root')) throw new Error(`Profile ${command} cannot be combined with --asset-root`);\n const selector = profileSelector(args);\n if (!selector) throw new Error(`lineage profile ${command} requires --profile or LINEAGE_PROFILE`);\n if (command === 'doctor') return doctorLineageProfile(selector, runtimeIdentity);\n if (command === 'repin-runtime') {\n const checkoutRoot = readOption(args, '--checkout-root');\n if (!checkoutRoot) throw new Error('Profile runtime repin requires --checkout-root');\n if (!args.includes('--confirm-write')) throw new Error('Profile runtime repin requires --confirm-write');\n const profile = resolveLineageProfile(selector);\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n try {\n return repinLineageDevelopmentProfileRuntime(selector, checkoutRoot, runtimeIdentity, true);\n } finally {\n writerLease.release();\n }\n }\n if (command === 'bind') {\n if (!args.includes('--confirm-write')) throw new Error('Profile bind requires --confirm-write');\n const profile = resolveLineageProfile(selector);\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n try {\n return bindLineageProfileDatabase(selector, runtimeIdentity, true);\n } finally {\n writerLease.release();\n }\n }\n throw new Error(`Unknown profile command: ${command}`);\n}\n\nfunction printProfileResult(result: LineageProfileDoctorResult | LineageProfileInitResult | LineageProfileBindResult | LineageProfileCloneResult | LineageProfileAssetsCloneResult | LineageProfileRuntimeRepinResult, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (result.schema_version === 'lineage.profile_init.v1') {\n console.log(`Initialized ${result.profile_id} at ${result.manifest_path}`);\n console.log(`Service: ${result.service_origin}`);\n } else if (result.schema_version === 'lineage.profile_doctor.v1') {\n console.log(`Profile doctor: ${result.ok ? 'ok' : 'failed'}`);\n for (const check of result.checks) console.log(`${check.status.toUpperCase()} ${check.id}: ${check.message}`);\n } else if (result.schema_version === 'lineage.profile_bind.v1') {\n console.log(`${result.already_bound ? 'Already bound' : 'Bound'} ${result.database_path} to ${result.identity.profile_id}`);\n } else if (result.schema_version === 'lineage.profile_clone_receipt.v1') {\n console.log(`Cloned ${result.source_database_path} to ${result.database_path} for ${result.target_identity.profile_id}`);\n console.log(`Receipt: ${result.receipt_path}`);\n } else if (result.schema_version === 'lineage.profile_runtime_repin_receipt.v1') {\n console.log(`${result.changed ? 'Repinned' : 'Already pinned'} ${result.profile_id} to checkout ${result.checkout_root}`);\n console.log(`Code fingerprint: ${result.new_code_fingerprint}`);\n } else {\n console.log(`Cloned ${result.files_copied} referenced asset file(s) into ${result.asset_root}`);\n console.log(`Receipt: ${result.receipt_path}`);\n }\n}\n\nexport function lineageProfileDoctorExitCode(result: LineageProfileDoctorResult): 0 | 1 {\n return result.ok ? 0 : 1;\n}\n\nexport function runLineageRuntimeCommand(config: LineageCliConfig, command: string): LineageRuntimeCodeIdentity {\n if (command === 'info') return getLineageCodeIdentity(config.channel);\n if (command === 'doctor') return assertLineageCodeOrigin(config.channel);\n throw new Error(`Unknown runtime command: ${command}`);\n}\n\nfunction printRuntimeResult(result: LineageRuntimeCodeIdentity, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n console.log(`Code origin: ${result.origin}`);\n console.log(`Code root: ${result.root}`);\n console.log(`Channel: ${result.channel}`);\n console.log(`Version: ${result.package_version}`);\n if (result.git_sha) console.log(`Git: ${result.git_sha}`);\n if (result.dirty !== undefined) console.log(`Dirty: ${result.dirty ? 'yes' : 'no'}`);\n console.log(`Fingerprint: ${result.fingerprint}`);\n console.log(`Verified: ${result.verified ? 'yes' : 'no'}`);\n for (const error of result.errors) console.log(`FAIL: ${error}`);\n}\n\nexport function lineageCliRequiresWriterLease(command: string, args: string[]): boolean {\n if (command === 'next' || command === 'brief' || command === 'inspect' || command === 'selection') return false;\n const positions = positionalArgs(args);\n const subcommand = positions[0] || '';\n if (command === 'generate') return positions[0] !== 'image' || positions[1] !== 'inspect';\n if (command === 'reroll') return subcommand !== 'list';\n if (command === 'tasks') return subcommand !== 'list' && subcommand !== 'inspect';\n if (command === 'db') return subcommand !== 'info';\n if (command === 'agent') return subcommand !== 'status' && subcommand !== 'graph' && subcommand !== 'inspect';\n return true;\n}\n\nexport function lineageCliCanDelegateMutation(command: string, args: string[]): boolean {\n const positions = positionalArgs(args);\n const subcommand = positions[0] || '';\n if (command === 'link-child') return true;\n if (command === 'generate') return positions[0] === 'image' && ['plan', 'import'].includes(positions[1] || '');\n if (command === 'reroll') return ['mark', 'cancel', 'plan', 'import'].includes(subcommand);\n if (command === 'tasks') return ['claim', 'start', 'comment', 'cancel', 'override', 'instructions'].includes(subcommand);\n if (command === 'agent') return ['claim', 'heartbeat', 'release', 'revoke', 'transfer'].includes(subcommand);\n return false;\n}\n\nfunction argsWithoutProfileSelector(args: string[]): string[] {\n const filtered: string[] = [];\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === '--profile') {\n index += 1;\n continue;\n }\n if (arg.startsWith('--profile=')) continue;\n filtered.push(arg);\n }\n return filtered;\n}\n\nexport function executeDelegatedLineageMutation(command: string, args: string[]): unknown {\n if (!lineageCliCanDelegateMutation(command, args)) throw new Error(`Unsupported managed writer command: ${command}`);\n if (command === 'agent') {\n const agentCommand = args[0] || '';\n return runLineageAgentCommand(agentCommand, args.slice(1));\n }\n return runLineageDataCommand(command, args);\n}\n\nfunction printDbResult(command: string, result: unknown, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (command === 'info' && result && typeof result === 'object' && 'database' in result) {\n const runtime = result as {\n asset_root: string;\n channel: string;\n code?: LineageRuntimeCodeIdentity;\n database: { error?: string; exists: boolean; modified_at?: string; path: string; projects?: number; size_bytes?: number; workspaces?: number };\n git_sha?: string;\n node_env?: string;\n version: string;\n };\n console.log(`Channel: ${runtime.channel}`);\n console.log(`Version: ${runtime.version}`);\n if (runtime.code) {\n console.log(`Code: ${runtime.code.origin} ${runtime.code.verified ? 'verified' : 'unverified'} ${runtime.code.fingerprint}`);\n console.log(`Code root: ${runtime.code.root}`);\n }\n if (runtime.git_sha) console.log(`Git: ${runtime.git_sha}`);\n if (runtime.node_env) console.log(`Node env: ${runtime.node_env}`);\n console.log(`Assets: ${runtime.asset_root}`);\n console.log(`SQLite: ${runtime.database.path}`);\n console.log(`Exists: ${runtime.database.exists ? 'yes' : 'no'}`);\n if (runtime.database.size_bytes !== undefined) console.log(`Size: ${runtime.database.size_bytes} bytes`);\n if (runtime.database.modified_at) console.log(`Modified: ${runtime.database.modified_at}`);\n if (runtime.database.projects !== undefined) console.log(`Projects: ${runtime.database.projects}`);\n if (runtime.database.workspaces !== undefined) console.log(`Workspaces: ${runtime.database.workspaces}`);\n if (runtime.database.error) console.log(`Warning: ${runtime.database.error}`);\n return;\n }\n console.log(String(result));\n}\n\nexport function runLineageAgentCommand(command: string, args: string[]): unknown {\n configureCliAssetRoot(args);\n const dbPath = readOption(args, '--db');\n if (dbPath) process.env.LINEAGE_DB = dbPath;\n const project = readOption(args, '--project') || process.env.LINEAGE_DEFAULT_PRODUCT || defaultProduct;\n const claimId = readOption(args, '--claim');\n const claimToken = readOption(args, '--claim-token') || process.env.LINEAGE_CLAIM_TOKEN;\n if (command === 'claim') {\n return createAgentClaim({\n agentId: readOption(args, '--agent-id'),\n agentKind: readOption(args, '--agent-kind'),\n agentName: readOption(args, '--agent-name') || '',\n channel: readOption(args, '--channel'),\n force: args.includes('--force'),\n project,\n reason: readOption(args, '--reason'),\n scopeType: (readOption(args, '--scope') || '') as AgentClaimScopeType,\n targetId: readOption(args, '--target') || '',\n targetTitle: readOption(args, '--target-title'),\n threadId: readOption(args, '--thread-id'),\n ttlSeconds: parseClaimTtl(readOption(args, '--ttl')),\n });\n }\n if (command === 'status') return listAgentClaims(project);\n if (command === 'graph') {\n const rootAssetId = readOption(args, '--root') || readOption(args, '--asset-id') || positionalArgs(args)[0];\n if (!rootAssetId) throw new Error('lineage agent graph requires --root');\n return getLineageSnapshot(project, rootAssetId);\n }\n if (command === 'inspect') {\n if (!claimId) throw new Error('lineage agent inspect requires --claim');\n return inspectAgentClaim(claimId, project);\n }\n if (command === 'heartbeat') {\n if (!claimToken) throw new Error('lineage agent heartbeat requires --claim-token');\n return heartbeatAgentClaim(claimToken, parseClaimTtl(readOption(args, '--ttl')));\n }\n if (command === 'release') {\n if (!claimToken) throw new Error('lineage agent release requires --claim-token');\n return releaseAgentClaim(claimToken);\n }\n if (command === 'revoke') {\n if (!claimId) throw new Error('lineage agent revoke requires --claim');\n return revokeAgentClaim(project, claimId, {\n actor: readOption(args, '--actor') || 'human',\n confirmWrite: args.includes('--confirm-write'),\n reason: readOption(args, '--reason'),\n });\n }\n if (command === 'transfer') {\n if (!claimId) throw new Error('lineage agent transfer requires --claim');\n return transferAgentClaim(project, claimId, {\n actor: readOption(args, '--actor') || 'human',\n confirmWrite: args.includes('--confirm-write'),\n reason: readOption(args, '--reason'),\n toAgentName: readOption(args, '--to-agent-name') || '',\n });\n }\n throw new Error(`Unknown agent command: ${command}`);\n}\n\nfunction printAgentResult(command: string, result: unknown, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (command === 'claim' && result && typeof result === 'object' && 'claim' in result) {\n const created = result as { claim?: { id: string; target_id: string }; claim_token?: string };\n console.log(`Claimed ${created.claim?.target_id || 'target'} as ${created.claim?.id || 'claim'}`);\n if (created.claim_token) console.log(`Token: ${created.claim_token}`);\n return;\n }\n if (command === 'status' && result && typeof result === 'object' && 'claims' in result) {\n const status = result as { claims: Array<{ agent_name: string; derived_state: string; target_id: string }> };\n if (status.claims.length === 0) {\n console.log('No agent claims.');\n return;\n }\n for (const claim of status.claims) console.log(`${claim.agent_name} ${claim.derived_state} ${claim.target_id}`);\n return;\n }\n if (result && typeof result === 'object' && 'claim' in result) {\n const inspected = result as { claim?: { id: string; status: string; target_id: string } };\n console.log(`${inspected.claim?.id || 'claim'} ${inspected.claim?.status || 'unknown'} ${inspected.claim?.target_id || ''}`.trim());\n return;\n }\n if (command === 'graph' && result && typeof result === 'object' && 'nodes' in result) {\n console.log(formatAgentGraphDigest(result as AgentGraphDigestSnapshot));\n return;\n }\n console.log(String(result));\n}\n\ninterface AgentGraphDigestSnapshot {\n active_asset_id: string;\n edges: Array<{ child_asset_id: string; parent_asset_id: string }>;\n latest?: string[];\n nodes: Array<{ asset_id: string; is_latest?: boolean; title?: string }>;\n root_asset_id: string;\n selected?: string[];\n}\n\nexport function formatAgentGraphDigest(snapshot: AgentGraphDigestSnapshot): string {\n const lines: string[] = [];\n const titleFor = (assetId: string) => {\n const node = snapshot.nodes.find(item => item.asset_id === assetId);\n return node?.title ? `${node.title} (${assetId})` : assetId;\n };\n const root = snapshot.nodes.find(node => node.asset_id === snapshot.root_asset_id);\n lines.push(`Lineage graph: ${root?.title || snapshot.root_asset_id}`);\n lines.push(`Root: ${snapshot.root_asset_id}`);\n lines.push(`Active: ${titleFor(snapshot.active_asset_id)}`);\n lines.push(`Nodes: ${snapshot.nodes.length} Edges: ${snapshot.edges.length}`);\n const selected = snapshot.selected || [];\n if (selected.length > 0) {\n lines.push('Next variation:');\n for (const assetId of selected) lines.push(`- ${titleFor(assetId)}`);\n }\n const latest = snapshot.latest || snapshot.nodes.filter(node => node.is_latest).map(node => node.asset_id);\n if (latest.length > 0) {\n lines.push('Latest leaves:');\n for (const assetId of latest) lines.push(`- ${titleFor(assetId)}`);\n }\n lines.push('Edges:');\n for (const edge of snapshot.edges) lines.push(`- ${titleFor(edge.parent_asset_id)} -> ${titleFor(edge.child_asset_id)}`);\n return lines.join('\\n');\n}\n\nfunction start(config: LineageCliConfig, args: string[]): void {\n let options: StartOptions;\n const json = args.includes('--json');\n try {\n options = resolveStartOptions(config, args);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n const serverPath = join(packageRoot(), 'dist', 'server.js');\n if (!existsSync(serverPath)) {\n const message = `Missing bundled server at ${serverPath}. Run npm run build before using ${config.binName} start from a source checkout.`;\n if (options.json) console.error(JSON.stringify({ ok: false, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n\n mkdirSync(dirname(options.dbPath), { recursive: true });\n const url = `http://${options.host}:${options.port}`;\n if (options.json) {\n console.log(JSON.stringify({ assetRoot: options.assetRoot, channel: config.channel, dbPath: options.dbPath, host: options.host, port: options.port, profile: options.profile ? { environment: options.profile.environment, id: options.profile.profile_id } : { bound: false, id: 'legacy-unbound' }, status: 'starting', url }, null, 2));\n } else {\n console.log(`${config.displayName} starting at ${url}`);\n if (options.profile) console.log(`Profile: ${options.profile.profile_id} (${options.profile.environment})`);\n console.log(`SQLite: ${options.dbPath}`);\n console.log(`Assets: ${options.assetRoot}`);\n }\n const code = getLineageCodeIdentity(config.channel);\n const serviceInstanceId = process.env.LINEAGE_SERVICE_INSTANCE_ID || randomUUID();\n\n const child = spawn(process.execPath, [serverPath], {\n env: {\n ...process.env,\n HOST: options.host,\n LINEAGE_ASSET_ROOT: options.assetRoot,\n LINEAGE_CHANNEL: config.channel,\n LINEAGE_DB: options.dbPath,\n LINEAGE_PROFILE: process.env.LINEAGE_PROFILE,\n LINEAGE_PROFILE_ENVIRONMENT: options.profile?.environment,\n LINEAGE_PROFILE_FINGERPRINT: options.profile?.profile_fingerprint,\n LINEAGE_PROFILE_ID: options.profile?.profile_id,\n LINEAGE_PROFILE_MANIFEST: options.profile?.manifest_path,\n LINEAGE_PROFILE_SERVICE_ORIGIN: options.profile?.service_origin,\n LINEAGE_LAUNCHER_PID: String(process.pid),\n LINEAGE_SERVICE_INSTANCE_ID: serviceInstanceId,\n LINEAGE_DB_ACCESS: undefined,\n NODE_ENV: 'production',\n PORT: String(options.port),\n },\n stdio: 'inherit',\n });\n\n if (options.open) {\n void openBrowserAfterReadiness(url, {\n channel: config.channel,\n code_fingerprint: code.fingerprint,\n database_path: options.dbPath,\n instance_id: serviceInstanceId,\n launcher_pid: process.pid,\n profile: options.profile,\n }, child).catch(error => {\n console.error(`${config.binName}: ${error instanceof Error ? error.message : String(error)}`);\n child.kill('SIGTERM');\n });\n }\n\n let forwardedSignal: NodeJS.Signals | undefined;\n const stop = (signal: NodeJS.Signals) => {\n forwardedSignal = signal;\n child.kill(signal);\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n child.on('exit', code => process.exit(code ?? (forwardedSignal ? signalExitCodes[forwardedSignal] || 1 : 0)));\n child.on('error', error => {\n console.error(`${config.binName}: failed to start server: ${error.message}`);\n process.exit(1);\n });\n}\n\nexport async function runLineageCli(config: LineageCliConfig, args = process.argv.slice(2)): Promise<void> {\n process.env.LINEAGE_CHANNEL = config.channel;\n if (args.includes('--help') || args.includes('-h') || args.length === 0) {\n printHelp(config);\n process.exit(0);\n }\n\n if (args.includes('--version') || args.includes('-v')) {\n console.log(packageVersion());\n process.exit(0);\n }\n\n const normalizedArgs = args[0] === 'lineage' ? args.slice(1) : args;\n const [command] = normalizedArgs;\n\n if (command === 'profile') {\n const commandArgs = normalizedArgs.slice(2);\n const profileCommand = normalizedArgs[1] || '';\n const json = commandArgs.includes('--json');\n try {\n const result = runLineageProfileCommand(config, profileCommand, commandArgs);\n if (result instanceof Promise) {\n result.then(value => {\n printProfileResult(value, json);\n process.exit(0);\n }).catch(error => {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `profile ${profileCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n });\n return;\n }\n printProfileResult(result, json);\n process.exit(result.schema_version === 'lineage.profile_doctor.v1' ? lineageProfileDoctorExitCode(result) : 0);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `profile ${profileCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n }\n\n if (command === 'runtime') {\n const runtimeCommand = normalizedArgs[1] || '';\n const commandArgs = normalizedArgs.slice(2);\n const json = commandArgs.includes('--json');\n try {\n printRuntimeResult(runLineageRuntimeCommand(config, runtimeCommand), json);\n process.exit(0);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `runtime ${runtimeCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n }\n\n const originDiagnosticOnly = command === 'db' && normalizedArgs[1] === 'info';\n if (!originDiagnosticOnly) {\n try {\n assertLineageCodeOrigin(config.channel);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const json = normalizedArgs.includes('--json');\n if (json) console.error(JSON.stringify({ ok: false, command, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n }\n\n if (command === 'start') {\n start(config, normalizedArgs.slice(1));\n return;\n }\n\n let managedWriterProfile: ResolvedLineageProfile | undefined;\n try {\n const profile = prepareCliProfile(config, normalizedArgs.slice(1));\n const requiresWriter = lineageCliRequiresWriterLease(command, normalizedArgs.slice(1));\n if (profile) {\n if (requiresWriter) {\n delete process.env.LINEAGE_DB_ACCESS;\n try {\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n process.once('exit', writerLease.release);\n } catch (error) {\n if (!(error instanceof ProfileWriterLeaseConflictError) || error.owner.role !== 'service') throw error;\n process.env.LINEAGE_DB_ACCESS = 'read-only';\n managedWriterProfile = profile;\n }\n } else {\n process.env.LINEAGE_DB_ACCESS = 'read-only';\n }\n } else if (requiresWriter) {\n throw new Error('Persistent writes require --profile; legacy-unbound access is read-only. Create a fresh profile with `profile init --profile <id> --confirm-write`, then pass that profile to the command');\n } else {\n process.env.LINEAGE_DB_ACCESS = 'read-only';\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const json = normalizedArgs.includes('--json');\n if (json) console.error(JSON.stringify({ ok: false, command, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n\n if (command === 'next' || command === 'brief' || command === 'inspect' || command === 'selection' || command === 'link-child' || command === 'generate' || command === 'reroll' || command === 'tasks') {\n const commandArgs = normalizedArgs.slice(1);\n const json = commandArgs.includes('--json');\n try {\n const result = managedWriterProfile\n ? await executeManagedWriterCommand(managedWriterProfile, config.channel, command, argsWithoutProfileSelector(commandArgs))\n : runLineageDataCommand(command, commandArgs);\n printDataResult(command, result, json);\n } catch (error) {\n const message = redactAgentClaimTokens(error instanceof Error ? error.message : String(error));\n if (json) {\n const output = isAgentClaimError(error)\n ? { ok: false, command, error: error.code, message, conflicts: error.conflicts }\n : { ok: false, command, error: message };\n console.error(JSON.stringify(output, null, 2));\n }\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n process.exit(0);\n }\n\n if (command === 'db') {\n const commandArgs = normalizedArgs.slice(2);\n const dbCommand = normalizedArgs[1] || '';\n const json = commandArgs.includes('--json');\n try {\n printDbResult(dbCommand, runLineageDbCommand(config, dbCommand, commandArgs), json);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `db ${dbCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n process.exit(0);\n }\n\n if (command === 'agent') {\n const commandArgs = normalizedArgs.slice(2);\n const agentCommand = normalizedArgs[1] || '';\n const json = commandArgs.includes('--json');\n try {\n const result = managedWriterProfile\n ? await executeManagedWriterCommand(\n managedWriterProfile,\n config.channel,\n 'agent',\n argsWithoutProfileSelector([agentCommand, ...commandArgs]),\n )\n : runLineageAgentCommand(agentCommand, commandArgs);\n printAgentResult(agentCommand, result, json);\n } catch (error) {\n const message = redactAgentClaimTokens(error instanceof Error ? error.message : String(error));\n if (json) {\n const output = isAgentClaimError(error)\n ? { ok: false, command: `agent ${agentCommand}`, error: error.code, message, conflicts: error.conflicts }\n : { ok: false, command: `agent ${agentCommand}`, error: message };\n console.error(JSON.stringify(output, null, 2));\n } else {\n console.error(`${config.binName}: ${message}`);\n }\n process.exit(1);\n }\n process.exit(0);\n }\n\n const json = args.includes('--json');\n const message = `Unknown command: ${command}`;\n if (json) console.error(JSON.stringify({ ok: false, command, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n}\n", "export const edgeSummaryWordLimit = 2 as const;\n\nexport type EdgeSummaryValidationCode = 'not_text' | 'required' | 'too_many_words';\n\nexport class EdgeSummaryValidationError extends Error {\n constructor(\n public readonly code: EdgeSummaryValidationCode,\n message: string,\n ) {\n super(message);\n this.name = 'EdgeSummaryValidationError';\n }\n}\n\nexport function normalizeEdgeSummary(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string') throw new EdgeSummaryValidationError('not_text', 'Edge summary must be text');\n const words = value.trim().split(/\\s+/u).filter(Boolean);\n if (words.length === 0) return undefined;\n if (words.length > edgeSummaryWordLimit) {\n throw new EdgeSummaryValidationError('too_many_words', `Edge summary must contain at most ${edgeSummaryWordLimit} words`);\n }\n return words.join(' ');\n}\n\nexport function requireEdgeSummary(value: unknown): string {\n const summary = normalizeEdgeSummary(value);\n if (!summary) throw new EdgeSummaryValidationError('required', 'Edge summary is required');\n return summary;\n}\n", "import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\n\nexport type AgentClaimScopeType = 'lineage_workspace' | 'lineage_task' | 'content_post' | 'content_queue_lane' | 'selection_set' | 'project_channel';\ntype AgentClaimStatus = 'active' | 'expired' | 'released' | 'revoked' | 'transferred';\n\nexport interface AgentClaim {\n id: string;\n project: string;\n channel?: string;\n scope_type: AgentClaimScopeType;\n target_id: string;\n target_title?: string;\n agent_id?: string;\n agent_name: string;\n agent_kind: string;\n thread_id?: string;\n status: AgentClaimStatus;\n created_at: string;\n heartbeat_at: string;\n expires_at: string;\n released_at?: string;\n revoked_at?: string;\n revoked_by?: string;\n override_reason?: string;\n metadata?: Record<string, unknown>;\n heartbeat_age_seconds: number;\n derived_state: 'active' | 'idle' | 'stale' | 'expired';\n}\n\ninterface AgentClaimEvent {\n claim_id: string;\n event_type: string;\n actor?: string;\n message?: string;\n created_at: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface CreateAgentClaimFields {\n project: string;\n channel?: string;\n scopeType: AgentClaimScopeType;\n targetId: string;\n targetTitle?: string;\n agentId?: string;\n agentName: string;\n agentKind?: string;\n threadId?: string;\n ttlSeconds?: number;\n force?: boolean;\n reason?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ValidateAgentClaimForWriteFields {\n claimToken?: string;\n project: string;\n channel?: string;\n scopeType: AgentClaimScopeType;\n targetId: string;\n writeKind: string;\n dangerLevel: 'claim' | 'warn' | 'enforce' | 'danger';\n confirmWrite?: boolean;\n recordEvent?: boolean;\n}\n\nexport type AgentClaimValidationResult =\n | { ok: true; claim: AgentClaim; warnings: string[] }\n | { ok: false; code: string; message: string; conflicts: AgentClaim[] };\n\ntype Row = Record<string, unknown>;\n\nconst defaultTtlSeconds = 20 * 60;\nconst idleAfterSeconds = 5 * 60;\nconst staleAfterSeconds = 15 * 60;\nconst scopes = new Set<AgentClaimScopeType>(['lineage_workspace', 'lineage_task', 'content_post', 'content_queue_lane', 'selection_set', 'project_channel']);\nconst claimTokenPattern = /claim_[a-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\n\nexport class AgentClaimError extends Error {\n constructor(message: string, public status = 400, public code = 'agent_claim_error', public conflicts: AgentClaim[] = []) {\n super(message);\n }\n}\n\nexport function isAgentClaimError(error: unknown): error is AgentClaimError {\n return error instanceof AgentClaimError;\n}\n\nexport function redactAgentClaimTokens(input: string): string {\n return input.replace(claimTokenPattern, '[redacted-claim-token]');\n}\n\nexport function parseClaimTtl(value?: string): number {\n if (!value) return defaultTtlSeconds;\n const match = value.trim().match(/^(\\d+)(s|m|h)?$/);\n if (!match) throw new AgentClaimError(`Invalid claim ttl: ${value}`);\n const amount = Number(match[1]);\n const unit = match[2] || 's';\n const multiplier = unit === 'h' ? 3600 : unit === 'm' ? 60 : 1;\n const seconds = amount * multiplier;\n if (!Number.isInteger(seconds) || seconds < 30 || seconds > 24 * 60 * 60) {\n throw new AgentClaimError('Claim ttl must be between 30 seconds and 24 hours');\n }\n return seconds;\n}\n\nfunction randomId(prefix: string): string {\n return `${prefix}_${Date.now().toString(36)}_${randomBytes(6).toString('base64url').toLowerCase()}`;\n}\n\nfunction tokenHash(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const left = Buffer.from(a);\n const right = Buffer.from(b);\n return left.length === right.length && timingSafeEqual(left, right);\n}\n\nfunction expiresAtFrom(timestamp: string, ttlSeconds: number): string {\n return new Date(new Date(timestamp).getTime() + ttlSeconds * 1000).toISOString();\n}\n\nfunction metadataJson(metadata?: Record<string, unknown>): string | null {\n return metadata ? JSON.stringify(metadata) : null;\n}\n\nfunction parseMetadata(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string' || !value) return undefined;\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction derivedState(row: { status: AgentClaimStatus; heartbeat_at: string; expires_at: string }, now = new Date()): AgentClaim['derived_state'] {\n if (row.status !== 'active') return row.status === 'expired' ? 'expired' : 'stale';\n if (new Date(row.expires_at).getTime() <= now.getTime()) return 'expired';\n const ageSeconds = Math.max(0, Math.floor((now.getTime() - new Date(row.heartbeat_at).getTime()) / 1000));\n if (ageSeconds >= staleAfterSeconds) return 'stale';\n if (ageSeconds >= idleAfterSeconds) return 'idle';\n return 'active';\n}\n\nfunction rowToClaim(row: Row, now = new Date()): AgentClaim {\n const heartbeatAt = String(row.heartbeat_at);\n const persistedStatus = String(row.status) as AgentClaimStatus;\n const state = derivedState({\n expires_at: String(row.expires_at),\n heartbeat_at: heartbeatAt,\n status: persistedStatus,\n }, now);\n return {\n id: String(row.id),\n project: String(row.project_id),\n channel: typeof row.channel === 'string' ? row.channel : undefined,\n scope_type: String(row.scope_type) as AgentClaimScopeType,\n target_id: String(row.target_id),\n target_title: typeof row.target_title === 'string' ? row.target_title : undefined,\n agent_id: typeof row.agent_id === 'string' ? row.agent_id : undefined,\n agent_name: String(row.agent_name),\n agent_kind: String(row.agent_kind),\n thread_id: typeof row.thread_id === 'string' ? row.thread_id : undefined,\n status: persistedStatus === 'active' && state === 'expired' ? 'expired' : persistedStatus,\n created_at: String(row.created_at),\n heartbeat_at: heartbeatAt,\n expires_at: String(row.expires_at),\n released_at: typeof row.released_at === 'string' ? row.released_at : undefined,\n revoked_at: typeof row.revoked_at === 'string' ? row.revoked_at : undefined,\n revoked_by: typeof row.revoked_by === 'string' ? row.revoked_by : undefined,\n override_reason: typeof row.override_reason === 'string' ? row.override_reason : undefined,\n metadata: parseMetadata(row.metadata_json),\n heartbeat_age_seconds: Math.max(0, Math.floor((now.getTime() - new Date(heartbeatAt).getTime()) / 1000)),\n derived_state: state,\n };\n}\n\nfunction eventToRow(row: Row): AgentClaimEvent {\n return {\n claim_id: String(row.claim_id),\n event_type: String(row.event_type),\n actor: typeof row.actor === 'string' ? row.actor : undefined,\n message: typeof row.message === 'string' ? row.message : undefined,\n created_at: String(row.created_at),\n metadata: parseMetadata(row.metadata_json),\n };\n}\n\nfunction ensureProject(database: DatabaseSync, project: string): void {\n const timestamp = nowIso();\n database.prepare(`\n insert into projects (id, product, created_at, updated_at)\n values (?, ?, ?, ?)\n on conflict(id) do update set product = excluded.product, updated_at = excluded.updated_at\n `).run(project, project, timestamp, timestamp);\n}\n\nfunction recordEvent(database: DatabaseSync, claimId: string, eventType: string, actor?: string, message?: string, metadata?: Record<string, unknown>): void {\n database.prepare(`\n insert into agent_claim_events (id, claim_id, event_type, actor, message, created_at, metadata_json)\n values (?, ?, ?, ?, ?, ?, ?)\n `).run(randomId('claim_event'), claimId, eventType, actor || null, message || null, nowIso(), metadataJson(metadata));\n}\n\nfunction expireActiveClaims(database: DatabaseSync): void {\n const timestamp = nowIso();\n const expired = database.prepare(`\n select id from agent_claims where status = 'active' and expires_at <= ?\n `).all(timestamp) as Array<{ id: string }>;\n if (expired.length === 0) return;\n database.prepare(`\n update agent_claims set status = 'expired' where status = 'active' and expires_at <= ?\n `).run(timestamp);\n for (const claim of expired) recordEvent(database, claim.id, 'expired', 'system', 'Claim expired after missed heartbeat.');\n}\n\nfunction normalizeScope(scopeType: AgentClaimScopeType): AgentClaimScopeType {\n if (!scopes.has(scopeType)) throw new AgentClaimError(`Unsupported claim scope: ${scopeType}`);\n return scopeType;\n}\n\nfunction channelOverlaps(left?: string, right?: string): boolean {\n return !left || !right || left === right;\n}\n\nfunction claimOverlaps(candidate: Pick<AgentClaim, 'project' | 'channel' | 'scope_type' | 'target_id'>, existing: AgentClaim): boolean {\n if (candidate.project !== existing.project) return false;\n if (!channelOverlaps(candidate.channel, existing.channel)) return false;\n if (candidate.scope_type === existing.scope_type && candidate.target_id === existing.target_id) return true;\n return candidate.scope_type === 'project_channel' || existing.scope_type === 'project_channel';\n}\n\nfunction activeClaims(database: DatabaseSync, project?: string): AgentClaim[] {\n const rows = project\n ? database.prepare(\"select * from agent_claims where project_id = ? and status = 'active' order by heartbeat_at desc\").all(project)\n : database.prepare(\"select * from agent_claims where status = 'active' order by project_id, heartbeat_at desc\").all();\n return (rows as Row[]).map(row => rowToClaim(row));\n}\n\nfunction findClaimById(database: DatabaseSync, claimId: string, project?: string): AgentClaim | null {\n const row = project\n ? database.prepare('select * from agent_claims where project_id = ? and id = ?').get(project, claimId)\n : database.prepare('select * from agent_claims where id = ?').get(claimId);\n return row ? rowToClaim(row as Row) : null;\n}\n\nfunction findClaimRowByToken(database: DatabaseSync, claimToken: string): Row | null {\n const claimId = claimToken.split('.')[0];\n const row = database.prepare('select * from agent_claims where id = ?').get(claimId) as Row | undefined;\n if (!row) return null;\n return safeEqual(String(row.token_hash), tokenHash(claimToken)) ? row : null;\n}\n\nfunction denied(code: string, message: string, conflicts: AgentClaim[] = []): AgentClaimValidationResult {\n return { ok: false, code, message, conflicts };\n}\n\nfunction scopeAllowsWrite(claim: AgentClaim, scopeType: AgentClaimScopeType, targetId: string, writeKind: string): boolean {\n if (claim.scope_type === scopeType && claim.target_id === targetId) return true;\n if (claim.scope_type === 'project_channel') return true;\n if (claim.scope_type === 'lineage_workspace' && scopeType === 'lineage_workspace') return claim.target_id === targetId;\n if (claim.scope_type === 'content_queue_lane' && writeKind === 'content_queue_next') return true;\n return false;\n}\n\nexport function createAgentClaim(fields: CreateAgentClaimFields) {\n const project = fields.project.trim();\n const targetId = fields.targetId.trim();\n const agentName = fields.agentName.trim();\n if (!project) throw new AgentClaimError('Agent claim requires project');\n if (!targetId) throw new AgentClaimError('Agent claim requires target');\n if (!agentName) throw new AgentClaimError('Agent claim requires agent name');\n const scopeType = normalizeScope(fields.scopeType);\n const ttlSeconds = fields.ttlSeconds || defaultTtlSeconds;\n const database = lineageDb();\n try {\n ensureProject(database, project);\n expireActiveClaims(database);\n const candidate = { project, channel: fields.channel?.trim() || undefined, scope_type: scopeType, target_id: targetId };\n const conflicts = activeClaims(database, project).filter(claim => claimOverlaps(candidate, claim));\n if (conflicts.length > 0 && !fields.force) {\n throw new AgentClaimError('Target already has an active overlapping agent claim.', 409, 'target_already_claimed', conflicts);\n }\n if (conflicts.length > 0 && !fields.reason?.trim()) {\n throw new AgentClaimError('Overriding an active claim requires --reason.', 400, 'override_reason_required', conflicts);\n }\n const timestamp = nowIso();\n for (const conflict of conflicts) {\n database.prepare(`\n update agent_claims\n set status = 'revoked', revoked_at = ?, revoked_by = ?, override_reason = ?\n where id = ? and status = 'active'\n `).run(timestamp, agentName, fields.reason || null, conflict.id);\n recordEvent(database, conflict.id, 'revoked', agentName, fields.reason || 'Revoked by forced claim takeover.');\n recordEvent(database, conflict.id, 'conflict', agentName, `Overridden by ${agentName}.`, { new_claim_target: targetId });\n }\n const id = randomId('claim');\n const secret = randomBytes(24).toString('base64url');\n const claimToken = `${id}.${secret}`;\n const expiresAt = expiresAtFrom(timestamp, ttlSeconds);\n database.prepare(`\n insert into agent_claims (\n id, token_hash, project_id, channel, scope_type, target_id, target_title, agent_id, agent_name,\n agent_kind, thread_id, status, created_at, heartbeat_at, expires_at, metadata_json\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?)\n `).run(\n id,\n tokenHash(claimToken),\n project,\n candidate.channel || null,\n scopeType,\n targetId,\n fields.targetTitle?.trim() || null,\n fields.agentId?.trim() || null,\n agentName,\n fields.agentKind?.trim() || 'codex',\n fields.threadId?.trim() || null,\n timestamp,\n timestamp,\n expiresAt,\n metadataJson(fields.metadata)\n );\n recordEvent(database, id, 'created', agentName, `Claimed ${scopeType} ${targetId}.`, { ttl_seconds: ttlSeconds });\n const claim = findClaimById(database, id);\n return { ok: true as const, claim, claim_token: claimToken, conflicts_revoked: conflicts.map(conflict => conflict.id) };\n } finally {\n database.close();\n }\n}\n\nexport function listAgentClaims(project?: string) {\n const database = lineageDb();\n try {\n if (process.env.LINEAGE_DB_ACCESS !== 'read-only') expireActiveClaims(database);\n const rows = project\n ? database.prepare('select * from agent_claims where project_id = ? order by status, heartbeat_at desc').all(project)\n : database.prepare('select * from agent_claims order by project_id, status, heartbeat_at desc').all();\n return { ok: true as const, claims: (rows as Row[]).map(row => rowToClaim(row)), fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function inspectAgentClaim(claimId: string, project?: string) {\n const database = lineageDb();\n try {\n if (process.env.LINEAGE_DB_ACCESS !== 'read-only') expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n const events = database.prepare('select * from agent_claim_events where claim_id = ? order by created_at').all(claim.id) as Row[];\n return { ok: true as const, claim, events: events.map(eventToRow) };\n } finally {\n database.close();\n }\n}\n\nexport function heartbeatAgentClaim(claimToken: string, ttlSeconds = defaultTtlSeconds) {\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const row = findClaimRowByToken(database, claimToken);\n if (!row) throw new AgentClaimError('Unknown or invalid agent claim token.', 401, 'claim_token_invalid');\n const claim = rowToClaim(row);\n if (claim.status !== 'active') throw new AgentClaimError(`Agent claim is ${claim.status}.`, 409, 'claim_not_active');\n const timestamp = nowIso();\n database.prepare('update agent_claims set heartbeat_at = ?, expires_at = ? where id = ?').run(timestamp, expiresAtFrom(timestamp, ttlSeconds), claim.id);\n recordEvent(database, claim.id, 'heartbeat', claim.agent_name, 'Claim heartbeat received.');\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function releaseAgentClaim(claimToken: string) {\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const row = findClaimRowByToken(database, claimToken);\n if (!row) throw new AgentClaimError('Unknown or invalid agent claim token.', 401, 'claim_token_invalid');\n const claim = rowToClaim(row);\n if (claim.status !== 'active') throw new AgentClaimError(`Agent claim is ${claim.status}.`, 409, 'claim_not_active');\n const timestamp = nowIso();\n database.prepare(\"update agent_claims set status = 'released', released_at = ? where id = ?\").run(timestamp, claim.id);\n recordEvent(database, claim.id, 'released', claim.agent_name, 'Claim released by token holder.');\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function releaseStaleAgentClaim(project: string, claimId: string, fields: { actor?: string; confirmWrite: boolean; reason?: string }) {\n if (!fields.confirmWrite) throw new AgentClaimError('Releasing a stale agent claim requires confirmWrite=true.', 400, 'confirm_write_required');\n if (!fields.reason?.trim()) throw new AgentClaimError('Releasing a stale agent claim requires a reason.', 400, 'reason_required');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n if (claim.status !== 'active' || claim.derived_state !== 'stale') {\n throw new AgentClaimError('Only stale active claims can be released without the claim token.', 409, 'claim_not_stale', [claim]);\n }\n const timestamp = nowIso();\n database.prepare(\"update agent_claims set status = 'released', released_at = ?, revoked_by = ?, override_reason = ? where id = ?\").run(timestamp, fields.actor || 'human', fields.reason, claim.id);\n recordEvent(database, claim.id, 'released', fields.actor || 'human', fields.reason);\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function revokeAgentClaim(project: string, claimId: string, fields: { actor?: string; confirmWrite: boolean; reason?: string }) {\n if (!fields.confirmWrite) throw new AgentClaimError('Revoking an agent claim requires confirmWrite=true.', 400, 'confirm_write_required');\n if (!fields.reason?.trim()) throw new AgentClaimError('Revoking an agent claim requires a reason.', 400, 'reason_required');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n const timestamp = nowIso();\n database.prepare(`\n update agent_claims set status = 'revoked', revoked_at = ?, revoked_by = ?, override_reason = ?\n where id = ?\n `).run(timestamp, fields.actor || 'human', fields.reason, claim.id);\n recordEvent(database, claim.id, 'revoked', fields.actor || 'human', fields.reason);\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function revokeAgentClaimInDatabase(database: DatabaseSync, project: string, claimId: string, fields: { actor?: string; reason?: string }) {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n if (claim.status !== 'active') return claim;\n const timestamp = nowIso();\n database.prepare(`\n update agent_claims set status = 'revoked', revoked_at = ?, revoked_by = ?, override_reason = ?\n where id = ? and status = 'active'\n `).run(timestamp, fields.actor || 'human', fields.reason || null, claim.id);\n recordEvent(database, claim.id, 'revoked', fields.actor || 'human', fields.reason);\n return findClaimById(database, claim.id, project);\n}\n\nexport function transferAgentClaim(project: string, claimId: string, fields: { confirmWrite: boolean; toAgentName: string; actor?: string; reason?: string }) {\n if (!fields.confirmWrite) throw new AgentClaimError('Transferring an agent claim requires confirmWrite=true.', 400, 'confirm_write_required');\n const toAgentName = fields.toAgentName.trim();\n if (!toAgentName) throw new AgentClaimError('Transfer requires toAgentName.', 400, 'agent_name_required');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n if (claim.status !== 'active') throw new AgentClaimError(`Agent claim is ${claim.status}.`, 409, 'claim_not_active');\n database.prepare('update agent_claims set agent_name = ? where id = ?').run(toAgentName, claim.id);\n recordEvent(database, claim.id, 'transferred', fields.actor || 'human', fields.reason || `Transferred claim to ${toAgentName}.`, { to_agent_name: toAgentName });\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function recordAgentClaimWriteAllowed(claim: Pick<AgentClaim, 'id' | 'agent_name'>, fields: Pick<ValidateAgentClaimForWriteFields, 'dangerLevel' | 'targetId' | 'writeKind'>) {\n const database = lineageDb();\n try {\n recordEvent(database, claim.id, 'write_allowed', claim.agent_name, `${fields.writeKind} allowed.`, {\n danger_level: fields.dangerLevel,\n target_id: fields.targetId,\n write_kind: fields.writeKind,\n });\n return { ok: true as const };\n } finally {\n database.close();\n }\n}\n\nexport function validateAgentClaimForWrite(fields: ValidateAgentClaimForWriteFields): AgentClaimValidationResult {\n if (fields.dangerLevel === 'danger' && !fields.confirmWrite) {\n return denied('human_confirmation_required', 'Dangerous write requires explicit human confirmation.');\n }\n if (!fields.claimToken) return denied('claim_required', 'Mutating agent write requires a matching claim token.');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const row = findClaimRowByToken(database, fields.claimToken);\n if (!row) return denied('claim_token_invalid', 'Unknown or invalid claim token.');\n const claim = rowToClaim(row);\n if (claim.status !== 'active') return denied('claim_not_active', `Agent claim is ${claim.status}.`);\n if (new Date(claim.expires_at).getTime() <= Date.now()) return denied('claim_expired', 'Agent claim has expired.');\n if (claim.project !== fields.project) return denied('claim_project_mismatch', `Claim project ${claim.project} does not match ${fields.project}.`, [claim]);\n if (fields.channel && claim.channel && claim.channel !== fields.channel) {\n return denied('claim_channel_mismatch', `Claim channel ${claim.channel} does not match ${fields.channel}.`, [claim]);\n }\n if (!scopeAllowsWrite(claim, fields.scopeType, fields.targetId, fields.writeKind)) {\n return denied('claim_scope_mismatch', `Claim does not cover ${fields.scopeType} ${fields.targetId}.`, [claim]);\n }\n if (fields.recordEvent !== false) {\n recordEvent(database, claim.id, 'write_allowed', claim.agent_name, `${fields.writeKind} allowed.`, {\n danger_level: fields.dangerLevel,\n target_id: fields.targetId,\n write_kind: fields.writeKind,\n });\n }\n return { ok: true, claim, warnings: [] };\n } finally {\n database.close();\n }\n}\n", "import type { DatabaseSync as DatabaseSyncType } from 'node:sqlite';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { packageRoot } from './assetCore';\nimport { assertProfileWriterLeaseHeld, assertSelectedProfileDatabaseIdentity } from './profileWriterLease';\nimport { loadNodeSqlite } from './nodeSqlite';\n\nexport type DatabaseSync = DatabaseSyncType;\n\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n\nexport function lineageDbPath(): string {\n return process.env.LINEAGE_DB || join(packageRoot, '.lineage', 'asset-lineage.sqlite');\n}\n\nexport function lineageDb(): DatabaseSync {\n const readOnly = process.env.LINEAGE_DB_ACCESS === 'read-only';\n if (!readOnly) assertProfileWriterLeaseHeld();\n if (!readOnly && !existsSync(lineageDbPath())) {\n throw new Error(`Refusing writable open of missing profile database ${lineageDbPath()}; bind an existing database or create a non-production clone first`);\n }\n if (!readOnly) mkdirSync(join(lineageDbPath(), '..'), { recursive: true });\n const { DatabaseSync } = loadNodeSqlite();\n const database = readOnly ? new DatabaseSync(lineageDbPath(), { readOnly: true }) : new DatabaseSync(lineageDbPath());\n if (process.env.LINEAGE_PROFILE) assertSelectedProfileDatabaseIdentity(database);\n database.exec('PRAGMA foreign_keys = ON');\n database.exec('PRAGMA busy_timeout = 5000');\n if (readOnly) return database;\n database.exec('PRAGMA journal_mode = WAL');\n database.exec(`\n create table if not exists projects (\n id text primary key,\n product text not null,\n catalog_path text,\n created_at text not null,\n updated_at text not null\n );\n create table if not exists assets (\n id text primary key,\n project_id text not null references projects(id),\n source text not null check (source in ('local', 'catalog')),\n local_path text,\n s3_key text,\n checksum_sha256 text,\n media_type text not null,\n title text not null,\n status text not null,\n channel text,\n campaign text,\n audience text,\n size_bytes integer,\n content_type text,\n created_at text not null,\n updated_at text not null,\n last_seen_at text not null\n );\n create index if not exists assets_project_source_seen on assets(project_id, source, last_seen_at);\n create index if not exists assets_project_checksum on assets(project_id, checksum_sha256);\n create index if not exists assets_project_channel_campaign on assets(project_id, channel, campaign);\n create table if not exists lineage_schema_migrations (\n key text primary key,\n applied_at text not null\n );\n create table if not exists asset_edges (\n id text primary key,\n project_id text not null references projects(id),\n parent_asset_id text not null references assets(id),\n child_asset_id text not null references assets(id),\n relation_type text not null check (relation_type in ('derived_from')),\n created_at text not null,\n summary text,\n summary_created_by text check (summary_created_by in ('human', 'agent', 'system')),\n summary_updated_by text check (summary_updated_by in ('human', 'agent', 'system')),\n summary_updated_at text,\n unique (project_id, parent_asset_id, child_asset_id, relation_type)\n );\n create index if not exists edges_parent on asset_edges(project_id, parent_asset_id);\n create index if not exists edges_child on asset_edges(project_id, child_asset_id);\n create table if not exists asset_attempts (\n id text primary key,\n project_id text not null references projects(id),\n node_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n attempt_index integer not null check (attempt_index > 0),\n source text not null check (source in ('initial', 'generated_child', 'reroll')),\n prompt text,\n generation_job_id text,\n file_path text,\n checksum_sha256 text,\n created_at text not null,\n promoted_at text,\n is_current integer not null check (is_current in (0, 1)),\n unique(project_id, node_asset_id, attempt_index),\n unique(project_id, node_asset_id, asset_id, source)\n );\n create unique index if not exists asset_attempts_one_current\n on asset_attempts(project_id, node_asset_id)\n where is_current = 1;\n create index if not exists asset_attempts_node_created\n on asset_attempts(project_id, node_asset_id, created_at);\n create table if not exists asset_reroll_requests (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n node_asset_id text not null references assets(id),\n status text not null check (status in ('pending', 'resolved', 'cancelled')),\n requested_by text not null check (requested_by in ('human', 'agent', 'system')),\n notes text,\n created_at text not null,\n resolved_at text\n );\n create unique index if not exists asset_reroll_requests_one_pending\n on asset_reroll_requests(project_id, root_asset_id, node_asset_id)\n where status = 'pending';\n create index if not exists asset_reroll_requests_root_status\n on asset_reroll_requests(project_id, root_asset_id, status, created_at);\n create table if not exists asset_reviews (\n asset_id text primary key references assets(id),\n review_state text not null check (review_state in ('unreviewed', 'approved', 'needs_revision', 'rejected', 'ignored')),\n reviewed_at text,\n ignored_at text,\n notes text,\n updated_at text not null\n );\n create table if not exists asset_selections (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n notes text,\n selected_at text not null,\n unique(project_id, root_asset_id)\n );\n create table if not exists asset_layouts (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n x real not null,\n y real not null,\n updated_at text not null,\n unique(project_id, root_asset_id, asset_id)\n );\n create table if not exists lineage_workspaces (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n title text not null,\n status text not null check (status in ('active', 'paused', 'archived')),\n notes text,\n created_by text not null check (created_by in ('human', 'agent', 'system')),\n active_at text,\n created_at text not null,\n updated_at text not null,\n unique(project_id, root_asset_id)\n );\n create index if not exists lineage_workspaces_project_status on lineage_workspaces(project_id, status, updated_at);\n create index if not exists lineage_workspaces_project_active on lineage_workspaces(project_id, active_at);\n create table if not exists asset_ledger_records (\n id text primary key,\n project_id text not null references projects(id),\n canonical_asset_id text not null,\n checksum_sha256 text,\n media_type text not null,\n title text not null,\n status text not null,\n channel text,\n campaign text,\n audience text,\n created_at text not null,\n updated_at text not null,\n first_seen_at text not null default (datetime('now')),\n last_seen_at text not null\n );\n create index if not exists asset_ledger_records_project_seen on asset_ledger_records(project_id, last_seen_at);\n create index if not exists asset_ledger_records_project_checksum on asset_ledger_records(project_id, checksum_sha256);\n create table if not exists asset_ledger_sources (\n id text primary key,\n project_id text not null references projects(id),\n record_id text not null references asset_ledger_records(id) on delete cascade,\n source_type text not null check (source_type in ('local', 'catalog', 's3')),\n asset_id text,\n local_path text,\n s3_bucket text,\n s3_region text,\n s3_key text,\n s3_version_id text,\n etag text,\n size_bytes integer,\n content_type text,\n updated_at text,\n first_seen_at text not null default (datetime('now')),\n last_seen_at text not null\n );\n create index if not exists asset_ledger_sources_project_type on asset_ledger_sources(project_id, source_type);\n create index if not exists asset_ledger_sources_record on asset_ledger_sources(project_id, record_id);\n create index if not exists asset_ledger_sources_s3_key on asset_ledger_sources(project_id, s3_key);\n create table if not exists asset_ledger_placements (\n id text primary key,\n project_id text not null references projects(id),\n asset_id text not null,\n channel text not null,\n status text not null,\n scheduled_at text,\n posted_at text,\n url text,\n notes text,\n updated_at text not null,\n synced_at text not null,\n unique(project_id, asset_id, channel)\n );\n create index if not exists asset_ledger_placements_project_status on asset_ledger_placements(project_id, status);\n create index if not exists asset_ledger_placements_asset on asset_ledger_placements(project_id, asset_id);\n create table if not exists asset_ledger_index_runs (\n id text primary key,\n project_id text not null references projects(id),\n source_mode text not null check (source_mode in ('all', 'catalog', 'local')),\n include_live_s3 integer not null default 0,\n status text not null check (status in ('running', 'complete', 'failed')),\n started_at text not null,\n completed_at text,\n assets_indexed integer not null default 0,\n records_after integer not null default 0,\n catalog_sources_after integer not null default 0,\n local_sources_after integer not null default 0,\n s3_sources_after integer not null default 0,\n error text\n );\n create index if not exists asset_ledger_index_runs_project_started on asset_ledger_index_runs(project_id, started_at);\n create table if not exists content_batches (\n id text not null,\n project_id text not null references projects(id),\n title text not null,\n campaign text,\n channel text,\n status text not null check (status in ('active', 'archived')),\n notes text,\n created_at text not null,\n updated_at text not null,\n primary key(project_id, id)\n );\n create index if not exists content_batches_project_updated on content_batches(project_id, updated_at);\n create table if not exists content_posts (\n id text not null,\n project_id text not null references projects(id),\n batch_id text not null,\n channel text not null,\n title text not null,\n phase text not null check (phase in ('draft', 'review', 'scheduled', 'posted', 'skipped', 'archived')),\n campaign text,\n body text,\n cta text,\n scheduled_at text,\n posted_at text,\n url text,\n notes text,\n source_path text,\n created_at text not null,\n updated_at text not null,\n primary key(project_id, id),\n foreign key(project_id, batch_id) references content_batches(project_id, id) on delete cascade\n );\n create index if not exists content_posts_project_phase on content_posts(project_id, phase);\n create index if not exists content_posts_batch on content_posts(project_id, batch_id);\n create table if not exists content_post_assets (\n id text primary key,\n project_id text not null references projects(id),\n post_id text not null,\n asset_id text not null,\n role text not null,\n notes text,\n attached_at text not null,\n unique(project_id, post_id, asset_id, role),\n foreign key(project_id, post_id) references content_posts(project_id, id) on delete cascade\n );\n create index if not exists content_post_assets_post on content_post_assets(project_id, post_id);\n create index if not exists content_post_assets_asset on content_post_assets(project_id, asset_id);\n create table if not exists content_targets (\n project_id text primary key references projects(id),\n post_id text not null,\n notes text,\n selected_at text not null,\n updated_at text not null,\n foreign key(project_id, post_id) references content_posts(project_id, id) on delete cascade\n );\n create table if not exists selection_sets (\n id text primary key,\n project_id text not null references projects(id),\n kind text not null check (kind in ('current', 'review')),\n key text not null,\n label text not null,\n status text not null check (status in ('active', 'archived')),\n created_by text not null check (created_by in ('human', 'agent', 'system')),\n created_at text not null,\n updated_at text not null,\n unique(project_id, kind, key)\n );\n create index if not exists selection_sets_project_kind on selection_sets(project_id, kind, updated_at);\n create table if not exists selection_items (\n id text primary key,\n set_id text not null references selection_sets(id) on delete cascade,\n asset_id text not null,\n role text not null check (role in ('primary', 'candidate', 'next_base')),\n variation_label text,\n position integer not null default 0,\n selected_by text check (selected_by in ('human', 'agent', 'system')),\n selected_at text,\n deselected_at text,\n notes text,\n created_at text not null,\n updated_at text not null,\n unique(set_id, asset_id)\n );\n create index if not exists selection_items_set_position on selection_items(set_id, position);\n create unique index if not exists selection_items_set_label on selection_items(set_id, variation_label) where variation_label is not null;\n create table if not exists generation_jobs (\n id text primary key,\n project_id text not null references projects(id),\n provider text not null default 'codex-handoff',\n adapter_version text not null,\n source_mode text not null check (source_mode in ('lineage_selection', 'lineage_reroll')),\n root_asset_id text not null references assets(id),\n prompt text not null,\n expected_output_count integer not null check (expected_output_count > 0),\n status text not null check (status in ('planned', 'imported', 'failed', 'cancelled')),\n output_dir text,\n handoff_json text,\n created_at text not null,\n updated_at text not null,\n imported_at text\n );\n create index if not exists generation_jobs_project_created on generation_jobs(project_id, created_at);\n create table if not exists generation_job_inputs (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n project_id text not null references projects(id),\n asset_id text not null references assets(id),\n root_asset_id text not null references assets(id),\n role text not null check (role in ('lineage_next_base', 'reference', 'reroll_target')),\n position integer not null,\n selection_strategy text not null,\n selection_snapshot_json text not null,\n unique(job_id, asset_id, role)\n );\n create index if not exists generation_job_inputs_job on generation_job_inputs(job_id, position);\n create table if not exists generation_job_outputs (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n project_id text not null references projects(id),\n output_index integer not null,\n file_path text not null,\n checksum_sha256 text not null,\n size_bytes integer not null,\n content_type text not null,\n imported_asset_id text not null references assets(id),\n parent_asset_id text not null references assets(id),\n imported_at text not null,\n edge_summary text,\n unique(job_id, output_index),\n unique(job_id, file_path)\n );\n create index if not exists generation_job_outputs_job on generation_job_outputs(job_id, output_index);\n create table if not exists generation_job_receipts (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n receipt_type text not null check (receipt_type in ('plan', 'import', 'error')),\n status text not null check (status in ('ok', 'error')),\n command text not null,\n payload_json text not null,\n created_at text not null\n );\n create index if not exists generation_job_receipts_job on generation_job_receipts(job_id, created_at);\n create table if not exists adapter_settings (project_id text not null references projects(id), adapter_type text not null check (adapter_type in ('cloud', 'scheduler', 'image_generator')), provider text not null, enabled integer not null check (enabled in (0, 1)), secret_ref text, safe_config_json text not null, created_at text not null, updated_at text not null, primary key(project_id, adapter_type, provider)); create index if not exists adapter_settings_project_type on adapter_settings(project_id, adapter_type);\n create table if not exists lineage_tasks (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n target_asset_id text not null references assets(id),\n task_type text not null check (task_type in ('iterate', 'reroll')),\n status text not null check (status in ('pending', 'claimed', 'in_progress', 'resolved', 'cancelled')),\n instructions text,\n created_by text not null check (created_by in ('human', 'agent', 'system')),\n created_at text not null,\n updated_at text not null,\n claimed_at text,\n started_at text,\n resolved_at text,\n cancelled_at text,\n resolved_generation_job_id text,\n resolved_asset_id text references assets(id),\n metadata_json text\n );\n create unique index if not exists lineage_tasks_one_open\n on lineage_tasks(project_id, root_asset_id, target_asset_id, task_type)\n where status in ('pending', 'claimed', 'in_progress');\n create index if not exists lineage_tasks_root_status\n on lineage_tasks(project_id, root_asset_id, status, updated_at);\n create index if not exists lineage_tasks_target\n on lineage_tasks(project_id, root_asset_id, target_asset_id, task_type, status);\n create table if not exists lineage_task_events (\n id text primary key,\n task_id text not null references lineage_tasks(id) on delete cascade,\n event_type text not null,\n actor text,\n message text,\n created_at text not null,\n metadata_json text\n );\n create index if not exists lineage_task_events_task_created\n on lineage_task_events(task_id, created_at);\n create table if not exists agent_claims (\n id text primary key,\n token_hash text not null,\n project_id text not null references projects(id),\n channel text,\n scope_type text not null check (scope_type in ('lineage_workspace', 'lineage_task', 'content_post', 'content_queue_lane', 'selection_set', 'project_channel')),\n target_id text not null,\n target_title text,\n agent_id text,\n agent_name text not null,\n agent_kind text not null,\n thread_id text,\n status text not null check (status in ('active', 'expired', 'released', 'revoked', 'transferred')),\n created_at text not null,\n heartbeat_at text not null,\n expires_at text not null,\n released_at text,\n revoked_at text,\n revoked_by text,\n override_reason text,\n metadata_json text\n );\n create unique index if not exists agent_claims_token_hash on agent_claims(token_hash);\n create index if not exists agent_claims_project_status on agent_claims(project_id, status, heartbeat_at);\n create index if not exists agent_claims_target on agent_claims(project_id, channel, scope_type, target_id, status);\n create table if not exists agent_claim_events (\n id text primary key,\n claim_id text not null references agent_claims(id) on delete cascade,\n event_type text not null,\n actor text,\n message text,\n created_at text not null,\n metadata_json text\n );\n create index if not exists agent_claim_events_claim_created on agent_claim_events(claim_id, created_at);\n `);\n ensureColumn(database, 'asset_edges', 'summary', 'text');\n ensureColumn(database, 'asset_edges', 'summary_created_by', \"text check (summary_created_by in ('human', 'agent', 'system'))\");\n ensureColumn(database, 'asset_edges', 'summary_updated_by', \"text check (summary_updated_by in ('human', 'agent', 'system'))\");\n ensureColumn(database, 'asset_edges', 'summary_updated_at', 'text');\n ensureColumn(database, 'generation_job_outputs', 'edge_summary', 'text');\n migrateAssetSelections(database);\n dropLegacyAssetSelectionRootUnique(database);\n ensureColumn(database, 'asset_selections', 'notes', 'text');\n backfillLineageTasks(database);\n ensureColumn(database, 'asset_ledger_records', 'first_seen_at', 'text');\n ensureColumn(database, 'asset_ledger_records', 'indexed_by_run_id', 'text');\n ensureColumn(database, 'asset_ledger_sources', 'first_seen_at', 'text');\n ensureColumn(database, 'asset_ledger_sources', 'indexed_by_run_id', 'text');\n ensureReviewStateValues(database);\n ensureAgentClaimScopeValues(database);\n ensureGenerationReceiptCheckValues(database);\n return database;\n}\n\nexport function backfillLineageTasks(database: DatabaseSync): void {\n database.exec(`\n create table if not exists lineage_schema_migrations (\n key text primary key,\n applied_at text not null\n )\n `);\n const marker = database.prepare(\"select key from lineage_schema_migrations where key = 'lineage_tasks_backfilled_v1'\").get();\n if (marker) return;\n\n database.exec('BEGIN IMMEDIATE');\n try {\n database.exec(`\n insert or ignore into lineage_tasks (\n id, project_id, root_asset_id, target_asset_id, task_type, status, instructions,\n created_by, created_at, updated_at, metadata_json\n )\n select\n s.project_id || ':' || s.root_asset_id || ':lineage-task:iterate:' || s.asset_id,\n s.project_id,\n s.root_asset_id,\n s.asset_id,\n 'iterate',\n 'pending',\n s.notes,\n 'human',\n s.selected_at,\n s.selected_at,\n null\n from asset_selections s;\n\n insert or ignore into lineage_tasks (\n id, project_id, root_asset_id, target_asset_id, task_type, status, instructions,\n created_by, created_at, updated_at, metadata_json\n )\n select\n r.project_id || ':' || r.root_asset_id || ':lineage-task:reroll:' || r.node_asset_id,\n r.project_id,\n r.root_asset_id,\n r.node_asset_id,\n 'reroll',\n 'pending',\n r.notes,\n r.requested_by,\n r.created_at,\n r.created_at,\n null\n from asset_reroll_requests r\n where r.status = 'pending';\n `);\n database.prepare(`\n insert into lineage_schema_migrations (key, applied_at)\n values ('lineage_tasks_backfilled_v1', ?)\n on conflict(key) do nothing\n `).run(nowIso());\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n}\n\nfunction ensureColumn(database: DatabaseSync, table: string, column: string, definition: string): void {\n const rows = database.prepare(`pragma table_info(${table})`).all() as Array<{ name: string }>;\n if (!rows.some(row => row.name === column)) database.exec(`alter table ${table} add column ${column} ${definition}`);\n}\n\nfunction migrateAssetSelections(database: DatabaseSync): void {\n const rows = database.prepare('pragma table_info(asset_selections)').all() as Array<{ name: string }>;\n if (rows.some(row => row.name === 'position')) return;\n const notesSelect = rows.some(row => row.name === 'notes') ? 'notes' : 'null';\n\n database.exec(`\n create table if not exists asset_selections_v2 (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n position integer not null default 0,\n notes text,\n selected_at text not null,\n unique(project_id, root_asset_id, asset_id)\n );\n insert or ignore into asset_selections_v2 (id, project_id, root_asset_id, asset_id, position, notes, selected_at)\n select\n project_id || ':' || root_asset_id || ':selected:' || asset_id,\n project_id,\n root_asset_id,\n asset_id,\n 0,\n ${notesSelect},\n selected_at\n from asset_selections;\n drop table asset_selections;\n alter table asset_selections_v2 rename to asset_selections;\n create index if not exists asset_selections_project_root_position\n on asset_selections(project_id, root_asset_id, position, selected_at);\n `);\n}\n\nfunction dropLegacyAssetSelectionRootUnique(database: DatabaseSync): void {\n const indexes = database.prepare('pragma index_list(asset_selections)').all() as Array<{ name: string; unique: number }>;\n for (const index of indexes) {\n if (!index.unique) continue;\n const columns = database.prepare(`pragma index_info(${index.name})`).all() as Array<{ name: string }>;\n const columnNames = columns.map(column => column.name).join(',');\n if (columnNames === 'project_id,root_asset_id') database.exec(`drop index if exists ${index.name}`);\n }\n}\n\nfunction ensureReviewStateValues(database: DatabaseSync): void {\n const createSql = database.prepare(\"select sql from sqlite_master where type = 'table' and name = 'asset_reviews'\").get() as { sql?: string } | undefined;\n if (createSql?.sql?.includes('needs_revision')) return;\n\n database.exec(`\n alter table asset_reviews rename to asset_reviews_old;\n create table asset_reviews (\n asset_id text primary key references assets(id),\n review_state text not null check (review_state in ('unreviewed', 'approved', 'needs_revision', 'rejected', 'ignored')),\n reviewed_at text,\n ignored_at text,\n notes text,\n updated_at text not null\n );\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n select asset_id, review_state, reviewed_at, ignored_at, notes, updated_at\n from asset_reviews_old;\n drop table asset_reviews_old;\n `);\n}\n\nfunction ensureAgentClaimScopeValues(database: DatabaseSync): void {\n const createSql = database.prepare(\"select sql from sqlite_master where type = 'table' and name = 'agent_claims'\").get() as { sql?: string } | undefined;\n if (createSql?.sql?.includes(\"'lineage_task'\")) return;\n\n database.exec('PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON; BEGIN IMMEDIATE');\n try {\n database.exec(`\n alter table agent_claims rename to agent_claims_old;\n create table agent_claims (\n id text primary key,\n token_hash text not null,\n project_id text not null references projects(id),\n channel text,\n scope_type text not null check (scope_type in ('lineage_workspace', 'lineage_task', 'content_post', 'content_queue_lane', 'selection_set', 'project_channel')),\n target_id text not null,\n target_title text,\n agent_id text,\n agent_name text not null,\n agent_kind text not null,\n thread_id text,\n status text not null check (status in ('active', 'expired', 'released', 'revoked', 'transferred')),\n created_at text not null,\n heartbeat_at text not null,\n expires_at text not null,\n released_at text,\n revoked_at text,\n revoked_by text,\n override_reason text,\n metadata_json text\n );\n insert into agent_claims\n select * from agent_claims_old;\n drop table agent_claims_old;\n create unique index if not exists agent_claims_token_hash on agent_claims(token_hash);\n create index if not exists agent_claims_project_status on agent_claims(project_id, status, heartbeat_at);\n create index if not exists agent_claims_target on agent_claims(project_id, channel, scope_type, target_id, status);\n `);\n const violations = database.prepare('pragma foreign_key_check').all();\n if (violations.length > 0) throw new Error(`Agent claim scope migration failed foreign key check: ${JSON.stringify(violations)}`);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n } finally {\n database.exec('PRAGMA legacy_alter_table = OFF; PRAGMA foreign_keys = ON');\n }\n}\n\nfunction tableCreateSql(database: DatabaseSync, table: string): string {\n const row = database.prepare(\"select sql from sqlite_master where type = 'table' and name = ?\").get(table) as { sql?: string } | undefined;\n return row?.sql || '';\n}\n\nfunction ensureGenerationReceiptCheckValues(database: DatabaseSync): void {\n const jobsSql = tableCreateSql(database, 'generation_jobs');\n const inputsSql = tableCreateSql(database, 'generation_job_inputs');\n const needsJobsMigration = Boolean(jobsSql && !jobsSql.includes(\"'lineage_reroll'\"));\n const needsInputsMigration = Boolean(inputsSql && !inputsSql.includes(\"'reroll_target'\"));\n if (!needsJobsMigration && !needsInputsMigration) return;\n\n database.exec('PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON; BEGIN IMMEDIATE');\n try {\n if (needsJobsMigration) migrateGenerationJobsCheck(database);\n if (needsInputsMigration) migrateGenerationJobInputsCheck(database);\n const violations = database.prepare('pragma foreign_key_check').all();\n if (violations.length > 0) throw new Error(`Generation receipt migration failed foreign key check: ${JSON.stringify(violations)}`);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n } finally {\n database.exec('PRAGMA legacy_alter_table = OFF; PRAGMA foreign_keys = ON');\n }\n}\n\nfunction migrateGenerationJobsCheck(database: DatabaseSync): void {\n database.exec(`\n alter table generation_jobs rename to generation_jobs_legacy_check;\n create table generation_jobs (\n id text primary key,\n project_id text not null references projects(id),\n provider text not null default 'codex-handoff',\n adapter_version text not null,\n source_mode text not null check (source_mode in ('lineage_selection', 'lineage_reroll')),\n root_asset_id text not null references assets(id),\n prompt text not null,\n expected_output_count integer not null check (expected_output_count > 0),\n status text not null check (status in ('planned', 'imported', 'failed', 'cancelled')),\n output_dir text,\n handoff_json text,\n created_at text not null,\n updated_at text not null,\n imported_at text\n );\n insert into generation_jobs (\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at, imported_at\n )\n select\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at, imported_at\n from generation_jobs_legacy_check;\n drop table generation_jobs_legacy_check;\n create index if not exists generation_jobs_project_created on generation_jobs(project_id, created_at);\n `);\n}\n\nfunction migrateGenerationJobInputsCheck(database: DatabaseSync): void {\n database.exec(`\n alter table generation_job_inputs rename to generation_job_inputs_legacy_check;\n create table generation_job_inputs (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n project_id text not null references projects(id),\n asset_id text not null references assets(id),\n root_asset_id text not null references assets(id),\n role text not null check (role in ('lineage_next_base', 'reference', 'reroll_target')),\n position integer not null,\n selection_strategy text not null,\n selection_snapshot_json text not null,\n unique(job_id, asset_id, role)\n );\n insert into generation_job_inputs (\n id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json\n )\n select\n id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json\n from generation_job_inputs_legacy_check;\n drop table generation_job_inputs_legacy_check;\n create index if not exists generation_job_inputs_job on generation_job_inputs(job_id, position);\n `);\n}\n", "import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { createS3StorageAdapter } from './adapters/storage';\nimport { listLocalReviewAssets, localPreviewPath as resolveLocalPreviewPath } from './localReview';\nimport { syncLedgerPlacement } from './assetLedgerWorkflow';\nimport { appName } from '../shared/appConstants';\nimport type {\n AssetCatalog,\n AssetContentType,\n AssetFacets,\n DoctorReport,\n AssetLibrarySnapshot,\n GrowthAsset,\n ListAssetsOptions,\n LiveS3Object,\n MutationResponse,\n PlacementFields,\n PlacementStatus,\n PresignResponse,\n ProjectSummary,\n UploadFields,\n} from '../shared/types';\n\nfunction isPackageRoot(path: string): boolean {\n const packageJson = join(path, 'package.json');\n if (!existsSync(packageJson)) return false;\n try {\n const packageInfo = JSON.parse(readFileSync(packageJson, 'utf8')) as { name?: string };\n return packageInfo.name === '@mean-weasel/lineage';\n } catch {\n return false;\n }\n}\n\nfunction resolvePackageRoot(): string {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n process.env.LINEAGE_REPO_ROOT,\n resolve(moduleDir, '..'),\n resolve(moduleDir, '../..'),\n process.cwd(),\n ].filter((candidate): candidate is string => Boolean(candidate));\n const root = candidates.find(isPackageRoot);\n if (!root) throw new Error('Unable to locate Lineage package root');\n return root;\n}\n\nexport const packageRoot = resolvePackageRoot();\nexport let repoRoot = resolve(process.env.LINEAGE_ASSET_ROOT || packageRoot);\n\nexport function setLineageAssetRoot(path?: string): string {\n repoRoot = resolve(path || packageRoot);\n return repoRoot;\n}\nexport const defaultProject = 'demo-project';\nexport const defaultProduct = process.env.LINEAGE_DEFAULT_PRODUCT || defaultProject;\nconst publicFallbackBucket = 'lineage-demo-assets';\nconst publicFallbackRegion = 'us-east-1';\nconst contentTypes = new Set<AssetContentType>(['image', 'video', 'gif', 'audio', 'doc', 'other']);\nconst baseChannels = ['linkedin', 'meta', 'tiktok', 'x-twitter', 'youtube'];\nconst placementStatuses = new Set<PlacementStatus>(['planned', 'scheduled', 'posted', 'skipped']);\nconst projectNamePattern = /^[a-z0-9][a-z0-9-]*$/;\n\ninterface CommandResult {\n stdout: string;\n stderr: string;\n}\n\nclass LineageAssetError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageAssetError(error: unknown): error is LineageAssetError {\n return error instanceof LineageAssetError;\n}\n\nexport function cleanProject(project = defaultProject): string {\n if (!projectNamePattern.test(project)) {\n throw new LineageAssetError('Project must be lowercase kebab-case');\n }\n return project;\n}\n\nexport function catalogPath(project = defaultProject): string {\n return join(repoRoot, cleanProject(project), 'assets', 'catalog.json');\n}\n\nfunction fixtureCatalogPath(project = defaultProject): string {\n return join(packageRoot, 'fixtures', cleanProject(project), 'assets', 'catalog.json');\n}\n\nfunction resolvedCatalogPath(project = defaultProject): string {\n const path = catalogPath(project);\n if (existsSync(path)) return path;\n const clean = cleanProject(project);\n if (clean === defaultProject && existsSync(fixtureCatalogPath(clean))) return fixtureCatalogPath(clean);\n return path;\n}\n\nexport function normalizeCatalog(catalog: Partial<AssetCatalog>, fallbackProject = defaultProject): AssetCatalog {\n const project = cleanProject(catalog.project || catalog.product || fallbackProject);\n const product = catalog.product || project;\n return {\n ...catalog,\n project,\n product,\n default_bucket: catalog.default_bucket || '',\n default_region: catalog.default_region || '',\n assets: (catalog.assets || []).map(asset => ({\n ...asset,\n source: asset.source || 'catalog',\n project: asset.project || asset.product || project,\n product: asset.product || asset.project || project,\n })),\n };\n}\n\nfunction fallbackS3(assetId: string, channel: string, status = 'working') {\n return {\n bucket: publicFallbackBucket,\n checksum_sha256: undefined,\n content_type: 'image/png',\n key: `products/${defaultProject}/campaigns/2026-06-public-demo/channels/${channel}/audiences/creators/statuses/${status}/types/image/assets/${assetId}/${assetId}.png`,\n region: publicFallbackRegion,\n size_bytes: 2048,\n updated_at: '2026-06-24T12:00:00.000Z',\n version_id: 'public-demo-version',\n };\n}\n\nfunction fallbackAsset(fields: Omit<GrowthAsset, 'audience' | 'campaign' | 'content_type' | 'cta' | 'hook' | 'product' | 'project' | 'source' | 'utm_content'> & {\n audience?: string;\n campaign?: string;\n cta?: string;\n hook?: string;\n utm_content?: string;\n}): GrowthAsset {\n return {\n audience: fields.audience || 'creators',\n campaign: fields.campaign || '2026-06-public-demo',\n content_type: 'image',\n cta: fields.cta || 'Save the idea',\n hook: fields.hook || 'Public demo creative for local review.',\n product: defaultProject,\n project: defaultProject,\n source: 'catalog',\n utm_content: fields.utm_content || fields.asset_id.replace(/-/g, '_'),\n ...fields,\n };\n}\n\nfunction defaultFallbackCatalog(): AssetCatalog {\n return normalizeCatalog({\n assets: [\n fallbackAsset({\n asset_id: 'demo-meta-short-form-upload-demo-post-static',\n channel: 'meta',\n s3: fallbackS3('demo-meta-short-form-upload-demo-post-static', 'meta'),\n status: 'working',\n title: 'Meta short-form demo post static',\n }),\n fallbackAsset({\n asset_id: 'demo-linkedin-ledger-catalog-shared',\n channel: 'linkedin',\n hook: 'Shared ledger creative with catalog metadata.',\n s3: fallbackS3('demo-linkedin-ledger-catalog-shared', 'linkedin'),\n status: 'working',\n title: 'LinkedIn ledger catalog shared',\n }),\n fallbackAsset({\n asset_id: 'demo-linkedin-upload-demo-done-static-grounded-v2',\n channel: 'linkedin',\n placements: [{\n channel: 'linkedin',\n notes: 'Synthetic public scheduled placement.',\n scheduled_at: '2026-06-24T16:00:00-07:00',\n status: 'scheduled',\n updated_at: '2026-06-24T12:30:00.000Z',\n }],\n s3: fallbackS3('demo-linkedin-upload-demo-done-static-grounded-v2', 'linkedin', 'approved'),\n status: 'approved',\n title: 'LinkedIn upload demo scheduled static',\n }),\n fallbackAsset({\n asset_id: 'demo-tiktok-upload-demo-export-vertical',\n channel: 'tiktok',\n format: 'vertical',\n hook: 'Fast vertical demo export for content queue tests.',\n s3: fallbackS3('demo-tiktok-upload-demo-export-vertical', 'tiktok'),\n status: 'working',\n title: 'TikTok upload demo export vertical',\n }),\n fallbackAsset({\n asset_id: 'demo-youtube-short-demo-posted-cut',\n channel: 'youtube',\n placements: [{\n channel: 'youtube',\n notes: 'Synthetic public posted placement.',\n posted_at: '2026-06-25T16:00:00-07:00',\n status: 'posted',\n updated_at: '2026-06-25T17:00:00.000Z',\n }],\n s3: fallbackS3('demo-youtube-short-demo-posted-cut', 'youtube', 'published'),\n status: 'published',\n title: 'YouTube short demo posted cut',\n }),\n fallbackAsset({\n asset_id: 'demo-x-twitter-carousel-demo-working-static',\n channel: 'x-twitter',\n format: 'static',\n s3: fallbackS3('demo-x-twitter-carousel-demo-working-static', 'x-twitter'),\n status: 'working',\n title: 'X Twitter carousel demo working static',\n }),\n ],\n default_bucket: '',\n default_region: '',\n product: defaultProject,\n project: defaultProject,\n }, defaultProject);\n}\n\nfunction isDefaultFallbackCatalog(catalog: AssetCatalog): boolean {\n return catalog.project === defaultProject && !existsSync(catalogPath(defaultProject));\n}\n\nfunction fallbackPreviewDataUrl(asset: GrowthAsset): string {\n const label = `${asset.title}\\n${asset.channel} / ${asset.status}`;\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"675\" viewBox=\"0 0 1200 675\"><rect width=\"1200\" height=\"675\" fill=\"#f7f5ef\"/><rect x=\"56\" y=\"56\" width=\"1088\" height=\"563\" rx=\"18\" fill=\"#10201c\"/><text x=\"96\" y=\"145\" fill=\"#9fe6c8\" font-family=\"Arial, sans-serif\" font-size=\"34\" font-weight=\"700\">Lineage public demo preview</text><text x=\"96\" y=\"230\" fill=\"#fff8e6\" font-family=\"Arial, sans-serif\" font-size=\"56\" font-weight=\"700\">${escapeSvgText(asset.asset_id)}</text><text x=\"96\" y=\"330\" fill=\"#d9e8df\" font-family=\"Arial, sans-serif\" font-size=\"34\">${escapeSvgText(label)}</text><text x=\"96\" y=\"500\" fill=\"#9fb7ae\" font-family=\"Arial, sans-serif\" font-size=\"26\">Synthetic local placeholder. No external storage requested.</text></svg>`;\n return `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;\n}\n\nfunction escapeSvgText(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\nexport function loadCatalog(project = defaultProject): AssetCatalog {\n const path = catalogPath(project);\n if (existsSync(path)) {\n try {\n return normalizeCatalog(JSON.parse(readFileSync(path, 'utf8')) as Partial<AssetCatalog>, project);\n } catch (error) {\n if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {\n throw new LineageAssetError(`Missing catalog: ${path}`, 404);\n }\n throw error;\n }\n }\n const clean = cleanProject(project);\n if (clean === defaultProject) {\n const fixturePath = fixtureCatalogPath(clean);\n if (existsSync(fixturePath)) {\n return normalizeCatalog(JSON.parse(readFileSync(fixturePath, 'utf8')) as Partial<AssetCatalog>, project);\n }\n return defaultFallbackCatalog();\n }\n throw new LineageAssetError(`Missing catalog: ${path}`, 404);\n}\n\nfunction saveCatalog(project: string, catalog: AssetCatalog): AssetCatalog {\n const normalized = normalizeCatalog(catalog, project);\n mkdirSync(dirname(catalogPath(project)), { recursive: true });\n writeFileSync(catalogPath(project), `${JSON.stringify(normalized, null, 2)}\\n`);\n return normalized;\n}\n\nfunction run(command: string, args: string[]): CommandResult {\n const result = spawnSync(command, args, {\n cwd: repoRoot,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n env: {\n ...process.env,\n AWS_REGION: process.env.AWS_REGION || 'us-east-1',\n AWS_DEFAULT_REGION: process.env.AWS_DEFAULT_REGION || 'us-east-1',\n },\n });\n\n if (result.status !== 0) {\n const detail = result.stderr.trim() || result.stdout.trim();\n throw new LineageAssetError(`${command} ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`, 502);\n }\n\n return { stdout: result.stdout, stderr: result.stderr };\n}\n\nfunction runAws(args: string[]): CommandResult {\n return run('aws', args);\n}\n\nexport function listProjects(): ProjectSummary[] {\n const projects = readdirSync(repoRoot, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && projectNamePattern.test(entry.name) && existsSync(catalogPath(entry.name)))\n .flatMap(entry => {\n try {\n const catalog = loadCatalog(entry.name);\n return [{ project: catalog.project, product: catalog.product, catalogPath: resolvedCatalogPath(entry.name), default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length }];\n } catch (error) {\n if (error instanceof LineageAssetError && error.status === 404) return [];\n throw error;\n }\n })\n .sort((a, b) => a.project.localeCompare(b.project));\n if (!projects.some(item => item.project === defaultProject)) {\n const catalog = loadCatalog(defaultProject);\n projects.push({ project: catalog.project, product: catalog.product, catalogPath: resolvedCatalogPath(defaultProject), default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length });\n projects.sort((a, b) => a.project.localeCompare(b.project));\n }\n return projects;\n}\n\nfunction assetById(catalog: AssetCatalog, assetId: string): GrowthAsset {\n const asset = catalog.assets.find(item => item.asset_id === assetId);\n if (!asset) throw new LineageAssetError(`Unknown asset: ${assetId}`, 404);\n return asset;\n}\n\nconst storageAdapter = createS3StorageAdapter({\n assetById,\n cleanProject,\n createError: (message, status) => new LineageAssetError(message, status),\n defaultProject,\n loadCatalog,\n runAws,\n repoRoot,\n saveCatalog,\n supportedContentTypes: contentTypes,\n});\n\nfunction uniqueSorted<T extends string>(values: Array<T | undefined>): T[] {\n return Array.from(new Set(values.filter(Boolean) as T[])).sort();\n}\n\nfunction facetsFor(assets: GrowthAsset[]): AssetFacets {\n return {\n audiences: uniqueSorted(assets.map(asset => asset.audience)),\n campaigns: uniqueSorted(assets.map(asset => asset.campaign)),\n channels: uniqueSorted([...baseChannels, ...assets.map(asset => asset.channel)]),\n contentTypes: uniqueSorted(assets.map(asset => asset.content_type)),\n placementStatuses: uniqueSorted(assets.flatMap(asset => asset.placements?.map(placement => placement.status) || [])),\n statuses: uniqueSorted(assets.map(asset => asset.status)),\n totalSizeBytes: assets.reduce((sum, asset) => sum + (asset.s3?.size_bytes || 0), 0),\n };\n}\n\nfunction filteredAssets(assets: GrowthAsset[], options: ListAssetsOptions): GrowthAsset[] {\n const query = options.query?.trim().toLowerCase();\n return assets.filter(asset => {\n if (options.status && options.status !== 'all' && asset.status !== options.status) return false;\n if (options.channel && options.channel !== 'all' && asset.channel !== options.channel) return false;\n if (options.type && options.type !== 'all' && asset.content_type !== options.type) return false;\n if (options.placementStatus === 'not-posted' && asset.placements?.some(placement => placement.status === 'posted')) return false;\n if (options.placementStatus && !['all', 'not-posted'].includes(options.placementStatus) && !asset.placements?.some(placement => placement.status === options.placementStatus)) return false;\n if (options.campaign && options.campaign !== 'all' && asset.campaign !== options.campaign) return false;\n if (options.audience && options.audience !== 'all' && asset.audience !== options.audience) return false;\n if (!query) return true;\n return [asset.asset_id, asset.title, asset.campaign, asset.channel, asset.audience, asset.hook, asset.cta]\n .join(' ')\n .toLowerCase()\n .includes(query);\n });\n}\n\nexport function listAssets(project = defaultProject, options: ListAssetsOptions = {}): AssetLibrarySnapshot {\n const catalog = loadCatalog(project);\n const pageSize = Math.min(Math.max(Number(options.pageSize || 10), 1), 100);\n const page = Math.max(Number(options.page || 1), 1);\n const localAssets = listLocalReviewAssets(repoRoot, catalog.project, catalog);\n const source = options.source || 'catalog';\n const sourceAssets = source === 'local' ? localAssets : source === 'all' ? [...localAssets, ...catalog.assets] : catalog.assets;\n const filtered = filteredAssets(sourceAssets, options);\n const totalPages = Math.max(Math.ceil(filtered.length / pageSize), 1);\n const safePage = Math.min(page, totalPages);\n const start = (safePage - 1) * pageSize;\n const pageAssets = filtered.slice(start, start + pageSize);\n let liveObjects: LiveS3Object[] = [];\n let error: string | undefined;\n if (options.includeLive && !isDefaultFallbackCatalog(catalog)) {\n try {\n liveObjects = storageAdapter.listLiveObjects(catalog);\n } catch (err) {\n error = err instanceof Error ? err.message : String(err);\n }\n }\n return {\n catalog: { project: catalog.project, product: catalog.product, default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length },\n assets: pageAssets,\n facets: facetsFor(catalog.assets),\n pagination: { page: safePage, pageSize, total: filtered.length, totalPages },\n liveObjects,\n orphanObjects: liveObjects.filter(object => !object.cataloged),\n identity: options.includeLive && !isDefaultFallbackCatalog(catalog) ? storageAdapter.getIdentity() : undefined,\n fetchedAt: new Date().toISOString(),\n error,\n };\n}\n\nexport function inspectAsset(project: string, assetId: string): GrowthAsset {\n return assetById(loadCatalog(project), assetId);\n}\n\nexport function validateProject(project = defaultProject): ProjectSummary {\n const catalog = loadCatalog(project);\n return { project: catalog.project, product: catalog.product, catalogPath: resolvedCatalogPath(project), default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length };\n}\n\nexport function doctorProject(project = defaultProject, options: { includeLive?: boolean } = {}): DoctorReport {\n const summary = validateProject(project);\n let liveCheck: DoctorReport['liveCheck'] = 'skipped';\n let liveError: string | undefined;\n if (options.includeLive && isDefaultFallbackCatalog(loadCatalog(project))) {\n liveCheck = 'skipped';\n liveError = `${appName} public fallback uses local catalog data only.`;\n } else if (options.includeLive) {\n try {\n storageAdapter.listLiveObjects(loadCatalog(project));\n liveCheck = 'ok';\n } catch (error) {\n liveCheck = 'error';\n liveError = error instanceof Error ? error.message : String(error);\n }\n }\n return { catalogExists: true, deleteEnabled: process.env.LINEAGE_ENABLE_CLOUD_DELETE === 'true', project: summary, liveCheck, liveError };\n}\n\nexport function pullAsset(project: string, assetId: string, out = '.asset-scratch'): MutationResponse {\n return storageAdapter.pullAsset(project, assetId, out);\n}\n\nfunction placementFromFields(fields: PlacementFields) {\n if (!fields.channel) throw new LineageAssetError('Placement requires channel');\n if (!placementStatuses.has(fields.status)) throw new LineageAssetError(`Unsupported placement status: ${fields.status}`);\n const now = new Date().toISOString();\n return {\n channel: fields.channel,\n status: fields.status,\n ...(fields.scheduledAt ? { scheduled_at: fields.scheduledAt } : {}),\n ...(fields.postedAt ? { posted_at: fields.postedAt } : {}),\n ...(fields.url ? { url: fields.url } : {}),\n ...(fields.notes ? { notes: fields.notes } : {}),\n updated_at: now,\n };\n}\n\nexport function previewPlacement(project: string, fields: PlacementFields) {\n const asset = inspectAsset(project, fields.assetId);\n return { asset_id: asset.asset_id, placement: placementFromFields(fields) };\n}\n\nexport function updatePlacement(project: string, fields: PlacementFields): MutationResponse {\n if (!fields.confirmWrite) throw new LineageAssetError('Placement updates require confirmWrite=true');\n const catalog = loadCatalog(project);\n const asset = assetById(catalog, fields.assetId);\n const placement = placementFromFields(fields);\n const existing = asset.placements?.findIndex(item => item.channel === placement.channel);\n if (existing !== undefined && existing >= 0) asset.placements![existing] = placement;\n else asset.placements = [...(asset.placements || []), placement];\n saveCatalog(project, catalog);\n syncLedgerPlacement(project, asset.asset_id, placement);\n return { ok: true, message: `Marked ${asset.asset_id} ${placement.status} for ${placement.channel}`, catalog };\n}\n\nexport function presignAsset(project: string, assetId: string, expiresIn = 900): PresignResponse {\n const catalog = loadCatalog(project);\n if (isDefaultFallbackCatalog(catalog)) {\n const asset = assetById(catalog, assetId);\n return { assetId: asset.asset_id, expiresIn, url: fallbackPreviewDataUrl(asset) };\n }\n return storageAdapter.presignAsset(project, assetId, expiresIn);\n}\n\nexport function localPreviewPath(relativePath: string): string {\n try {\n return resolveLocalPreviewPath(repoRoot, relativePath);\n } catch (error) {\n throw new LineageAssetError(error instanceof Error ? error.message : 'Unknown local review asset', 404);\n }\n}\n\nexport function promoteAsset(project: string, assetId: string, confirmWrite: boolean): MutationResponse {\n return storageAdapter.promoteAsset(project, assetId, confirmWrite);\n}\n\nexport function archiveAsset(project: string, assetId: string, confirmArchive: boolean): MutationResponse {\n if (!confirmArchive) throw new LineageAssetError('Archive requires confirmArchive=true');\n const catalog = loadCatalog(project);\n const asset = assetById(catalog, assetId);\n asset.status = 'archived';\n saveCatalog(project, catalog);\n return { ok: true, message: `Archived ${assetId}`, catalog };\n}\n\nexport function uploadAsset(file: string, fields: UploadFields): MutationResponse {\n return storageAdapter.uploadAsset(file, fields);\n}\n\nexport function deleteObjectGuarded(project: string, assetId: string, confirmation: string): MutationResponse {\n return storageAdapter.deleteObjectGuarded(project, assetId, confirmation);\n}\n\nexport function ensureUploadDir(): string {\n const dir = join(repoRoot, '.asset-scratch', 'studio-uploads');\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n return dir;\n}\n\nexport function cleanupUploadedTemp(file?: string): void {\n if (!file) return;\n const uploadRoot = ensureUploadDir();\n const resolved = resolve(file);\n if (resolved.startsWith(`${uploadRoot}/`) && existsSync(resolved)) {\n unlinkSync(resolved);\n }\n}\n", "import { copyFileSync, existsSync, mkdirSync, statSync } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport { contentTypeFor, fileSha256 } from '../../localReview';\nimport type { AssetCatalog, LiveS3Object, MutationResponse, PresignResponse } from '../../../shared/types';\nimport type { StorageAdapter, StorageAdapterDependencies } from './types';\n\nexport function parseAssetIdFromS3Key(key: string): string | undefined {\n const marker = '/assets/';\n const index = key.indexOf(marker);\n if (index === -1) return undefined;\n return key.slice(index + marker.length).split('/')[0];\n}\n\nfunction previewDataUrl(asset: { asset_id: string; channel?: string; status?: string; title?: string }): string {\n const title = asset.title || asset.asset_id;\n const label = `${asset.channel || 'catalog'} / ${asset.status || 'working'}`;\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"675\" viewBox=\"0 0 1200 675\"><rect width=\"1200\" height=\"675\" fill=\"#f7f5ef\"/><rect x=\"56\" y=\"56\" width=\"1088\" height=\"563\" rx=\"18\" fill=\"#10201c\"/><text x=\"96\" y=\"145\" fill=\"#9fe6c8\" font-family=\"Arial, sans-serif\" font-size=\"34\" font-weight=\"700\">Lineage catalog preview</text><text x=\"96\" y=\"230\" fill=\"#fff8e6\" font-family=\"Arial, sans-serif\" font-size=\"56\" font-weight=\"700\">${escapeSvgText(asset.asset_id)}</text><text x=\"96\" y=\"330\" fill=\"#d9e8df\" font-family=\"Arial, sans-serif\" font-size=\"34\">${escapeSvgText(title)}</text><text x=\"96\" y=\"500\" fill=\"#9fb7ae\" font-family=\"Arial, sans-serif\" font-size=\"26\">${escapeSvgText(label)}. No external storage requested.</text></svg>`;\n return `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;\n}\n\nfunction escapeSvgText(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\nexport function createS3StorageAdapter(deps: StorageAdapterDependencies): StorageAdapter {\n return {\n deleteObjectGuarded(project, assetId, confirmation): MutationResponse {\n const enabled = process.env.LINEAGE_ENABLE_CLOUD_DELETE === 'true';\n if (!enabled) {\n throw deps.createError('S3 delete is disabled. Use archive unless a human enables LINEAGE_ENABLE_CLOUD_DELETE.', 403);\n }\n if (confirmation !== `delete ${assetId}`) {\n throw deps.createError(`Delete confirmation must exactly equal: delete ${assetId}`);\n }\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n if (!asset.s3) throw deps.createError(`Asset has no S3 object: ${assetId}`);\n deps.runAws(['s3api', 'delete-object', '--bucket', asset.s3.bucket, '--key', asset.s3.key, '--region', asset.s3.region]);\n asset.status = 'archived';\n deps.saveCatalog(project, catalog);\n return { ok: true, message: `Deleted current S3 object and archived ${assetId}`, catalog };\n },\n\n getIdentity() {\n try {\n const output = deps.runAws(['sts', 'get-caller-identity', '--query', '{Account:Account,Arn:Arn}', '--output', 'json']);\n const parsed = JSON.parse(output.stdout) as { Account: string; Arn: string };\n return { account: parsed.Account, arn: parsed.Arn };\n } catch {\n return undefined;\n }\n },\n\n listLiveObjects(catalog: AssetCatalog): LiveS3Object[] {\n const bucket = catalog.default_bucket;\n const region = catalog.default_region;\n // Existing uploaded objects live under products/<project>; do not rewrite keys during project migration.\n const prefix = `products/${catalog.product}/`;\n const output = deps.runAws(['s3api', 'list-objects-v2', '--bucket', bucket, '--prefix', prefix, '--region', region, '--output', 'json']);\n const parsed = JSON.parse(output.stdout) as {\n Contents?: Array<{ Key: string; Size: number; LastModified: string; StorageClass?: string }>;\n };\n const catalogKeys = new Set(catalog.assets.map(asset => asset.s3?.key).filter(Boolean));\n return (parsed.Contents || []).map(item => ({\n key: item.Key,\n size: item.Size,\n lastModified: item.LastModified,\n storageClass: item.StorageClass,\n cataloged: catalogKeys.has(item.Key),\n assetId: parseAssetIdFromS3Key(item.Key),\n }));\n },\n\n presignAsset(project, assetId, expiresIn = 900): PresignResponse {\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n return { assetId, expiresIn, url: previewDataUrl(asset) };\n },\n\n promoteAsset(project, assetId, confirmWrite): MutationResponse {\n if (!confirmWrite) throw deps.createError('Promote requires confirmWrite=true');\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n asset.status = 'published';\n deps.saveCatalog(project, catalog);\n return {\n ok: true,\n message: `Promoted ${assetId}`,\n catalog,\n };\n },\n\n pullAsset(project, assetId, out = '.asset-scratch'): MutationResponse {\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n return {\n ok: true,\n message: `Prepared ${assetId} for local review`,\n output: {\n assetId: asset.asset_id,\n out,\n storage: asset.local ? 'local' : asset.s3 ? 'catalog-s3-metadata' : 'catalog',\n note: 'Lineage public package does not pull cloud objects automatically.',\n },\n };\n },\n\n uploadAsset(file, fields): MutationResponse {\n if (!fields.confirmWrite) throw deps.createError('Upload requires confirmWrite=true');\n if (!existsSync(file)) throw deps.createError(`Upload file missing: ${file}`, 404);\n if (!['working', 'published'].includes(fields.status)) throw deps.createError('Upload status must be working or published');\n if (!deps.supportedContentTypes.has(fields.type)) throw deps.createError(`Unsupported asset type: ${fields.type}`);\n\n const project = deps.cleanProject(fields.project || fields.product || deps.defaultProject);\n const catalog = deps.loadCatalog(project);\n const relativePath = join('uploads', project, fields.assetId, basename(file));\n const absolutePath = join(deps.repoRoot, '.asset-scratch', relativePath);\n mkdirSync(dirname(absolutePath), { recursive: true });\n copyFileSync(file, absolutePath);\n const stats = statSync(absolutePath);\n const contentType = contentTypeFor(absolutePath);\n const checksumSha256 = fileSha256(absolutePath);\n const now = new Date().toISOString();\n const nextAsset = {\n asset_id: fields.assetId,\n audience: fields.audience,\n campaign: fields.campaign,\n channel: fields.channel,\n content_type: fields.type,\n cta: fields.cta,\n hook: fields.hook,\n ...(fields.format ? { format: fields.format } : {}),\n local: {\n absolute_path: absolutePath,\n checksum_sha256: checksumSha256,\n content_type: contentType,\n relative_path: relativePath,\n size_bytes: stats.size,\n updated_at: now,\n },\n ...(fields.messageFamily ? { message_family: fields.messageFamily } : {}),\n ...(fields.notes ? { notes: fields.notes } : {}),\n product: project,\n project,\n source: 'catalog' as const,\n status: fields.status,\n title: fields.title,\n utm_content: fields.utmContent,\n };\n const existing = catalog.assets.findIndex(asset => asset.asset_id === fields.assetId);\n if (existing >= 0) catalog.assets[existing] = { ...catalog.assets[existing], ...nextAsset };\n else catalog.assets.push(nextAsset);\n deps.saveCatalog(project, catalog);\n return {\n ok: true,\n message: `Recorded ${fields.assetId} locally`,\n output: {\n file: basename(absolutePath),\n relativePath,\n sizeBytes: stats.size,\n contentType,\n checksumSha256,\n },\n catalog,\n };\n },\n };\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, extname, join, relative, resolve } from 'node:path';\nimport type { AssetCatalog, AssetContentType, GrowthAsset } from '../shared/types';\n\nconst mimeByExt: Record<string, string> = {\n '.gif': 'image/gif',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.mov': 'video/quicktime',\n '.mp4': 'video/mp4',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.webp': 'image/webp',\n};\nconst localReviewExts = new Set(Object.keys(mimeByExt));\nconst channelFromName = /\\b(linkedin|meta|tiktok|youtube|x-twitter|x)\\b/i;\nconst campaignFromPath = /\\b(20\\d{2}-\\d{2}-[a-z0-9-]+)\\b/i;\n\nclass LocalReviewError extends Error {\n status = 400;\n}\n\nfunction localReviewRoot(repoRoot: string): string {\n return join(repoRoot, '.asset-scratch');\n}\n\nexport function contentTypeFor(file: string): string {\n return mimeByExt[extname(file).toLowerCase()] || 'application/octet-stream';\n}\n\nexport function fileSha256(file: string): string {\n return createHash('sha256').update(readFileSync(file)).digest('hex');\n}\n\nfunction isPathInside(child: string, parent: string): boolean {\n const relativePath = relative(parent, child);\n return Boolean(relativePath) && !relativePath.startsWith('..') && !relativePath.startsWith('/');\n}\n\nfunction walkLocalReviewFiles(dir: string, files: string[] = []): string[] {\n if (!existsSync(dir)) return files;\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return files;\n throw error;\n }\n for (const entry of entries) {\n if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'studio-uploads' || entry.name === 'playwright-results' || entry.name === 'lineage-demo') continue;\n if (process.env.NODE_ENV !== 'test' && /^vitest-/.test(entry.name)) continue;\n const path = join(dir, entry.name);\n if (entry.isDirectory()) walkLocalReviewFiles(path, files);\n else if (entry.isFile() && localReviewExts.has(extname(entry.name).toLowerCase())) files.push(path);\n }\n return files;\n}\n\nfunction inferCampaign(relativePath: string): string {\n return campaignFromPath.exec(relativePath)?.[1] || 'local-review';\n}\n\nfunction inferChannel(relativePath: string): string {\n const match = channelFromName.exec(relativePath);\n if (!match) return 'local';\n return match[1].toLowerCase() === 'x' ? 'x-twitter' : match[1].toLowerCase();\n}\n\nfunction inferContentType(file: string): AssetContentType {\n const mime = contentTypeFor(file);\n if (mime.startsWith('image/gif')) return 'gif';\n if (mime.startsWith('image/')) return 'image';\n if (mime.startsWith('video/')) return 'video';\n return 'other';\n}\n\nexport function listLocalReviewAssets(repoRoot: string, project: string, catalog: AssetCatalog): GrowthAsset[] {\n const catalogChecksums = new Set(catalog.assets.map(asset => asset.s3?.checksum_sha256).filter(Boolean));\n const root = localReviewRoot(repoRoot);\n return walkLocalReviewFiles(root)\n .flatMap(file => {\n try {\n const stats = statSync(file);\n const checksum = fileSha256(file);\n const relativePath = relative(root, file);\n return [{ checksum, file, relativePath, stats }];\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n })\n .filter(item => !catalogChecksums.has(item.checksum))\n .map(item => {\n const fileSlug = basename(item.file, extname(item.file));\n const channel = inferChannel(item.relativePath);\n return {\n asset_id: `local-${item.checksum.slice(0, 12)}`,\n project,\n product: project,\n source: 'local',\n campaign: inferCampaign(item.relativePath),\n channel,\n audience: 'local-review',\n status: 'planned',\n content_type: inferContentType(item.file),\n title: fileSlug.replace(/[-_]+/g, ' '),\n hook: item.relativePath,\n cta: 'Review before upload',\n utm_content: fileSlug.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').toLowerCase() || 'local_review',\n notes: 'Local pre-push asset. Review and refine before uploading to S3.',\n local: {\n relative_path: item.relativePath,\n absolute_path: item.file,\n size_bytes: item.stats.size,\n content_type: contentTypeFor(item.file),\n checksum_sha256: item.checksum,\n updated_at: item.stats.mtime.toISOString(),\n },\n };\n });\n}\n\nexport function localPreviewPath(repoRoot: string, relativePath: string): string {\n const root = localReviewRoot(repoRoot);\n const resolved = resolve(root, relativePath);\n if (!isPathInside(resolved, root) || !existsSync(resolved)) throw new LocalReviewError('Unknown local review asset');\n if (!localReviewExts.has(extname(resolved).toLowerCase())) throw new LocalReviewError('Local preview type is not supported');\n return resolved;\n}\n", "import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';\nimport { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport type { LineageRuntimeChannel } from '../shared/runtimeInfoTypes';\nimport type { ResolvedLineageProfile } from '../shared/lineageProfileTypes';\nimport type { DatabaseSync } from './assetLineageDb';\nimport { assertProfileChannel } from './lineageProfiles';\n\nconst writerLeaseSchemaVersion = 'lineage.profile_writer_lease.v1' as const;\nconst ownerFileName = 'owner.json';\n\ninterface WriterLeaseOwner {\n acquired_at: string;\n environment: ResolvedLineageProfile['environment'];\n pid: number;\n profile_fingerprint: string;\n profile_id: string;\n role: 'service' | 'cli';\n schema_version: typeof writerLeaseSchemaVersion;\n service_origin?: string;\n token: string;\n}\n\nexport interface ProfileWriterLease {\n authenticate: (token: string | undefined) => boolean;\n lock_path: string;\n owner: Omit<WriterLeaseOwner, 'token'>;\n release: () => void;\n}\n\nexport interface ProfileWriterDelegation {\n owner: Omit<WriterLeaseOwner, 'token'>;\n service_origin: string;\n token: string;\n}\n\nexport class ProfileWriterLeaseConflictError extends Error {\n constructor(\n message: string,\n public readonly owner: Omit<WriterLeaseOwner, 'token'>,\n ) {\n super(message);\n this.name = 'ProfileWriterLeaseConflictError';\n }\n}\n\nexport function profileWriterLockPath(profile: Pick<ResolvedLineageProfile, 'manifest_path'>): string {\n return join(dirname(profile.manifest_path), 'writer.lock');\n}\n\nfunction ownerPath(lockPath: string): string {\n return join(lockPath, ownerFileName);\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error && typeof error === 'object' && 'code' in error ? String((error as NodeJS.ErrnoException).code) : undefined;\n}\n\nfunction readOwner(lockPath: string): WriterLeaseOwner {\n const stat = lstatSync(lockPath);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new Error(`Writer lease path is not a safe directory: ${lockPath}; manual inspection is required`);\n }\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(ownerPath(lockPath), 'utf8'));\n } catch (error) {\n throw new Error(`Writer lease metadata is unreadable at ${lockPath}; refusing automatic recovery`, { cause: error });\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error(`Writer lease metadata is invalid at ${lockPath}; refusing automatic recovery`);\n }\n const owner = raw as Partial<WriterLeaseOwner>;\n if (\n owner.schema_version !== writerLeaseSchemaVersion\n || typeof owner.profile_id !== 'string'\n || typeof owner.profile_fingerprint !== 'string'\n || !/^[a-f0-9]{64}$/i.test(owner.profile_fingerprint)\n || (owner.environment !== 'production' && owner.environment !== 'preview' && owner.environment !== 'development')\n || (owner.role !== 'service' && owner.role !== 'cli')\n || !Number.isSafeInteger(owner.pid)\n || Number(owner.pid) <= 0\n || typeof owner.acquired_at !== 'string'\n || Number.isNaN(Date.parse(owner.acquired_at))\n || (owner.role === 'service' && (typeof owner.service_origin !== 'string' || !owner.service_origin))\n || (owner.role === 'cli' && owner.service_origin !== undefined)\n || typeof owner.token !== 'string'\n || owner.token.length < 16\n ) {\n throw new Error(`Writer lease metadata is invalid at ${lockPath}; refusing automatic recovery`);\n }\n return owner as WriterLeaseOwner;\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n if (errorCode(error) === 'ESRCH') return false;\n return true;\n }\n}\n\nfunction createLeaseDirectory(lockPath: string, owner: WriterLeaseOwner): void {\n mkdirSync(lockPath, { mode: 0o700 });\n try {\n writeFileSync(ownerPath(lockPath), `${JSON.stringify(owner, null, 2)}\\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n } catch (error) {\n rmSync(lockPath, { force: true, recursive: true });\n throw error;\n }\n}\n\nfunction reclaimDeadOwner(lockPath: string, owner: WriterLeaseOwner): void {\n if (processIsAlive(owner.pid)) {\n const { token: _token, ...publicOwner } = owner;\n throw new ProfileWriterLeaseConflictError(\n `Lineage profile ${owner.profile_id} already has an active ${owner.role} writer (pid ${owner.pid}); use that managed service or stop it before starting another writer`,\n publicOwner,\n );\n }\n const tokenFence = createHash('sha256').update(owner.token).digest('hex').slice(0, 24);\n const tombstone = `${lockPath}.stale-${owner.pid}-${tokenFence}`;\n try {\n renameSync(lockPath, tombstone);\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return;\n throw error;\n }\n rmSync(tombstone, { force: true, recursive: true });\n}\n\nexport function acquireProfileWriterLease(\n profile: ResolvedLineageProfile,\n channel: LineageRuntimeChannel,\n role: WriterLeaseOwner['role'] = 'service'\n): ProfileWriterLease {\n assertProfileChannel(profile, channel);\n const lockPath = profileWriterLockPath(profile);\n const owner: WriterLeaseOwner = {\n acquired_at: new Date().toISOString(),\n environment: profile.environment,\n pid: process.pid,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n role,\n schema_version: writerLeaseSchemaVersion,\n ...(role === 'service' ? { service_origin: profile.service_origin } : {}),\n token: randomUUID(),\n };\n\n for (let attempt = 0; attempt < 4; attempt += 1) {\n try {\n createLeaseDirectory(lockPath, owner);\n process.env.LINEAGE_WRITER_LEASE_TOKEN = owner.token;\n process.env.LINEAGE_WRITER_LOCK_PATH = lockPath;\n const { token: _token, ...publicOwner } = owner;\n let released = false;\n return {\n authenticate: candidate => {\n if (!candidate) return false;\n const expected = Buffer.from(owner.token);\n const actual = Buffer.from(candidate);\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n },\n lock_path: lockPath,\n owner: publicOwner,\n release: () => {\n if (released) return;\n released = true;\n try {\n const current = readOwner(lockPath);\n if (current.token === owner.token && current.pid === owner.pid) rmSync(lockPath, { force: true, recursive: true });\n } catch {\n // Never remove a lock whose ownership cannot be proven.\n }\n if (process.env.LINEAGE_WRITER_LEASE_TOKEN === owner.token) delete process.env.LINEAGE_WRITER_LEASE_TOKEN;\n if (process.env.LINEAGE_WRITER_LOCK_PATH === lockPath) delete process.env.LINEAGE_WRITER_LOCK_PATH;\n },\n };\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') throw error;\n let existing: WriterLeaseOwner;\n try {\n existing = readOwner(lockPath);\n } catch (readError) {\n if (errorCode(readError) === 'ENOENT') continue;\n throw readError;\n }\n if (\n existing.profile_id !== profile.profile_id\n || existing.environment !== profile.environment\n || existing.profile_fingerprint !== profile.profile_fingerprint\n ) {\n throw new Error(`Writer lease identity at ${lockPath} does not match ${profile.profile_id}/${profile.environment}; manual inspection is required`, { cause: error });\n }\n reclaimDeadOwner(lockPath, existing);\n }\n }\n throw new Error(`Could not acquire writer lease for Lineage profile ${profile.profile_id}; another writer is racing for ownership`);\n}\n\nexport function assertProfileWriterLeaseHeld(): void {\n if (!process.env.LINEAGE_PROFILE) {\n throw new Error('Persistent writes require a selected named Lineage profile and its writer lease; legacy-unbound access is read-only. Create a fresh profile with `profile init --profile <id> --confirm-write`, then pass that profile to the command');\n }\n const profileId = process.env.LINEAGE_PROFILE_ID;\n const profileFingerprint = process.env.LINEAGE_PROFILE_FINGERPRINT;\n const environment = process.env.LINEAGE_PROFILE_ENVIRONMENT;\n const manifestPath = process.env.LINEAGE_PROFILE_MANIFEST;\n const lockPath = process.env.LINEAGE_WRITER_LOCK_PATH;\n const token = process.env.LINEAGE_WRITER_LEASE_TOKEN;\n if (!profileId || !profileFingerprint || !environment || !manifestPath || !lockPath || !token) {\n throw new Error('Named Lineage profiles may write only through a process holding the profile writer lease');\n }\n const expectedLockPath = join(dirname(resolve(manifestPath)), 'writer.lock');\n if (resolve(lockPath) !== expectedLockPath) throw new Error('Profile writer lease path does not match the selected profile manifest');\n const owner = readOwner(lockPath);\n if (\n owner.pid !== process.pid\n || owner.token !== token\n || owner.profile_id !== profileId\n || owner.profile_fingerprint !== profileFingerprint\n || owner.environment !== environment\n ) {\n throw new Error('Current process does not own the selected Lineage profile writer lease');\n }\n}\n\nexport function assertSelectedProfileDatabaseIdentity(database: DatabaseSync): void {\n const profileId = process.env.LINEAGE_PROFILE_ID;\n const environment = process.env.LINEAGE_PROFILE_ENVIRONMENT;\n const profileFingerprint = process.env.LINEAGE_PROFILE_FINGERPRINT;\n if (!process.env.LINEAGE_PROFILE || !profileId || !environment || !profileFingerprint) {\n throw new Error('Writable SQLite identity validation requires a fully resolved named Lineage profile');\n }\n const table = database.prepare(\"select name from sqlite_master where type = 'table' and name = 'lineage_profile_identity'\").get();\n if (!table) throw new Error(`Refusing writable open: database is not bound to Lineage profile ${profileId}`);\n const columns = new Set((database.prepare('pragma table_info(lineage_profile_identity)').all() as Array<{ name: string }>).map(row => row.name));\n if (!columns.has('profile_id') || !columns.has('environment') || !columns.has('profile_fingerprint')) {\n throw new Error(`Refusing writable open: database identity for ${profileId} is missing required fingerprint fields`);\n }\n const rows = database.prepare('select profile_id, environment, profile_fingerprint from lineage_profile_identity').all() as Array<Record<string, unknown>>;\n if (rows.length !== 1) throw new Error(`Refusing writable open: expected exactly one database profile identity, found ${rows.length}`);\n const identity = rows[0];\n if (\n identity.profile_id !== profileId\n || identity.environment !== environment\n || identity.profile_fingerprint !== profileFingerprint\n ) {\n throw new Error(\n `Refusing writable open: database identity ${String(identity.profile_id)}/${String(identity.environment)}/${String(identity.profile_fingerprint)} does not match selected profile ${profileId}/${environment}/${profileFingerprint}`\n );\n }\n}\n\nexport function inspectProfileWriterLease(profile: ResolvedLineageProfile): Omit<WriterLeaseOwner, 'token'> | undefined {\n const lockPath = profileWriterLockPath(profile);\n if (!existsSync(lockPath)) return undefined;\n const { token: _token, ...owner } = readOwner(lockPath);\n return owner;\n}\n\nexport function getProfileWriterDelegation(profile: ResolvedLineageProfile): ProfileWriterDelegation {\n const lockPath = profileWriterLockPath(profile);\n if (!existsSync(lockPath)) {\n throw new Error(\n `Lineage profile ${profile.profile_id} mutating commands require its managed service at ${profile.service_origin}; no active service writer lease was found`\n );\n }\n const owner = readOwner(lockPath);\n if (\n owner.profile_id !== profile.profile_id\n || owner.environment !== profile.environment\n || owner.profile_fingerprint !== profile.profile_fingerprint\n ) {\n throw new Error(`Writer lease identity at ${lockPath} does not match ${profile.profile_id}/${profile.environment}; refusing delegation`);\n }\n if (owner.role !== 'service' || owner.service_origin !== profile.service_origin) {\n throw new Error(`Writer lease for Lineage profile ${profile.profile_id} is not the configured managed service at ${profile.service_origin}`);\n }\n if (!processIsAlive(owner.pid)) {\n throw new Error(`Managed service writer lease for Lineage profile ${profile.profile_id} is stale; refusing delegation`);\n }\n const { token, ...publicOwner } = owner;\n return { owner: publicOwner, service_origin: owner.service_origin, token };\n}\n", "import { createHash, randomUUID } from 'node:crypto';\nimport {\n chmodSync,\n closeSync,\n constants as fsConstants,\n copyFileSync,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n type Stats,\n writeFileSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport {\n lineageProfileAssetsCloneReceiptSchemaVersion,\n lineageProfileCloneReceiptSchemaVersion,\n lineageProfileDoctorSchemaVersion,\n lineageProfileInitSchemaVersion,\n lineageProfileRuntimeRepinReceiptSchemaVersion,\n lineageProfileSchemaVersion,\n type LineageProfileBindResult,\n type LineageProfileAssetsCloneResult,\n type LineageProfileCloneResult,\n type LineageProfileDoctorCheck,\n type LineageProfileDoctorResult,\n type LineageProfileEnvironment,\n type LineageProfileIdentity,\n type LineageProfileInitResult,\n type LineageProfileManifest,\n type LineageProfileRuntimeRepinResult,\n type ResolvedLineageProfile,\n} from '../shared/lineageProfileTypes';\nimport type { LineageRuntimeChannel, LineageRuntimeCodeIdentity, LineageRuntimeInfo } from '../shared/runtimeInfoTypes';\nimport type { DatabaseSync } from './assetLineageDb';\nimport { loadNodeSqlite } from './nodeSqlite';\n\nconst profileIdPattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;\n\nfunction lineageDataRoot(): string {\n if (process.env.LINEAGE_HOME) return resolve(process.env.LINEAGE_HOME);\n if (platform() === 'darwin') return join(homedir(), 'Library', 'Application Support', 'Lineage');\n if (platform() === 'win32') return join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Lineage');\n return join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'lineage');\n}\n\nfunction lineageProfileRoot(): string {\n return resolve(process.env.LINEAGE_PROFILE_ROOT || join(lineageDataRoot(), 'profiles'));\n}\n\nfunction environmentChannel(environment: LineageProfileEnvironment): LineageRuntimeChannel {\n if (environment === 'production') return 'stable';\n if (environment === 'preview') return 'preview';\n return 'dev';\n}\n\nfunction channelEnvironment(channel: LineageRuntimeChannel): LineageProfileEnvironment {\n if (channel === 'stable') return 'production';\n if (channel === 'preview') return 'preview';\n return 'development';\n}\n\nfunction profileManifestPath(selector: string): { manifestPath: string; namedProfileId?: string } {\n const value = selector.trim();\n if (!value) throw new Error('Profile selector must not be empty');\n const looksLikePath = isAbsolute(value) || value.includes('/') || value.includes('\\\\') || value.endsWith('.json');\n if (looksLikePath) return { manifestPath: resolve(value) };\n if (!profileIdPattern.test(value)) throw new Error(`Invalid profile ID: ${value}`);\n return { manifestPath: join(lineageProfileRoot(), value, 'profile.json'), namedProfileId: value };\n}\n\nfunction requiredString(record: Record<string, unknown>, key: string): string {\n const value = record[key];\n if (typeof value !== 'string' || !value.trim()) throw new Error(`Profile manifest requires a non-empty ${key}`);\n return value.trim();\n}\n\nfunction optionalString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n if (value === undefined) return undefined;\n if (typeof value !== 'string' || !value.trim()) throw new Error(`Profile manifest ${key} must be a non-empty string`);\n return value.trim();\n}\n\nfunction validateEnvironment(value: string): LineageProfileEnvironment {\n if (value === 'production' || value === 'preview' || value === 'development') return value;\n throw new Error(`Invalid profile environment: ${value}`);\n}\n\nfunction validateChannel(value: unknown): LineageRuntimeChannel | undefined {\n if (value === undefined) return undefined;\n if (value === 'stable' || value === 'preview' || value === 'dev') return value;\n throw new Error(`Invalid expected runtime channel: ${String(value)}`);\n}\n\nfunction validateCodeOrigin(value: unknown): 'checkout' | 'package' | undefined {\n if (value === undefined) return undefined;\n if (value === 'checkout' || value === 'package') return value;\n throw new Error(`Invalid expected runtime code_origin: ${String(value)}`);\n}\n\nfunction validateFingerprint(value: string | undefined, field: string): string | undefined {\n if (value === undefined) return undefined;\n if (!/^[a-f0-9]{64}$/i.test(value)) throw new Error(`Profile ${field} must be a 64-character SHA-256 fingerprint`);\n return value.toLowerCase();\n}\n\nfunction resolveManifestPath(manifestPath: string, value: string): string {\n return resolve(dirname(manifestPath), value);\n}\n\nfunction validateServiceOrigin(value: string): string {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(`Invalid profile service_origin: ${value}`);\n }\n if (parsed.protocol !== 'http:') throw new Error('Profile service_origin must use http for the local Lineage service');\n if (!parsed.port) throw new Error('Profile service_origin must include an explicit port');\n if (parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash) {\n throw new Error('Profile service_origin must contain only scheme, host, and port');\n }\n return parsed.origin;\n}\n\nexport function resolveLineageProfile(selector: string): ResolvedLineageProfile {\n const { manifestPath, namedProfileId } = profileManifestPath(selector);\n if (!existsSync(manifestPath)) throw new Error(`Profile manifest does not exist: ${manifestPath}`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Could not parse profile manifest ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Profile manifest must be a JSON object');\n const record = raw as Record<string, unknown>;\n const schemaVersion = requiredString(record, 'schema_version');\n if (schemaVersion !== lineageProfileSchemaVersion) throw new Error(`Unsupported profile schema_version: ${schemaVersion}`);\n const profileId = requiredString(record, 'profile_id');\n if (!profileIdPattern.test(profileId)) throw new Error(`Invalid profile ID: ${profileId}`);\n if (namedProfileId && namedProfileId !== profileId) {\n throw new Error(`Named profile ${namedProfileId} does not match immutable manifest profile_id ${profileId}`);\n }\n const expectedRaw = record.expected_runtime;\n if (expectedRaw !== undefined && (!expectedRaw || typeof expectedRaw !== 'object' || Array.isArray(expectedRaw))) {\n throw new Error('Profile expected_runtime must be an object');\n }\n const expected = expectedRaw as Record<string, unknown> | undefined;\n const expectedGitSha = expected ? optionalString(expected, 'git_sha') : undefined;\n const expectedVersion = expected ? optionalString(expected, 'version') : undefined;\n const expectedCodeFingerprint = validateFingerprint(expected ? optionalString(expected, 'code_fingerprint') : undefined, 'expected_runtime.code_fingerprint');\n const expectedCodeOrigin = validateCodeOrigin(expected?.code_origin);\n const migrationsRaw = record.required_schema_migrations;\n if (migrationsRaw !== undefined && (!Array.isArray(migrationsRaw) || migrationsRaw.some(value => typeof value !== 'string' || !value.trim()))) {\n throw new Error('Profile required_schema_migrations must be an array of non-empty strings');\n }\n const environment = validateEnvironment(requiredString(record, 'environment'));\n const expectedChannel = validateChannel(expected?.channel);\n if (expectedChannel && expectedChannel !== environmentChannel(environment)) {\n throw new Error(`Profile environment ${environment} conflicts with expected runtime channel ${expectedChannel}`);\n }\n const manifest: LineageProfileManifest = {\n asset_root: resolveManifestPath(manifestPath, requiredString(record, 'asset_root')),\n database_path: resolveManifestPath(manifestPath, requiredString(record, 'database_path')),\n environment,\n ...(expected ? {\n expected_runtime: {\n ...(expectedChannel ? { channel: expectedChannel } : {}),\n ...(expectedCodeFingerprint ? { code_fingerprint: expectedCodeFingerprint } : {}),\n ...(expectedCodeOrigin ? { code_origin: expectedCodeOrigin } : {}),\n ...(expectedGitSha ? { git_sha: expectedGitSha } : {}),\n ...(expectedVersion ? { version: expectedVersion } : {}),\n },\n } : {}),\n profile_id: profileId,\n ...(migrationsRaw ? { required_schema_migrations: (migrationsRaw as string[]).map(value => value.trim()) } : {}),\n schema_version: lineageProfileSchemaVersion,\n service_origin: validateServiceOrigin(requiredString(record, 'service_origin')),\n };\n return { ...manifest, manifest_path: manifestPath, profile_fingerprint: lineageProfileFingerprint(manifest) };\n}\n\nexport function lineageProfileFingerprint(profile: LineageProfileManifest): string {\n return createHash('sha256').update(JSON.stringify({\n asset_root: resolve(profile.asset_root),\n database_path: resolve(profile.database_path),\n environment: profile.environment,\n profile_id: profile.profile_id,\n schema_version: profile.schema_version,\n service_origin: profile.service_origin,\n })).digest('hex');\n}\n\ntype ProfileRuntime = {\n channel: LineageRuntimeChannel;\n code?: LineageRuntimeCodeIdentity;\n gitSha?: string;\n version: string;\n};\n\ntype ProfileInitializationLease = (\n profile: ResolvedLineageProfile,\n initialize: () => LineageProfileIdentity,\n) => LineageProfileIdentity;\n\nexport function initializeLineageProfile(\n profileId: string,\n serviceOrigin: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n withWriterLease: ProfileInitializationLease,\n): LineageProfileInitResult {\n if (!confirmWrite) throw new Error('Profile init requires --confirm-write');\n if (!profileIdPattern.test(profileId)) throw new Error(`Invalid profile ID: ${profileId}`);\n if (!runtime.code?.verified) throw new Error('Profile init requires a verified runtime code identity');\n if (runtime.code.origin !== 'checkout' && runtime.code.origin !== 'package') {\n throw new Error(`Profile init requires checkout or package code, not ${runtime.code.origin}`);\n }\n if (!runtime.code.fingerprint || !/^[a-f0-9]{64}$/i.test(runtime.code.fingerprint)) {\n throw new Error('Profile init requires a valid executing code fingerprint');\n }\n const validatedServiceOrigin = validateServiceOrigin(serviceOrigin);\n\n const root = lineageProfileRoot();\n mkdirSync(root, { recursive: true, mode: 0o700 });\n const profileDirectory = join(root, profileId);\n try {\n mkdirSync(profileDirectory, { mode: 0o700 });\n } catch (error) {\n if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {\n const doctor = doctorLineageProfile(profileId, runtime);\n if (doctor.ok) {\n throw new Error(`Profile ${profileId} already exists and passes doctor. No files were changed. Reuse it with \\`start --profile ${profileId}\\`; verify it first with \\`profile doctor --profile ${profileId} --json\\`.`, { cause: error });\n }\n const failures = doctor.checks.filter(check => check.status === 'fail').map(check => `${check.id}: ${check.message}`).join('; ');\n throw new Error(`Profile ${profileId} already exists but did not pass doctor. No files were changed. Run \\`profile doctor --profile ${profileId} --json\\`, then inspect ${profileDirectory} manually before retrying. ${failures}`, { cause: error });\n }\n throw error;\n }\n\n const manifestPath = join(profileDirectory, 'profile.json');\n const databasePath = join(profileDirectory, 'lineage.sqlite');\n const assetRoot = join(profileDirectory, 'media');\n const environment = channelEnvironment(runtime.channel);\n const manifest: LineageProfileManifest = {\n asset_root: assetRoot,\n database_path: databasePath,\n environment,\n expected_runtime: {\n channel: runtime.channel,\n code_fingerprint: runtime.code.fingerprint.toLowerCase(),\n code_origin: runtime.code.origin,\n },\n profile_id: profileId,\n schema_version: lineageProfileSchemaVersion,\n service_origin: validatedServiceOrigin,\n };\n const profile: ResolvedLineageProfile = {\n ...manifest,\n manifest_path: manifestPath,\n profile_fingerprint: lineageProfileFingerprint(manifest),\n };\n\n try {\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n const identity = withWriterLease(profile, () => {\n mkdirSync(assetRoot, { mode: 0o700 });\n const databaseFd = openSync(databasePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR, 0o600);\n closeSync(databaseFd);\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(databasePath);\n let boundIdentity: LineageProfileIdentity;\n try {\n boundIdentity = bindOpenDatabase(database, profile, false);\n } finally {\n database.close();\n }\n const manifestPayload = {\n asset_root: './media',\n database_path: './lineage.sqlite',\n environment: profile.environment,\n expected_runtime: profile.expected_runtime,\n profile_id: profile.profile_id,\n schema_version: profile.schema_version,\n service_origin: profile.service_origin,\n };\n writeFileSync(manifestPath, `${JSON.stringify(manifestPayload, null, 2)}\\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n const manifestFd = openSync(manifestPath, 'r');\n try { fsyncSync(manifestFd); } finally { closeSync(manifestFd); }\n const directoryFd = openSync(profileDirectory, 'r');\n try { fsyncSync(directoryFd); } finally { closeSync(directoryFd); }\n const published = resolveLineageProfile(profileId);\n if (published.profile_fingerprint !== profile.profile_fingerprint) {\n throw new Error('Initialized profile fingerprint does not match its published manifest');\n }\n return boundIdentity;\n });\n return {\n asset_root: profile.asset_root,\n database_path: profile.database_path,\n environment: profile.environment,\n identity,\n manifest_path: profile.manifest_path,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n runtime: {\n channel: runtime.channel,\n code_fingerprint: runtime.code.fingerprint,\n code_origin: runtime.code.origin,\n },\n schema_version: lineageProfileInitSchemaVersion,\n service_origin: profile.service_origin,\n };\n } catch (error) {\n rmSync(profileDirectory, { force: true, recursive: true });\n throw error;\n }\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction assertOwnerOnlyPath(path: string, kind: 'manifest' | 'profile directory'): Stats {\n const stats = lstatSync(path);\n const expectedType = kind === 'manifest' ? stats.isFile() : stats.isDirectory();\n if (!expectedType || stats.isSymbolicLink()) throw new Error(`Profile ${kind} must be a nonsymlink ${kind === 'manifest' ? 'regular file' : 'directory'}: ${path}`);\n if ((stats.mode & 0o077) !== 0) throw new Error(`Profile ${kind} must be owner-only: ${path}`);\n if (typeof process.getuid === 'function' && stats.uid !== process.getuid()) throw new Error(`Profile ${kind} must be owned by the current user: ${path}`);\n return stats;\n}\n\nfunction runtimeRepinInvariant(profile: ResolvedLineageProfile): string {\n return JSON.stringify({\n asset_root: profile.asset_root,\n database_path: profile.database_path,\n environment: profile.environment,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n required_schema_migrations: profile.required_schema_migrations || [],\n schema_version: profile.schema_version,\n service_origin: profile.service_origin,\n });\n}\n\nfunction sameFileIdentity(left: Stats, right: Stats): boolean {\n return left.dev === right.dev\n && left.ino === right.ino\n && left.size === right.size\n && left.mtimeMs === right.mtimeMs\n && left.ctimeMs === right.ctimeMs;\n}\n\nexport function repinLineageDevelopmentProfileRuntime(\n selector: string,\n checkoutRoot: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): LineageProfileRuntimeRepinResult {\n if (!confirmWrite) throw new Error('Profile runtime repin requires --confirm-write');\n if (runtime.channel !== 'dev') throw new Error(`Profile runtime repin requires dev code, not ${runtime.channel}`);\n if (!runtime.code?.verified) throw new Error('Profile runtime repin requires a verified checkout runtime');\n if (runtime.code.origin !== 'checkout') throw new Error(`Profile runtime repin requires checkout code, not ${runtime.code.origin}`);\n if (!runtime.code.fingerprint || !/^[a-f0-9]{64}$/i.test(runtime.code.fingerprint)) {\n throw new Error('Profile runtime repin requires a valid executing code fingerprint');\n }\n if (!checkoutRoot.trim()) throw new Error('Profile runtime repin requires --checkout-root');\n const intendedRoot = realpathSync(resolve(checkoutRoot));\n if (!statSync(intendedRoot).isDirectory()) throw new Error(`Profile runtime repin checkout root is not a directory: ${intendedRoot}`);\n const executingRoot = realpathSync(runtime.code.root);\n if (intendedRoot !== executingRoot) {\n throw new Error(`Profile runtime repin checkout root ${intendedRoot} does not match executing code root ${executingRoot}`);\n }\n\n const profile = resolveLineageProfile(selector);\n if (profile.environment !== 'development') throw new Error(`Profile runtime repin requires a development profile, not ${profile.environment}`);\n if (profile.expected_runtime?.channel !== 'dev') throw new Error('Development profile runtime repin requires an existing dev channel pin');\n if (profile.expected_runtime.code_origin !== 'checkout') throw new Error('Development profile runtime repin requires an existing checkout origin pin');\n if (!profile.expected_runtime.code_fingerprint) throw new Error('Development profile runtime repin requires an existing code fingerprint pin');\n\n const manifestPath = profile.manifest_path;\n assertOwnerOnlyPath(dirname(manifestPath), 'profile directory');\n const beforeStats = assertOwnerOnlyPath(manifestPath, 'manifest');\n const beforeText = readFileSync(manifestPath, 'utf8');\n const beforeHash = sha256(beforeText);\n let raw: unknown;\n try {\n raw = JSON.parse(beforeText);\n } catch (error) {\n throw new Error(`Could not parse profile manifest ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Profile manifest must be a JSON object');\n const previousFingerprint = profile.expected_runtime.code_fingerprint;\n const nextExpectedRuntime = {\n channel: 'dev' as const,\n code_fingerprint: runtime.code.fingerprint,\n code_origin: 'checkout' as const,\n ...(runtime.gitSha ? { git_sha: runtime.gitSha } : {}),\n version: runtime.version,\n };\n const updated = { ...(raw as Record<string, unknown>), expected_runtime: nextExpectedRuntime };\n const afterText = `${JSON.stringify(updated, null, 2)}\\n`;\n const afterHash = sha256(afterText);\n const result: LineageProfileRuntimeRepinResult = {\n changed: beforeText !== afterText,\n checkout_root: intendedRoot,\n manifest_after_sha256: afterHash,\n manifest_before_sha256: beforeHash,\n manifest_path: manifestPath,\n new_code_fingerprint: runtime.code.fingerprint,\n previous_code_fingerprint: previousFingerprint,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n schema_version: lineageProfileRuntimeRepinReceiptSchemaVersion,\n };\n if (!result.changed) return result;\n\n const temporaryPath = join(dirname(manifestPath), `.profile.runtime-repin-${randomUUID()}.tmp`);\n let temporaryExists = false;\n try {\n writeFileSync(temporaryPath, afterText, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n temporaryExists = true;\n chmodSync(temporaryPath, 0o600);\n const temporaryFd = openSync(temporaryPath, 'r');\n try { fsyncSync(temporaryFd); } finally { closeSync(temporaryFd); }\n const preparedReplacement = resolveLineageProfile(temporaryPath);\n if (runtimeRepinInvariant(preparedReplacement) !== runtimeRepinInvariant(profile)) {\n throw new Error('Profile runtime repin would change immutable profile routing identity');\n }\n\n const currentStats = assertOwnerOnlyPath(manifestPath, 'manifest');\n const currentText = readFileSync(manifestPath, 'utf8');\n if (!sameFileIdentity(beforeStats, currentStats) || sha256(currentText) !== beforeHash) {\n throw new Error('Profile manifest changed while runtime repin was being prepared; refusing replacement');\n }\n renameSync(temporaryPath, manifestPath);\n temporaryExists = false;\n chmodSync(manifestPath, 0o600);\n const directoryFd = openSync(dirname(manifestPath), 'r');\n try { fsyncSync(directoryFd); } finally { closeSync(directoryFd); }\n\n const replacement = resolveLineageProfile(manifestPath);\n if (runtimeRepinInvariant(replacement) !== runtimeRepinInvariant(profile)) {\n throw new Error('Profile runtime repin changed immutable profile routing identity');\n }\n if (readFileSync(manifestPath, 'utf8') !== afterText) throw new Error('Profile runtime repin replacement bytes do not match the prepared manifest');\n return result;\n } finally {\n if (temporaryExists) rmSync(temporaryPath, { force: true });\n }\n}\n\ntype ProfileAssetReferenceKind = 'root' | 'scratch';\n\ninterface ProfileAssetReference {\n kind: ProfileAssetReferenceKind;\n value: string;\n}\n\nfunction assertProfileRuntimePin(profile: ResolvedLineageProfile, runtime?: ProfileRuntime): void {\n if (!profile.expected_runtime?.code_fingerprint || !profile.expected_runtime.code_origin) {\n throw new Error(`Profile ${profile.profile_id} must pin expected_runtime.code_fingerprint and expected_runtime.code_origin before binding or writing`);\n }\n if (!runtime?.code?.verified) {\n throw new Error(`Profile ${profile.profile_id} requires a verified runtime code identity before binding or writing`);\n }\n if (runtime.code.fingerprint !== profile.expected_runtime.code_fingerprint) {\n throw new Error(`Profile ${profile.profile_id} expects code fingerprint ${profile.expected_runtime.code_fingerprint}, found ${runtime.code.fingerprint}`);\n }\n if (runtime.code.origin !== profile.expected_runtime.code_origin) {\n throw new Error(`Profile ${profile.profile_id} expects code origin ${profile.expected_runtime.code_origin}, found ${runtime.code.origin}`);\n }\n}\n\nexport function assertProfileChannel(profile: ResolvedLineageProfile, channel: LineageRuntimeChannel): void {\n const requiredChannel = environmentChannel(profile.environment);\n if (channel === requiredChannel) return;\n if (profile.environment === 'production') {\n throw new Error(`Refusing to open production profile ${profile.profile_id} from ${channel} code; use the stable channel`);\n }\n throw new Error(`Profile ${profile.profile_id} requires the ${requiredChannel} channel, not ${channel}`);\n}\n\nfunction tableExists(database: DatabaseSync, table: string): boolean {\n return Boolean(database.prepare(\"select name from sqlite_master where type = 'table' and name = ?\").get(table));\n}\n\nfunction tableColumns(database: DatabaseSync, table: string): Set<string> {\n if (!tableExists(database, table)) return new Set();\n return new Set((database.prepare(`pragma table_info(${table})`).all() as Array<{ name: string }>).map(row => row.name));\n}\n\nfunction inspectDatabase(profile: ResolvedLineageProfile): NonNullable<LineageProfileDoctorResult['database']> {\n const result: NonNullable<LineageProfileDoctorResult['database']> = {\n exists: existsSync(profile.database_path),\n migration_keys: [],\n path: profile.database_path,\n };\n if (!result.exists) return result;\n try {\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(profile.database_path, { readOnly: true });\n try {\n if (tableExists(database, 'lineage_profile_identity')) {\n const columns = tableColumns(database, 'lineage_profile_identity');\n const fingerprintExpression = columns.has('profile_fingerprint') ? 'profile_fingerprint' : \"'' as profile_fingerprint\";\n const rows = database.prepare(`select profile_id, environment, bound_at, ${fingerprintExpression} from lineage_profile_identity`).all() as Array<Record<string, unknown>>;\n if (rows.length === 1) {\n const identity: LineageProfileIdentity = {\n bound_at: typeof rows[0].bound_at === 'string' ? rows[0].bound_at : undefined,\n environment: String(rows[0].environment) as LineageProfileEnvironment,\n profile_fingerprint: typeof rows[0].profile_fingerprint === 'string' ? rows[0].profile_fingerprint : '',\n profile_id: String(rows[0].profile_id),\n };\n result.identity = identity;\n } else {\n result.error = `Expected exactly one lineage_profile_identity row, found ${rows.length}`;\n }\n }\n if (tableExists(database, 'lineage_schema_migrations')) {\n result.migration_keys = (database.prepare('select key from lineage_schema_migrations order by key').all() as Array<{ key: string }>).map(row => row.key);\n }\n } finally {\n database.close();\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n }\n return result;\n}\n\nexport function doctorLineageProfile(\n selector: string,\n runtime: ProfileRuntime\n): LineageProfileDoctorResult {\n const checks: LineageProfileDoctorCheck[] = [];\n const result: LineageProfileDoctorResult = {\n checks,\n ok: false,\n runtime: {\n channel: runtime.channel,\n code_fingerprint: runtime.code?.fingerprint,\n code_origin: runtime.code?.origin,\n code_verified: runtime.code?.verified,\n git_sha: runtime.gitSha,\n version: runtime.version,\n },\n schema_version: lineageProfileDoctorSchemaVersion,\n };\n let profile: ResolvedLineageProfile;\n try {\n profile = resolveLineageProfile(selector);\n result.profile = profile;\n result.manifest_path = profile.manifest_path;\n checks.push({ id: 'manifest', message: `Loaded ${profile.profile_id}`, status: 'pass' });\n } catch (error) {\n checks.push({ id: 'manifest', message: error instanceof Error ? error.message : String(error), status: 'fail' });\n return result;\n }\n\n try {\n assertProfileChannel(profile, runtime.channel);\n checks.push({ id: 'runtime_channel', message: `${runtime.channel} code matches ${profile.environment}`, status: 'pass' });\n } catch (error) {\n checks.push({ id: 'runtime_channel', message: error instanceof Error ? error.message : String(error), status: 'fail' });\n }\n try {\n assertProfileRuntimePin(profile, runtime);\n checks.push({ id: 'runtime_code', message: `Verified ${runtime.code!.origin} code ${runtime.code!.fingerprint}`, status: 'pass' });\n } catch (error) {\n checks.push({ id: 'runtime_code', message: error instanceof Error ? error.message : String(error), status: 'fail' });\n }\n if (profile.expected_runtime?.version && profile.expected_runtime.version !== runtime.version) {\n checks.push({ id: 'runtime_version', message: `Expected version ${profile.expected_runtime.version}, found ${runtime.version}`, status: 'fail' });\n } else {\n checks.push({ id: 'runtime_version', message: `Runtime version ${runtime.version}`, status: 'pass' });\n }\n if (profile.expected_runtime?.git_sha && profile.expected_runtime.git_sha !== runtime.gitSha) {\n checks.push({ id: 'runtime_git_sha', message: `Expected Git SHA ${profile.expected_runtime.git_sha}, found ${runtime.gitSha || 'unavailable'}`, status: 'fail' });\n } else if (profile.expected_runtime?.git_sha) {\n checks.push({ id: 'runtime_git_sha', message: `Git SHA ${runtime.gitSha}`, status: 'pass' });\n }\n\n const assetExists = existsSync(profile.asset_root);\n const assetIsDirectory = assetExists && statSync(profile.asset_root).isDirectory();\n result.asset_root = { exists: assetExists, is_directory: assetIsDirectory, path: profile.asset_root };\n checks.push({\n id: 'asset_root',\n message: assetIsDirectory ? `Asset root exists: ${profile.asset_root}` : `Asset root is missing or not a directory: ${profile.asset_root}`,\n status: assetIsDirectory ? 'pass' : 'fail',\n });\n\n const database = inspectDatabase(profile);\n result.database = database;\n checks.push({\n id: 'database_exists',\n message: database.exists ? `Database exists: ${profile.database_path}` : `Database does not exist: ${profile.database_path}`,\n status: database.exists ? 'pass' : 'fail',\n });\n if (database.error) checks.push({ id: 'database_read', message: database.error, status: 'fail' });\n if (!database.identity) {\n checks.push({ id: 'database_identity', message: 'Database is not bound to a Lineage profile', status: 'fail' });\n } else if (\n database.identity.profile_id !== profile.profile_id\n || database.identity.environment !== profile.environment\n || database.identity.profile_fingerprint !== profile.profile_fingerprint\n ) {\n checks.push({\n id: 'database_identity',\n message: `Database identity ${database.identity.profile_id}/${database.identity.environment}/${database.identity.profile_fingerprint || 'no-fingerprint'} does not match ${profile.profile_id}/${profile.environment}/${profile.profile_fingerprint}`,\n status: 'fail',\n });\n } else {\n checks.push({ id: 'database_identity', message: `Database is bound to ${profile.profile_id}`, status: 'pass' });\n }\n const missingMigrations = (profile.required_schema_migrations || []).filter(key => !database.migration_keys.includes(key));\n checks.push({\n id: 'database_schema',\n message: missingMigrations.length ? `Missing required schema migrations: ${missingMigrations.join(', ')}` : `${database.migration_keys.length} schema migration marker(s) available`,\n status: missingMigrations.length ? 'fail' : 'pass',\n });\n result.ok = checks.every(check => check.status !== 'fail');\n return result;\n}\n\nexport function runtimeProfileIdentity(channel: LineageRuntimeChannel): {\n bound: boolean;\n environment: LineageProfileEnvironment;\n fingerprint?: string;\n id: string;\n manifest_path?: string;\n service_origin?: string;\n warning?: string;\n} {\n const selector = process.env.LINEAGE_PROFILE;\n const id = process.env.LINEAGE_PROFILE_ID;\n const environment = process.env.LINEAGE_PROFILE_ENVIRONMENT as LineageProfileEnvironment | undefined;\n if (selector && id && environment) {\n return {\n bound: true,\n environment,\n fingerprint: process.env.LINEAGE_PROFILE_FINGERPRINT,\n id,\n manifest_path: process.env.LINEAGE_PROFILE_MANIFEST,\n service_origin: process.env.LINEAGE_PROFILE_SERVICE_ORIGIN,\n };\n }\n return {\n bound: false,\n environment: channelEnvironment(channel),\n id: 'legacy-unbound',\n warning: id || environment || process.env.LINEAGE_PROFILE_FINGERPRINT || process.env.LINEAGE_PROFILE_MANIFEST\n ? 'Invalid unbound runtime: derived profile identity was supplied without a resolved LINEAGE_PROFILE selector.'\n : 'Legacy unbound runtime: database and asset paths are not protected by a named profile.',\n };\n}\n\nexport function assertRuntimeProfileSafety(channel: LineageRuntimeChannel): void {\n const hasDerivedIdentity = Boolean(\n process.env.LINEAGE_PROFILE_ID\n || process.env.LINEAGE_PROFILE_ENVIRONMENT\n || process.env.LINEAGE_PROFILE_FINGERPRINT\n || process.env.LINEAGE_PROFILE_MANIFEST\n || process.env.LINEAGE_PROFILE_SERVICE_ORIGIN\n );\n if (hasDerivedIdentity && !process.env.LINEAGE_PROFILE) {\n throw new Error('Derived Lineage profile identity requires LINEAGE_PROFILE; start through the Lineage CLI with --profile');\n }\n const profile = runtimeProfileIdentity(channel);\n if (profile.bound && profile.environment === 'production' && channel !== 'stable') {\n throw new Error(`Refusing to open production profile ${profile.id} from ${channel} code; use the stable channel`);\n }\n}\n\nexport function assertUnselectedDatabaseIsUnbound(runtime: LineageRuntimeInfo): void {\n if (!runtime.schema.profile_id) return;\n const environment = runtime.schema.profile_environment || 'unknown';\n throw new Error(\n `Database ${runtime.database.path} is bound to Lineage profile ${runtime.schema.profile_id}/${environment}; select that profile with --profile`\n );\n}\n\nexport function assertResolvedRuntimeProfileEnvironment(profile: ResolvedLineageProfile): void {\n const serviceUrl = new URL(profile.service_origin);\n const expected = new Map<string, string>([\n ['LINEAGE_PROFILE_ID', profile.profile_id],\n ['LINEAGE_PROFILE_ENVIRONMENT', profile.environment],\n ['LINEAGE_PROFILE_FINGERPRINT', profile.profile_fingerprint],\n ['LINEAGE_PROFILE_MANIFEST', profile.manifest_path],\n ['LINEAGE_PROFILE_SERVICE_ORIGIN', profile.service_origin],\n ['LINEAGE_DB', profile.database_path],\n ['LINEAGE_ASSET_ROOT', profile.asset_root],\n ['HOST', serviceUrl.hostname],\n ['PORT', serviceUrl.port],\n ]);\n const conflicts: string[] = [];\n for (const [key, expectedValue] of expected) {\n const actual = process.env[key];\n const pathValue = key === 'LINEAGE_PROFILE_MANIFEST' || key === 'LINEAGE_DB' || key === 'LINEAGE_ASSET_ROOT';\n const matches = actual && (pathValue ? resolve(actual) === resolve(expectedValue) : actual === expectedValue);\n if (!matches) conflicts.push(`${key}=${actual || '(missing)'}`);\n }\n if (conflicts.length > 0) {\n throw new Error(`Resolved profile environment conflicts with ${profile.profile_id}: ${conflicts.join(', ')}`);\n }\n}\n\nfunction ensureProfileIdentityTable(database: DatabaseSync): void {\n if (!tableExists(database, 'lineage_profile_identity')) {\n database.exec(`\n create table lineage_profile_identity (\n profile_id text primary key,\n environment text not null,\n profile_fingerprint text not null,\n bound_at text not null\n )\n `);\n return;\n }\n const columns = tableColumns(database, 'lineage_profile_identity');\n if (!columns.has('profile_id') || !columns.has('environment') || !columns.has('bound_at')) {\n throw new Error('Existing lineage_profile_identity table has an unsupported shape');\n }\n if (!columns.has('profile_fingerprint')) {\n database.exec(\"alter table lineage_profile_identity add column profile_fingerprint text not null default ''\");\n }\n}\n\nfunction assertRequiredMigrations(database: DatabaseSync, profile: ResolvedLineageProfile): void {\n const required = profile.required_schema_migrations || [];\n if (required.length === 0) return;\n if (!tableExists(database, 'lineage_schema_migrations')) {\n throw new Error(`Database is missing required schema migrations: ${required.join(', ')}`);\n }\n const available = new Set((database.prepare('select key from lineage_schema_migrations').all() as Array<{ key: string }>).map(row => row.key));\n const missing = required.filter(key => !available.has(key));\n if (missing.length > 0) throw new Error(`Database is missing required schema migrations: ${missing.join(', ')}`);\n}\n\nfunction profileIdentity(profile: ResolvedLineageProfile): LineageProfileIdentity {\n return {\n bound_at: new Date().toISOString(),\n environment: profile.environment,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n };\n}\n\nfunction bindOpenDatabase(database: DatabaseSync, profile: ResolvedLineageProfile, replace: boolean): LineageProfileIdentity {\n database.exec('begin immediate');\n try {\n ensureProfileIdentityTable(database);\n assertRequiredMigrations(database, profile);\n const rows = database.prepare('select profile_id, environment, profile_fingerprint, bound_at from lineage_profile_identity').all() as unknown as LineageProfileIdentity[];\n if (!replace && rows.length > 0) {\n if (rows.length !== 1) throw new Error(`Expected at most one lineage_profile_identity row, found ${rows.length}`);\n const existing = rows[0];\n const sameBaseIdentity = existing.profile_id === profile.profile_id && existing.environment === profile.environment;\n const migratableLegacyIdentity = sameBaseIdentity && !existing.profile_fingerprint;\n if (!migratableLegacyIdentity && existing.profile_fingerprint !== profile.profile_fingerprint) {\n throw new Error(`Database is already bound to ${existing.profile_id}/${existing.environment}/${existing.profile_fingerprint || 'no-fingerprint'}`);\n }\n if (!migratableLegacyIdentity) {\n database.exec('commit');\n return existing;\n }\n }\n const identity = profileIdentity(profile);\n database.exec('delete from lineage_profile_identity');\n database.prepare('insert into lineage_profile_identity (profile_id, environment, profile_fingerprint, bound_at) values (?, ?, ?, ?)')\n .run(identity.profile_id, identity.environment, identity.profile_fingerprint, identity.bound_at!);\n const integrity = database.prepare('pragma integrity_check').get() as { integrity_check?: string } | undefined;\n if (integrity?.integrity_check !== 'ok') throw new Error(`SQLite integrity check failed: ${integrity?.integrity_check || 'unknown result'}`);\n database.exec('commit');\n return identity;\n } catch (error) {\n try { database.exec('rollback'); } catch { /* best effort */ }\n throw error;\n }\n}\n\nexport function bindLineageProfileDatabase(\n selector: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): LineageProfileBindResult {\n if (!confirmWrite) throw new Error('Profile bind requires --confirm-write');\n const profile = resolveLineageProfile(selector);\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n if (!existsSync(profile.database_path)) throw new Error(`Profile database does not exist: ${profile.database_path}`);\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(profile.database_path);\n try {\n const before = inspectDatabase(profile).identity;\n const identity = bindOpenDatabase(database, profile, false);\n return {\n already_bound: Boolean(before?.profile_fingerprint === profile.profile_fingerprint),\n database_path: profile.database_path,\n identity,\n schema_version: 'lineage.profile_bind.v1',\n };\n } finally {\n database.close();\n }\n}\n\nexport async function cloneLineageProfileDatabase(\n sourceDatabasePath: string,\n targetSelector: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): Promise<LineageProfileCloneResult> {\n if (!confirmWrite) throw new Error('Profile clone requires --confirm-write');\n const profile = resolveLineageProfile(targetSelector);\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n if (profile.environment === 'production') throw new Error('Profile clone target must be preview or development, never production');\n const sourcePath = resolve(sourceDatabasePath);\n const targetPath = resolve(profile.database_path);\n if (sourcePath === targetPath) throw new Error('Profile clone source and target database paths must be different');\n if (!existsSync(sourcePath)) throw new Error(`Profile clone source database does not exist: ${sourcePath}`);\n if (existsSync(targetPath)) throw new Error(`Profile clone target database already exists: ${targetPath}`);\n mkdirSync(dirname(targetPath), { recursive: true });\n const temporaryPath = `${targetPath}.clone-${randomUUID()}.tmp`;\n const receiptDirectory = join(dirname(profile.manifest_path), 'clone-receipts');\n let targetCreated = false;\n const { DatabaseSync, backup } = loadNodeSqlite();\n const source = new DatabaseSync(sourcePath, { readOnly: true });\n try {\n const pagesCopied = await backup(source, temporaryPath);\n chmodSync(temporaryPath, 0o600);\n const cloned = new DatabaseSync(temporaryPath);\n let identity: LineageProfileIdentity;\n try {\n identity = bindOpenDatabase(cloned, profile, true);\n } finally {\n cloned.close();\n }\n // Both paths share a directory. Linking is atomic and fails with EEXIST,\n // unlike rename(), which may silently replace a target created by a racer.\n linkSync(temporaryPath, targetPath);\n targetCreated = true;\n rmSync(temporaryPath, { force: true });\n mkdirSync(receiptDirectory, { recursive: true, mode: 0o700 });\n const receiptPath = join(receiptDirectory, `${Date.now()}-${randomUUID()}.json`);\n const result: LineageProfileCloneResult = {\n database_path: targetPath,\n pages_copied: pagesCopied,\n receipt_path: receiptPath,\n schema_version: lineageProfileCloneReceiptSchemaVersion,\n source_database_path: sourcePath,\n target_identity: identity,\n };\n writeFileSync(receiptPath, `${JSON.stringify({ ...result, created_at: new Date().toISOString() }, null, 2)}\\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n return result;\n } catch (error) {\n rmSync(temporaryPath, { force: true });\n if (targetCreated) rmSync(targetPath, { force: true });\n throw error;\n } finally {\n source.close();\n }\n}\n\nfunction pathIsInside(path: string, parent: string): boolean {\n const child = relative(parent, path);\n return child !== '' && !child.startsWith('..') && !isAbsolute(child);\n}\n\nfunction fileSha256(path: string): string {\n return createHash('sha256').update(readFileSync(path)).digest('hex');\n}\n\nfunction profileAssetReferences(database: DatabaseSync): ProfileAssetReference[] {\n const references: ProfileAssetReference[] = [];\n const addColumn = (table: string, column: string, kind: ProfileAssetReferenceKind) => {\n if (!tableColumns(database, table).has(column)) return;\n const rows = database.prepare(`select ${column} value from ${table} where ${column} is not null and ${column} <> ''`).all() as Array<{ value: string }>;\n for (const row of rows) references.push({ kind, value: row.value });\n };\n addColumn('assets', 'local_path', 'scratch');\n addColumn('asset_attempts', 'file_path', 'scratch');\n addColumn('generation_job_outputs', 'file_path', 'scratch');\n addColumn('asset_ledger_sources', 'local_path', 'scratch');\n addColumn('content_posts', 'source_path', 'root');\n if (tableColumns(database, 'projects').has('id')) {\n const projects = database.prepare(\"select id from projects where id is not null and id <> ''\").all() as Array<{ id: string }>;\n for (const project of projects) {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(project.id)) throw new Error('A project ID cannot be mapped safely into the source asset root');\n references.push({ kind: 'root', value: join(project.id, 'assets', 'catalog.json') });\n }\n }\n return references;\n}\n\nfunction resolveProfileAssetReference(sourceRoot: string, reference: ProfileAssetReference): { path: string; relative_path: string } {\n if (reference.value.includes('\\0')) throw new Error('A referenced asset path contains a null byte');\n const sourceScratch = join(sourceRoot, '.asset-scratch');\n const base = reference.kind === 'scratch' ? sourceScratch : sourceRoot;\n const value = reference.kind === 'scratch' && reference.value.startsWith('.asset-scratch/')\n ? reference.value.slice('.asset-scratch/'.length)\n : reference.value;\n const candidate = isAbsolute(value) ? resolve(value) : resolve(base, value);\n if (!pathIsInside(candidate, base)) throw new Error('A referenced asset path escapes the declared source asset root');\n return { path: candidate, relative_path: relative(sourceRoot, candidate) };\n}\n\nexport function cloneLineageProfileAssets(\n sourceAssetRoot: string,\n targetSelector: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): LineageProfileAssetsCloneResult {\n if (!confirmWrite) throw new Error('Profile asset clone requires --confirm-write');\n const profile = resolveLineageProfile(targetSelector);\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n if (!existsSync(profile.database_path)) throw new Error(`Profile database does not exist: ${profile.database_path}`);\n const sourceRoot = resolve(sourceAssetRoot);\n const targetRoot = resolve(profile.asset_root);\n if (!existsSync(sourceRoot) || !statSync(sourceRoot).isDirectory()) throw new Error(`Source asset root does not exist: ${sourceRoot}`);\n if (sourceRoot === targetRoot || pathIsInside(targetRoot, sourceRoot) || pathIsInside(sourceRoot, targetRoot)) {\n throw new Error('Source and target asset roots must be disjoint');\n }\n if (pathIsInside(profile.database_path, targetRoot)) throw new Error('Profile database must not be stored inside its asset root');\n if (existsSync(targetRoot)) throw new Error(`Profile asset clone target already exists: ${targetRoot}`);\n const databaseIdentity = inspectDatabase(profile).identity;\n if (databaseIdentity && (\n databaseIdentity.profile_id !== profile.profile_id\n || databaseIdentity.environment !== profile.environment\n || (databaseIdentity.profile_fingerprint && databaseIdentity.profile_fingerprint !== profile.profile_fingerprint)\n )) {\n throw new Error(`Profile database is already bound to ${databaseIdentity.profile_id}/${databaseIdentity.environment}`);\n }\n\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(profile.database_path, { readOnly: true });\n let references: ProfileAssetReference[];\n try {\n database.exec('begin');\n references = profileAssetReferences(database);\n database.exec('commit');\n } catch (error) {\n try { database.exec('rollback'); } catch { /* best effort */ }\n throw error;\n } finally {\n database.close();\n }\n\n const sourceRealRoot = realpathSync(sourceRoot);\n const files = new Map<string, string>();\n let missingReferences = 0;\n let duplicateReferences = 0;\n for (const reference of references) {\n const resolved = resolveProfileAssetReference(sourceRoot, reference);\n if (!existsSync(resolved.path)) {\n missingReferences += 1;\n continue;\n }\n const stats = statSync(resolved.path);\n if (!stats.isFile()) {\n missingReferences += 1;\n continue;\n }\n const realSource = realpathSync(resolved.path);\n if (!pathIsInside(realSource, sourceRealRoot)) throw new Error('A referenced asset symlink escapes the declared source asset root');\n const existing = files.get(resolved.relative_path);\n if (existing) {\n if (realpathSync(existing) !== realSource) throw new Error('Two source assets map to the same target path');\n duplicateReferences += 1;\n continue;\n }\n files.set(resolved.relative_path, resolved.path);\n }\n\n mkdirSync(dirname(targetRoot), { recursive: true, mode: 0o700 });\n mkdirSync(targetRoot, { mode: 0o700 });\n try {\n let bytesCopied = 0;\n const treeHash = createHash('sha256');\n for (const relativePath of [...files.keys()].sort()) {\n const sourcePath = files.get(relativePath)!;\n const destinationPath = join(targetRoot, relativePath);\n mkdirSync(dirname(destinationPath), { recursive: true, mode: 0o700 });\n copyFileSync(sourcePath, destinationPath, fsConstants.COPYFILE_EXCL);\n chmodSync(destinationPath, 0o600);\n const sourceHash = fileSha256(sourcePath);\n const destinationHash = fileSha256(destinationPath);\n if (sourceHash !== destinationHash) throw new Error('A source asset changed or failed checksum verification during clone');\n bytesCopied += statSync(destinationPath).size;\n treeHash.update(relativePath.replaceAll('\\\\', '/'));\n treeHash.update('\\0');\n treeHash.update(destinationHash);\n treeHash.update('\\0');\n }\n chmodSync(targetRoot, 0o700);\n const receiptPath = join(targetRoot, '.lineage-profile-assets.json');\n const result: LineageProfileAssetsCloneResult = {\n asset_root: targetRoot,\n bytes_copied: bytesCopied,\n code_fingerprint: runtime.code!.fingerprint,\n database_path: profile.database_path,\n duplicate_references: duplicateReferences,\n files_copied: files.size,\n missing_references: missingReferences,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n receipt_path: receiptPath,\n references_discovered: references.length,\n runtime_channel: runtime.channel,\n schema_version: lineageProfileAssetsCloneReceiptSchemaVersion,\n source_asset_root: sourceRoot,\n tree_sha256: treeHash.digest('hex'),\n };\n writeFileSync(receiptPath, `${JSON.stringify({ ...result, created_at: new Date().toISOString() }, null, 2)}\\n`, {\n encoding: 'utf8',\n flag: 'wx',\n mode: 0o600,\n });\n return result;\n } catch (error) {\n rmSync(targetRoot, { force: true, recursive: true });\n throw error;\n }\n}\n", "import type { LineageRuntimeChannel } from './runtimeInfoTypes';\n\nexport const lineageProfileSchemaVersion = 'lineage.profile.v1' as const;\nexport const lineageProfileInitSchemaVersion = 'lineage.profile_init.v1' as const;\nexport const lineageProfileDoctorSchemaVersion = 'lineage.profile_doctor.v1' as const;\nexport const lineageProfileCloneReceiptSchemaVersion = 'lineage.profile_clone_receipt.v1' as const;\nexport const lineageProfileAssetsCloneReceiptSchemaVersion = 'lineage.profile_assets_clone_receipt.v1' as const;\nexport const lineageProfileRuntimeRepinReceiptSchemaVersion = 'lineage.profile_runtime_repin_receipt.v1' as const;\n\nexport type LineageProfileEnvironment = 'production' | 'preview' | 'development';\n\ninterface LineageProfileExpectedRuntime {\n channel?: LineageRuntimeChannel;\n code_fingerprint?: string;\n code_origin?: 'checkout' | 'package';\n git_sha?: string;\n version?: string;\n}\n\nexport interface LineageProfileManifest {\n asset_root: string;\n database_path: string;\n environment: LineageProfileEnvironment;\n expected_runtime?: LineageProfileExpectedRuntime;\n profile_id: string;\n required_schema_migrations?: string[];\n schema_version: typeof lineageProfileSchemaVersion;\n service_origin: string;\n}\n\nexport interface ResolvedLineageProfile extends LineageProfileManifest {\n manifest_path: string;\n profile_fingerprint: string;\n}\n\nexport interface LineageProfileIdentity {\n bound_at?: string;\n environment: LineageProfileEnvironment;\n profile_fingerprint: string;\n profile_id: string;\n}\n\nexport interface LineageProfileBindResult {\n already_bound: boolean;\n database_path: string;\n identity: LineageProfileIdentity;\n schema_version: 'lineage.profile_bind.v1';\n}\n\nexport interface LineageProfileInitResult {\n asset_root: string;\n database_path: string;\n environment: LineageProfileEnvironment;\n identity: LineageProfileIdentity;\n manifest_path: string;\n profile_fingerprint: string;\n profile_id: string;\n runtime: {\n channel: LineageRuntimeChannel;\n code_fingerprint: string;\n code_origin: 'checkout' | 'package';\n };\n schema_version: typeof lineageProfileInitSchemaVersion;\n service_origin: string;\n}\n\nexport interface LineageProfileCloneResult {\n database_path: string;\n pages_copied: number;\n receipt_path: string;\n schema_version: typeof lineageProfileCloneReceiptSchemaVersion;\n source_database_path: string;\n target_identity: LineageProfileIdentity;\n}\n\nexport interface LineageProfileAssetsCloneResult {\n asset_root: string;\n bytes_copied: number;\n code_fingerprint: string;\n database_path: string;\n duplicate_references: number;\n files_copied: number;\n missing_references: number;\n profile_fingerprint: string;\n profile_id: string;\n receipt_path: string;\n references_discovered: number;\n runtime_channel: LineageRuntimeChannel;\n schema_version: typeof lineageProfileAssetsCloneReceiptSchemaVersion;\n source_asset_root: string;\n tree_sha256: string;\n}\n\nexport interface LineageProfileRuntimeRepinResult {\n changed: boolean;\n checkout_root: string;\n manifest_after_sha256: string;\n manifest_before_sha256: string;\n manifest_path: string;\n new_code_fingerprint: string;\n previous_code_fingerprint: string;\n profile_fingerprint: string;\n profile_id: string;\n schema_version: typeof lineageProfileRuntimeRepinReceiptSchemaVersion;\n}\n\ntype LineageProfileDoctorCheckStatus = 'pass' | 'fail' | 'warning';\n\nexport interface LineageProfileDoctorCheck {\n id: string;\n message: string;\n status: LineageProfileDoctorCheckStatus;\n}\n\nexport interface LineageProfileDoctorResult {\n asset_root?: {\n exists: boolean;\n is_directory: boolean;\n path: string;\n };\n checks: LineageProfileDoctorCheck[];\n database?: {\n error?: string;\n exists: boolean;\n identity?: LineageProfileIdentity;\n migration_keys: string[];\n path: string;\n };\n manifest_path?: string;\n ok: boolean;\n profile?: ResolvedLineageProfile;\n runtime: {\n channel: LineageRuntimeChannel;\n code_fingerprint?: string;\n code_origin?: 'checkout' | 'package' | 'unknown';\n code_verified?: boolean;\n git_sha?: string;\n version: string;\n };\n schema_version: typeof lineageProfileDoctorSchemaVersion;\n}\n", "import { createRequire } from 'node:module';\n\nconst require = createRequire(import.meta.url);\nconst sqliteExperimentalWarning = 'SQLite is an experimental feature and might change at any time';\n\nexport function loadNodeSqlite(): typeof import('node:sqlite') {\n const emitWarning = process.emitWarning;\n process.emitWarning = ((warning: string | Error, ...args: unknown[]) => {\n const message = warning instanceof Error ? warning.message : warning;\n const type = typeof args[0] === 'string' ? args[0] : warning instanceof Error ? warning.name : undefined;\n if (message === sqliteExperimentalWarning && type === 'ExperimentalWarning') return;\n return Reflect.apply(emitWarning, process, [warning, ...args]);\n }) as typeof process.emitWarning;\n try {\n return require('node:sqlite') as typeof import('node:sqlite');\n } finally {\n process.emitWarning = emitWarning;\n }\n}\n", "import { join } from 'node:path';\nimport { EdgeSummaryValidationError, normalizeEdgeSummary, requireEdgeSummary } from '../shared/edgeSummary';\nimport { defaultProject, listAssets, repoRoot } from './assetCore';\nimport { lineageDb as db, lineageDbPath, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { LINEAGE_NEXT_VARIATION_LIMIT, normalizeSelectionInput, selectedRows, selectionId } from './assetLineageSelection';\nimport { cancelLineageTask, listLineageTasks, upsertLineageTask } from './assetLineageTasks';\nimport { activeLineageWorkspaceRoot } from './assetLineageWorkspaces';\nimport { requireLineageWorkspaceClaimForWrite } from './lineageClaimGuards';\nimport type {\n AssetReviewState,\n GrowthAsset,\n LineageAttempt,\n LineageAttemptPromotionResponse,\n LineageAttemptsResponse,\n LineageEdge,\n LineageChildrenResponse,\n LineageEdgeSummaryFields,\n LineageEdgeSummaryMutationResponse,\n LineageIndexSummary,\n LineageLayoutFields,\n LineageLinkFields,\n LineageNode,\n LineageNextResponse,\n LineagePosition,\n LineageRerollRequest,\n LineageRerollRequestMutationResponse,\n LineageRerollRequestsResponse,\n LineageSnapshot,\n LineageTask,\n ReviewFields,\n SelectionFields,\n} from '../shared/types';\n\nexport class LineageError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageError(error: unknown): error is LineageError {\n return error instanceof LineageError;\n}\n\nfunction collectAssets(project: string, source: 'catalog' | 'local'): GrowthAsset[] {\n const first = listAssets(project, { source, page: 1, pageSize: 100 });\n const assets = [...first.assets];\n for (let page = 2; page <= first.pagination.totalPages; page += 1) {\n assets.push(...listAssets(project, { source, page, pageSize: 100 }).assets);\n }\n return assets;\n}\n\nfunction upsertProject(database: DatabaseSync, project: string): void {\n const timestamp = nowIso();\n database.prepare(`\n insert into projects (id, product, catalog_path, created_at, updated_at)\n values (?, ?, ?, ?, ?)\n on conflict(id) do update set product = excluded.product, updated_at = excluded.updated_at\n `).run(project, project, join(repoRoot, project, 'assets', 'catalog.json'), timestamp, timestamp);\n}\n\nfunction upsertAsset(database: DatabaseSync, project: string, asset: GrowthAsset): void {\n const timestamp = nowIso();\n const source = asset.source === 'local' ? 'local' : 'catalog';\n database.prepare(`\n insert into assets (\n id, project_id, source, local_path, s3_key, checksum_sha256, media_type, title, status,\n channel, campaign, audience, size_bytes, content_type, created_at, updated_at, last_seen_at\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n on conflict(id) do update set\n source = excluded.source, local_path = excluded.local_path, s3_key = excluded.s3_key,\n checksum_sha256 = excluded.checksum_sha256, media_type = excluded.media_type,\n title = excluded.title, status = excluded.status, channel = excluded.channel,\n campaign = excluded.campaign, audience = excluded.audience, size_bytes = excluded.size_bytes,\n content_type = excluded.content_type, updated_at = excluded.updated_at, last_seen_at = excluded.last_seen_at\n `).run(\n asset.asset_id, project, source, asset.local?.relative_path || null, asset.s3?.key || null,\n asset.local?.checksum_sha256 || asset.s3?.checksum_sha256 || null, asset.content_type, asset.title,\n asset.status, asset.channel || null, asset.campaign || null, asset.audience || null,\n asset.local?.size_bytes || asset.s3?.size_bytes || null, asset.local?.content_type || asset.s3?.content_type || null,\n timestamp, timestamp, timestamp\n );\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, updated_at)\n values (?, 'unreviewed', ?)\n on conflict(asset_id) do nothing\n `).run(asset.asset_id, timestamp);\n}\n\nexport function indexLineageAssets(project = defaultProject): LineageIndexSummary {\n const database = db();\n const catalog = collectAssets(project, 'catalog');\n const local = collectAssets(project, 'local');\n upsertProject(database, project);\n for (const asset of [...catalog, ...local]) upsertAsset(database, project, asset);\n database.close();\n return { catalog: catalog.length, local: local.length, total: catalog.length + local.length, database: lineageDbPath() };\n}\n\nfunction requireAsset(database: DatabaseSync, project: string, assetId: string): void {\n const row = database.prepare('select id from assets where project_id = ? and id = ?').get(project, assetId);\n if (!row) throw new LineageError(`Unknown indexed asset: ${assetId}`, 404);\n}\n\nfunction parentOf(database: DatabaseSync, project: string, assetId: string): string | undefined {\n const row = database.prepare('select parent_asset_id from asset_edges where project_id = ? and child_asset_id = ? order by created_at limit 1').get(project, assetId) as { parent_asset_id?: string } | undefined;\n return row?.parent_asset_id;\n}\n\nfunction rootFor(database: DatabaseSync, project: string, assetId: string): string {\n let root = assetId;\n const seen = new Set<string>();\n while (!seen.has(root)) {\n seen.add(root);\n const parent = parentOf(database, project, root);\n if (!parent) return root;\n root = parent;\n }\n return assetId;\n}\n\nfunction assertCanonicalRoot(database: DatabaseSync, project: string, root: string): void {\n requireAsset(database, project, root);\n const canonicalRoot = rootFor(database, project, root);\n if (canonicalRoot !== root) throw new LineageError(`Asset ${root} is not a lineage root`, 400);\n}\n\nfunction explicitWorkspaceRoot(database: DatabaseSync, project: string, assetId: string): string | undefined {\n const row = database.prepare(`\n select root_asset_id from lineage_workspaces\n where project_id = ? and root_asset_id = ? and status != 'archived'\n `).get(project, assetId) as { root_asset_id?: string } | undefined;\n return row?.root_asset_id;\n}\n\nfunction nearestWorkspaceRoot(database: DatabaseSync, project: string, assetId: string): string {\n let current = assetId;\n const seen = new Set<string>();\n while (!seen.has(current)) {\n seen.add(current);\n const explicit = explicitWorkspaceRoot(database, project, current);\n if (explicit) return explicit;\n const parent = parentOf(database, project, current);\n if (!parent) return current;\n current = parent;\n }\n return assetId;\n}\n\nfunction assetChannel(database: DatabaseSync, project: string, assetId: string): string | undefined {\n const row = database.prepare('select channel from assets where project_id = ? and id = ?').get(project, assetId) as { channel?: string } | undefined;\n return row?.channel;\n}\n\nfunction lineageWriteClaimContext(database: DatabaseSync, project: string, assetId: string): { channel?: string; rootAssetId: string } {\n return {\n channel: assetChannel(database, project, assetId),\n rootAssetId: nearestWorkspaceRoot(database, project, assetId),\n };\n}\n\nexport function getLineageWriteClaimContext(project: string, assetId: string): { channel?: string; rootAssetId: string } {\n const database = db();\n try {\n requireAsset(database, project, assetId);\n return lineageWriteClaimContext(database, project, assetId);\n } finally {\n database.close();\n }\n}\n\nfunction latestSelectedRoot(database: DatabaseSync, project: string): string | undefined {\n const row = database.prepare('select root_asset_id from asset_selections where project_id = ? order by selected_at desc limit 1').get(project) as { root_asset_id?: string } | undefined;\n return row?.root_asset_id;\n}\n\nfunction resolveRoot(database: DatabaseSync, project: string, rootAssetId?: string): string {\n if (rootAssetId) {\n requireAsset(database, project, rootAssetId);\n return rootAssetId;\n }\n const root = activeLineageWorkspaceRoot(project) || latestSelectedRoot(database, project);\n if (!root) throw new LineageError('Lineage command requires --root unless a project selection exists');\n requireAsset(database, project, root);\n return root;\n}\n\nfunction edgeId(project: string, parent: string, child: string): string {\n return `${project}:${parent}:derived_from:${child}`;\n}\n\nfunction rerollRequestId(project: string, root: string, node: string, timestamp: string): string {\n return `${project}:${root}:reroll:${node}:${Date.parse(timestamp) || Date.now()}`;\n}\n\nfunction rowString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction lineageEdgeFromRow(row: Record<string, unknown>): LineageEdge {\n const summary = rowString(row.summary);\n const summaryCreatedBy = rowString(row.summary_created_by) as LineageEdge['summary_created_by'];\n const summaryUpdatedBy = rowString(row.summary_updated_by) as LineageEdge['summary_updated_by'];\n const summaryUpdatedAt = rowString(row.summary_updated_at);\n return {\n id: String(row.id),\n parent_asset_id: String(row.parent_asset_id),\n child_asset_id: String(row.child_asset_id),\n relation_type: row.relation_type as LineageEdge['relation_type'],\n created_at: String(row.created_at),\n ...(summary ? { summary } : {}),\n ...(summaryCreatedBy ? { summary_created_by: summaryCreatedBy } : {}),\n ...(summaryUpdatedBy ? { summary_updated_by: summaryUpdatedBy } : {}),\n ...(summaryUpdatedAt ? { summary_updated_at: summaryUpdatedAt } : {}),\n };\n}\n\nfunction nextEdgeSummaryTimestamp(current?: string): string {\n const currentMillis = current ? Date.parse(current) : Number.NaN;\n const nextMillis = Number.isFinite(currentMillis) ? Math.max(Date.now(), currentMillis + 1) : Date.now();\n return new Date(nextMillis).toISOString();\n}\n\nfunction expectedEdgeSummaryTimestamp(value: unknown): string | null {\n if (value === null) return null;\n if (typeof value === 'string' && value.length > 0) return value;\n throw new LineageError('Edge summary update requires expectedSummaryUpdatedAt as a timestamp or null');\n}\n\nfunction validatedHumanEdgeSummary(value: unknown): string {\n try {\n return requireEdgeSummary(value);\n } catch (error) {\n if (error instanceof EdgeSummaryValidationError) throw new LineageError(error.message);\n throw error;\n }\n}\n\nfunction rerollRequestFrom(row: Record<string, unknown>): LineageRerollRequest {\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n root_asset_id: String(row.root_asset_id),\n node_asset_id: String(row.node_asset_id),\n status: row.status as LineageRerollRequest['status'],\n requested_by: row.requested_by as LineageRerollRequest['requested_by'],\n notes: rowString(row.notes),\n created_at: String(row.created_at),\n resolved_at: rowString(row.resolved_at),\n };\n}\n\nfunction tasksByTarget(tasks: LineageTask[]): Map<string, Partial<Record<'iterate' | 'reroll', LineageTask>>> {\n const byTarget = new Map<string, Partial<Record<'iterate' | 'reroll', LineageTask>>>();\n for (const task of tasks) {\n if (task.task_type !== 'iterate' && task.task_type !== 'reroll') continue;\n const existing = byTarget.get(task.target_asset_id) || {};\n existing[task.task_type] = task;\n byTarget.set(task.target_asset_id, existing);\n }\n return byTarget;\n}\n\nfunction withRerollTask(request: LineageRerollRequest, task?: LineageTask): LineageRerollRequest {\n return task ? { ...request, task_id: task.id, task } : request;\n}\n\nfunction taskBackedRerollRequest(project: string, rootAssetId: string, task: LineageTask): LineageRerollRequest {\n return {\n id: `${task.id}:request`,\n project_id: project,\n root_asset_id: rootAssetId,\n node_asset_id: task.target_asset_id,\n status: 'pending',\n requested_by: task.created_by,\n notes: task.instructions,\n created_at: task.created_at,\n task_id: task.id,\n task,\n };\n}\n\nfunction attemptFrom(row: Record<string, unknown>): LineageAttempt {\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n node_asset_id: String(row.node_asset_id),\n asset_id: String(row.asset_id),\n attempt_index: Number(row.attempt_index),\n source: row.source as LineageAttempt['source'],\n prompt: rowString(row.prompt),\n generation_job_id: rowString(row.generation_job_id),\n file_path: rowString(row.file_path),\n checksum_sha256: rowString(row.checksum_sha256),\n created_at: String(row.created_at),\n promoted_at: rowString(row.promoted_at),\n is_current: Boolean(Number(row.is_current)),\n };\n}\n\nfunction implicitAttempt(row: { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string }, isCurrent = true): LineageAttempt {\n const createdAt = row.asset_created_at || nowIso();\n return {\n id: `${row.project}:${row.asset_id}:attempt:implicit`,\n project_id: row.project,\n node_asset_id: row.asset_id,\n asset_id: row.asset_id,\n attempt_index: 1,\n source: 'initial',\n file_path: row.local_path,\n checksum_sha256: row.checksum_sha256,\n created_at: createdAt,\n promoted_at: createdAt,\n is_current: isCurrent,\n };\n}\n\nfunction withImplicitAttempt(physicalAttempts: LineageAttempt[], row: { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string }): LineageAttempt[] {\n if (physicalAttempts.some(attempt => attempt.source === 'initial')) return physicalAttempts;\n return [...physicalAttempts, implicitAttempt(row, !physicalAttempts.some(attempt => attempt.is_current))];\n}\n\nfunction assertNodeInRoot(database: DatabaseSync, project: string, root: string, node: string): void {\n assertCanonicalRoot(database, project, root);\n requireAsset(database, project, node);\n const nodeRoot = rootFor(database, project, node);\n if (nodeRoot !== root) throw new LineageError(`Asset ${node} is not in lineage rooted at ${root}`);\n}\n\nfunction assertAttemptAssetNotVisibleLineageNode(database: DatabaseSync, project: string, root: string, assetId: string): void {\n const visibleNodeIds = new Set([\n root,\n ...descendants(database, project, root).flatMap(edge => [edge.parent_asset_id, edge.child_asset_id]),\n ]);\n if (visibleNodeIds.has(assetId)) throw new LineageError(`Attempt asset ${assetId} is already a visible lineage node in ${root}`, 400);\n}\n\nfunction canPreviewLocally(mediaType: string, localPath?: string): boolean {\n return Boolean(localPath && ['image', 'video', 'gif'].includes(mediaType));\n}\n\nfunction localPreviewUrl(project: string, localPath?: string): string | undefined {\n if (!localPath) return undefined;\n const params = new URLSearchParams({ project, path: localPath });\n return `/api/assets/local-preview?${params.toString()}`;\n}\n\nexport function linkLineageAssets(project: string, fields: LineageLinkFields) {\n const summary = normalizeEdgeSummary(fields.summary);\n if (summary && !fields.summaryActor) throw new LineageError('Lineage edge summary requires an explicit author');\n if (!summary && fields.summaryActor) throw new LineageError('Lineage edge summary author requires a summary');\n const database = db();\n requireAsset(database, project, fields.parentAssetId);\n requireAsset(database, project, fields.childAssetId);\n if (fields.parentAssetId === fields.childAssetId) throw new LineageError('Lineage link cannot point to itself');\n const claimContext = lineageWriteClaimContext(database, project, fields.parentAssetId);\n try {\n requireLineageWorkspaceClaimForWrite({\n channel: claimContext.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n project,\n rootAssetId: claimContext.rootAssetId,\n writeKind: 'lineage_link',\n });\n } catch (error) {\n database.close();\n throw error;\n }\n const createdAt = nowIso();\n const edge: LineageEdge = {\n id: edgeId(project, fields.parentAssetId, fields.childAssetId), parent_asset_id: fields.parentAssetId,\n child_asset_id: fields.childAssetId, relation_type: 'derived_from' as const, created_at: createdAt,\n ...(summary ? {\n summary,\n summary_created_by: fields.summaryActor!,\n summary_updated_by: fields.summaryActor!,\n summary_updated_at: createdAt,\n } : {}),\n };\n if (!fields.confirmWrite) {\n database.close();\n return { ok: true as const, dryRun: true, edge };\n }\n const inserted = database.prepare(`\n insert into asset_edges (\n id, project_id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n )\n values (?, ?, ?, ?, 'derived_from', ?, ?, ?, ?, ?)\n on conflict(project_id, parent_asset_id, child_asset_id, relation_type) do nothing\n `).run(\n edge.id,\n project,\n edge.parent_asset_id,\n edge.child_asset_id,\n edge.created_at,\n edge.summary || null,\n edge.summary_created_by || null,\n edge.summary_updated_by || null,\n edge.summary_updated_at || null,\n );\n if (inserted.changes === 0) {\n const existingRow = database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ? and child_asset_id = ? and relation_type = 'derived_from'\n `).get(project, edge.parent_asset_id, edge.child_asset_id) as Record<string, unknown> | undefined;\n if (!existingRow) {\n database.close();\n throw new LineageError('Lineage edge conflict could not be resolved', 409);\n }\n const existingEdge = lineageEdgeFromRow(existingRow);\n if (summary && (\n existingEdge.summary !== summary\n || existingEdge.summary_created_by !== fields.summaryActor\n || existingEdge.summary_updated_by !== fields.summaryActor\n || !existingEdge.summary_updated_at\n )) {\n database.close();\n throw new LineageError('Lineage edge already exists with a different summary or provenance', 409);\n }\n database.close();\n return {\n ok: true as const,\n idempotent: true as const,\n message: `Already linked ${existingEdge.child_asset_id} from ${existingEdge.parent_asset_id}`,\n edge: existingEdge,\n };\n }\n database.close();\n return { ok: true as const, message: `Linked ${edge.child_asset_id} from ${edge.parent_asset_id}`, edge };\n}\n\nexport function updateLineageEdgeSummary(project: string, fields: LineageEdgeSummaryFields): LineageEdgeSummaryMutationResponse {\n if (!fields.confirmWrite) throw new LineageError('Edge summary updates require confirmWrite=true');\n if (fields.action !== 'set' && fields.action !== 'clear') throw new LineageError('Edge summary action must be set or clear');\n const expectedUpdatedAt = expectedEdgeSummaryTimestamp(fields.expectedSummaryUpdatedAt);\n const summary = fields.action === 'set' ? validatedHumanEdgeSummary(fields.summary) : undefined;\n if (fields.action === 'clear' && fields.summary !== undefined) throw new LineageError('Clear edge summary must not include summary text');\n\n const database = db();\n try {\n const row = database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and id = ?\n `).get(project, fields.edgeId) as Record<string, unknown> | undefined;\n if (!row) throw new LineageError(`Unknown lineage edge: ${fields.edgeId}`, 404);\n const current = lineageEdgeFromRow(row);\n const currentUpdatedAt = current.summary_updated_at || null;\n if (currentUpdatedAt !== expectedUpdatedAt) {\n throw new LineageError('Edge summary changed since it was opened; refresh and retry', 409);\n }\n if (fields.action === 'clear' && !current.summary) throw new LineageError('Edge summary is already clear');\n if (fields.action === 'set' && summary === current.summary) throw new LineageError('Edge summary is unchanged');\n\n const claimContext = lineageWriteClaimContext(database, project, current.parent_asset_id);\n requireLineageWorkspaceClaimForWrite({\n channel: claimContext.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n project,\n rootAssetId: claimContext.rootAssetId,\n writeKind: 'lineage_edge_summary',\n });\n\n const updatedAt = nextEdgeSummaryTimestamp(current.summary_updated_at);\n const createdBy = fields.action === 'set'\n ? (current.summary ? current.summary_created_by || 'human' : 'human')\n : current.summary_created_by || 'human';\n const result = database.prepare(`\n update asset_edges\n set summary = ?, summary_created_by = ?, summary_updated_by = 'human', summary_updated_at = ?\n where project_id = ? and id = ?\n and ((summary_updated_at is null and ? is null) or summary_updated_at = ?)\n `).run(\n summary || null,\n createdBy,\n updatedAt,\n project,\n fields.edgeId,\n expectedUpdatedAt,\n expectedUpdatedAt,\n );\n if (Number(result.changes) !== 1) {\n throw new LineageError('Edge summary changed since it was opened; refresh and retry', 409);\n }\n const updatedRow = database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and id = ?\n `).get(project, fields.edgeId) as Record<string, unknown>;\n const edge = lineageEdgeFromRow(updatedRow);\n return {\n ok: true,\n edge,\n message: fields.action === 'clear' ? 'Cleared edge label' : `Saved edge label \u201C${edge.summary}\u201D`,\n };\n } finally {\n database.close();\n }\n}\n\nfunction descendants(database: DatabaseSync, project: string, root: string): LineageEdge[] {\n const edges: LineageEdge[] = [];\n const queue = [root];\n const seen = new Set<string>();\n while (queue.length > 0) {\n const parent = queue.shift()!;\n if (seen.has(parent)) continue;\n seen.add(parent);\n const rows = (database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ?\n order by created_at\n `).all(project, parent) as Array<Record<string, unknown>>).map(lineageEdgeFromRow);\n edges.push(...rows);\n queue.push(...rows.map(row => row.child_asset_id));\n }\n return edges;\n}\n\nexport function getLineageSnapshot(project: string, assetId: string): LineageSnapshot {\n const database = db();\n requireAsset(database, project, assetId);\n const root = explicitWorkspaceRoot(database, project, assetId) || rootFor(database, project, assetId);\n const edges = descendants(database, project, root);\n const selected = selectedRows(database, project, root);\n const tasks = listLineageTasks(project, root).tasks;\n const ids = [...new Set([\n root,\n ...edges.flatMap(edge => [edge.parent_asset_id, edge.child_asset_id]),\n ...selected.map(row => row.asset_id),\n ...tasks.map(task => task.target_asset_id),\n ])];\n const placeholders = ids.map(() => '?').join(',');\n const rows = database.prepare(`\n select a.id asset_id, a.project_id project, a.source, a.title, a.media_type, a.status, a.channel, a.campaign,\n a.local_path, a.s3_key, a.checksum_sha256, coalesce(r.review_state, 'unreviewed') review_state,\n r.notes review_notes, a.created_at asset_created_at, l.x layout_x, l.y layout_y\n from assets a left join asset_reviews r on r.asset_id = a.id\n left join asset_layouts l on l.project_id = a.project_id and l.root_asset_id = ? and l.asset_id = a.id\n where a.project_id = ? and a.id in (${placeholders})\n `).all(root, project, ...ids) as unknown as Array<Omit<LineageNode, 'attempt_count' | 'current_attempt' | 'is_latest' | 'lineage_tasks' | 'position' | 'preview_url' | 'reroll_request' | 'selection_note' | 'user_selected'> & { asset_created_at?: string; layout_x?: number; layout_y?: number }>;\n const attemptRows = ids.length > 0\n ? database.prepare(`select * from asset_attempts where project_id = ? and node_asset_id in (${placeholders}) order by node_asset_id, attempt_index desc`).all(project, ...ids) as Array<Record<string, unknown>>\n : [];\n const attemptsByNode = new Map<string, LineageAttempt[]>();\n for (const attempt of attemptRows.map(attemptFrom)) {\n attemptsByNode.set(attempt.node_asset_id, [...(attemptsByNode.get(attempt.node_asset_id) || []), attempt]);\n }\n const lineageTasksByNode = tasksByTarget(tasks);\n const rerollRows = ids.length > 0\n ? database.prepare(`select * from asset_reroll_requests where project_id = ? and root_asset_id = ? and status = 'pending' and node_asset_id in (${placeholders}) order by created_at`).all(project, root, ...ids) as Array<Record<string, unknown>>\n : [];\n const rerollsByNode = new Map(rerollRows.map(row => {\n const request = rerollRequestFrom(row);\n return [request.node_asset_id, withRerollTask(request, lineageTasksByNode.get(request.node_asset_id)?.reroll)] as const;\n }));\n const childIds = new Set(edges.map(edge => edge.parent_asset_id));\n const selectedIds = new Set(selected.map(row => row.asset_id));\n const selections = selected.map(row => ({\n asset_id: row.asset_id, notes: row.notes || undefined,\n position: Number(row.position || 0), selected_at: row.selected_at,\n }));\n const selection = selections[0] || null;\n const nodes = rows.map(row => {\n const position: LineagePosition | undefined = typeof row.layout_x === 'number' && typeof row.layout_y === 'number' ? { x: row.layout_x, y: row.layout_y } : undefined;\n const { asset_created_at: _assetCreatedAt, layout_x: _layoutX, layout_y: _layoutY, ...node } = row;\n const nodeSelection = selections.find(item => item.asset_id === row.asset_id);\n const attempts = withImplicitAttempt(attemptsByNode.get(row.asset_id) || [], row);\n const currentAttempt = attempts.find(attempt => attempt.is_current) || attempts[0];\n const previewPath = currentAttempt?.file_path || row.local_path;\n const lineageTasks = lineageTasksByNode.get(row.asset_id);\n return {\n ...node,\n attempt_count: attempts.length,\n current_attempt: currentAttempt,\n is_latest: !childIds.has(row.asset_id),\n lineage_tasks: lineageTasks && Object.keys(lineageTasks).length > 0 ? lineageTasks : undefined,\n position,\n preview_url: canPreviewLocally(row.media_type, previewPath) ? localPreviewUrl(project, previewPath) : undefined,\n reroll_request: rerollsByNode.get(row.asset_id),\n selection_note: nodeSelection?.notes,\n user_selected: selectedIds.has(row.asset_id),\n };\n });\n database.close();\n return {\n project,\n root_asset_id: root,\n active_asset_id: assetId,\n selected: selections.map(row => row.asset_id),\n selection,\n selections,\n tasks,\n latest: nodes.filter(node => node.is_latest).map(node => node.asset_id),\n nodes,\n edges,\n fetchedAt: nowIso(),\n };\n}\n\nexport function updateLineageLayout(project: string, fields: LineageLayoutFields) {\n if (fields.positions.length === 0) throw new LineageError('Lineage layout requires at least one position');\n const database = db();\n requireAsset(database, project, fields.rootAssetId);\n for (const position of fields.positions) requireAsset(database, project, position.assetId);\n try {\n requireLineageWorkspaceClaimForWrite({\n channel: assetChannel(database, project, fields.rootAssetId),\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n project,\n rootAssetId: fields.rootAssetId,\n writeKind: 'lineage_layout',\n });\n } catch (error) {\n database.close();\n throw error;\n }\n if (!fields.confirmWrite) {\n database.close();\n return { ok: true as const, dryRun: true, root_asset_id: fields.rootAssetId, positions: fields.positions };\n }\n const timestamp = nowIso();\n const statement = database.prepare(`\n insert into asset_layouts (id, project_id, root_asset_id, asset_id, x, y, updated_at)\n values (?, ?, ?, ?, ?, ?, ?)\n on conflict(project_id, root_asset_id, asset_id) do update set\n x = excluded.x, y = excluded.y, updated_at = excluded.updated_at\n `);\n for (const position of fields.positions) {\n statement.run(`${project}:${fields.rootAssetId}:layout:${position.assetId}`, project, fields.rootAssetId, position.assetId, position.x, position.y, timestamp);\n }\n database.close();\n return { ok: true as const, message: `Saved ${fields.positions.length} lineage positions`, root_asset_id: fields.rootAssetId, positions: fields.positions };\n}\n\nexport function getLineageNextAsset(project: string, rootAssetId?: string): LineageNextResponse {\n const database = db();\n const root = resolveRoot(database, project, rootAssetId);\n database.close();\n const snapshot = getLineageSnapshot(project, root);\n const pendingIterateTasks = (snapshot.tasks || []).filter(task => task.task_type === 'iterate' && task.status === 'pending');\n const taskIdsInSelectionOrder = [\n ...snapshot.selections\n .map(selection => selection.asset_id)\n .filter(assetId => pendingIterateTasks.some(task => task.target_asset_id === assetId)),\n ...pendingIterateTasks\n .map(task => task.target_asset_id)\n .filter(assetId => !snapshot.selections.some(selection => selection.asset_id === assetId)),\n ];\n const taskSelectedIds = [...new Set(taskIdsInSelectionOrder)];\n const selectedIds = taskSelectedIds.length > 0 ? taskSelectedIds : snapshot.selected;\n const selectedNodes = selectedIds\n .map(assetId => snapshot.nodes.find(node => node.asset_id === assetId))\n .filter((node): node is LineageNode => Boolean(node));\n const taskSelections = taskSelectedIds.map((assetId, position) => {\n const task = pendingIterateTasks.find(item => item.target_asset_id === assetId);\n return {\n asset_id: assetId,\n notes: task?.instructions,\n position,\n selected_at: task?.created_at || nowIso(),\n };\n });\n const selectedSelection = taskSelections.length > 0 ? taskSelections[0] : snapshot.selection;\n const selectedSelections = taskSelections.length > 0 ? taskSelections : snapshot.selections;\n const latestNodes = snapshot.nodes.filter(node => snapshot.latest.includes(node.asset_id));\n const warnings: string[] = [];\n for (const selectedNode of selectedNodes) {\n if (selectedNode.is_latest) continue;\n warnings.push('Selected asset is not a latest leaf; agents should treat this as an intentional branch choice.');\n }\n if (selectedNodes.length > 0) {\n return {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: 'selected',\n selection_mode: selectedNodes.length > 1 ? 'multiple' : 'single',\n recommended_action: 'evolve_variations',\n reason: 'user_selected',\n next_asset: selectedNodes[0],\n next_assets: selectedNodes,\n latest: snapshot.latest,\n selected: selectedIds,\n selection: selectedSelection,\n selections: selectedSelections,\n candidates: latestNodes,\n warnings,\n fetchedAt: nowIso(),\n };\n }\n if (latestNodes.length === 1) {\n return {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: 'single_latest',\n selection_mode: 'fallback',\n recommended_action: 'evolve_variations',\n reason: 'single_latest_fallback',\n next_asset: latestNodes[0],\n next_assets: [latestNodes[0]],\n latest: snapshot.latest,\n selected: selectedIds,\n selection: selectedSelection,\n selections: selectedSelections,\n candidates: latestNodes,\n warnings,\n fetchedAt: nowIso(),\n };\n }\n return {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: latestNodes.length > 1 ? 'ambiguous_latest' : 'empty',\n selection_mode: 'none',\n recommended_action: latestNodes.length > 1 ? 'choose_next_base' : 'none',\n reason: latestNodes.length > 1 ? 'multiple_latest_no_selection' : 'no_lineage_candidates',\n next_asset: null,\n next_assets: [],\n latest: snapshot.latest,\n selected: selectedIds,\n selection: selectedSelection,\n selections: selectedSelections,\n candidates: latestNodes,\n warnings,\n fetchedAt: nowIso(),\n };\n}\n\nexport function getLineageChildren(project: string, parentAssetId: string): LineageChildrenResponse {\n const snapshot = getLineageSnapshot(project, parentAssetId);\n const edges = snapshot.edges.filter(edge => edge.parent_asset_id === parentAssetId);\n const childIds = new Set(edges.map(edge => edge.child_asset_id));\n return {\n project, parent_asset_id: parentAssetId,\n children: snapshot.nodes.filter(node => childIds.has(node.asset_id)),\n edges, fetchedAt: nowIso(),\n };\n}\n\nexport function listLineageRerollRequests(project: string, rootAssetId: string): LineageRerollRequestsResponse {\n const database = db();\n try {\n assertCanonicalRoot(database, project, rootAssetId);\n const rerollTasks = listLineageTasks(project, rootAssetId).tasks.filter(task => task.task_type === 'reroll');\n const pendingRerollTasks = listLineageTasks(project, rootAssetId, ['pending']).tasks.filter(task => task.task_type === 'reroll');\n const rerollTaskByTarget = new Map(rerollTasks.map(task => [task.target_asset_id, task]));\n const rows = database.prepare(`\n select * from asset_reroll_requests\n where project_id = ? and root_asset_id = ? and status = 'pending'\n order by created_at, id\n `).all(project, rootAssetId) as Array<Record<string, unknown>>;\n const requests = rows.map(row => {\n const request = rerollRequestFrom(row);\n return withRerollTask(request, rerollTaskByTarget.get(request.node_asset_id));\n });\n const legacyTargets = new Set(requests.map(request => request.node_asset_id));\n for (const task of pendingRerollTasks) {\n if (!legacyTargets.has(task.target_asset_id)) requests.push(taskBackedRerollRequest(project, rootAssetId, task));\n }\n return { project, root_asset_id: rootAssetId, requests, fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function getLineageAttempts(project: string, rootAssetId: string, nodeAssetId: string): LineageAttemptsResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, rootAssetId, nodeAssetId);\n const rows = database.prepare(`\n select * from asset_attempts\n where project_id = ? and node_asset_id = ?\n order by attempt_index desc, created_at desc\n `).all(project, nodeAssetId) as Array<Record<string, unknown>>;\n const asset = database.prepare('select id asset_id, project_id project, local_path, checksum_sha256, created_at asset_created_at from assets where project_id = ? and id = ?').get(project, nodeAssetId) as { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string };\n return { project, root_asset_id: rootAssetId, node_asset_id: nodeAssetId, attempts: withImplicitAttempt(rows.map(attemptFrom), asset), fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function promoteLineageAttempt(project: string, fields: {\n rootAssetId: string;\n nodeAssetId: string;\n attemptId: string;\n confirmWrite: boolean;\n}): LineageAttemptPromotionResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n const asset = database.prepare('select id asset_id, project_id project, local_path, checksum_sha256, created_at asset_created_at from assets where project_id = ? and id = ?').get(project, fields.nodeAssetId) as { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string };\n const rows = database.prepare(`\n select * from asset_attempts\n where project_id = ? and node_asset_id = ?\n order by attempt_index desc, created_at desc\n `).all(project, fields.nodeAssetId) as Array<Record<string, unknown>>;\n const attempts = withImplicitAttempt(rows.map(attemptFrom), asset);\n const target = attempts.find(attempt => attempt.id === fields.attemptId);\n if (!target) throw new LineageError(`Attempt ${fields.attemptId} is not in ${fields.nodeAssetId}`, 404);\n const timestamp = nowIso();\n const promotedAttempt = { ...target, is_current: true, promoted_at: timestamp };\n if (!fields.confirmWrite) {\n return {\n ok: true,\n dryRun: true,\n project,\n root_asset_id: fields.rootAssetId,\n node_asset_id: fields.nodeAssetId,\n attempt: promotedAttempt,\n attempts: attempts.map(attempt => ({ ...attempt, is_current: attempt.id === target.id, promoted_at: attempt.id === target.id ? timestamp : attempt.promoted_at })),\n fetchedAt: timestamp,\n };\n }\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare('update asset_attempts set is_current = 0 where project_id = ? and node_asset_id = ?').run(project, fields.nodeAssetId);\n if (target.source !== 'initial') {\n const result = database.prepare(`\n update asset_attempts\n set is_current = 1, promoted_at = ?\n where project_id = ? and node_asset_id = ? and id = ?\n `).run(timestamp, project, fields.nodeAssetId, target.id);\n if (result.changes !== 1) throw new LineageError(`Attempt ${fields.attemptId} is not in ${fields.nodeAssetId}`, 404);\n }\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n const refreshedRows = database.prepare(`\n select * from asset_attempts\n where project_id = ? and node_asset_id = ?\n order by attempt_index desc, created_at desc\n `).all(project, fields.nodeAssetId) as Array<Record<string, unknown>>;\n const refreshedAttempts = withImplicitAttempt(refreshedRows.map(attemptFrom), asset);\n const attempt = refreshedAttempts.find(item => item.id === target.id) || promotedAttempt;\n return {\n ok: true,\n project,\n root_asset_id: fields.rootAssetId,\n node_asset_id: fields.nodeAssetId,\n attempt,\n attempts: refreshedAttempts,\n fetchedAt: nowIso(),\n };\n } finally {\n database.close();\n }\n}\n\nexport function recordLineageRerollAttempt(project: string, fields: {\n rootAssetId: string;\n nodeAssetId: string;\n assetId: string;\n prompt: string;\n generationJobId: string;\n filePath: string;\n checksumSha256: string;\n confirmWrite: boolean;\n}): { ok: true; attempt: LineageAttempt; dryRun?: true } {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n requireAsset(database, project, fields.assetId);\n assertAttemptAssetNotVisibleLineageNode(database, project, fields.rootAssetId, fields.assetId);\n const timestamp = nowIso();\n const maxRow = database.prepare('select max(attempt_index) max_index from asset_attempts where project_id = ? and node_asset_id = ?').get(project, fields.nodeAssetId) as { max_index?: number | null };\n const attemptIndex = Number(maxRow.max_index || 1) + 1;\n const attempt: LineageAttempt = {\n id: `${project}:${fields.nodeAssetId}:attempt:${attemptIndex}`,\n project_id: project,\n node_asset_id: fields.nodeAssetId,\n asset_id: fields.assetId,\n attempt_index: attemptIndex,\n source: 'reroll',\n prompt: fields.prompt,\n generation_job_id: fields.generationJobId,\n file_path: fields.filePath,\n checksum_sha256: fields.checksumSha256,\n created_at: timestamp,\n promoted_at: timestamp,\n is_current: true,\n };\n if (!fields.confirmWrite) return { ok: true, dryRun: true, attempt };\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare('update asset_attempts set is_current = 0 where project_id = ? and node_asset_id = ?').run(project, fields.nodeAssetId);\n database.prepare(`\n insert into asset_attempts (\n id, project_id, node_asset_id, asset_id, attempt_index, source, prompt, generation_job_id,\n file_path, checksum_sha256, created_at, promoted_at, is_current\n ) values (?, ?, ?, ?, ?, 'reroll', ?, ?, ?, ?, ?, ?, 1)\n `).run(\n attempt.id, project, fields.nodeAssetId, fields.assetId, attempt.attempt_index, fields.prompt,\n fields.generationJobId, fields.filePath, fields.checksumSha256, timestamp, timestamp\n );\n database.prepare(`\n update asset_reroll_requests\n set status = 'resolved', resolved_at = ?\n where project_id = ? and root_asset_id = ? and node_asset_id = ? and status = 'pending'\n `).run(timestamp, project, fields.rootAssetId, fields.nodeAssetId);\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n values (?, 'unreviewed', ?, null, null, ?)\n on conflict(asset_id) do update set\n review_state = excluded.review_state, reviewed_at = excluded.reviewed_at,\n ignored_at = excluded.ignored_at, updated_at = excluded.updated_at\n `).run(fields.nodeAssetId, timestamp, timestamp);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n return { ok: true, attempt };\n } finally {\n database.close();\n }\n}\n\nexport function markLineageRerollRequest(project: string, fields: { rootAssetId: string; nodeAssetId: string; notes?: string; requestedBy?: 'agent' | 'human' | 'system'; confirmWrite: boolean }): LineageRerollRequestMutationResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n const existing = database.prepare(`\n select * from asset_reroll_requests\n where project_id = ? and root_asset_id = ? and node_asset_id = ? and status = 'pending'\n order by created_at desc limit 1\n `).get(project, fields.rootAssetId, fields.nodeAssetId) as Record<string, unknown> | undefined;\n const timestamp = nowIso();\n const request: LineageRerollRequest = existing ? {\n ...rerollRequestFrom(existing),\n notes: fields.notes || rerollRequestFrom(existing).notes,\n requested_by: fields.requestedBy || rerollRequestFrom(existing).requested_by,\n } : {\n id: rerollRequestId(project, fields.rootAssetId, fields.nodeAssetId, timestamp),\n project_id: project,\n root_asset_id: fields.rootAssetId,\n node_asset_id: fields.nodeAssetId,\n status: 'pending',\n requested_by: fields.requestedBy || 'human',\n notes: fields.notes,\n created_at: timestamp,\n };\n if (!fields.confirmWrite) return { ok: true, dryRun: true, request };\n const taskResult = upsertLineageTask(project, {\n createdBy: request.requested_by,\n instructions: request.notes,\n rootAssetId: fields.rootAssetId,\n targetAssetId: fields.nodeAssetId,\n taskType: 'reroll',\n });\n if (existing) {\n database.prepare(`\n update asset_reroll_requests\n set requested_by = ?, notes = ?\n where id = ?\n `).run(request.requested_by, request.notes || null, request.id);\n } else {\n database.prepare(`\n insert into asset_reroll_requests (id, project_id, root_asset_id, node_asset_id, status, requested_by, notes, created_at, resolved_at)\n values (?, ?, ?, ?, 'pending', ?, ?, ?, null)\n `).run(request.id, project, fields.rootAssetId, fields.nodeAssetId, request.requested_by, request.notes || null, request.created_at);\n }\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n values (?, 'needs_revision', ?, null, ?, ?)\n on conflict(asset_id) do update set\n review_state = excluded.review_state, reviewed_at = excluded.reviewed_at,\n ignored_at = excluded.ignored_at, notes = coalesce(excluded.notes, asset_reviews.notes), updated_at = excluded.updated_at\n `).run(fields.nodeAssetId, timestamp, request.notes || null, timestamp);\n return {\n ok: true,\n request: withRerollTask(rerollRequestFrom(database.prepare('select * from asset_reroll_requests where id = ?').get(request.id) as Record<string, unknown>), taskResult.task),\n task_id: taskResult.task.id,\n task: taskResult.task,\n };\n } finally {\n database.close();\n }\n}\n\nexport function clearLineageRerollRequest(project: string, fields: { rootAssetId: string; nodeAssetId: string; confirmWrite: boolean }): LineageRerollRequestMutationResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n const existing = database.prepare(`\n select * from asset_reroll_requests\n where project_id = ? and root_asset_id = ? and node_asset_id = ? and status = 'pending'\n order by created_at desc limit 1\n `).get(project, fields.rootAssetId, fields.nodeAssetId) as Record<string, unknown> | undefined;\n if (!existing) throw new LineageError(`No pending re-roll request for ${fields.nodeAssetId}`, 404);\n const timestamp = nowIso();\n const request = { ...rerollRequestFrom(existing), status: 'cancelled' as const, resolved_at: timestamp };\n if (!fields.confirmWrite) return { ok: true, dryRun: true, request };\n const task = listLineageTasks(project, fields.rootAssetId, ['pending']).tasks.find(item => item.task_type === 'reroll' && item.target_asset_id === fields.nodeAssetId);\n const cancelledTask = task ? cancelLineageTask(project, {\n actor: 'human',\n confirmWrite: true,\n taskId: task.id,\n }).task : undefined;\n database.prepare(`\n update asset_reroll_requests\n set status = 'cancelled', resolved_at = ?\n where id = ?\n `).run(timestamp, request.id);\n return {\n ok: true,\n request: withRerollTask(request, cancelledTask),\n task_id: cancelledTask?.id,\n task: cancelledTask,\n };\n } finally {\n database.close();\n }\n}\n\nexport function updateSelectedAsset(project: string, fields: SelectionFields) {\n const database = db();\n let root: string;\n let current: ReturnType<typeof selectedRows>;\n let inputAssetIds: string[];\n let mode: NonNullable<SelectionFields['mode']>;\n let limit: number;\n let nextIds: string[];\n const notesByAsset = new Map<string, string | undefined>();\n try {\n inputAssetIds = normalizeSelectionInput(fields);\n root = fields.rootAssetId || (inputAssetIds[0] ? rootFor(database, project, inputAssetIds[0]) : '');\n if (!root) throw new LineageError('Selection requires rootAssetId or assetId');\n requireAsset(database, project, root);\n for (const assetId of inputAssetIds) requireAsset(database, project, assetId);\n mode = fields.mode || 'replace';\n limit = fields.maxSelections || LINEAGE_NEXT_VARIATION_LIMIT;\n if (!fields.confirmWrite) {\n return { ok: true as const, dryRun: true, root_asset_id: root, asset_ids: inputAssetIds, mode, clear: Boolean(fields.clear), max_selections: limit };\n }\n current = selectedRows(database, project, root);\n nextIds = current.map(row => row.asset_id);\n if (fields.clear) {\n nextIds = [];\n } else if (mode === 'replace') {\n nextIds = inputAssetIds;\n } else if (mode === 'add') {\n nextIds = [...nextIds, ...inputAssetIds];\n } else if (mode === 'remove') {\n nextIds = nextIds.filter(assetId => !inputAssetIds.includes(assetId));\n } else if (mode === 'toggle') {\n for (const assetId of inputAssetIds) {\n nextIds = nextIds.includes(assetId) ? nextIds.filter(id => id !== assetId) : [...nextIds, assetId];\n }\n }\n nextIds = [...new Set(nextIds)];\n if (!fields.clear && inputAssetIds.length === 0) throw new LineageError('Selection set requires assetId or assetIds');\n if (nextIds.length > limit) throw new LineageError(`Select at most ${limit} assets for next variation`);\n for (const assetId of nextIds) {\n const existing = current.find(row => row.asset_id === assetId);\n notesByAsset.set(assetId, inputAssetIds.includes(assetId) ? fields.notes || existing?.notes : existing?.notes);\n }\n } finally {\n database.close();\n }\n\n const removedIds = current.map(row => row.asset_id).filter(assetId => !nextIds.includes(assetId));\n const openIterateTasks = listLineageTasks(project, root, ['pending']).tasks.filter(task => task.task_type === 'iterate');\n for (const assetId of removedIds) {\n const task = openIterateTasks.find(item => item.target_asset_id === assetId);\n if (task) {\n cancelLineageTask(project, {\n actor: 'human',\n confirmWrite: true,\n taskId: task.id,\n });\n }\n }\n for (const assetId of nextIds) {\n upsertLineageTask(project, {\n createdBy: 'human',\n instructions: notesByAsset.get(assetId),\n rootAssetId: root,\n targetAssetId: assetId,\n taskType: 'iterate',\n });\n }\n\n const writeDatabase = db();\n writeDatabase.prepare('delete from asset_selections where project_id = ? and root_asset_id = ?').run(project, root);\n const timestamp = nowIso();\n const insert = writeDatabase.prepare(`\n insert into asset_selections (id, project_id, root_asset_id, asset_id, position, notes, selected_at)\n values (?, ?, ?, ?, ?, ?, ?)\n `);\n nextIds.forEach((assetId, position) => {\n insert.run(selectionId(project, root, assetId), project, root, assetId, position, notesByAsset.get(assetId) || null, timestamp);\n });\n writeDatabase.close();\n const message = nextIds.length === 0 ? `Cleared selected assets for ${root}` : `Selected ${nextIds.length} asset${nextIds.length === 1 ? '' : 's'} for ${root}`;\n return { ok: true as const, message, root_asset_id: root, asset_id: nextIds[0] || null, asset_ids: nextIds, mode };\n}\n\nexport function updateAssetReview(project: string, fields: ReviewFields) {\n const allowed = new Set<AssetReviewState>(['unreviewed', 'approved', 'needs_revision', 'rejected', 'ignored']);\n if (!allowed.has(fields.reviewState)) throw new LineageError(`Unsupported review state: ${fields.reviewState}`);\n const database = db();\n requireAsset(database, project, fields.assetId);\n if (!fields.confirmWrite) {\n database.close();\n return { ok: true as const, dryRun: true, asset_id: fields.assetId, review_state: fields.reviewState, notes: fields.notes };\n }\n const timestamp = nowIso();\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n values (?, ?, ?, ?, ?, ?)\n on conflict(asset_id) do update set\n review_state = excluded.review_state, reviewed_at = excluded.reviewed_at,\n ignored_at = excluded.ignored_at, notes = excluded.notes, updated_at = excluded.updated_at\n `).run(fields.assetId, fields.reviewState, timestamp, fields.reviewState === 'ignored' ? timestamp : null, fields.notes || null, timestamp);\n database.close();\n return { ok: true as const, message: `Marked ${fields.assetId} ${fields.reviewState}`, asset_id: fields.assetId, review_state: fields.reviewState };\n}\n", "import type { SelectionFields } from '../shared/types';\nimport type { DatabaseSync } from './assetLineageDb';\n\nexport const LINEAGE_NEXT_VARIATION_LIMIT = 3;\n\nexport interface LineageSelectionRow {\n asset_id: string;\n notes?: string;\n position: number;\n selected_at: string;\n}\n\nexport function selectionId(project: string, root: string, assetId: string): string {\n return `${project}:${root}:selected:${assetId}`;\n}\n\nexport function selectedRows(database: DatabaseSync, project: string, root: string): LineageSelectionRow[] {\n return database.prepare(`\n select asset_id, notes, position, selected_at\n from asset_selections\n where project_id = ? and root_asset_id = ?\n order by position, selected_at, asset_id\n `).all(project, root) as unknown as LineageSelectionRow[];\n}\n\nexport function normalizeSelectionInput(fields: SelectionFields): string[] {\n return [...new Set([...(fields.assetIds || []), fields.assetId || ''].map(assetId => assetId.trim()).filter(Boolean))];\n}\n", "import { randomBytes } from 'node:crypto';\nimport { createAgentClaim, recordAgentClaimWriteAllowed, releaseAgentClaim, revokeAgentClaimInDatabase, validateAgentClaimForWrite, type AgentClaim } from './agentClaims';\nimport { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\nimport type {\n LineageTask,\n LineageTaskActor,\n LineageTaskEvent,\n LineageTaskMutationResponse,\n LineageTaskStatus,\n LineageTasksResponse,\n LineageTaskType,\n} from '../shared/types';\n\nclass LineageTaskError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageTaskError(error: unknown): error is LineageTaskError {\n return error instanceof LineageTaskError;\n}\n\ntype Row = Record<string, unknown>;\ntype LineageTaskMutationResult = Omit<LineageTaskMutationResponse, 'events'> & { project: string; events: LineageTaskEvent[] };\ntype LineageTaskClaimResult = LineageTaskMutationResult & { claim: AgentClaim; claim_token: string };\n\nconst activeStatuses: LineageTaskStatus[] = ['pending', 'claimed', 'in_progress'];\nconst taskTypes = new Set<LineageTaskType>(['iterate', 'reroll']);\nconst taskStatuses = new Set<LineageTaskStatus>(['pending', 'claimed', 'in_progress', 'resolved', 'cancelled']);\n\nexport function taskIdFor(project: string, rootAssetId: string, targetAssetId: string, taskType: LineageTaskType): string {\n return `${project}:${rootAssetId}:lineage-task:${taskType}:${targetAssetId}`;\n}\n\nfunction randomId(prefix: string): string {\n return `${prefix}_${Date.now().toString(36)}_${randomBytes(6).toString('base64url').toLowerCase()}`;\n}\n\nfunction metadataJson(metadata?: Record<string, unknown>): string | null {\n return metadata ? JSON.stringify(metadata) : null;\n}\n\nfunction metadataWithoutClaim(metadata?: Record<string, unknown>): Record<string, unknown> | undefined {\n if (!metadata) return undefined;\n const next = { ...metadata };\n delete next.claim_id;\n return Object.keys(next).length > 0 ? next : undefined;\n}\n\nfunction parseMetadata(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string' || !value) return undefined;\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeProject(project: string): string {\n const trimmed = project.trim();\n if (!trimmed) throw new LineageTaskError('Lineage task requires project');\n return trimmed;\n}\n\nfunction normalizeTaskType(taskType: LineageTaskType): LineageTaskType {\n if (!taskTypes.has(taskType)) throw new LineageTaskError(`Unsupported lineage task type: ${taskType}`);\n return taskType;\n}\n\nfunction normalizeStatus(status: LineageTaskStatus): LineageTaskStatus {\n if (!taskStatuses.has(status)) throw new LineageTaskError(`Unsupported lineage task status: ${status}`);\n return status;\n}\n\nfunction normalizeActor(actor: string, label: string): string {\n const trimmed = actor.trim();\n if (!trimmed) throw new LineageTaskError(`${label} is required`);\n return trimmed;\n}\n\nfunction requireAsset(database: DatabaseSync, project: string, assetId: string): void {\n const row = database.prepare('select id from assets where project_id = ? and id = ?').get(project, assetId);\n if (!row) throw new LineageTaskError(`Unknown indexed asset: ${assetId}`, 404);\n}\n\nfunction taskFromRow(row: Row): LineageTask {\n const metadata = parseMetadata(row.metadata_json);\n const claimId = typeof metadata?.claim_id === 'string' ? metadata.claim_id : undefined;\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n root_asset_id: String(row.root_asset_id),\n target_asset_id: String(row.target_asset_id),\n task_type: String(row.task_type) as LineageTaskType,\n status: String(row.status) as LineageTaskStatus,\n instructions: typeof row.instructions === 'string' ? row.instructions : undefined,\n created_by: String(row.created_by) as LineageTaskActor,\n created_at: String(row.created_at),\n updated_at: String(row.updated_at),\n claimed_at: typeof row.claimed_at === 'string' ? row.claimed_at : undefined,\n started_at: typeof row.started_at === 'string' ? row.started_at : undefined,\n resolved_at: typeof row.resolved_at === 'string' ? row.resolved_at : undefined,\n cancelled_at: typeof row.cancelled_at === 'string' ? row.cancelled_at : undefined,\n resolved_generation_job_id: typeof row.resolved_generation_job_id === 'string' ? row.resolved_generation_job_id : undefined,\n resolved_asset_id: typeof row.resolved_asset_id === 'string' ? row.resolved_asset_id : undefined,\n claimed_by_claim_id: claimId,\n metadata,\n };\n}\n\nfunction eventFromRow(row: Row): LineageTaskEvent {\n return {\n id: String(row.id),\n task_id: String(row.task_id),\n event_type: String(row.event_type) as LineageTaskEvent['event_type'],\n actor: typeof row.actor === 'string' ? row.actor : undefined,\n message: typeof row.message === 'string' ? row.message : undefined,\n created_at: String(row.created_at),\n metadata: parseMetadata(row.metadata_json),\n };\n}\n\nfunction findTask(database: DatabaseSync, project: string, taskId: string): LineageTask | null {\n const row = database.prepare('select * from lineage_tasks where project_id = ? and id = ?').get(project, taskId) as Row | undefined;\n return row ? taskFromRow(row) : null;\n}\n\nfunction requireTask(database: DatabaseSync, project: string, taskId: string): LineageTask {\n const task = findTask(database, project, taskId);\n if (!task) throw new LineageTaskError(`Unknown lineage task: ${taskId}`, 404);\n return task;\n}\n\nfunction taskEvents(database: DatabaseSync, taskId: string): LineageTaskEvent[] {\n const rows = database.prepare('select * from lineage_task_events where task_id = ? order by created_at, rowid').all(taskId) as Row[];\n return rows.map(eventFromRow);\n}\n\nfunction recordEvent(database: DatabaseSync, taskId: string, eventType: string, actor?: string, message?: string, metadata?: Record<string, unknown>): void {\n database.prepare(`\n insert into lineage_task_events (id, task_id, event_type, actor, message, created_at, metadata_json)\n values (?, ?, ?, ?, ?, ?, ?)\n `).run(randomId('lineage_task_event'), taskId, eventType, actor || null, message || null, nowIso(), metadataJson(metadata));\n}\n\nfunction taskWithEvents(database: DatabaseSync, project: string, taskId: string): LineageTaskMutationResult {\n return { project, ok: true, task: requireTask(database, project, taskId), events: taskEvents(database, taskId) };\n}\n\nfunction assertChanged(result: { changes: number | bigint }, message: string): void {\n if (Number(result.changes) !== 1) throw new LineageTaskError(message, 409);\n}\n\nfunction transaction<T>(database: DatabaseSync, callback: () => T): T {\n database.exec('BEGIN IMMEDIATE');\n try {\n const value = callback();\n database.exec('COMMIT');\n return value;\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n}\n\nfunction taskReadWithEvents(database: DatabaseSync, project: string, taskId: string) {\n return { task: requireTask(database, project, taskId), events: taskEvents(database, taskId) };\n}\n\nexport function listLineageTasks(project: string, rootAssetId: string, statuses: LineageTaskStatus[] = activeStatuses): LineageTasksResponse {\n const normalizedProject = normalizeProject(project);\n const normalizedStatuses = statuses.map(normalizeStatus);\n const database = lineageDb();\n try {\n requireAsset(database, normalizedProject, rootAssetId);\n if (normalizedStatuses.length === 0) {\n return { project: normalizedProject, root_asset_id: rootAssetId, tasks: [], fetchedAt: nowIso() };\n }\n const placeholders = normalizedStatuses.map(() => '?').join(',');\n const rows = database.prepare(`\n select * from lineage_tasks\n where project_id = ? and root_asset_id = ? and status in (${placeholders})\n order by updated_at desc, created_at desc, id\n `).all(normalizedProject, rootAssetId, ...normalizedStatuses) as Row[];\n return { project: normalizedProject, root_asset_id: rootAssetId, tasks: rows.map(taskFromRow), fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function getLineageTask(project: string, taskId: string) {\n const normalizedProject = normalizeProject(project);\n const database = lineageDb();\n try {\n return { project: normalizedProject, ...taskReadWithEvents(database, normalizedProject, taskId) };\n } finally {\n database.close();\n }\n}\n\nexport function upsertLineageTask(project: string, fields: {\n createdBy: LineageTaskActor;\n instructions?: string;\n rootAssetId: string;\n targetAssetId: string;\n taskType: LineageTaskType;\n}): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const taskType = normalizeTaskType(fields.taskType);\n const taskId = taskIdFor(normalizedProject, fields.rootAssetId, fields.targetAssetId, taskType);\n const database = lineageDb();\n try {\n requireAsset(database, normalizedProject, fields.rootAssetId);\n requireAsset(database, normalizedProject, fields.targetAssetId);\n const existing = database.prepare(`\n select * from lineage_tasks\n where project_id = ? and root_asset_id = ? and target_asset_id = ? and task_type = ?\n and status in ('pending', 'claimed', 'in_progress')\n order by created_at desc limit 1\n `).get(normalizedProject, fields.rootAssetId, fields.targetAssetId, taskType) as Row | undefined;\n const instructions = fields.instructions?.trim() || undefined;\n if (existing) {\n const task = taskFromRow(existing);\n if (task.status !== 'pending' && instructions !== undefined && instructions !== task.instructions) {\n throw new LineageTaskError('Only pending lineage tasks can update instructions.', 409);\n }\n if (task.status === 'pending' && instructions !== undefined && instructions !== task.instructions) {\n const timestamp = nowIso();\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set instructions = ?, updated_at = ?\n where id = ? and status = 'pending'\n `).run(instructions, timestamp, task.id);\n assertChanged(result, 'Only pending lineage tasks can update instructions.');\n recordEvent(database, task.id, 'instructions_updated', fields.createdBy, 'Instructions updated.');\n });\n }\n return taskWithEvents(database, normalizedProject, task.id);\n }\n const closedTask = findTask(database, normalizedProject, taskId);\n if (closedTask) {\n const timestamp = nowIso();\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'pending', instructions = ?, created_by = ?, updated_at = ?,\n claimed_at = null, started_at = null, resolved_at = null, cancelled_at = null,\n resolved_generation_job_id = null, resolved_asset_id = null, metadata_json = null\n where id = ? and status not in ('pending', 'claimed', 'in_progress')\n `).run(instructions || null, fields.createdBy, timestamp, taskId);\n assertChanged(result, 'Lineage task changed while reopening.');\n recordEvent(database, taskId, 'created', fields.createdBy, 'Lineage task created.');\n });\n return taskWithEvents(database, normalizedProject, taskId);\n }\n const timestamp = nowIso();\n transaction(database, () => {\n database.prepare(`\n insert into lineage_tasks (\n id, project_id, root_asset_id, target_asset_id, task_type, status, instructions,\n created_by, created_at, updated_at, metadata_json\n ) values (?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, null)\n `).run(taskId, normalizedProject, fields.rootAssetId, fields.targetAssetId, taskType, instructions || null, fields.createdBy, timestamp, timestamp);\n recordEvent(database, taskId, 'created', fields.createdBy, 'Lineage task created.');\n });\n return taskWithEvents(database, normalizedProject, taskId);\n } finally {\n database.close();\n }\n}\n\nexport function updateLineageTaskInstructions(project: string, fields: { taskId: string; instructions: string }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const instructions = fields.instructions.trim();\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status !== 'pending') throw new LineageTaskError('Only pending lineage tasks can update instructions.', 409);\n const timestamp = nowIso();\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set instructions = ?, updated_at = ?\n where id = ? and status = 'pending'\n `).run(instructions || null, timestamp, task.id);\n assertChanged(result, 'Only pending lineage tasks can update instructions.');\n recordEvent(database, task.id, 'instructions_updated', 'human', 'Instructions updated.');\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function addLineageTaskComment(project: string, fields: { taskId: string; actor: string; message: string }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Comment actor');\n const message = fields.message.trim();\n if (!message) throw new LineageTaskError('Comment message is required');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n transaction(database, () => {\n recordEvent(database, task.id, 'comment_added', actor, message);\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function claimLineageTask(project: string, fields: { taskId: string; agentName: string }): LineageTaskClaimResult {\n const normalizedProject = normalizeProject(project);\n const agentName = normalizeActor(fields.agentName, 'Agent name');\n const beforeClaimDb = lineageDb();\n try {\n const task = requireTask(beforeClaimDb, normalizedProject, fields.taskId);\n if (task.status !== 'pending') throw new LineageTaskError('Only pending lineage tasks can be claimed.', 409);\n } finally {\n beforeClaimDb.close();\n }\n\n const claimResult = createAgentClaim({\n agentName,\n project: normalizedProject,\n scopeType: 'lineage_task',\n targetId: fields.taskId,\n targetTitle: fields.taskId,\n });\n if (!claimResult.claim) throw new LineageTaskError('Unable to create lineage task claim.', 500);\n const claim = claimResult.claim;\n\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status !== 'pending') {\n releaseAgentClaim(claimResult.claim_token);\n throw new LineageTaskError('Only pending lineage tasks can be claimed.', 409);\n }\n const timestamp = nowIso();\n const metadata = { ...(task.metadata || {}), claim_id: claim.id };\n try {\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'claimed', claimed_at = ?, updated_at = ?, metadata_json = ?\n where id = ? and status = 'pending'\n `).run(timestamp, timestamp, metadataJson(metadata), task.id);\n assertChanged(result, 'Only pending lineage tasks can be claimed.');\n recordEvent(database, task.id, 'claimed', agentName, 'Lineage task claimed.', { claim_id: claim.id });\n });\n } catch (error) {\n releaseAgentClaim(claimResult.claim_token);\n throw error;\n }\n return {\n ...taskWithEvents(database, normalizedProject, task.id),\n claim,\n claim_token: claimResult.claim_token,\n };\n } finally {\n database.close();\n }\n}\n\nexport function startLineageTask(project: string, fields: { taskId: string; claimToken: string }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const precheckDatabase = lineageDb();\n try {\n const task = requireTask(precheckDatabase, normalizedProject, fields.taskId);\n if (task.status !== 'claimed') throw new LineageTaskError('Only claimed lineage tasks can be started.', 409);\n } finally {\n precheckDatabase.close();\n }\n const validation = validateAgentClaimForWrite({\n claimToken: fields.claimToken,\n dangerLevel: 'enforce',\n project: normalizedProject,\n recordEvent: false,\n scopeType: 'lineage_task',\n targetId: fields.taskId,\n writeKind: 'lineage_task_start',\n });\n if (!validation.ok) throw new LineageTaskError(validation.message, 409);\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status !== 'claimed') throw new LineageTaskError('Only claimed lineage tasks can be started.', 409);\n if (task.claimed_by_claim_id && task.claimed_by_claim_id !== validation.claim.id) {\n throw new LineageTaskError('Claim token does not match the task claim.', 409);\n }\n const timestamp = nowIso();\n const metadata = { ...(task.metadata || {}), claim_id: validation.claim.id };\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'in_progress', started_at = ?, updated_at = ?, metadata_json = ?\n where id = ? and status = 'claimed'\n `).run(timestamp, timestamp, metadataJson(metadata), task.id);\n assertChanged(result, 'Only claimed lineage tasks can be started.');\n recordEvent(database, task.id, 'started', validation.claim.agent_name, 'Lineage task started.', { claim_id: validation.claim.id });\n });\n recordAgentClaimWriteAllowed(validation.claim, {\n dangerLevel: 'enforce',\n targetId: fields.taskId,\n writeKind: 'lineage_task_start',\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function overrideLineageTask(project: string, fields: {\n actor: string;\n instructions?: string;\n reason: string;\n taskId: string;\n}): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Override actor');\n const reason = fields.reason.trim();\n if (!reason) throw new LineageTaskError('Override reason is required');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (!['claimed', 'in_progress'].includes(task.status)) {\n throw new LineageTaskError(`Only claimed or in-progress lineage tasks can be overridden; task is ${task.status}.`, 409);\n }\n const timestamp = nowIso();\n const instructions = fields.instructions === undefined ? task.instructions : (fields.instructions.trim() || undefined);\n const metadata = metadataWithoutClaim(task.metadata);\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'pending', instructions = ?, claimed_at = null, started_at = null,\n updated_at = ?, metadata_json = ?\n where project_id = ? and id = ? and status in ('claimed', 'in_progress')\n `).run(instructions || null, timestamp, metadataJson(metadata), normalizedProject, task.id);\n assertChanged(result, `Only active lineage task ${task.id} could be overridden.`);\n if (task.claimed_by_claim_id) {\n revokeAgentClaimInDatabase(database, normalizedProject, task.claimed_by_claim_id, {\n actor,\n reason,\n });\n }\n recordEvent(database, task.id, 'human_override', actor, reason, {\n previous_claim_id: task.claimed_by_claim_id,\n previous_status: task.status,\n });\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function cancelLineageTask(project: string, fields: { taskId: string; actor: string; confirmWrite: boolean; override?: boolean }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Cancel actor');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status === 'cancelled') return { project: normalizedProject, ok: true, task, events: taskEvents(database, task.id) };\n if (!['pending', 'claimed', 'in_progress'].includes(task.status)) {\n throw new LineageTaskError(`Only open lineage tasks can be cancelled; task is ${task.status}.`, 409);\n }\n if (task.status !== 'pending' && !fields.override) {\n throw new LineageTaskError('Cancelling an active lineage task requires override=true.', 409);\n }\n const overridingActiveTask = fields.override === true && task.status !== 'pending';\n const metadata = overridingActiveTask ? metadataWithoutClaim(task.metadata) : task.metadata;\n const timestamp = nowIso();\n const cancelledTask = {\n ...task,\n cancelled_at: timestamp,\n claimed_at: overridingActiveTask ? undefined : task.claimed_at,\n claimed_by_claim_id: overridingActiveTask ? undefined : task.claimed_by_claim_id,\n started_at: overridingActiveTask ? undefined : task.started_at,\n status: 'cancelled' as const,\n updated_at: timestamp,\n metadata,\n };\n if (!fields.confirmWrite) return { project: normalizedProject, ok: true, dryRun: true as const, task: cancelledTask, events: taskEvents(database, task.id) };\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'cancelled', cancelled_at = ?, claimed_at = ?, started_at = ?,\n updated_at = ?, metadata_json = ?\n where id = ? and status = ?\n `).run(\n timestamp,\n overridingActiveTask ? null : task.claimed_at || null,\n overridingActiveTask ? null : task.started_at || null,\n timestamp,\n metadataJson(metadata),\n task.id,\n task.status\n );\n assertChanged(result, `Only ${task.status} lineage task ${task.id} could be cancelled.`);\n if (overridingActiveTask) {\n if (task.claimed_by_claim_id) {\n revokeAgentClaimInDatabase(database, normalizedProject, task.claimed_by_claim_id, {\n actor,\n reason: 'Lineage task cancelled by human override.',\n });\n }\n recordEvent(database, task.id, 'human_override', actor, 'Lineage task cancelled by human override.', {\n previous_claim_id: task.claimed_by_claim_id,\n previous_status: task.status,\n });\n }\n recordEvent(database, task.id, 'cancelled', actor, 'Lineage task cancelled.');\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function cancelLineageIterateTasksForAssets(project: string, fields: {\n actor: string;\n assetIds?: string[];\n confirmWrite: boolean;\n rootAssetId: string;\n}): LineageTaskMutationResult[] {\n const targetIds = fields.assetIds ? new Set(fields.assetIds) : undefined;\n return listLineageTasks(project, fields.rootAssetId, ['pending']).tasks\n .filter(task => task.task_type === 'iterate')\n .filter(task => !targetIds || targetIds.has(task.target_asset_id))\n .map(task => cancelLineageTask(project, {\n actor: fields.actor,\n confirmWrite: fields.confirmWrite,\n taskId: task.id,\n }));\n}\n\nexport function resolveLineageTask(project: string, fields: {\n actor: string;\n confirmWrite: boolean;\n resolvedAssetId?: string;\n resolvedGenerationJobId?: string;\n taskId: string;\n}): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Resolve actor');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (fields.resolvedAssetId) requireAsset(database, normalizedProject, fields.resolvedAssetId);\n if (task.status === 'resolved') return { project: normalizedProject, ok: true, task, events: taskEvents(database, task.id) };\n if (!['pending', 'claimed', 'in_progress'].includes(task.status)) {\n throw new LineageTaskError(`Only open lineage tasks can be resolved; task is ${task.status}.`, 409);\n }\n const timestamp = nowIso();\n const resolvedTask = {\n ...task,\n status: 'resolved' as const,\n resolved_asset_id: fields.resolvedAssetId,\n resolved_at: timestamp,\n resolved_generation_job_id: fields.resolvedGenerationJobId,\n updated_at: timestamp,\n };\n if (!fields.confirmWrite) return { project: normalizedProject, ok: true, dryRun: true as const, task: resolvedTask, events: taskEvents(database, task.id) };\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'resolved', resolved_at = ?, resolved_generation_job_id = ?, resolved_asset_id = ?, updated_at = ?\n where id = ? and status = ?\n `).run(timestamp, fields.resolvedGenerationJobId || null, fields.resolvedAssetId || null, timestamp, task.id, task.status);\n assertChanged(result, `Only ${task.status} lineage task ${task.id} could be resolved.`);\n recordEvent(database, task.id, 'resolved', actor, 'Lineage task resolved.', {\n resolved_asset_id: fields.resolvedAssetId,\n resolved_generation_job_id: fields.resolvedGenerationJobId,\n });\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n", "import { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { cancelLineageIterateTasksForAssets } from './assetLineageTasks';\nimport type {\n LineageWorkspace,\n LineageWorkspaceActor,\n LineageWorkspaceFields,\n LineageWorkspaceSnapshot,\n LineageWorkspaceStatus,\n LineageWorkspaceUpdateFields,\n} from '../shared/types';\n\ntype Row = Record<string, unknown>;\n\nconst actors = new Set<LineageWorkspaceActor>(['human', 'agent', 'system']);\nconst statuses = new Set<LineageWorkspaceStatus>(['active', 'paused', 'archived']);\n\nexport class LineageWorkspaceError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageWorkspaceError(error: unknown): error is LineageWorkspaceError {\n return error instanceof LineageWorkspaceError;\n}\n\nexport function lineageWorkspaceId(project: string, rootAssetId: string): string {\n return `${project}:lineage-workspace:${rootAssetId}`;\n}\n\nfunction ensureProject(database: DatabaseSync, project: string): void {\n const timestamp = nowIso();\n database.prepare(`\n insert into projects (id, product, created_at, updated_at)\n values (?, ?, ?, ?)\n on conflict(id) do update set product = excluded.product, updated_at = excluded.updated_at\n `).run(project, project, timestamp, timestamp);\n}\n\nfunction normalizeStatus(value: LineageWorkspaceStatus | undefined, fallback: LineageWorkspaceStatus): LineageWorkspaceStatus {\n const status = value || fallback;\n if (!statuses.has(status)) throw new LineageWorkspaceError(`Unsupported lineage workspace status: ${status}`);\n return status;\n}\n\nfunction normalizeActor(value: LineageWorkspaceActor | undefined): LineageWorkspaceActor {\n const actor = value || 'human';\n if (!actors.has(actor)) throw new LineageWorkspaceError(`Unsupported lineage workspace actor: ${actor}`);\n return actor;\n}\n\nfunction requireAsset(database: DatabaseSync, project: string, assetId: string): { id: string; title: string } {\n const row = database.prepare('select id, title from assets where project_id = ? and id = ?').get(project, assetId) as { id: string; title: string } | undefined;\n if (!row) throw new LineageWorkspaceError(`Unknown indexed asset: ${assetId}`, 404);\n return row;\n}\n\nfunction rowToWorkspace(row: Row): LineageWorkspace {\n return {\n id: String(row.id),\n project: String(row.project_id),\n root_asset_id: String(row.root_asset_id),\n title: String(row.title),\n status: String(row.status) as LineageWorkspaceStatus,\n notes: typeof row.notes === 'string' ? row.notes : undefined,\n created_by: String(row.created_by) as LineageWorkspaceActor,\n active_at: typeof row.active_at === 'string' ? row.active_at : undefined,\n created_at: String(row.created_at),\n updated_at: String(row.updated_at),\n };\n}\n\nfunction workspaceById(database: DatabaseSync, project: string, id: string): LineageWorkspace | null {\n const row = database.prepare('select * from lineage_workspaces where project_id = ? and id = ?').get(project, id) as Row | undefined;\n return row ? rowToWorkspace(row) : null;\n}\n\nfunction workspaceByRoot(database: DatabaseSync, project: string, rootAssetId: string): LineageWorkspace | null {\n const row = database.prepare('select * from lineage_workspaces where project_id = ? and root_asset_id = ?').get(project, rootAssetId) as Row | undefined;\n return row ? rowToWorkspace(row) : null;\n}\n\nfunction knownRoots(database: DatabaseSync, project: string): Array<{ root_asset_id: string; selected_at?: string }> {\n const rows = database.prepare(`\n select root_asset_id, max(selected_at) selected_at from asset_selections where project_id = ? group by root_asset_id\n union\n select root_asset_id, null selected_at from asset_layouts where project_id = ? group by root_asset_id\n union\n select parent_asset_id root_asset_id, null selected_at\n from asset_edges\n where project_id = ?\n and parent_asset_id not in (select child_asset_id from asset_edges where project_id = ?)\n group by parent_asset_id\n `).all(project, project, project, project) as Array<{ root_asset_id: string; selected_at?: string | null }>;\n const roots = new Map<string, { root_asset_id: string; selected_at?: string }>();\n for (const row of rows) {\n const existing = roots.get(row.root_asset_id);\n roots.set(row.root_asset_id, {\n root_asset_id: row.root_asset_id,\n selected_at: row.selected_at || existing?.selected_at,\n });\n }\n return [...roots.values()];\n}\n\nfunction seedLegacyWorkspaces(database: DatabaseSync, project: string): void {\n if (process.env.LINEAGE_DB_ACCESS === 'read-only') return;\n ensureProject(database, project);\n const timestamp = nowIso();\n const statement = database.prepare(`\n insert into lineage_workspaces (\n id, project_id, root_asset_id, title, status, notes, created_by, active_at, created_at, updated_at\n )\n select ?, ?, a.id, a.title || ' lineage', 'active', null, 'system', ?, ?, ?\n from assets a\n where a.project_id = ? and a.id = ?\n on conflict(project_id, root_asset_id) do nothing\n `);\n for (const root of knownRoots(database, project)) {\n statement.run(\n lineageWorkspaceId(project, root.root_asset_id),\n project,\n root.selected_at || null,\n timestamp,\n timestamp,\n project,\n root.root_asset_id\n );\n }\n}\n\nfunction inferredLegacyWorkspaces(database: DatabaseSync, project: string): LineageWorkspace[] {\n if (process.env.LINEAGE_DB_ACCESS !== 'read-only') return [];\n const persistedRoots = new Set(\n (database.prepare('select root_asset_id from lineage_workspaces where project_id = ?').all(project) as Array<{ root_asset_id: string }>)\n .map(row => row.root_asset_id),\n );\n const asset = database.prepare('select id, title from assets where project_id = ? and id = ?');\n return knownRoots(database, project).flatMap(root => {\n if (persistedRoots.has(root.root_asset_id)) return [];\n const row = asset.get(project, root.root_asset_id) as { id: string; title: string } | undefined;\n if (!row) return [];\n const timestamp = root.selected_at || nowIso();\n return [{\n active_at: root.selected_at,\n created_at: timestamp,\n created_by: 'system' as const,\n id: lineageWorkspaceId(project, root.root_asset_id),\n project,\n root_asset_id: root.root_asset_id,\n status: 'active' as const,\n title: `${row.title} lineage`,\n updated_at: timestamp,\n }];\n });\n}\n\nfunction sortWorkspaces(workspaces: LineageWorkspace[]): LineageWorkspace[] {\n const statusRank: Record<LineageWorkspaceStatus, number> = { active: 0, paused: 1, archived: 2 };\n return workspaces.sort((left, right) => statusRank[left.status] - statusRank[right.status]\n || (right.active_at || '').localeCompare(left.active_at || '')\n || right.updated_at.localeCompare(left.updated_at)\n || left.title.localeCompare(right.title));\n}\n\nfunction listRows(database: DatabaseSync, project: string): LineageWorkspace[] {\n return (database.prepare(`\n select * from lineage_workspaces\n where project_id = ?\n order by\n case status when 'active' then 0 when 'paused' then 1 else 2 end,\n active_at desc nulls last,\n updated_at desc,\n title\n `).all(project) as Row[]).map(rowToWorkspace);\n}\n\nexport function listLineageWorkspaces(project: string): LineageWorkspaceSnapshot {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const workspaces = sortWorkspaces([...listRows(database, project), ...inferredLegacyWorkspaces(database, project)]);\n return {\n project,\n active_workspace: workspaces.find(workspace => workspace.status !== 'archived') || null,\n workspaces,\n fetchedAt: nowIso(),\n };\n } finally {\n database.close();\n }\n}\n\nexport function inspectLineageWorkspace(project: string, workspaceId: string): LineageWorkspace {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const workspace = workspaceById(database, project, workspaceId)\n || workspaceByRoot(database, project, workspaceId)\n || inferredLegacyWorkspaces(database, project).find(item => item.id === workspaceId || item.root_asset_id === workspaceId);\n if (!workspace) throw new LineageWorkspaceError(`Unknown lineage workspace: ${workspaceId}`, 404);\n return workspace;\n } finally {\n database.close();\n }\n}\n\nexport function createLineageWorkspace(project: string, fields: LineageWorkspaceFields) {\n const rootAssetId = fields.rootAssetId.trim();\n if (!rootAssetId) throw new LineageWorkspaceError('Lineage workspace requires rootAssetId');\n const status = normalizeStatus(fields.status, 'active');\n const actor = normalizeActor(fields.createdBy);\n const database = lineageDb();\n try {\n const root = requireAsset(database, project, rootAssetId);\n const timestamp = nowIso();\n const workspace: LineageWorkspace = {\n id: lineageWorkspaceId(project, rootAssetId),\n project,\n root_asset_id: rootAssetId,\n title: fields.title?.trim() || `${root.title} lineage`,\n status,\n notes: fields.notes?.trim() || undefined,\n created_by: actor,\n active_at: fields.activate !== false && status !== 'archived' ? timestamp : undefined,\n created_at: timestamp,\n updated_at: timestamp,\n };\n if (!fields.confirmWrite) return { ok: true as const, dryRun: true as const, workspace };\n ensureProject(database, project);\n database.prepare(`\n insert into lineage_workspaces (\n id, project_id, root_asset_id, title, status, notes, created_by, active_at, created_at, updated_at\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n on conflict(project_id, root_asset_id) do update set\n title = excluded.title,\n status = excluded.status,\n notes = excluded.notes,\n active_at = coalesce(excluded.active_at, lineage_workspaces.active_at),\n updated_at = excluded.updated_at\n `).run(\n workspace.id,\n project,\n workspace.root_asset_id,\n workspace.title,\n workspace.status,\n workspace.notes || null,\n workspace.created_by,\n workspace.active_at || null,\n workspace.created_at,\n workspace.updated_at\n );\n return {\n ok: true as const,\n message: `Saved lineage workspace ${workspace.title}`,\n workspace: workspaceById(database, project, workspace.id),\n };\n } finally {\n database.close();\n }\n}\n\nexport function updateLineageWorkspace(project: string, workspaceId: string, fields: LineageWorkspaceUpdateFields) {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const current = workspaceById(database, project, workspaceId) || workspaceByRoot(database, project, workspaceId);\n if (!current) throw new LineageWorkspaceError(`Unknown lineage workspace: ${workspaceId}`, 404);\n const timestamp = nowIso();\n const next: LineageWorkspace = {\n ...current,\n title: fields.title?.trim() || current.title,\n status: normalizeStatus(fields.status, current.status),\n notes: fields.notes === undefined ? current.notes : fields.notes.trim() || undefined,\n active_at: fields.activate ? timestamp : current.active_at,\n updated_at: timestamp,\n };\n if (!fields.confirmWrite) return { ok: true as const, dryRun: true as const, workspace: next };\n database.prepare(`\n update lineage_workspaces\n set title = ?, status = ?, notes = ?, active_at = ?, updated_at = ?\n where project_id = ? and id = ?\n `).run(next.title, next.status, next.notes || null, next.active_at || null, timestamp, project, current.id);\n return {\n ok: true as const,\n message: `Updated lineage workspace ${next.title}`,\n workspace: workspaceById(database, project, current.id),\n };\n } finally {\n database.close();\n }\n}\n\nexport function activateLineageWorkspace(project: string, workspaceId: string, confirmWrite: boolean) {\n return updateLineageWorkspace(project, workspaceId, { activate: true, status: 'active', confirmWrite });\n}\n\nexport function archiveLineageWorkspace(project: string, workspaceId: string, confirmWrite: boolean) {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const current = workspaceById(database, project, workspaceId) || workspaceByRoot(database, project, workspaceId);\n if (!current) throw new LineageWorkspaceError(`Unknown lineage workspace: ${workspaceId}`, 404);\n const timestamp = nowIso();\n const next: LineageWorkspace = {\n ...current,\n status: 'archived',\n active_at: undefined,\n updated_at: timestamp,\n };\n if (!confirmWrite) return { ok: true as const, dryRun: true as const, workspace: next };\n cancelLineageIterateTasksForAssets(project, {\n actor: 'human',\n confirmWrite: true,\n rootAssetId: current.root_asset_id,\n });\n database.prepare(`\n update lineage_workspaces\n set status = 'archived', active_at = null, updated_at = ?\n where project_id = ? and id = ?\n `).run(timestamp, project, current.id);\n database.prepare('delete from asset_selections where project_id = ? and root_asset_id = ?').run(project, current.root_asset_id);\n return {\n ok: true as const,\n message: `Archived lineage workspace ${current.title}`,\n workspace: workspaceById(database, project, current.id),\n };\n } finally {\n database.close();\n }\n}\n\nexport function activeLineageWorkspaceRoot(project: string): string | undefined {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n return sortWorkspaces([...listRows(database, project), ...inferredLegacyWorkspaces(database, project)])\n .find(workspace => workspace.status !== 'archived')?.root_asset_id;\n } finally {\n database.close();\n }\n}\n", "import { AgentClaimError, listAgentClaims, validateAgentClaimForWrite } from './agentClaims';\nimport { lineageWorkspaceId } from './assetLineageWorkspaces';\n\nfunction channelOverlaps(left?: string, right?: string): boolean {\n return !left || !right || left === right;\n}\n\nfunction hasActiveLineageWorkspaceClaim(project: string, targetId: string, channel?: string): boolean {\n return listAgentClaims(project).claims.some(claim => {\n if (claim.project !== project || claim.status !== 'active' || claim.derived_state === 'expired') return false;\n if (claim.scope_type === 'lineage_workspace') return claim.target_id === targetId;\n return claim.scope_type === 'project_channel' && channelOverlaps(channel, claim.channel);\n });\n}\n\nexport function requireLineageWorkspaceClaimForWrite(fields: {\n channel?: string;\n claimToken?: string;\n confirmWrite: boolean;\n project: string;\n rootAssetId: string;\n writeKind: string;\n}): void {\n if (!fields.confirmWrite) return;\n const targetId = lineageWorkspaceId(fields.project, fields.rootAssetId);\n if (!fields.claimToken && !hasActiveLineageWorkspaceClaim(fields.project, targetId, fields.channel)) return;\n const validation = validateAgentClaimForWrite({\n channel: fields.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n dangerLevel: 'enforce',\n project: fields.project,\n scopeType: 'lineage_workspace',\n targetId,\n writeKind: fields.writeKind,\n });\n if (!validation.ok) {\n const status = validation.code === 'claim_required' || validation.code === 'claim_token_invalid' ? 401 : 409;\n throw new AgentClaimError(validation.message, status, validation.code, validation.conflicts);\n }\n}\n", "import { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { packageRoot } from './assetCore';\n\nconst require = createRequire(import.meta.url);\n\nexport function lineageCliLauncher(channel = process.env.LINEAGE_CHANNEL): string {\n if (channel === 'dev') {\n const sourceCli = join(packageRoot, 'src', 'cli', 'lineage-dev.ts');\n const builtCli = join(packageRoot, 'dist', 'cli', 'lineage-dev.js');\n return existsSync(sourceCli)\n ? `${shellQuote(process.execPath)} --import ${shellQuote(require.resolve('tsx'))} ${shellQuote(sourceCli)}`\n : `${shellQuote(process.execPath)} ${shellQuote(builtCli)}`;\n }\n if (channel === 'preview') return 'lineage-preview';\n if (channel === 'stable') return 'lineage-stable';\n throw new Error('LINEAGE_CHANNEL must be stable, preview, or dev before generating a Lineage command');\n}\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nexport function lineageRuntimeSelector(databasePath?: string): string {\n const manifest = process.env.LINEAGE_PROFILE_MANIFEST?.trim();\n const database = databasePath || process.env.LINEAGE_DB || join(packageRoot, '.lineage', 'asset-lineage.sqlite');\n return manifest ? `--profile ${shellQuote(manifest)}` : `--db ${shellQuote(database)}`;\n}\n\nexport function lineageCliCommand(command: string): string {\n const normalized = command.trim().replace(/\\s+--json$/, '');\n return `${lineageCliLauncher()} ${normalized} ${lineageRuntimeSelector()} --json`;\n}\n", "import type { LineageBriefResponse, LineageSelectedChildFields } from '../shared/types';\nimport { requireEdgeSummary } from '../shared/edgeSummary';\nimport { AgentClaimError, validateAgentClaimForWrite } from './agentClaims';\nimport { getLineageNextAsset, getLineageWriteClaimContext, LineageError, linkLineageAssets, listLineageRerollRequests } from './assetLineage';\nimport { nowIso } from './assetLineageDb';\nimport { lineageWorkspaceId } from './assetLineageWorkspaces';\nimport { lineageCliCommand, shellQuote } from './lineageRuntimeCommand';\n\nfunction lineageCommand(command: string, project: string, rootAssetId: string): string {\n return lineageCliCommand(`${command} --project ${shellQuote(project)} --root ${shellQuote(rootAssetId)}`);\n}\n\nfunction linkChildCommand(project: string, rootAssetId: string): string {\n return lineageCliCommand(`link-child --project ${shellQuote(project)} --root ${shellQuote(rootAssetId)} --child <asset-id> --summary \"<one-or-two-words>\" --confirm-write`);\n}\n\nfunction rerollImportGuidance(rootAssetId: string, targetAssetId: string): string {\n return `Use lineage reroll plan --root ${rootAssetId} --target ${targetAssetId} and lineage reroll import instead.`;\n}\n\nexport function getLineageBrief(project: string, rootAssetId?: string): LineageBriefResponse {\n const next = getLineageNextAsset(project, rootAssetId);\n const assets = next.next_assets;\n const asset = next.next_asset;\n const referenceAssetIds = assets.map(item => item.asset_id);\n const rationale = next.selections.map(selection => selection.notes).find(Boolean) || asset?.selection_note || next.selection?.notes;\n const channels = [...new Set(assets.map(item => item.channel || 'unknown'))];\n const campaigns = [...new Set(assets.map(item => item.campaign || 'unknown'))];\n const prompt = assets.length > 0\n ? [\n assets.length === 1\n ? `Create 3-4 variations from asset ${assets[0].asset_id} (${assets[0].title}).`\n : `Create 3-4 variations using these ${assets.length} selected references: ${referenceAssetIds.join(', ')}.`,\n rationale ? `Preserve this selection rationale: ${rationale}` : 'Preserve the strongest visible ideas while exploring distinct alternatives.',\n `Keep project=${project}, root=${next.root_asset_id}, channels=${channels.join(',')}, campaigns=${campaigns.join(',')}.`,\n 'After generation, index outputs and link chosen children with lineage link-child.',\n ].join(' ')\n : 'Select one to three latest lineage candidates before generating variations.';\n return {\n project,\n root_asset_id: next.root_asset_id,\n strategy: next.strategy,\n selection_mode: next.selection_mode,\n recommended_action: next.recommended_action,\n reason: next.reason,\n next_asset: asset,\n next_assets: assets,\n selection: next.selection,\n selections: next.selections,\n latest: next.latest,\n warnings: next.warnings,\n brief: {\n title: asset ? `Evolve ${assets.length > 1 ? `${assets.length} selected bases` : asset.title}` : 'Choose next lineage base',\n objective: asset ? 'Generate the next branch of visual variations from the selected lineage base or bases.' : 'Resolve the next base before generation.',\n prompt,\n reference_asset_id: asset?.asset_id,\n reference_asset_ids: referenceAssetIds,\n rationale,\n },\n handoff: {\n next_command: lineageCommand('next', project, next.root_asset_id),\n inspect_command: asset ? lineageCliCommand(`inspect --project ${shellQuote(project)} --asset-id ${shellQuote(asset.asset_id)}`) : undefined,\n link_child_command: asset ? linkChildCommand(project, next.root_asset_id) : undefined,\n },\n fetchedAt: nowIso(),\n };\n}\n\nexport function linkSelectedLineageChild(project: string, fields: LineageSelectedChildFields) {\n const summary = fields.summaryActor ? requireEdgeSummary(fields.summary) : fields.summary;\n const next = getLineageNextAsset(project, fields.rootAssetId);\n if (!next.next_asset) throw new LineageError('Cannot link child until a next base is selected or unambiguous');\n const rerollRequests = listLineageRerollRequests(project, next.root_asset_id).requests;\n const pendingRerollForParent = rerollRequests.find(request => request.node_asset_id === next.next_asset?.asset_id);\n if (pendingRerollForParent && fields.confirmWrite) {\n throw new LineageError(\n `Pending re-roll exists for ${pendingRerollForParent.node_asset_id}. lineage link-child creates a visible child variation edge; it does not re-roll the same node. ${rerollImportGuidance(next.root_asset_id, pendingRerollForParent.node_asset_id)} Cancel the re-roll first if you intentionally want a new child variation.`,\n 409\n );\n }\n if (fields.confirmWrite) {\n const claimContext = getLineageWriteClaimContext(project, next.next_asset.asset_id);\n const validation = validateAgentClaimForWrite({\n channel: claimContext.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n dangerLevel: 'enforce',\n project,\n scopeType: 'lineage_workspace',\n targetId: lineageWorkspaceId(project, claimContext.rootAssetId),\n writeKind: 'link_child',\n });\n if (!validation.ok) throw new AgentClaimError(validation.message, validation.code === 'claim_required' ? 401 : 403, validation.code, validation.conflicts);\n }\n const result = linkLineageAssets(project, {\n childAssetId: fields.childAssetId,\n confirmWrite: fields.confirmWrite,\n claimToken: fields.claimToken,\n parentAssetId: next.next_asset.asset_id,\n summary,\n summaryActor: fields.summaryActor,\n });\n return {\n ...result,\n root_asset_id: next.root_asset_id,\n parent_asset_id: next.next_asset.asset_id,\n child_asset_id: fields.childAssetId,\n reference_asset_ids: next.next_assets.map(asset => asset.asset_id),\n warning: [\n pendingRerollForParent\n ? `Pending re-roll exists for ${pendingRerollForParent.node_asset_id}. link-child would create a visible child variation; use reroll plan/import to update the same node attempt.`\n : undefined,\n rerollRequests.length > 0 && !pendingRerollForParent\n ? `This lineage has ${rerollRequests.length} pending re-roll target(s). link-child is only for new visible child variations, not re-roll attempts.`\n : undefined,\n next.next_assets.length > 1\n ? 'Linked child to the primary selected base; add explicit edges to other selected references if the child derives from them too.'\n : undefined,\n ].filter(Boolean).join(' ') || undefined,\n };\n}\n", "import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { defaultProject, repoRoot } from './assetCore';\nimport { getLineageNextAsset, getLineageSnapshot, indexLineageAssets, listLineageRerollRequests, recordLineageRerollAttempt } from './assetLineage';\nimport { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { cancelLineageIterateTasksForAssets, listLineageTasks, resolveLineageTask } from './assetLineageTasks';\nimport { activeLineageWorkspaceRoot } from './assetLineageWorkspaces';\nimport { contentTypeFor, fileSha256 } from './localReview';\nimport { lineageCliCommand } from './lineageRuntimeCommand';\nimport { createGenerationOutputManifestDraft, parseGenerationOutputManifest, type GenerationOutputManifest } from '../shared/generationOutputManifest';\nimport type {\n GenerationHandoffPacket,\n GenerationImportResponse,\n GenerationInspectResponse,\n GenerationJob,\n GenerationJobInput,\n GenerationJobOutput,\n GenerationJobReceipt,\n GenerationPlanResponse,\n GenerationProvider,\n GenerationSourceMode,\n LineageNextResponse,\n LineageRerollRequest,\n} from '../shared/types';\n\nconst legacyAdapterVersion = 'generation-receipts-v1';\nconst manifestAdapterVersion = 'generation-receipts-v2';\nconst provider: GenerationProvider = 'codex-handoff';\n\nclass GenerationReceiptError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isGenerationReceiptError(error: unknown): error is GenerationReceiptError {\n return error instanceof GenerationReceiptError;\n}\n\nfunction jobId(): string {\n return `gen-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;\n}\n\nfunction quote(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction parseJson<T>(value: string | null | undefined, fallback: T): T {\n if (!value) return fallback;\n return JSON.parse(value) as T;\n}\n\nfunction positiveInteger(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) > 0;\n}\n\nfunction resolveLineageSelection(project: string): LineageNextResponse {\n const rootAssetId = activeLineageWorkspaceRoot(project);\n if (!rootAssetId) throw new GenerationReceiptError('No active lineage workspace for generation planning');\n const next = getLineageNextAsset(project, rootAssetId);\n if (!next.next_asset) throw new GenerationReceiptError(`No clear lineage next asset: ${next.reason}`);\n if (next.strategy !== 'selected') throw new GenerationReceiptError('Generation v1 requires an explicit selected lineage next base');\n if (next.selection_mode !== 'multiple' && next.selection?.asset_id !== next.next_asset.asset_id) throw new GenerationReceiptError('Generation v1 requires one explicit selected lineage next base');\n return next;\n}\n\nfunction selectedParents(next: LineageNextResponse) {\n const parents = next.next_assets.length > 0 ? next.next_assets : next.next_asset ? [next.next_asset] : [];\n if (parents.length === 0) throw new GenerationReceiptError('Missing lineage next base');\n return parents;\n}\n\nfunction parentMappings(next: LineageNextResponse, perBaseCount: number) {\n return selectedParents(next).map((parent, parentIndex) => ({\n parent,\n output_indexes: Array.from({ length: perBaseCount }, (_value, index) => parentIndex * perBaseCount + index),\n }));\n}\n\nfunction buildHandoff(\n project: string,\n id: string,\n prompt: string,\n count: number,\n perBaseCount: number,\n next: LineageNextResponse,\n inputs: GenerationJobInput[],\n): GenerationHandoffPacket {\n const parent = next.next_asset;\n if (!parent) throw new GenerationReceiptError('Missing lineage next base');\n const parents = parentMappings(next, perBaseCount);\n const outputManifest = createGenerationOutputManifestDraft({ id, expected_output_count: count, inputs });\n const importCommand = lineageCliCommand(`generate image import --project ${quote(project)} --job-id ${quote(id)} --manifest ${quote('.asset-scratch/generation-output-manifest.json')} --confirm-write`);\n return {\n schema_version: 'lineage.generation_handoff.v2', provider, project, job_id: id, prompt, expected_output_count: count,\n per_base_count: next.selection_mode === 'multiple' ? perBaseCount : undefined,\n lineage: {\n root_asset_id: next.root_asset_id, parent_asset_id: parent.asset_id, selection_strategy: next.strategy,\n parent_title: parent.title, parent_local_path: parent.local_path, parent_s3_key: parent.s3_key,\n parents: parents.length > 1 ? parents.map(mapping => ({\n parent_asset_id: mapping.parent.asset_id, parent_title: mapping.parent.title,\n parent_local_path: mapping.parent.local_path, parent_s3_key: mapping.parent.s3_key, output_indexes: mapping.output_indexes,\n })) : undefined,\n },\n instructions: [\n 'Use Codex image generation outside Lineage server code.',\n 'Write generated output files under .asset-scratch before import.',\n 'Do not call live provider APIs from the CLI or server.',\n 'Fill every output_manifest entry with its generated file path and a one- or two-word edge summary.',\n 'Import the completed manifest with --confirm-write to persist every lineage child.',\n ],\n import_command: importCommand,\n output_manifest: outputManifest,\n guardrails: { live_generation: false, external_services: false, output_root: '.asset-scratch', confirm_write_required: true },\n };\n}\n\nfunction buildRerollHandoff(project: string, id: string, prompt: string, rootAssetId: string, target: { asset_id: string; title: string; local_path?: string; s3_key?: string }, request: LineageRerollRequest): GenerationHandoffPacket {\n const importCommand = lineageCliCommand(`reroll import --project ${quote(project)} --job-id ${quote(id)} --file <.asset-scratch-file> --confirm-write`);\n return {\n schema_version: 'lineage.generation_handoff.v1',\n provider,\n project,\n job_id: id,\n prompt,\n expected_output_count: 1,\n lineage: {\n root_asset_id: rootAssetId,\n parent_asset_id: target.asset_id,\n selection_strategy: 'reroll_request',\n parent_title: target.title,\n parent_local_path: target.local_path,\n parent_s3_key: target.s3_key,\n },\n instructions: [\n 'Use Codex image generation outside Lineage server code.',\n 'Write the regenerated output file under .asset-scratch before import.',\n 'Do not call live provider APIs from the CLI or server.',\n 'Import exactly one output with reroll import, not link-child or generate image import.',\n `Resolve re-roll request ${request.id}; do not create a visible lineage child edge.`,\n ],\n import_command: importCommand,\n guardrails: { live_generation: false, external_services: false, output_root: '.asset-scratch', confirm_write_required: true },\n };\n}\n\nfunction inputsFrom(jobIdValue: string, project: string, next: LineageNextResponse): GenerationJobInput[] {\n return selectedParents(next).map((parent, position) => ({\n id: `${jobIdValue}:input:${position}`,\n job_id: jobIdValue,\n project_id: project,\n asset_id: parent.asset_id,\n root_asset_id: next.root_asset_id,\n role: 'lineage_next_base',\n position,\n selection_strategy: next.strategy,\n selection_snapshot: next,\n }));\n}\n\nfunction receiptFrom(row: Record<string, unknown>): GenerationJobReceipt {\n return {\n id: String(row.id),\n job_id: String(row.job_id),\n receipt_type: row.receipt_type as GenerationJobReceipt['receipt_type'],\n status: row.status as GenerationJobReceipt['status'],\n command: String(row.command),\n payload: parseJson(String(row.payload_json), null),\n created_at: String(row.created_at),\n };\n}\n\nfunction outputFrom(row: Record<string, unknown>): GenerationJobOutput {\n const edgeSummary = typeof row.edge_summary === 'string' && row.edge_summary.length > 0 ? row.edge_summary : undefined;\n return {\n id: String(row.id),\n job_id: String(row.job_id),\n project_id: String(row.project_id),\n output_index: Number(row.output_index),\n file_path: String(row.file_path),\n checksum_sha256: String(row.checksum_sha256),\n size_bytes: Number(row.size_bytes),\n content_type: String(row.content_type),\n imported_asset_id: String(row.imported_asset_id),\n parent_asset_id: String(row.parent_asset_id),\n imported_at: String(row.imported_at),\n ...(edgeSummary ? { edge_summary: edgeSummary } : {}),\n };\n}\n\nexport function loadGenerationJob(database: DatabaseSync, project: string, id: string): GenerationJob {\n const row = database.prepare('select * from generation_jobs where project_id = ? and id = ?').get(project, id) as Record<string, unknown> | undefined;\n if (!row) throw new GenerationReceiptError(`Unknown generation job: ${id}`, 404);\n const inputRows = database.prepare('select * from generation_job_inputs where job_id = ? order by position').all(id) as Array<Record<string, unknown>>;\n const inputs = inputRows.map(input => ({\n id: String(input.id),\n job_id: String(input.job_id),\n project_id: String(input.project_id),\n asset_id: String(input.asset_id),\n root_asset_id: String(input.root_asset_id),\n role: input.role as GenerationJobInput['role'],\n position: Number(input.position),\n selection_strategy: String(input.selection_strategy),\n selection_snapshot: parseJson<LineageNextResponse>(String(input.selection_snapshot_json), {} as LineageNextResponse),\n }));\n const outputs = (database.prepare('select * from generation_job_outputs where job_id = ? order by output_index').all(id) as Array<Record<string, unknown>>).map(outputFrom);\n const receipts = (database.prepare('select * from generation_job_receipts where job_id = ? order by created_at, id').all(id) as Array<Record<string, unknown>>).map(receiptFrom);\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n provider: row.provider as GenerationProvider,\n adapter_version: String(row.adapter_version) as GenerationJob['adapter_version'],\n source_mode: String(row.source_mode) as GenerationSourceMode,\n root_asset_id: String(row.root_asset_id),\n prompt: String(row.prompt),\n expected_output_count: Number(row.expected_output_count),\n status: row.status as GenerationJob['status'],\n output_dir: typeof row.output_dir === 'string' ? row.output_dir : undefined,\n handoff: parseJson<GenerationHandoffPacket>(String(row.handoff_json), {} as GenerationHandoffPacket),\n created_at: String(row.created_at),\n updated_at: String(row.updated_at),\n imported_at: typeof row.imported_at === 'string' ? row.imported_at : undefined,\n inputs,\n outputs,\n receipts,\n };\n}\n\nfunction insertReceipt(database: DatabaseSync, id: string, type: 'plan' | 'import' | 'error', command: string, payload: unknown): void {\n database.prepare(`\n insert into generation_job_receipts (id, job_id, receipt_type, status, command, payload_json, created_at)\n values (?, ?, ?, 'ok', ?, ?, ?)\n `).run(`${id}:receipt:${type}:${Date.now()}`, id, type, command, JSON.stringify(payload), nowIso());\n}\n\nexport function planImageGeneration(project = defaultProject, fields: { prompt: string; count?: number; dryRun?: boolean; fromLineageSelection: boolean; perBaseCount?: number }): GenerationPlanResponse {\n const prompt = fields.prompt.trim();\n if (!prompt) throw new GenerationReceiptError('Missing --prompt');\n if (!fields.fromLineageSelection) throw new GenerationReceiptError('Generation v1 requires --from-lineage-selection');\n const next = resolveLineageSelection(project);\n const parentCount = selectedParents(next).length;\n if (parentCount > 1 && !positiveInteger(fields.perBaseCount)) throw new GenerationReceiptError('Multi-parent generation requires --per-base-count');\n const perBaseCount = parentCount > 1 ? Number(fields.perBaseCount) : Number(fields.count ?? fields.perBaseCount);\n const count = parentCount * perBaseCount;\n if (!positiveInteger(perBaseCount)) throw new GenerationReceiptError('Generation count must be a positive integer');\n if (fields.count !== undefined && fields.count !== count) throw new GenerationReceiptError(`Generation count mismatch: expected ${count} from selected bases, received ${fields.count}`);\n const id = jobId();\n const inputs = inputsFrom(id, project, next);\n const handoff = buildHandoff(project, id, prompt, count, perBaseCount, next, inputs);\n const mappings = parentMappings(next, perBaseCount).map(mapping => ({ parent_asset_id: mapping.parent.asset_id, output_indexes: mapping.output_indexes }));\n const timestamp = nowIso();\n const preview: GenerationJob = {\n id,\n project_id: project,\n provider,\n adapter_version: manifestAdapterVersion,\n source_mode: 'lineage_selection',\n root_asset_id: next.root_asset_id,\n prompt,\n expected_output_count: count,\n status: 'planned',\n output_dir: '.asset-scratch',\n handoff,\n created_at: timestamp,\n updated_at: timestamp,\n inputs,\n outputs: [],\n receipts: [{\n id: `${id}:receipt:plan:preview`,\n job_id: id,\n receipt_type: 'plan',\n status: 'ok',\n command: 'generate image plan',\n payload: { prompt, expected_output_count: count, per_base_count: parentCount > 1 ? perBaseCount : undefined, lineage: handoff.lineage, parent_mappings: mappings },\n created_at: timestamp,\n }],\n };\n if (fields.dryRun) return { ok: true, command: 'generate image plan', project, dryRun: true, wouldWrite: true, job: preview };\n\n const database = lineageDb();\n try {\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare(`\n insert into generation_jobs (\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at\n ) values (?, ?, ?, ?, 'lineage_selection', ?, ?, ?, 'planned', ?, ?, ?, ?)\n `).run(id, project, provider, manifestAdapterVersion, next.root_asset_id, prompt, count, '.asset-scratch', JSON.stringify(handoff), timestamp, timestamp);\n const insertInput = database.prepare('insert into generation_job_inputs (id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json) values (?, ?, ?, ?, ?, ?, ?, ?, ?)');\n for (const input of inputs) insertInput.run(input.id, id, project, input.asset_id, input.root_asset_id, input.role, input.position, input.selection_strategy, JSON.stringify(next));\n insertReceipt(database, id, 'plan', 'generate image plan', preview.receipts[0].payload);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n return { ok: true, command: 'generate image plan', project, job: loadGenerationJob(database, project, id) };\n } finally {\n database.close();\n }\n}\n\nexport function planImageReroll(project = defaultProject, fields: { rootAssetId: string; targetAssetId: string; prompt: string; dryRun?: boolean }): GenerationPlanResponse {\n const prompt = fields.prompt.trim();\n if (!prompt) throw new GenerationReceiptError('Missing --prompt');\n if (!fields.rootAssetId) throw new GenerationReceiptError('Missing --root');\n if (!fields.targetAssetId) throw new GenerationReceiptError('Missing --target');\n const snapshot = getLineageSnapshot(project, fields.rootAssetId);\n const target = snapshot.nodes.find(node => node.asset_id === fields.targetAssetId);\n if (!target) throw new GenerationReceiptError(`Re-roll target is not in lineage: ${fields.targetAssetId}`, 404);\n const request = listLineageRerollRequests(project, snapshot.root_asset_id).requests.find(item => item.node_asset_id === fields.targetAssetId);\n if (!request) throw new GenerationReceiptError(`No pending re-roll request for ${fields.targetAssetId}`);\n const id = jobId();\n const timestamp = nowIso();\n const handoff = buildRerollHandoff(project, id, prompt, snapshot.root_asset_id, target, request);\n const input: GenerationJobInput = {\n id: `${id}:input:0`,\n job_id: id,\n project_id: project,\n asset_id: target.asset_id,\n root_asset_id: snapshot.root_asset_id,\n role: 'reroll_target',\n position: 0,\n selection_strategy: 'reroll_request',\n selection_snapshot: {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: 'selected',\n selection_mode: 'single',\n recommended_action: 'evolve_variations',\n reason: 'user_selected',\n next_asset: target,\n next_assets: [target],\n latest: snapshot.latest,\n selected: [target.asset_id],\n selection: null,\n selections: [],\n candidates: snapshot.nodes,\n warnings: ['Re-roll target: import output as an attempt, not a lineage child.'],\n fetchedAt: timestamp,\n },\n };\n const preview: GenerationJob = {\n id,\n project_id: project,\n provider,\n adapter_version: legacyAdapterVersion,\n source_mode: 'lineage_reroll',\n root_asset_id: snapshot.root_asset_id,\n prompt,\n expected_output_count: 1,\n status: 'planned',\n output_dir: '.asset-scratch',\n handoff,\n created_at: timestamp,\n updated_at: timestamp,\n inputs: [input],\n outputs: [],\n receipts: [{\n id: `${id}:receipt:plan:preview`,\n job_id: id,\n receipt_type: 'plan',\n status: 'ok',\n command: 'reroll plan',\n payload: { prompt, expected_output_count: 1, lineage: handoff.lineage, reroll_request_id: request.id },\n created_at: timestamp,\n }],\n };\n if (fields.dryRun) return { ok: true, command: 'reroll plan', project, dryRun: true, wouldWrite: true, job: preview };\n const database = lineageDb();\n try {\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare(`\n insert into generation_jobs (\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at\n ) values (?, ?, ?, ?, 'lineage_reroll', ?, ?, 1, 'planned', ?, ?, ?, ?)\n `).run(id, project, provider, legacyAdapterVersion, snapshot.root_asset_id, prompt, '.asset-scratch', JSON.stringify(handoff), timestamp, timestamp);\n database.prepare('insert into generation_job_inputs (id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json) values (?, ?, ?, ?, ?, ?, ?, ?, ?)')\n .run(input.id, id, project, input.asset_id, input.root_asset_id, input.role, input.position, input.selection_strategy, JSON.stringify(input.selection_snapshot));\n insertReceipt(database, id, 'plan', 'reroll plan', preview.receipts[0].payload);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n return { ok: true, command: 'reroll plan', project, job: loadGenerationJob(database, project, id) };\n } finally {\n database.close();\n }\n}\n\nfunction parentForOutput(job: GenerationJob, outputIndex: number): string {\n const inputs = job.inputs.filter(input => input.role === 'lineage_next_base');\n if (inputs.length === 0) throw new GenerationReceiptError('Generation job has no lineage_next_base input');\n if (inputs.length === 1) return inputs[0].asset_id;\n if (job.expected_output_count % inputs.length !== 0) throw new GenerationReceiptError('Generation job has invalid parent mapping');\n return inputs[Math.floor(outputIndex / (job.expected_output_count / inputs.length))]?.asset_id || inputs[inputs.length - 1].asset_id;\n}\n\nfunction parentInputs(job: GenerationJob): GenerationJobInput[] {\n const inputs = job.inputs.filter(input => input.role === 'lineage_next_base');\n if (inputs.length === 0) throw new GenerationReceiptError('Generation job has no lineage_next_base input');\n return inputs;\n}\n\nfunction parentFilesFor(job: GenerationJob, parentFiles: Record<string, string[]>): Array<{ file: string; parentAssetId: string }> {\n const inputs = parentInputs(job);\n const expectedPerParent = job.expected_output_count / inputs.length;\n if (!Number.isInteger(expectedPerParent)) throw new GenerationReceiptError('Generation job has invalid parent mapping');\n const allowedParents = new Set(inputs.map(input => input.asset_id));\n const seenParents = new Set<string>();\n const mapped: Array<{ file: string; parentAssetId: string }> = [];\n for (const parentAssetId of Object.keys(parentFiles)) {\n if (!allowedParents.has(parentAssetId)) throw new GenerationReceiptError(`Unknown generation parent mapping: ${parentAssetId}`);\n if (seenParents.has(parentAssetId)) throw new GenerationReceiptError(`Duplicate generation parent mapping: ${parentAssetId}`);\n seenParents.add(parentAssetId);\n }\n for (const input of inputs) {\n const files = (parentFiles[input.asset_id] || []).map(file => file.trim()).filter(Boolean);\n if (files.length === 0) throw new GenerationReceiptError(`Missing generation parent mapping for ${input.asset_id}`);\n if (files.length !== expectedPerParent) throw new GenerationReceiptError(`Parent ${input.asset_id} requires ${expectedPerParent} output file${expectedPerParent === 1 ? '' : 's'}, received ${files.length}`);\n for (const file of files) mapped.push({ file, parentAssetId: input.asset_id });\n }\n return mapped;\n}\n\nfunction orderedFilesFor(job: GenerationJob, files: string[]): Array<{ file: string; parentAssetId: string }> {\n return files.map((file, index) => ({ file, parentAssetId: parentForOutput(job, index) }));\n}\n\nexport function inspectImageGeneration(project = defaultProject, jobIdValue: string): GenerationInspectResponse {\n if (!jobIdValue) throw new GenerationReceiptError('Missing --job-id');\n const database = lineageDb();\n try {\n return { ok: true, command: 'generate image inspect', project, job: loadGenerationJob(database, project, jobIdValue) };\n } finally {\n database.close();\n }\n}\n\nfunction isPathInside(child: string, parent: string): boolean {\n const rel = relative(parent, child);\n return Boolean(rel) && !rel.startsWith('..') && !rel.startsWith('/');\n}\n\nfunction scratchCandidate(file: string): { candidate: string; scratchRoot: string } {\n const scratchRoot = resolve(repoRoot, '.asset-scratch');\n const candidate = file.startsWith('.asset-scratch/') || resolve(file).startsWith(scratchRoot)\n ? resolve(repoRoot, file)\n : resolve(scratchRoot, file);\n if (!isPathInside(candidate, scratchRoot)) throw new GenerationReceiptError(`Import file must be under .asset-scratch: ${file}`);\n return { candidate, scratchRoot };\n}\n\nfunction resolveScratchManifestPath(file: string): string {\n const { candidate, scratchRoot } = scratchCandidate(file);\n return relative(scratchRoot, candidate);\n}\n\nfunction resolveScratchFile(file: string): { relativePath: string; checksum: string; size: number; contentType: string; assetId: string } {\n const { candidate, scratchRoot } = scratchCandidate(file);\n if (!existsSync(candidate)) throw new GenerationReceiptError(`Missing import file: ${file}`, 404);\n const realScratchRoot = realpathSync(scratchRoot);\n const realCandidate = realpathSync(candidate);\n if (!isPathInside(realCandidate, realScratchRoot)) throw new GenerationReceiptError(`Import file must be under .asset-scratch: ${file}`);\n const stats = statSync(candidate);\n if (!stats.isFile()) throw new GenerationReceiptError(`Import path is not a file: ${file}`);\n const checksum = fileSha256(candidate);\n return {\n relativePath: relative(scratchRoot, candidate),\n checksum,\n size: stats.size,\n contentType: contentTypeFor(candidate),\n assetId: `local-${checksum.slice(0, 12)}`,\n };\n}\n\ninterface GenerationImportRow {\n edgeSummary?: string;\n file: string;\n parentAssetId: string;\n}\n\nfunction generationManifestConflict(): never {\n throw new GenerationReceiptError('Generation import already exists with different output, summary, or provenance', 409);\n}\n\nfunction confirmManifestRetry(project: string, job: GenerationJob, manifest: GenerationOutputManifest): GenerationImportResponse {\n if (job.outputs.length !== manifest.outputs.length) generationManifestConflict();\n const database = lineageDb();\n try {\n for (const expected of manifest.outputs) {\n const recorded = job.outputs.find(output => output.output_index === expected.output_index);\n if (\n !recorded\n || recorded.file_path !== expected.file_path\n || recorded.parent_asset_id !== expected.parent_asset_id\n || recorded.edge_summary !== expected.edge_summary\n ) generationManifestConflict();\n const edge = database.prepare(`\n select summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ? and child_asset_id = ? and relation_type = 'derived_from'\n `).get(project, recorded.parent_asset_id, recorded.imported_asset_id) as Record<string, unknown> | undefined;\n if (\n !edge\n || edge.summary !== expected.edge_summary\n || edge.summary_created_by !== 'agent'\n || edge.summary_updated_by !== 'agent'\n || typeof edge.summary_updated_at !== 'string'\n || edge.summary_updated_at.length === 0\n ) generationManifestConflict();\n }\n return { ok: true, command: 'generate image import', project, job, imported: job.outputs, idempotent: true };\n } finally {\n database.close();\n }\n}\n\nexport function importImageGenerationOutputs(\n project = defaultProject,\n fields: { jobId: string; files?: string[]; parentFiles?: Record<string, string[]>; manifest?: unknown; confirmWrite: boolean },\n): GenerationImportResponse {\n if (!fields.jobId) throw new GenerationReceiptError('Missing --job-id');\n if (!fields.confirmWrite) throw new GenerationReceiptError('Generation import requires --confirm-write');\n const database = lineageDb();\n let job: GenerationJob;\n try {\n job = loadGenerationJob(database, project, fields.jobId);\n } finally {\n database.close();\n }\n if (job.source_mode !== 'lineage_selection') throw new GenerationReceiptError(`Generation job is not an image-selection job: ${job.source_mode}`);\n\n const hasManifestInput = fields.manifest !== undefined;\n const hasParentFilesInput = fields.parentFiles !== undefined;\n const hasFilesInput = fields.files !== undefined;\n if (hasManifestInput && (hasParentFilesInput || hasFilesInput)) {\n throw new GenerationReceiptError('Use --manifest or legacy --files/--parent-files, not both');\n }\n if (hasParentFilesInput && hasFilesInput) throw new GenerationReceiptError('Use --files or --parent-files, not both');\n\n let manifest: GenerationOutputManifest | undefined;\n let parentFileRows: GenerationImportRow[];\n let mappingStrategy: 'generation_output_manifest_v1' | 'explicit_parent_files' | 'ordered_per_base';\n if (job.adapter_version === manifestAdapterVersion) {\n if (!hasManifestInput) throw new GenerationReceiptError('New generation jobs require --manifest');\n manifest = parseGenerationOutputManifest(fields.manifest, job, { resolveFilePath: resolveScratchManifestPath });\n if (job.status === 'imported') return confirmManifestRetry(project, job, manifest);\n if (job.status !== 'planned') throw new GenerationReceiptError(`Generation job is not importable from status: ${job.status}`);\n parentFileRows = manifest.outputs.map(output => ({\n edgeSummary: output.edge_summary,\n file: output.file_path,\n parentAssetId: output.parent_asset_id,\n }));\n mappingStrategy = 'generation_output_manifest_v1';\n } else if (job.adapter_version === legacyAdapterVersion) {\n if (hasManifestInput) throw new GenerationReceiptError('Already-planned legacy generation jobs require --files or --parent-files');\n if (job.status !== 'planned') throw new GenerationReceiptError(`Generation job is not importable from status: ${job.status}`);\n const hasExplicitParentFiles = Boolean(fields.parentFiles && Object.keys(fields.parentFiles).length > 0);\n parentFileRows = hasExplicitParentFiles\n ? parentFilesFor(job, fields.parentFiles || {})\n : orderedFilesFor(job, (fields.files || []).map(file => file.trim()).filter(Boolean));\n mappingStrategy = hasExplicitParentFiles ? 'explicit_parent_files' : 'ordered_per_base';\n } else {\n throw new GenerationReceiptError(`Unsupported generation adapter version: ${job.adapter_version}`);\n }\n if (parentFileRows.length === 0) throw new GenerationReceiptError('Generation import requires --files or --parent-files');\n if (parentFileRows.length !== job.expected_output_count) {\n throw new GenerationReceiptError(`Output count mismatch: expected ${job.expected_output_count}, received ${parentFileRows.length}`);\n }\n const resolved = parentFileRows.map(row => ({ ...resolveScratchFile(row.file), edgeSummary: row.edgeSummary, parentAssetId: row.parentAssetId }));\n const uniquePaths = new Set(resolved.map(file => file.relativePath));\n if (uniquePaths.size !== resolved.length) throw new GenerationReceiptError('Generation import files must be unique');\n cancelLineageIterateTasksForAssets(project, {\n actor: 'system',\n confirmWrite: false,\n rootAssetId: job.root_asset_id,\n });\n indexLineageAssets(project);\n const writeDb = lineageDb();\n try {\n const timestamp = nowIso();\n writeDb.exec('BEGIN IMMEDIATE');\n try {\n for (const [index, file] of resolved.entries()) {\n const assetRow = writeDb.prepare('select id from assets where project_id = ? and id = ?').get(project, file.assetId);\n if (!assetRow) throw new GenerationReceiptError(`Indexed local asset was not found: ${file.relativePath}`);\n const outputId = `${fields.jobId}:output:${index}`;\n writeDb.prepare(`insert into generation_job_outputs (\n id, job_id, project_id, output_index, file_path, checksum_sha256, size_bytes, content_type,\n imported_asset_id, parent_asset_id, imported_at, edge_summary\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n outputId, fields.jobId, project, index, file.relativePath, file.checksum, file.size,\n file.contentType, file.assetId, file.parentAssetId, timestamp, file.edgeSummary || null,\n );\n const insertedEdge = writeDb.prepare(`insert into asset_edges (\n id, project_id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n ) values (?, ?, ?, ?, 'derived_from', ?, ?, ?, ?, ?)\n on conflict(project_id, parent_asset_id, child_asset_id, relation_type) do nothing`).run(\n `${project}:${file.parentAssetId}:derived_from:${file.assetId}`,\n project,\n file.parentAssetId,\n file.assetId,\n timestamp,\n file.edgeSummary || null,\n file.edgeSummary ? 'agent' : null,\n file.edgeSummary ? 'agent' : null,\n file.edgeSummary ? timestamp : null,\n );\n if (file.edgeSummary && insertedEdge.changes === 0) {\n const edge = writeDb.prepare(`\n select summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ? and child_asset_id = ? and relation_type = 'derived_from'\n `).get(project, file.parentAssetId, file.assetId) as Record<string, unknown> | undefined;\n if (\n !edge\n || edge.summary !== file.edgeSummary\n || edge.summary_created_by !== 'agent'\n || edge.summary_updated_by !== 'agent'\n || typeof edge.summary_updated_at !== 'string'\n || edge.summary_updated_at.length === 0\n ) generationManifestConflict();\n }\n }\n writeDb.prepare(`\n update generation_jobs\n set status = 'imported', imported_at = ?, updated_at = ?\n where project_id = ? and id = ?\n `).run(timestamp, timestamp, project, fields.jobId);\n insertReceipt(writeDb, fields.jobId, 'import', 'generate image import', {\n mapping_strategy: mappingStrategy,\n files: resolved.map((file, index) => ({\n output_index: index,\n file_path: file.relativePath,\n imported_asset_id: file.assetId,\n parent_asset_id: file.parentAssetId,\n ...(file.edgeSummary ? { edge_summary: file.edgeSummary } : {}),\n })),\n selection_reset: { root_asset_id: job.root_asset_id, cleared: true },\n });\n writeDb.prepare('delete from asset_selections where project_id = ? and root_asset_id = ?').run(project, job.root_asset_id);\n writeDb.exec('COMMIT');\n } catch (error) {\n writeDb.exec('ROLLBACK');\n throw error;\n }\n cancelLineageIterateTasksForAssets(project, {\n actor: 'system',\n confirmWrite: true,\n rootAssetId: job.root_asset_id,\n });\n const importedJob = loadGenerationJob(writeDb, project, fields.jobId);\n return { ok: true, command: 'generate image import', project, job: importedJob, imported: importedJob.outputs };\n } finally {\n writeDb.close();\n }\n}\n\nexport function importImageRerollOutput(project = defaultProject, fields: { jobId: string; file: string; confirmWrite: boolean }): GenerationImportResponse {\n if (!fields.jobId) throw new GenerationReceiptError('Missing --job-id');\n if (!fields.confirmWrite) throw new GenerationReceiptError('Generation import requires --confirm-write');\n const database = lineageDb();\n let job: GenerationJob;\n try {\n job = loadGenerationJob(database, project, fields.jobId);\n } finally {\n database.close();\n }\n if (job.status !== 'planned') throw new GenerationReceiptError(`Generation job is not importable from status: ${job.status}`);\n if (job.source_mode !== 'lineage_reroll') throw new GenerationReceiptError(`Generation job is not a re-roll job: ${job.source_mode}`);\n const target = job.inputs.filter(input => input.role === 'reroll_target');\n if (target.length !== 1) throw new GenerationReceiptError('Re-roll import requires exactly one reroll_target input');\n const resolved = resolveScratchFile(fields.file);\n indexLineageAssets(project);\n const writeDb = lineageDb();\n try {\n const timestamp = nowIso();\n writeDb.exec('BEGIN IMMEDIATE');\n try {\n const assetRow = writeDb.prepare('select id from assets where project_id = ? and id = ?').get(project, resolved.assetId);\n if (!assetRow) throw new GenerationReceiptError(`Indexed local asset was not found: ${resolved.relativePath}`);\n const outputId = `${fields.jobId}:output:0`;\n writeDb.prepare(`insert into generation_job_outputs (\n id, job_id, project_id, output_index, file_path, checksum_sha256, size_bytes, content_type, imported_asset_id, parent_asset_id, imported_at\n ) values (?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?)`).run(outputId, fields.jobId, project, resolved.relativePath, resolved.checksum, resolved.size, resolved.contentType, resolved.assetId, target[0].asset_id, timestamp);\n writeDb.prepare(`\n update generation_jobs\n set status = 'imported', imported_at = ?, updated_at = ?\n where project_id = ? and id = ?\n `).run(timestamp, timestamp, project, fields.jobId);\n insertReceipt(writeDb, fields.jobId, 'import', 'reroll import', {\n file: { output_index: 0, file_path: resolved.relativePath, imported_asset_id: resolved.assetId, parent_asset_id: target[0].asset_id },\n reroll: { root_asset_id: job.root_asset_id, node_asset_id: target[0].asset_id },\n });\n writeDb.exec('COMMIT');\n } catch (error) {\n writeDb.exec('ROLLBACK');\n throw error;\n }\n recordLineageRerollAttempt(project, {\n rootAssetId: job.root_asset_id,\n nodeAssetId: target[0].asset_id,\n assetId: resolved.assetId,\n prompt: job.prompt,\n generationJobId: fields.jobId,\n filePath: resolved.relativePath,\n checksumSha256: resolved.checksum,\n confirmWrite: true,\n });\n const rerollTask = listLineageTasks(project, job.root_asset_id).tasks.find(task => task.task_type === 'reroll' && task.target_asset_id === target[0].asset_id);\n if (rerollTask) {\n resolveLineageTask(project, {\n actor: 'agent',\n confirmWrite: true,\n resolvedAssetId: resolved.assetId,\n resolvedGenerationJobId: fields.jobId,\n taskId: rerollTask.id,\n });\n }\n const importedJob = loadGenerationJob(writeDb, project, fields.jobId);\n return { ok: true, command: 'reroll import', project, job: importedJob, imported: importedJob.outputs };\n } finally {\n writeDb.close();\n }\n}\n", "import { EdgeSummaryValidationError, requireEdgeSummary } from './edgeSummary';\nimport type { GenerationJob, GenerationJobInput } from './generationTypes';\n\nexport const generationOutputManifestSchemaVersion = 'lineage.generation_output_manifest.v1' as const;\n\ninterface GenerationOutputManifestEntry {\n output_index: number;\n file_path: string;\n parent_asset_id: string;\n edge_summary: string;\n}\n\nexport interface GenerationOutputManifest {\n schema_version: typeof generationOutputManifestSchemaVersion;\n job_id: string;\n outputs: GenerationOutputManifestEntry[];\n}\n\ninterface GenerationOutputManifestDraftEntry {\n output_index: number;\n file_path: '';\n parent_asset_id: string;\n edge_summary: '';\n}\n\nexport interface GenerationOutputManifestDraft {\n schema_version: typeof generationOutputManifestSchemaVersion;\n job_id: string;\n outputs: GenerationOutputManifestDraftEntry[];\n}\n\nexport type GenerationOutputManifestJob = Pick<GenerationJob, 'id' | 'expected_output_count'> & {\n inputs: Array<Pick<GenerationJobInput, 'asset_id' | 'position' | 'role'>>;\n};\n\nexport interface GenerationOutputManifestParseOptions {\n resolveFilePath: (filePath: string) => string;\n}\n\nclass GenerationOutputManifestError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GenerationOutputManifestError';\n }\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new GenerationOutputManifestError(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction exactKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {\n const allowedKeys = new Set(allowed);\n const unsupported = Object.keys(value).filter(key => !allowedKeys.has(key)).sort();\n if (unsupported.length > 0) {\n throw new GenerationOutputManifestError(`${label} contains unsupported field: ${unsupported[0]}`);\n }\n}\n\nfunction nonEmptyText(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new GenerationOutputManifestError(`${label} is required`);\n return value.trim();\n}\n\nexport function expectedGenerationOutputParents(job: GenerationOutputManifestJob): string[] {\n if (!Number.isInteger(job.expected_output_count) || job.expected_output_count <= 0) {\n throw new GenerationOutputManifestError('Generation job expected output count must be a positive integer');\n }\n const parents = job.inputs\n .filter(input => input.role === 'lineage_next_base')\n .sort((left, right) => left.position - right.position);\n if (parents.length === 0) throw new GenerationOutputManifestError('Generation job has no lineage_next_base input');\n const parentIds = new Set<string>();\n const parentPositions = new Set<number>();\n for (const parent of parents) {\n if (typeof parent.asset_id !== 'string' || !parent.asset_id || parent.asset_id.trim() !== parent.asset_id) {\n throw new GenerationOutputManifestError('Generation job has invalid lineage parent asset id');\n }\n if (!Number.isInteger(parent.position) || parent.position < 0 || parentPositions.has(parent.position)) {\n throw new GenerationOutputManifestError('Generation job has invalid lineage parent positions');\n }\n if (parentIds.has(parent.asset_id)) throw new GenerationOutputManifestError(`Generation job has duplicate lineage parent: ${parent.asset_id}`);\n parentIds.add(parent.asset_id);\n parentPositions.add(parent.position);\n }\n if (job.expected_output_count % parents.length !== 0) {\n throw new GenerationOutputManifestError('Generation job has invalid parent mapping');\n }\n const outputsPerParent = job.expected_output_count / parents.length;\n return Array.from({ length: job.expected_output_count }, (_value, outputIndex) => {\n return parents[Math.floor(outputIndex / outputsPerParent)].asset_id;\n });\n}\n\nexport function createGenerationOutputManifestDraft(job: GenerationOutputManifestJob): GenerationOutputManifestDraft {\n return {\n schema_version: generationOutputManifestSchemaVersion,\n job_id: job.id,\n outputs: expectedGenerationOutputParents(job).map((parentAssetId, outputIndex) => ({\n output_index: outputIndex,\n file_path: '',\n parent_asset_id: parentAssetId,\n edge_summary: '',\n })),\n };\n}\n\nexport function parseGenerationOutputManifest(\n value: unknown,\n job: GenerationOutputManifestJob,\n options: GenerationOutputManifestParseOptions,\n): GenerationOutputManifest {\n if (!options || typeof options.resolveFilePath !== 'function') {\n throw new GenerationOutputManifestError('Generation output manifest requires a file-path resolver');\n }\n const manifest = record(value, 'Generation output manifest');\n exactKeys(manifest, ['schema_version', 'job_id', 'outputs'], 'Generation output manifest');\n if (manifest.schema_version !== generationOutputManifestSchemaVersion) {\n throw new GenerationOutputManifestError(`Generation output manifest schema_version must be ${generationOutputManifestSchemaVersion}`);\n }\n if (manifest.job_id !== job.id) throw new GenerationOutputManifestError(`Generation output manifest job_id must be ${job.id}`);\n if (!Array.isArray(manifest.outputs)) throw new GenerationOutputManifestError('Generation output manifest outputs must be an array');\n\n const expectedParents = expectedGenerationOutputParents(job);\n if (manifest.outputs.length !== expectedParents.length) {\n throw new GenerationOutputManifestError(`Generation output manifest requires ${expectedParents.length} outputs, received ${manifest.outputs.length}`);\n }\n\n const seenIndexes = new Set<number>();\n const outputs = manifest.outputs.map((value, position): GenerationOutputManifestEntry => {\n const output = record(value, `Generation output at position ${position}`);\n exactKeys(output, ['output_index', 'file_path', 'parent_asset_id', 'edge_summary'], `Generation output at position ${position}`);\n const outputIndex = output.output_index;\n if (!Number.isInteger(outputIndex) || Number(outputIndex) < 0) {\n throw new GenerationOutputManifestError(`Generation output at position ${position} requires a non-negative integer output_index`);\n }\n const normalizedIndex = Number(outputIndex);\n if (seenIndexes.has(normalizedIndex)) throw new GenerationOutputManifestError(`Duplicate generation output_index: ${normalizedIndex}`);\n seenIndexes.add(normalizedIndex);\n const expectedParent = expectedParents[normalizedIndex];\n if (!expectedParent) throw new GenerationOutputManifestError(`Unknown generation output_index: ${normalizedIndex}`);\n\n const filePath = nonEmptyText(output.file_path, `Generation output ${normalizedIndex} file_path`);\n const parentAssetId = nonEmptyText(output.parent_asset_id, `Generation output ${normalizedIndex} parent_asset_id`);\n if (parentAssetId !== expectedParent) {\n throw new GenerationOutputManifestError(`Generation output ${normalizedIndex} must use parent_asset_id ${expectedParent}`);\n }\n let edgeSummary: string;\n try {\n edgeSummary = requireEdgeSummary(output.edge_summary);\n } catch (error) {\n if (error instanceof EdgeSummaryValidationError) {\n throw new GenerationOutputManifestError(`Generation output ${normalizedIndex}: ${error.message}`);\n }\n throw error;\n }\n return {\n output_index: normalizedIndex,\n file_path: filePath,\n parent_asset_id: parentAssetId,\n edge_summary: edgeSummary,\n };\n });\n\n for (const outputIndex of expectedParents.keys()) {\n if (!seenIndexes.has(outputIndex)) throw new GenerationOutputManifestError(`Missing generation output_index: ${outputIndex}`);\n }\n outputs.sort((left, right) => left.output_index - right.output_index);\n const seenPaths = new Set<string>();\n const resolvedOutputs = outputs.map(output => {\n const filePath = nonEmptyText(options.resolveFilePath(output.file_path), `Generation output ${output.output_index} resolved file_path`);\n if (seenPaths.has(filePath)) throw new GenerationOutputManifestError(`Duplicate generation output file_path: ${filePath}`);\n seenPaths.add(filePath);\n return { ...output, file_path: filePath };\n });\n return {\n schema_version: generationOutputManifestSchemaVersion,\n job_id: job.id,\n outputs: resolvedOutputs,\n };\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, statSync } from 'node:fs';\nimport { isAbsolute, resolve } from 'node:path';\nimport { listAssets, repoRoot, validateProject } from './assetCore';\nimport { getLineageSnapshot } from './assetLineage';\nimport { lineageDbPath } from './assetLineageDb';\nimport { lineageWorkspaceId, listLineageWorkspaces } from './assetLineageWorkspaces';\nimport { contentTypeFor, fileSha256 } from './localReview';\nimport type {\n GrowthAsset,\n LineageNode,\n LineageSelectionPacket,\n LineageSelectionPacketAsset,\n LineageSelectionPacketDiagnostic,\n LineageSelectionPacketStorageState,\n LineageSelectionPacketV1,\n LineageSelectionPacketV2,\n LineageSelectionPacketV2Asset,\n LineageSelectionPacketV2Attempt,\n LineageSelectionPacketV2IdentityProjection,\n LineageWorkspace,\n} from '../shared/types';\n\nexport interface LineageSelectionPacketOptions {\n campaign?: string;\n channel?: string;\n command?: string;\n contextNotes?: string;\n dbPath?: string;\n labels?: string[];\n packageVersion?: string;\n rootAssetId?: string;\n schema?: 'v2';\n strict?: boolean;\n workspaceId?: string;\n}\n\nexport class LineageSelectionPacketError extends Error {\n constructor(\n message: string,\n public warnings: string[] = [],\n public errors: string[] = [],\n public diagnostics: LineageSelectionPacketDiagnostic[] = [],\n ) {\n super(message);\n }\n}\n\nfunction listAllAssets(project: string): GrowthAsset[] {\n const pageSize = 100;\n const first = listAssets(project, { page: 1, pageSize, source: 'all' });\n const assets = [...first.assets];\n for (let page = 2; page <= first.pagination.totalPages; page += 1) {\n assets.push(...listAssets(project, { page, pageSize, source: 'all' }).assets);\n }\n return assets;\n}\n\nfunction resolveWorkspace(project: string, options: LineageSelectionPacketOptions): LineageWorkspace {\n if (options.rootAssetId && options.workspaceId) {\n throw new LineageSelectionPacketError('Use either --root or --workspace, not both.', [], ['ambiguous_workspace']);\n }\n const snapshot = listLineageWorkspaces(project);\n const target = options.workspaceId || options.rootAssetId;\n const workspace = target\n ? snapshot.workspaces.find(item => item.id === target || item.root_asset_id === target)\n : snapshot.active_workspace;\n if (workspace) return workspace;\n if (options.rootAssetId) {\n return {\n id: lineageWorkspaceId(project, options.rootAssetId),\n project,\n root_asset_id: options.rootAssetId,\n title: `${options.rootAssetId} lineage`,\n status: 'active',\n created_by: 'system',\n created_at: '',\n updated_at: '',\n };\n }\n const message = options.workspaceId\n ? `Unknown lineage workspace: ${options.workspaceId}`\n : 'No active lineage workspace. Pass --root or activate a workspace first.';\n throw new LineageSelectionPacketError(message, [], [options.workspaceId ? 'unknown_workspace' : 'missing_active_workspace']);\n}\n\nfunction resolveLocalReference(reference?: string): string | undefined {\n if (!reference) return undefined;\n if (isAbsolute(reference)) return reference;\n const repoRelative = resolve(repoRoot, reference);\n if (existsSync(repoRelative)) return repoRelative;\n return resolve(repoRoot, '.asset-scratch', reference);\n}\n\nfunction fileSize(path?: string): number | undefined {\n if (!path || !existsSync(path)) return undefined;\n try {\n return statSync(path).size;\n } catch {\n return undefined;\n }\n}\n\nfunction storageState(hasLocal: boolean, hasS3: boolean): LineageSelectionPacketStorageState {\n if (hasLocal && hasS3) return 'local_and_s3';\n if (hasLocal) return 'local_only';\n if (hasS3) return 's3_backed';\n return 'unresolved';\n}\n\nfunction currentAttemptFor(node: LineageNode): LineageSelectionPacketAsset['current_attempt'] {\n if (!node.current_attempt) return undefined;\n return {\n asset_id: node.current_attempt.asset_id,\n checksum_sha256: node.current_attempt.checksum_sha256,\n file_path: node.current_attempt.file_path,\n generation_job_id: node.current_attempt.generation_job_id,\n id: node.current_attempt.id,\n is_current: node.current_attempt.is_current,\n source: node.current_attempt.source,\n };\n}\n\nfunction assetForNode(node: LineageNode, catalogAsset: GrowthAsset | undefined, warnings: string[]): LineageSelectionPacketAsset {\n const localReference = catalogAsset?.local?.absolute_path || node.current_attempt?.file_path || node.local_path || catalogAsset?.local?.relative_path;\n const absolutePath = catalogAsset?.local?.absolute_path || resolveLocalReference(localReference);\n const localExists = absolutePath ? existsSync(absolutePath) : false;\n const hasLocalClaim = Boolean(absolutePath || node.local_path || catalogAsset?.local?.relative_path);\n const s3Key = catalogAsset?.s3?.key || node.s3_key;\n const hasS3 = Boolean(s3Key);\n const checksum = catalogAsset?.local?.checksum_sha256 || node.current_attempt?.checksum_sha256 || node.checksum_sha256 || catalogAsset?.s3?.checksum_sha256;\n const mimeType = catalogAsset?.local?.content_type || catalogAsset?.s3?.content_type;\n const mediaType = catalogAsset?.content_type || node.media_type;\n\n if (hasLocalClaim && !localExists) warnings.push(`Selected asset ${node.asset_id} has a local path but the file is missing: ${absolutePath || node.local_path}`);\n if (!hasLocalClaim && !hasS3) warnings.push(`Selected asset ${node.asset_id} has neither a local file nor S3 key.`);\n if (mediaType && mediaType !== 'image' && mediaType !== 'gif') warnings.push(`Selected asset ${node.asset_id} is ${mediaType}, not an image/gif asset.`);\n\n return {\n asset_id: node.asset_id,\n campaign: catalogAsset?.campaign || node.campaign,\n channel: catalogAsset?.channel || node.channel,\n checksum_sha256: checksum,\n current_attempt: currentAttemptFor(node),\n local: {\n absolute_path: absolutePath,\n content_type: catalogAsset?.local?.content_type,\n exists: localExists,\n relative_path: catalogAsset?.local?.relative_path || node.local_path || node.current_attempt?.file_path,\n size_bytes: catalogAsset?.local?.size_bytes || fileSize(absolutePath),\n },\n media_type: mediaType,\n mime_type: mimeType,\n review_notes: node.review_notes,\n review_state: node.review_state,\n s3: {\n bucket: catalogAsset?.s3?.bucket,\n checksum_sha256: catalogAsset?.s3?.checksum_sha256,\n content_type: catalogAsset?.s3?.content_type,\n etag: catalogAsset?.s3?.etag,\n key: s3Key,\n region: catalogAsset?.s3?.region,\n size_bytes: catalogAsset?.s3?.size_bytes,\n version_id: catalogAsset?.s3?.version_id,\n },\n selection_note: node.selection_note,\n source: catalogAsset?.source || node.source,\n status: catalogAsset?.status || node.status,\n storage_state: storageState(hasLocalClaim, hasS3),\n title: catalogAsset?.title || node.title || node.asset_id,\n };\n}\n\nfunction packetId(packetIdentity: unknown): string {\n const digest = createHash('sha256').update(JSON.stringify(packetIdentity)).digest('hex').slice(0, 24);\n return `lineage_packet_${digest}`;\n}\n\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/;\n\nfunction canonicalValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(item => canonicalValue(item));\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)\n .map(([key, item]) => [key, canonicalValue(item)]),\n );\n }\n return value;\n}\n\nexport function canonicalLineageSelectionPacketIdentityJson(projection: LineageSelectionPacketV2IdentityProjection): string {\n return JSON.stringify(canonicalValue(projection));\n}\n\nexport function lineageSelectionPacketV2IdentityProjection(packet: LineageSelectionPacketV2): LineageSelectionPacketV2IdentityProjection {\n const assetsById = new Map(packet.assets.map(asset => [asset.asset_id, asset]));\n const selection = packet.selection.items.map(item => {\n const asset = assetsById.get(item.asset_id);\n if (!asset) {\n const diagnostics: LineageSelectionPacketDiagnostic[] = [{ asset_id: item.asset_id, code: 'selected_asset_missing', severity: 'error' }];\n throw new LineageSelectionPacketError(\n `Selected asset ${item.asset_id} is absent from the v2 packet asset envelope.`,\n [],\n ['selected_asset_missing'],\n diagnostics,\n );\n }\n return {\n asset_id: item.asset_id,\n campaign: asset.campaign,\n channel: asset.channel,\n current_attempt: {\n asset_id: asset.current_attempt.asset_id,\n attempt_index: asset.current_attempt.attempt_index,\n checksum_sha256: asset.current_attempt.checksum_sha256,\n id: asset.current_attempt.id,\n source: asset.current_attempt.source,\n },\n media_type: asset.media_type,\n mime_type: asset.mime_type,\n position: item.position,\n selection_note: item.selection_note,\n title: asset.title,\n };\n });\n return {\n schema_version: 'lineage.selection_packet.v2',\n project: packet.project,\n product: packet.product,\n workspace: {\n id: packet.workspace.id,\n root_asset_id: packet.workspace.root_asset_id,\n },\n context: {\n campaign: packet.context.campaign,\n channel: packet.context.channel,\n labels: packet.context.labels,\n notes: packet.context.notes,\n },\n selection,\n diagnostics: packet.diagnostics.map(diagnostic => ({\n code: diagnostic.code,\n severity: diagnostic.severity,\n ...(diagnostic.asset_id ? { asset_id: diagnostic.asset_id } : {}),\n })),\n };\n}\n\nexport function lineageSelectionPacketV2IdentitySha256(packet: LineageSelectionPacketV2): string {\n const projection = lineageSelectionPacketV2IdentityProjection(packet);\n return createHash('sha256').update(canonicalLineageSelectionPacketIdentityJson(projection)).digest('hex');\n}\n\nfunction addDiagnostic(diagnostics: LineageSelectionPacketDiagnostic[], diagnostic: LineageSelectionPacketDiagnostic): void {\n if (diagnostics.some(item => item.code === diagnostic.code && item.severity === diagnostic.severity && item.asset_id === diagnostic.asset_id)) return;\n diagnostics.push(diagnostic);\n}\n\nfunction requireV2CurrentAttempt(\n node: LineageNode,\n warnings: string[],\n diagnostics: LineageSelectionPacketDiagnostic[],\n): LineageSelectionPacketV2Attempt {\n const attempt = node.current_attempt;\n if (!attempt) {\n const message = `Selected asset ${node.asset_id} has no current attempt identity.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_missing', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, warnings, ['current_attempt_missing'], [...diagnostics, diagnostic]);\n }\n if (!attempt.id || !attempt.asset_id || !Number.isInteger(attempt.attempt_index) || attempt.attempt_index <= 0 || !attempt.source || attempt.is_current !== true) {\n const message = `Selected asset ${node.asset_id} has malformed current attempt identity.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_invalid_identity', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, warnings, ['current_attempt_invalid_identity'], [...diagnostics, diagnostic]);\n }\n if (!attempt.checksum_sha256 || !SHA256_PATTERN.test(attempt.checksum_sha256)) {\n const message = `Selected asset ${node.asset_id} current attempt does not have a valid lowercase SHA-256 checksum.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_invalid_checksum', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, warnings, ['current_attempt_invalid_checksum'], [...diagnostics, diagnostic]);\n }\n return {\n asset_id: attempt.asset_id,\n attempt_index: attempt.attempt_index,\n checksum_sha256: attempt.checksum_sha256,\n file_path: attempt.file_path,\n generation_job_id: attempt.generation_job_id,\n id: attempt.id,\n is_current: attempt.is_current,\n source: attempt.source,\n };\n}\n\nfunction assetForNodeV2(\n node: LineageNode,\n visibleCatalogAsset: GrowthAsset | undefined,\n catalogById: Map<string, GrowthAsset>,\n warnings: string[],\n errors: string[],\n diagnostics: LineageSelectionPacketDiagnostic[],\n): LineageSelectionPacketV2Asset {\n const currentAttempt = requireV2CurrentAttempt(node, warnings, diagnostics);\n const currentAttemptCatalogAsset = catalogById.get(currentAttempt.asset_id);\n const isVisibleNodeAttempt = currentAttempt.asset_id === node.asset_id;\n const mediaCatalogAsset = currentAttemptCatalogAsset || (isVisibleNodeAttempt ? visibleCatalogAsset : undefined);\n const localReference = currentAttempt.file_path\n || mediaCatalogAsset?.local?.absolute_path\n || mediaCatalogAsset?.local?.relative_path\n || (isVisibleNodeAttempt ? node.local_path : undefined);\n const absolutePath = resolveLocalReference(localReference);\n const localExists = absolutePath ? existsSync(absolutePath) : false;\n const hasLocalClaim = Boolean(localReference);\n const s3Key = mediaCatalogAsset?.s3?.key || (isVisibleNodeAttempt ? node.s3_key : undefined);\n const hasS3 = Boolean(s3Key);\n const mimeType = mediaCatalogAsset?.local?.content_type\n || mediaCatalogAsset?.s3?.content_type\n || visibleCatalogAsset?.local?.content_type\n || visibleCatalogAsset?.s3?.content_type\n || (localReference ? contentTypeFor(localReference) : undefined);\n const mediaType = mediaCatalogAsset?.content_type || visibleCatalogAsset?.content_type || node.media_type;\n\n if (localExists && absolutePath && fileSha256(absolutePath) !== currentAttempt.checksum_sha256) {\n const message = `Selected asset ${node.asset_id} current attempt checksum does not match its local file.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_checksum_mismatch', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, [...warnings, message], ['current_attempt_checksum_mismatch'], [...diagnostics, diagnostic]);\n }\n const s3Checksum = mediaCatalogAsset?.s3?.checksum_sha256;\n if (hasS3 && s3Checksum && s3Checksum !== currentAttempt.checksum_sha256) {\n const message = `Selected asset ${node.asset_id} current attempt checksum does not match its S3 media envelope.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_checksum_mismatch', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, [...warnings, message], ['current_attempt_checksum_mismatch'], [...diagnostics, diagnostic]);\n }\n\n if (hasLocalClaim && !localExists) {\n warnings.push(`Selected asset ${node.asset_id} current attempt has a local path but the file is missing: ${absolutePath || localReference}`);\n }\n if (!hasLocalClaim && !hasS3) {\n const message = `Selected asset ${node.asset_id} current attempt has neither a local file nor S3 key.`;\n warnings.push(message);\n errors.push(message);\n }\n if (mediaType && mediaType !== 'image' && mediaType !== 'gif') {\n warnings.push(`Selected asset ${node.asset_id} is ${mediaType}, not an image/gif asset.`);\n addDiagnostic(diagnostics, { asset_id: node.asset_id, code: 'unsupported_media_type', severity: 'warning' });\n }\n\n const conflictingChecksums = [\n currentAttemptCatalogAsset?.local?.checksum_sha256,\n currentAttemptCatalogAsset?.s3?.checksum_sha256,\n visibleCatalogAsset?.local?.checksum_sha256,\n visibleCatalogAsset?.s3?.checksum_sha256,\n node.checksum_sha256,\n ].filter((checksum): checksum is string => Boolean(checksum && checksum !== currentAttempt.checksum_sha256));\n if (conflictingChecksums.length > 0) {\n warnings.push(`Selected asset ${node.asset_id} catalog or visible-node checksum differs from its current attempt; current attempt checksum is authoritative.`);\n }\n\n return {\n asset_id: node.asset_id,\n campaign: visibleCatalogAsset?.campaign || node.campaign,\n channel: visibleCatalogAsset?.channel || node.channel,\n checksum_sha256: currentAttempt.checksum_sha256,\n current_attempt: currentAttempt,\n local: {\n absolute_path: absolutePath,\n content_type: mediaCatalogAsset?.local?.content_type,\n exists: localExists,\n relative_path: mediaCatalogAsset?.local?.relative_path || currentAttempt.file_path || (isVisibleNodeAttempt ? node.local_path : undefined),\n size_bytes: mediaCatalogAsset?.local?.size_bytes || fileSize(absolutePath),\n },\n media_type: mediaType,\n mime_type: mimeType,\n review_notes: node.review_notes,\n review_state: node.review_state,\n s3: {\n bucket: mediaCatalogAsset?.s3?.bucket,\n checksum_sha256: mediaCatalogAsset?.s3?.checksum_sha256,\n content_type: mediaCatalogAsset?.s3?.content_type,\n etag: mediaCatalogAsset?.s3?.etag,\n key: s3Key,\n region: mediaCatalogAsset?.s3?.region,\n size_bytes: mediaCatalogAsset?.s3?.size_bytes,\n version_id: mediaCatalogAsset?.s3?.version_id,\n },\n selection_note: node.selection_note,\n source: mediaCatalogAsset?.source || visibleCatalogAsset?.source || node.source,\n status: visibleCatalogAsset?.status || node.status,\n storage_state: storageState(hasLocalClaim, hasS3),\n title: visibleCatalogAsset?.title || node.title || node.asset_id,\n };\n}\n\nfunction getLineageSelectionPacketV1(project: string, options: LineageSelectionPacketOptions = {}): LineageSelectionPacketV1 {\n const workspace = resolveWorkspace(project, options);\n const snapshot = getLineageSnapshot(project, workspace.root_asset_id);\n const catalogSummary = validateProject(project);\n const catalogAssets = listAllAssets(project);\n const catalogById = new Map(catalogAssets.map(asset => [asset.asset_id, asset]));\n const warnings: string[] = [];\n const errors: string[] = [];\n const nodeById = new Map(snapshot.nodes.map(node => [node.asset_id, node]));\n const selectedItems = snapshot.selections.map(selection => ({\n asset_id: selection.asset_id,\n position: selection.position,\n selected_at: selection.selected_at,\n selection_note: selection.notes,\n }));\n\n if (selectedItems.length === 0) warnings.push(`Lineage workspace ${workspace.id} has no selected assets.`);\n\n const assets = selectedItems.flatMap(item => {\n const node = nodeById.get(item.asset_id);\n if (!node) {\n const message = `Selected asset ${item.asset_id} is not present in the resolved workspace snapshot.`;\n warnings.push(message);\n errors.push('selected_asset_outside_workspace');\n return [];\n }\n return [assetForNode(node, catalogById.get(item.asset_id), warnings)];\n });\n\n if (assets.some(asset => !asset.dimensions)) warnings.push('Image dimensions are unavailable for one or more selected assets.');\n if (options.strict) {\n const strictErrors = [\n ...(selectedItems.length === 0 ? ['empty_selection'] : []),\n ...assets.filter(asset => asset.local.absolute_path && !asset.local.exists).map(asset => `missing_local_file:${asset.asset_id}`),\n ...errors,\n ];\n if (strictErrors.length > 0) {\n throw new LineageSelectionPacketError(`Lineage selection packet strict mode failed: ${strictErrors.join(', ')}`, warnings, strictErrors);\n }\n }\n\n const context = {\n campaign: options.campaign,\n channel: options.channel,\n labels: options.labels || [],\n notes: options.contextNotes,\n };\n const identity = {\n assets: assets.map(asset => ({\n asset_id: asset.asset_id,\n checksum_sha256: asset.checksum_sha256,\n local_path: asset.local.absolute_path,\n s3_key: asset.s3.key,\n storage_state: asset.storage_state,\n })),\n context,\n project,\n root_asset_id: workspace.root_asset_id,\n schema_version: 'lineage.selection_packet.v1',\n selection: selectedItems,\n workspace_id: workspace.id,\n };\n\n return {\n assets,\n context,\n created_at: new Date().toISOString(),\n errors,\n kind: 'lineage.selection_packet',\n packet_id: packetId(identity),\n product: catalogSummary.product,\n project,\n schema_version: 'lineage.selection_packet.v1',\n selection: {\n asset_ids: selectedItems.map(item => item.asset_id),\n count: selectedItems.length,\n items: selectedItems,\n root_asset_id: workspace.root_asset_id,\n },\n source: {\n app: 'lineage',\n command: options.command,\n db_path: options.dbPath || process.env.LINEAGE_DB || lineageDbPath(),\n package: options.packageVersion,\n },\n warnings: [...new Set(warnings)],\n workspace: {\n active_at: workspace.active_at,\n id: workspace.id,\n notes: workspace.notes,\n root_asset_id: workspace.root_asset_id,\n status: workspace.status,\n title: workspace.title,\n },\n };\n}\n\nfunction getLineageSelectionPacketV2(project: string, options: LineageSelectionPacketOptions): LineageSelectionPacketV2 {\n const workspace = resolveWorkspace(project, options);\n const snapshot = getLineageSnapshot(project, workspace.root_asset_id);\n const catalogSummary = validateProject(project);\n const catalogAssets = listAllAssets(project);\n const catalogById = new Map(catalogAssets.map(asset => [asset.asset_id, asset]));\n const warnings: string[] = [];\n const errors: string[] = [];\n const diagnostics: LineageSelectionPacketDiagnostic[] = [];\n const nodeById = new Map(snapshot.nodes.map(node => [node.asset_id, node]));\n const selectedItems = snapshot.selections.map(selection => ({\n asset_id: selection.asset_id,\n position: selection.position,\n selected_at: selection.selected_at,\n selection_note: selection.notes,\n }));\n\n if (selectedItems.length === 0) {\n warnings.push(`Lineage workspace ${workspace.id} has no selected assets.`);\n addDiagnostic(diagnostics, { code: 'empty_selection', severity: 'warning' });\n }\n\n const assets: LineageSelectionPacketV2Asset[] = [];\n for (const item of selectedItems) {\n const node = nodeById.get(item.asset_id);\n if (!node) {\n const message = `Selected asset ${item.asset_id} is not present in the resolved workspace snapshot.`;\n warnings.push(message);\n errors.push(message);\n const diagnostic = { asset_id: item.asset_id, code: 'selected_asset_outside_workspace', severity: 'error' } as const;\n addDiagnostic(diagnostics, diagnostic);\n throw new LineageSelectionPacketError(message, warnings, ['selected_asset_outside_workspace'], diagnostics);\n }\n assets.push(assetForNodeV2(node, catalogById.get(item.asset_id), catalogById, warnings, errors, diagnostics));\n }\n\n if (assets.some(asset => !asset.dimensions)) {\n warnings.push('Image dimensions are unavailable for one or more selected assets.');\n }\n\n if (options.strict) {\n const strictErrors = [\n ...(selectedItems.length === 0 ? ['empty_selection'] : []),\n ...assets.filter(asset => asset.local.absolute_path && !asset.local.exists).map(asset => `missing_local_file:${asset.asset_id}`),\n ...assets.filter(asset => asset.storage_state === 'unresolved').map(asset => `unresolved_current_attempt_media:${asset.asset_id}`),\n ...diagnostics\n .filter(diagnostic => diagnostic.severity === 'error')\n .map(diagnostic => `${diagnostic.code}${diagnostic.asset_id ? `:${diagnostic.asset_id}` : ''}`),\n ];\n if (strictErrors.length > 0) {\n throw new LineageSelectionPacketError(\n `Lineage selection packet strict mode failed: ${strictErrors.join(', ')}`,\n warnings,\n strictErrors,\n diagnostics,\n );\n }\n }\n\n const packet: LineageSelectionPacketV2 = {\n assets,\n context: {\n campaign: options.campaign,\n channel: options.channel,\n labels: options.labels || [],\n notes: options.contextNotes,\n },\n created_at: new Date().toISOString(),\n diagnostics,\n errors: [...new Set(errors)],\n identity_sha256: '',\n kind: 'lineage.selection_packet',\n packet_id: '',\n product: catalogSummary.product,\n project,\n schema_version: 'lineage.selection_packet.v2',\n selection: {\n asset_ids: selectedItems.map(item => item.asset_id),\n count: selectedItems.length,\n items: selectedItems,\n root_asset_id: workspace.root_asset_id,\n },\n source: {\n app: 'lineage',\n command: options.command,\n db_path: options.dbPath || process.env.LINEAGE_DB || lineageDbPath(),\n package: options.packageVersion,\n },\n warnings: [...new Set(warnings)],\n workspace: {\n active_at: workspace.active_at,\n id: workspace.id,\n notes: workspace.notes,\n root_asset_id: workspace.root_asset_id,\n status: workspace.status,\n title: workspace.title,\n },\n };\n packet.identity_sha256 = lineageSelectionPacketV2IdentitySha256(packet);\n packet.packet_id = `lineage_packet_${packet.identity_sha256.slice(0, 24)}`;\n return packet;\n}\n\nexport function getLineageSelectionPacket(project: string, options: LineageSelectionPacketOptions = {}): LineageSelectionPacket {\n return options.schema === 'v2'\n ? getLineageSelectionPacketV2(project, options)\n : getLineageSelectionPacketV1(project, options);\n}\n", "import { createHash } from 'node:crypto';\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } from 'node:fs';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { lineageDbPath, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { repoRoot } from './assetCore';\nimport { runtimeProfileIdentity } from './lineageProfiles';\nimport { loadNodeSqlite } from './nodeSqlite';\nimport { lineageCliLauncher, lineageRuntimeSelector } from './lineageRuntimeCommand';\nimport {\n lineageRuntimeBuildSchemaVersion,\n lineageRuntimeInstallSchemaVersion,\n type LineageRuntimeBuildIdentity,\n type LineageRuntimeChannel,\n type LineageRuntimeCodeIdentity,\n type LineageRuntimeInfo,\n type LineageRuntimeInstallReceipt,\n} from '../shared/runtimeInfoTypes';\n\nconst processStartedAt = new Date().toISOString();\n\nfunction isLineagePackageRoot(root: string): boolean {\n try {\n const info = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string };\n return info.name === '@mean-weasel/lineage';\n } catch {\n return false;\n }\n}\n\nfunction executingCodeRoot(): string {\n const moduleDirectory = dirname(fileURLToPath(import.meta.url));\n const candidates = [resolve(moduleDirectory, '../..'), resolve(moduleDirectory, '..')];\n const root = candidates.find(isLineagePackageRoot);\n if (!root) throw new Error(`Unable to derive Lineage code root from executing module ${fileURLToPath(import.meta.url)}`);\n return canonicalRoot(root);\n}\n\nconst codeRoot = executingCodeRoot();\n\nfunction sha256(value: string | Buffer): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction canonicalRoot(root: string): string {\n try {\n return realpathSync(root);\n } catch {\n return resolve(root);\n }\n}\n\nfunction packageInfo(root = codeRoot): { name: string; version: string } {\n try {\n const info = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; version?: string };\n return { name: info.name || '@mean-weasel/lineage', version: info.version || '0.0.0' };\n } catch {\n return { name: '@mean-weasel/lineage', version: '0.0.0' };\n }\n}\n\nexport function normalizeRuntimeChannel(value?: string): LineageRuntimeChannel {\n if (value === 'stable' || value === 'preview' || value === 'dev') return value;\n if (value === 'production') return 'stable';\n if (value === 'next') return 'preview';\n if (value === 'development') return 'dev';\n return process.env.NODE_ENV === 'production' ? 'stable' : 'dev';\n}\n\nfunction git(root: string, args: string[]): string | undefined {\n const result = spawnSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });\n return result.status === 0 ? result.stdout : undefined;\n}\n\nfunction untrackedFingerprint(root: string, status: string): string {\n const hash = createHash('sha256');\n hash.update(status);\n const listed = git(root, ['ls-files', '--others', '--exclude-standard', '-z']);\n if (listed === undefined) return hash.digest('hex');\n for (const relativePath of listed.split('\\0').filter(Boolean).sort()) {\n hash.update('\\0');\n hash.update(relativePath);\n const path = join(root, relativePath);\n try {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) hash.update(readlinkSync(path));\n else if (stat.isFile()) hash.update(readFileSync(path));\n else hash.update(`[${stat.mode}:${stat.size}]`);\n } catch (error) {\n hash.update(`[unreadable:${error instanceof Error ? error.message : String(error)}]`);\n }\n }\n return hash.digest('hex');\n}\n\nfunction checkoutCodeIdentity(root: string, channel: LineageRuntimeChannel, version: string): LineageRuntimeCodeIdentity {\n const errors: string[] = [];\n const gitRootRaw = git(root, ['rev-parse', '--show-toplevel'])?.trim();\n const gitSha = git(root, ['rev-parse', 'HEAD'])?.trim();\n const status = git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);\n const diff = git(root, ['diff', '--binary', 'HEAD', '--']);\n const canonicalGitRoot = gitRootRaw ? canonicalRoot(gitRootRaw) : undefined;\n if (!canonicalGitRoot || canonicalGitRoot !== root) errors.push('Code root is not the canonical root of a Git checkout/worktree');\n if (!gitSha || !/^[a-f0-9]{40}$/i.test(gitSha)) errors.push('Checkout Git revision is unavailable');\n if (status === undefined || diff === undefined) errors.push('Checkout dirty state could not be inspected');\n if (channel !== 'dev') errors.push(`Checkout code may run only as dev, not ${channel}`);\n const dirty = Boolean(status);\n const sourceFingerprint = sha256(`${gitSha || 'unknown'}\\0${sha256(diff || '')}\\0${untrackedFingerprint(root, status || '')}`);\n return {\n channel,\n dirty,\n errors,\n fingerprint: sha256(JSON.stringify({ channel, dirty, git_sha: gitSha, origin: 'checkout', root, source_fingerprint: sourceFingerprint, version })),\n git_sha: gitSha,\n origin: 'checkout',\n package_version: version,\n root,\n source_fingerprint: sourceFingerprint,\n verified: errors.length === 0,\n };\n}\n\nfunction buildFingerprint(build: Omit<LineageRuntimeBuildIdentity, 'build_fingerprint'>): string {\n return sha256(JSON.stringify({\n package_name: build.package_name,\n package_version: build.package_version,\n schema_version: build.schema_version,\n source_dirty: build.source_dirty,\n source_fingerprint: build.source_fingerprint,\n source_git_sha: build.source_git_sha,\n }));\n}\n\nfunction readBuildIdentity(root: string, errors: string[]): LineageRuntimeBuildIdentity | undefined {\n const path = join(root, 'dist', 'runtime-build.json');\n let build: LineageRuntimeBuildIdentity;\n try {\n build = JSON.parse(readFileSync(path, 'utf8')) as LineageRuntimeBuildIdentity;\n } catch (error) {\n errors.push(`Embedded build identity is missing or unreadable at ${path}: ${error instanceof Error ? error.message : String(error)}`);\n return undefined;\n }\n if (build.schema_version !== lineageRuntimeBuildSchemaVersion) errors.push(`Unsupported build identity schema: ${String(build.schema_version)}`);\n if (!/^[a-f0-9]{40}$/i.test(build.source_git_sha || '')) errors.push('Embedded build Git revision is invalid');\n if (!/^[a-f0-9]{64}$/i.test(build.source_fingerprint || '')) errors.push('Embedded source fingerprint is invalid');\n const expected = buildFingerprint(build);\n if (build.build_fingerprint !== expected) errors.push('Embedded build fingerprint does not match its contents');\n return build;\n}\n\nfunction readInstallReceipt(path: string | undefined, errors: string[]): (LineageRuntimeInstallReceipt & { receipt_path: string }) | undefined {\n if (!path) {\n errors.push('Packaged runtime was not launched through a channel install receipt');\n return undefined;\n }\n let receipt: LineageRuntimeInstallReceipt;\n const receiptPath = resolve(path);\n try {\n receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) as LineageRuntimeInstallReceipt;\n } catch (error) {\n errors.push(`Runtime install receipt is missing or unreadable at ${receiptPath}: ${error instanceof Error ? error.message : String(error)}`);\n return undefined;\n }\n if (receipt.schema_version !== lineageRuntimeInstallSchemaVersion) errors.push(`Unsupported runtime install receipt schema: ${String(receipt.schema_version)}`);\n if (!isAbsolute(receipt.package_root || '')) errors.push('Runtime install receipt package_root must be absolute');\n if (!receipt.package_integrity?.startsWith('sha512-')) errors.push('Runtime install receipt package integrity is invalid');\n if (receipt.package_source !== 'registry' && receipt.package_source !== 'local') errors.push('Runtime install receipt package source is invalid');\n if (typeof receipt.package_spec !== 'string' || !receipt.package_spec) errors.push('Runtime install receipt package spec is invalid');\n if (!/^[a-f0-9]{64}$/i.test(receipt.package_tree_sha256 || '')) errors.push('Runtime install receipt package tree hash is invalid');\n if (Number.isNaN(Date.parse(receipt.installed_at))) errors.push('Runtime install receipt timestamp is invalid');\n return { ...receipt, receipt_path: receiptPath };\n}\n\nexport function lineagePackageTreeSha256(root: string): string {\n const hash = createHash('sha256');\n const visit = (directory: string, relativeDirectory = '') => {\n for (const entry of readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {\n const relativePath = relativeDirectory ? join(relativeDirectory, entry.name) : entry.name;\n const path = join(directory, entry.name);\n hash.update(relativePath.replaceAll('\\\\', '/'));\n hash.update('\\0');\n if (entry.isDirectory()) {\n hash.update('directory\\0');\n visit(path, relativePath);\n } else if (entry.isSymbolicLink()) {\n hash.update('symlink\\0');\n hash.update(readlinkSync(path));\n } else if (entry.isFile()) {\n hash.update('file\\0');\n hash.update(readFileSync(path));\n } else {\n hash.update('other\\0');\n }\n hash.update('\\0');\n }\n };\n visit(root);\n return hash.digest('hex');\n}\n\nfunction packageCodeIdentity(\n root: string,\n channel: LineageRuntimeChannel,\n info: { name: string; version: string },\n receiptPath?: string,\n): LineageRuntimeCodeIdentity {\n const errors: string[] = [];\n const build = readBuildIdentity(root, errors);\n const install = readInstallReceipt(receiptPath, errors);\n if (channel === 'dev') errors.push('Published package code cannot run as dev; use a Git checkout/worktree');\n if (build?.package_name !== info.name || build?.package_version !== info.version) {\n errors.push('Embedded build package identity does not match package.json');\n }\n if (build?.source_dirty) errors.push('Stable and preview package installs require a clean-source build');\n if (install) {\n if (install.channel !== channel) errors.push(`Install receipt channel ${install.channel} does not match requested ${channel}`);\n if (canonicalRoot(install.package_root) !== root) errors.push('Install receipt package root does not match the executing package root');\n if (install.package_name !== info.name || install.package_version !== info.version) errors.push('Install receipt package identity does not match package.json');\n if (build && install.build_fingerprint !== build.build_fingerprint) errors.push('Install receipt build fingerprint does not match the embedded build');\n try {\n if (lineagePackageTreeSha256(root) !== install.package_tree_sha256) errors.push('Installed package tree does not match the channel install receipt');\n } catch (error) {\n errors.push(`Installed package tree could not be verified: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n const gitSha = build?.source_git_sha;\n const sourceFingerprint = build?.source_fingerprint;\n return {\n build,\n channel,\n dirty: build?.source_dirty,\n errors,\n fingerprint: sha256(JSON.stringify({\n build_fingerprint: build?.build_fingerprint,\n channel,\n install_integrity: install?.package_integrity,\n origin: 'package',\n root,\n version: info.version,\n })),\n git_sha: gitSha,\n install,\n origin: 'package',\n package_version: info.version,\n root,\n source_fingerprint: sourceFingerprint,\n verified: errors.length === 0,\n };\n}\n\nexport function getLineageCodeIdentity(\n channel: LineageRuntimeChannel,\n options: { receiptPath?: string; root?: string } = {},\n): LineageRuntimeCodeIdentity {\n const root = canonicalRoot(options.root || codeRoot);\n const info = packageInfo(root);\n if (existsSync(join(root, '.git'))) return checkoutCodeIdentity(root, channel, info.version);\n if (existsSync(join(root, 'package.json'))) {\n return packageCodeIdentity(root, channel, info, options.receiptPath ?? process.env.LINEAGE_RUNTIME_RECEIPT);\n }\n const errors = [`Code root has neither checkout metadata nor package.json: ${root}`];\n return {\n channel,\n errors,\n fingerprint: sha256(JSON.stringify({ channel, origin: 'unknown', root, version: info.version })),\n origin: 'unknown',\n package_version: info.version,\n root,\n verified: false,\n };\n}\n\nexport function assertLineageCodeOrigin(channel: LineageRuntimeChannel): LineageRuntimeCodeIdentity {\n const identity = getLineageCodeIdentity(channel);\n if (!identity.verified) {\n const migration = channel === 'dev'\n ? 'Run dev from a Git checkout with npm run lineage:dev -- <command>.'\n : `Install and launch an isolated ${channel} runtime with lineage-channel install ${channel}.`;\n throw new Error(`Unverified ${channel} code origin: ${identity.errors.join('; ')}. ${migration}`);\n }\n return identity;\n}\n\nfunction tableExists(database: DatabaseSync, table: string): boolean {\n return Boolean(database.prepare(\"select name from sqlite_master where type = 'table' and name = ?\").get(table));\n}\n\nfunction tableCount(database: DatabaseSync, table: string): number | undefined {\n if (!tableExists(database, table)) return undefined;\n const row = database.prepare(`select count(*) count from ${table}`).get() as { count?: number } | undefined;\n return typeof row?.count === 'number' ? row.count : undefined;\n}\n\nfunction migrationKeys(database: DatabaseSync): string[] {\n if (!tableExists(database, 'lineage_schema_migrations')) return [];\n return (database.prepare('select key from lineage_schema_migrations order by key').all() as Array<{ key: string }>).map(row => row.key);\n}\n\nexport function getLineageRuntimeInfo(options: { channel?: string; code?: LineageRuntimeCodeIdentity; dbPath?: string } = {}): LineageRuntimeInfo {\n const info = packageInfo();\n const dbPath = options.dbPath || lineageDbPath();\n const channel = normalizeRuntimeChannel(options.channel || process.env.LINEAGE_CHANNEL || process.env.LINEAGE_RELEASE_CHANNEL);\n const code = options.code || getLineageCodeIdentity(channel);\n const databaseInfo: LineageRuntimeInfo['database'] = { exists: existsSync(dbPath), path: dbPath };\n const schema: LineageRuntimeInfo['schema'] = { migration_keys: [] };\n const serviceInstanceId = process.env.LINEAGE_SERVICE_INSTANCE_ID;\n const launcherPid = process.env.LINEAGE_LAUNCHER_PID ? Number(process.env.LINEAGE_LAUNCHER_PID) : undefined;\n const isServiceProcess = Boolean(serviceInstanceId && Number.isInteger(launcherPid) && launcherPid! > 0);\n\n if (databaseInfo.exists) {\n try {\n const stat = statSync(dbPath);\n databaseInfo.modified_at = stat.mtime.toISOString();\n databaseInfo.size_bytes = stat.size;\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(dbPath, { readOnly: true });\n try {\n databaseInfo.projects = tableCount(database, 'projects');\n databaseInfo.workspaces = tableCount(database, 'lineage_workspaces');\n schema.migration_keys = migrationKeys(database);\n if (tableExists(database, 'lineage_profile_identity')) {\n const columns = new Set((database.prepare('pragma table_info(lineage_profile_identity)').all() as Array<{ name: string }>).map(row => row.name));\n const fingerprintExpression = columns.has('profile_fingerprint') ? 'profile_fingerprint' : \"null as profile_fingerprint\";\n const rows = database.prepare(`select profile_id, environment, ${fingerprintExpression} from lineage_profile_identity`).all() as Array<{\n environment: LineageRuntimeInfo['profile']['environment'];\n profile_fingerprint?: string;\n profile_id: string;\n }>;\n if (rows.length === 1) {\n schema.profile_id = rows[0].profile_id;\n schema.profile_environment = rows[0].environment;\n if (rows[0].profile_fingerprint) schema.profile_fingerprint = rows[0].profile_fingerprint;\n }\n }\n } finally {\n database.close();\n }\n } catch (error) {\n databaseInfo.error = error instanceof Error ? error.message : String(error);\n }\n }\n\n return {\n asset_root: repoRoot,\n channel,\n cli: {\n launcher: lineageCliLauncher(channel),\n runtime_selector: lineageRuntimeSelector(dbPath),\n },\n code,\n database: databaseInfo,\n fetchedAt: nowIso(),\n git_sha: code.git_sha,\n node_env: process.env.NODE_ENV,\n package_name: info.name,\n process: {\n pid: process.pid,\n role: isServiceProcess ? 'service' : 'command',\n started_at: processStartedAt,\n },\n profile: runtimeProfileIdentity(channel),\n schema,\n ...(isServiceProcess ? {\n service: {\n instance_id: serviceInstanceId,\n launcher_pid: launcherPid,\n mode: process.env.LINEAGE_SERVICE_MODE === 'managed' ? 'managed' as const : 'foreground' as const,\n pid: process.pid,\n started_at: processStartedAt,\n },\n } : {}),\n version: info.version,\n };\n}\n", "export type LineageRuntimeChannel = 'stable' | 'preview' | 'dev';\n\nexport const lineageRuntimeBuildSchemaVersion = 'lineage.runtime_build.v1' as const;\nexport const lineageRuntimeInstallSchemaVersion = 'lineage.runtime_install.v1' as const;\n\ntype LineageRuntimeEnvironment = 'production' | 'preview' | 'development';\n\ninterface LineageRuntimeDatabaseInfo {\n error?: string;\n exists: boolean;\n modified_at?: string;\n path: string;\n projects?: number;\n size_bytes?: number;\n workspaces?: number;\n}\n\ninterface LineageRuntimeProfileInfo {\n bound: boolean;\n environment: LineageRuntimeEnvironment;\n fingerprint?: string;\n id: string;\n manifest_path?: string;\n service_origin?: string;\n warning?: string;\n}\n\ninterface LineageRuntimeSchemaInfo {\n migration_keys: string[];\n profile_environment?: LineageRuntimeEnvironment;\n profile_fingerprint?: string;\n profile_id?: string;\n}\n\nexport interface LineageRuntimeBuildIdentity {\n build_fingerprint: string;\n package_name: string;\n package_version: string;\n schema_version: typeof lineageRuntimeBuildSchemaVersion;\n source_dirty: boolean;\n source_fingerprint: string;\n source_git_sha: string;\n}\n\nexport interface LineageRuntimeInstallReceipt {\n build_fingerprint: string;\n channel: Exclude<LineageRuntimeChannel, 'dev'>;\n installed_at: string;\n package_integrity: string;\n package_name: string;\n package_root: string;\n package_source: 'local' | 'registry';\n package_spec: string;\n package_tree_sha256: string;\n package_version: string;\n schema_version: typeof lineageRuntimeInstallSchemaVersion;\n}\n\nexport interface LineageRuntimeCodeIdentity {\n build?: LineageRuntimeBuildIdentity;\n channel: LineageRuntimeChannel;\n dirty?: boolean;\n errors: string[];\n fingerprint: string;\n git_sha?: string;\n install?: LineageRuntimeInstallReceipt & { receipt_path: string };\n origin: 'checkout' | 'package' | 'unknown';\n package_version: string;\n root: string;\n source_fingerprint?: string;\n verified: boolean;\n}\n\nexport interface LineageRuntimeInfo {\n asset_root: string;\n channel: LineageRuntimeChannel;\n cli: {\n launcher: string;\n runtime_selector: string;\n };\n code?: LineageRuntimeCodeIdentity;\n database: LineageRuntimeDatabaseInfo;\n fetchedAt: string;\n git_sha?: string;\n node_env?: string;\n package_name: string;\n process?: {\n pid: number;\n role: 'command' | 'service';\n started_at: string;\n };\n profile: LineageRuntimeProfileInfo;\n schema: LineageRuntimeSchemaInfo;\n service?: {\n instance_id?: string;\n mode: 'foreground' | 'managed';\n launcher_pid?: number;\n pid: number;\n started_at: string;\n };\n version: string;\n}\n", "import type express from 'express';\nimport type { LineageRuntimeChannel } from '../shared/runtimeInfoTypes';\nimport type { ResolvedLineageProfile } from '../shared/lineageProfileTypes';\nimport { AgentClaimError, type AgentClaim } from './agentClaims';\nimport type { ProfileWriterLease } from './profileWriterLease';\nimport { getProfileWriterDelegation } from './profileWriterLease';\n\nexport const managedWriterRequestSchemaVersion = 'lineage.managed_writer_request.v1' as const;\nconst managedWriterResponseSchemaVersion = 'lineage.managed_writer_response.v1' as const;\nexport const managedWriterRoute = '/api/managed-writer/execute' as const;\nconst delegationHeader = 'X-Lineage-Writer-Delegation';\n\ninterface ManagedWriterIdentity {\n channel: LineageRuntimeChannel;\n environment: ResolvedLineageProfile['environment'];\n profile_id: string;\n service_origin: string;\n}\n\ninterface ManagedWriterRequest {\n args: string[];\n channel: LineageRuntimeChannel;\n command: string;\n environment: ResolvedLineageProfile['environment'];\n profile_id: string;\n schema_version: typeof managedWriterRequestSchemaVersion;\n service_origin: string;\n}\n\ninterface ManagedWriterResponse {\n ok: true;\n result: unknown;\n schema_version: typeof managedWriterResponseSchemaVersion;\n service: ManagedWriterIdentity;\n}\n\nexport class ManagedWriterRoutingError extends Error {\n constructor(message: string, public readonly status = 409, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ManagedWriterRoutingError';\n }\n}\n\nexport function isManagedWriterRoutingError(error: unknown): error is ManagedWriterRoutingError {\n return error instanceof ManagedWriterRoutingError;\n}\n\nexport function managedWriterTimeoutMs(command: string, args: string[]): number {\n const positions = args.filter(arg => !arg.startsWith('-'));\n const slowImport = (command === 'reroll' && positions[0] === 'import')\n || (command === 'generate' && positions[0] === 'image' && positions[1] === 'import');\n return slowImport ? 5 * 60_000 : 30_000;\n}\n\nfunction requestBody(value: unknown): ManagedWriterRequest {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ManagedWriterRoutingError('Managed writer request must be a JSON object', 400);\n }\n const body = value as Partial<ManagedWriterRequest>;\n if (body.schema_version !== managedWriterRequestSchemaVersion) {\n throw new ManagedWriterRoutingError(`Unsupported managed writer request schema: ${String(body.schema_version)}`, 400);\n }\n if (typeof body.command !== 'string' || !body.command || !Array.isArray(body.args) || body.args.some(arg => typeof arg !== 'string')) {\n throw new ManagedWriterRoutingError('Managed writer request requires a command and string args', 400);\n }\n if (\n typeof body.profile_id !== 'string'\n || typeof body.channel !== 'string'\n || typeof body.environment !== 'string'\n || typeof body.service_origin !== 'string'\n ) {\n throw new ManagedWriterRoutingError('Managed writer request requires profile identity', 400);\n }\n return body as ManagedWriterRequest;\n}\n\nfunction containsProtectedOverride(args: string[]): boolean {\n return args.some(arg => arg === '--db' || arg.startsWith('--db=')\n || arg === '--asset-root' || arg.startsWith('--asset-root=')\n || arg === '--profile' || arg.startsWith('--profile='));\n}\n\nexport function registerManagedWriterRoute(\n app: express.Express,\n fields: {\n channel: LineageRuntimeChannel;\n accepts: (command: string, args: string[]) => boolean;\n execute: (command: string, args: string[]) => unknown;\n profile?: ResolvedLineageProfile;\n writerLease?: ProfileWriterLease;\n },\n): void {\n app.post(managedWriterRoute, (req, res, next) => {\n try {\n if (!fields.profile || !fields.writerLease) {\n throw new ManagedWriterRoutingError('Managed writer delegation is unavailable for an unprofiled service', 404);\n }\n if (!fields.writerLease.authenticate(req.header(delegationHeader))) {\n throw new ManagedWriterRoutingError('Managed writer delegation was not authorized', 401);\n }\n const body = requestBody(req.body);\n if (\n body.profile_id !== fields.profile.profile_id\n || body.channel !== fields.channel\n || body.environment !== fields.profile.environment\n || body.service_origin !== fields.profile.service_origin\n ) {\n throw new ManagedWriterRoutingError('Managed writer request profile/service identity does not match this service', 409);\n }\n if (containsProtectedOverride(body.args)) {\n throw new ManagedWriterRoutingError('Managed writer requests cannot override profile, database, or asset root', 400);\n }\n if (!fields.accepts(body.command, body.args)) {\n throw new ManagedWriterRoutingError(`Unsupported managed writer command: ${body.command}`, 400);\n }\n const result = fields.execute(body.command, body.args);\n const response: ManagedWriterResponse = {\n ok: true,\n result,\n schema_version: managedWriterResponseSchemaVersion,\n service: {\n channel: fields.channel,\n environment: fields.profile.environment,\n profile_id: fields.profile.profile_id,\n service_origin: fields.profile.service_origin,\n },\n };\n res.json(response);\n } catch (error) {\n next(error);\n }\n });\n}\n\nfunction errorMessage(body: unknown, fallback: string): string {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return fallback;\n const record = body as Record<string, unknown>;\n if (typeof record.message === 'string') return record.message;\n if (typeof record.error === 'string') return record.error;\n return fallback;\n}\n\nfunction agentClaimError(body: unknown, status: number): AgentClaimError | undefined {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return undefined;\n const record = body as Record<string, unknown>;\n if (typeof record.message !== 'string' || typeof record.error !== 'string') return undefined;\n const conflicts = Array.isArray(record.conflicts) ? record.conflicts as AgentClaim[] : [];\n return new AgentClaimError(record.message, status, record.error, conflicts);\n}\n\nfunction assertResponseIdentity(\n body: unknown,\n profile: ResolvedLineageProfile,\n channel: LineageRuntimeChannel,\n): asserts body is ManagedWriterResponse {\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n throw new ManagedWriterRoutingError('Managed writer service returned a non-object response', 502);\n }\n const response = body as Partial<ManagedWriterResponse>;\n if (\n response.ok !== true\n || response.schema_version !== managedWriterResponseSchemaVersion\n || !response.service\n || response.service.profile_id !== profile.profile_id\n || response.service.environment !== profile.environment\n || response.service.service_origin !== profile.service_origin\n || response.service.channel !== channel\n ) {\n throw new ManagedWriterRoutingError('Managed writer response identity does not match the selected profile/service', 502);\n }\n}\n\nexport async function executeManagedWriterCommand(\n profile: ResolvedLineageProfile,\n channel: LineageRuntimeChannel,\n command: string,\n args: string[],\n): Promise<unknown> {\n const delegation = getProfileWriterDelegation(profile);\n let response: Response;\n try {\n response = await fetch(new URL(managedWriterRoute, delegation.service_origin), {\n body: JSON.stringify({\n args,\n channel,\n command,\n environment: profile.environment,\n profile_id: profile.profile_id,\n schema_version: managedWriterRequestSchemaVersion,\n service_origin: profile.service_origin,\n } satisfies ManagedWriterRequest),\n headers: {\n 'Content-Type': 'application/json',\n [delegationHeader]: delegation.token,\n },\n method: 'POST',\n redirect: 'error',\n signal: AbortSignal.timeout(managedWriterTimeoutMs(command, args)),\n });\n } catch (error) {\n throw new ManagedWriterRoutingError(\n `Managed service for Lineage profile ${profile.profile_id} is unavailable or did not respond at ${profile.service_origin}; no direct fallback was attempted and the mutation outcome is unknown`,\n 503,\n { cause: error },\n );\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new ManagedWriterRoutingError('Managed writer service returned invalid JSON; mutation result is unknown', 502, { cause: error });\n }\n if (!response.ok) {\n const claimError = agentClaimError(body, response.status);\n if (claimError) throw claimError;\n throw new ManagedWriterRoutingError(errorMessage(body, `Managed writer service returned HTTP ${response.status}`), response.status);\n }\n assertResponseIdentity(body, profile, channel);\n return body.result;\n}\n", "#!/usr/bin/env node\n\nimport { runLineageCli } from './lineageCli';\n\nawait runLineageCli({\n binName: 'lineage-preview',\n channel: 'preview',\n defaultHost: 'lineage-pre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;;;AwB1zCA,MAAM,cAAc;AAAA,EAClB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AACf,CAAC;",
|
|
6
|
-
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "randomUUID", "homedir", "platform", "dirname", "join", "resolve", "fileURLToPath", "createHash", "timingSafeEqual", "existsSync", "mkdirSync", "join", "existsSync", "mkdirSync", "readdirSync", "readFileSync", "dirname", "join", "resolve", "existsSync", "statSync", "basename", "join", "repoRoot", "repoRoot", "existsSync", "join", "basename", "statSync", "join", "existsSync", "packageInfo", "readFileSync", "dirname", "resolve", "join", "existsSync", "existsSync", "readFileSync", "mkdirSync", "dirname", "start", "createHash", "randomUUID", "existsSync", "lstatSync", "mkdirSync", "readFileSync", "renameSync", "rmSync", "writeFileSync", "dirname", "join", "resolve", "createHash", "chmodSync", "copyFileSync", "existsSync", "mkdirSync", "readFileSync", "statSync", "writeFileSync", "dirname", "join", "relative", "resolve", "require", "resolve", "join", "record", "dirname", "existsSync", "readFileSync", "createHash", "mkdirSync", "writeFileSync", "statSync", "chmodSync", "existsSync", "resolve", "mkdirSync", "dirname", "join", "chmodSync", "writeFileSync", "relative", "fileSha256", "createHash", "readFileSync", "statSync", "copyFileSync", "join", "dirname", "lstatSync", "readFileSync", "mkdirSync", "writeFileSync", "rmSync", "createHash", "renameSync", "randomUUID", "resolve", "existsSync", "join", "existsSync", "mkdirSync", "createHash", "timingSafeEqual", "claim", "join", "randomBytes", "randomId", "randomBytes", "metadataJson", "parseMetadata", "recordEvent", "timestamp", "ensureProject", "ensureProject", "channelOverlaps", "join", "requireAsset", "canonicalRoot", "requireAsset", "requireAsset", "requireAsset", "existsSync", "createRequire", "join", "require", "createRequire", "join", "existsSync", "existsSync", "realpathSync", "statSync", "relative", "resolve", "randomUUID", "value", "randomUUID", "relative", "resolve", "existsSync", "realpathSync", "statSync", "createHash", "existsSync", "statSync", "isAbsolute", "resolve", "isAbsolute", "resolve", "existsSync", "statSync", "createHash", "createHash", "spawnSync", "existsSync", "lstatSync", "readFileSync", "readdirSync", "realpathSync", "statSync", "dirname", "isAbsolute", "join", "resolve", "fileURLToPath", "readFileSync", "join", "dirname", "fileURLToPath", "resolve", "sha256", "createHash", "realpathSync", "spawnSync", "lstatSync", "isAbsolute", "readdirSync", "existsSync", "tableExists", "statSync", "record", "packageRoot", "resolve", "dirname", "fileURLToPath", "packageInfo", "readFileSync", "join", "platform", "homedir", "mkdirSync", "writeFileSync", "jobId", "join", "packageRoot", "existsSync", "mkdirSync", "dirname", "randomUUID", "code", "json", "message"]
|
|
4
|
+
"sourcesContent": ["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { homedir, platform } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { requireEdgeSummary } from '../shared/edgeSummary';\nimport {\n createAgentClaim,\n heartbeatAgentClaim,\n inspectAgentClaim,\n isAgentClaimError,\n listAgentClaims,\n parseClaimTtl,\n redactAgentClaimTokens,\n releaseAgentClaim,\n revokeAgentClaim,\n transferAgentClaim,\n type AgentClaimScopeType,\n} from '../server/agentClaims';\nimport { defaultProduct, packageRoot as lineagePackageRoot, setLineageAssetRoot } from '../server/assetCore';\nimport {\n clearLineageRerollRequest,\n getLineageNextAsset,\n getLineageSnapshot,\n listLineageRerollRequests,\n markLineageRerollRequest,\n} from '../server/assetLineage';\nimport { getLineageBrief, linkSelectedLineageChild } from '../server/assetLineageHandoff';\nimport {\n addLineageTaskComment,\n cancelLineageTask,\n claimLineageTask,\n getLineageTask,\n listLineageTasks,\n overrideLineageTask,\n startLineageTask,\n updateLineageTaskInstructions,\n} from '../server/assetLineageTasks';\nimport {\n importImageGenerationOutputs,\n importImageRerollOutput,\n inspectImageGeneration,\n planImageGeneration,\n planImageReroll,\n} from '../server/generationReceipts';\nimport { getLineageSelectionPacket } from '../server/lineageSelectionPacket';\nimport { assertLineageCodeOrigin, getLineageCodeIdentity, getLineageRuntimeInfo } from '../server/runtimeInfo';\nimport {\n assertProfileChannel,\n assertUnselectedDatabaseIsUnbound,\n bindLineageProfileDatabase,\n cloneLineageProfileAssets,\n cloneLineageProfileDatabase,\n doctorLineageProfile,\n initializeLineageProfile,\n repinLineageDevelopmentProfileRuntime,\n resolveLineageProfile,\n} from '../server/lineageProfiles';\nimport { executeManagedWriterCommand } from '../server/managedWriterRouting';\nimport { acquireProfileWriterLease, ProfileWriterLeaseConflictError } from '../server/profileWriterLease';\nimport type {\n LineageProfileAssetsCloneResult,\n LineageProfileBindResult,\n LineageProfileCloneResult,\n LineageProfileDoctorResult,\n LineageProfileInitResult,\n LineageProfileRuntimeRepinResult,\n ResolvedLineageProfile,\n} from '../shared/lineageProfileTypes';\nimport type { LineageRuntimeCodeIdentity, LineageRuntimeInfo } from '../shared/runtimeInfoTypes';\n\nexport interface LineageCliConfig {\n binName: 'lineage' | 'lineage-dev' | 'lineage-preview';\n channel: 'stable' | 'preview' | 'dev';\n defaultHost: string;\n defaultPort: number;\n displayName: string;\n}\n\ninterface StartOptions {\n assetRoot: string;\n dbPath: string;\n host: string;\n json: boolean;\n open: boolean;\n port: number;\n profile?: ResolvedLineageProfile;\n}\n\ninterface DataCommandOptions {\n assetId?: string;\n childAssetId?: string;\n claimToken?: string;\n confirmWrite: boolean;\n dbPath?: string;\n json: boolean;\n project: string;\n rootAssetId?: string;\n summary?: string;\n}\n\nconst signalExitCodes: Partial<Record<NodeJS.Signals, number>> = {\n SIGINT: 130,\n SIGTERM: 143,\n};\n\nfunction packageRoot(): string {\n return resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');\n}\n\nfunction packageVersion(): string {\n try {\n const packageInfo = JSON.parse(readFileSync(join(packageRoot(), 'package.json'), 'utf8')) as { version?: string };\n return packageInfo.version || '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nfunction dataRoot(displayName: string): string {\n if (process.env.LINEAGE_HOME) return process.env.LINEAGE_HOME;\n if (platform() === 'darwin') return join(homedir(), 'Library', 'Application Support', displayName);\n if (platform() === 'win32') return join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), displayName);\n return join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), displayName.toLowerCase().replace(/\\s+/g, '-'));\n}\n\nfunction readOption(args: string[], name: string): string | undefined {\n const prefix = `${name}=`;\n const inline = args.find(arg => arg.startsWith(prefix));\n if (inline) return inline.slice(prefix.length);\n const index = args.indexOf(name);\n if (index >= 0) return args[index + 1];\n return undefined;\n}\n\nfunction readOptions(args: string[], name: string): string[] {\n const values: string[] = [];\n const prefix = `${name}=`;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg.startsWith(prefix)) values.push(arg.slice(prefix.length));\n else if (arg === name && args[index + 1] && !args[index + 1].startsWith('--')) {\n values.push(args[index + 1]);\n index += 1;\n }\n }\n return values;\n}\n\nfunction readJsonFile(path: string, label: string): unknown {\n try {\n return JSON.parse(readFileSync(resolve(path), 'utf8')) as unknown;\n } catch (error) {\n throw new Error(`${label} must be a readable JSON file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nfunction parentFilesOption(value: string | undefined): Record<string, string[]> | undefined {\n if (value === undefined) return undefined;\n const mappings: Record<string, string[]> = {};\n for (const rawMapping of value.split(';')) {\n const separator = rawMapping.indexOf('=');\n const parent = separator >= 0 ? rawMapping.slice(0, separator).trim() : '';\n const files = separator >= 0 ? rawMapping.slice(separator + 1).split(',').map(file => file.trim()).filter(Boolean) : [];\n if (!parent || files.length === 0) throw new Error('lineage generate image import --parent-files requires parent=file[,file][;parent=file]');\n if (Object.hasOwn(mappings, parent)) throw new Error(`Duplicate generation parent mapping: ${parent}`);\n mappings[parent] = files;\n }\n return mappings;\n}\n\nexport function resolveStartOptions(config: LineageCliConfig, args: string[]): StartOptions {\n if (!profileSelector(args)) {\n throw new Error('Start requires --profile or LINEAGE_PROFILE. Create one with `profile init --profile <id> --confirm-write`, then start again with that profile');\n }\n const profile = prepareCliProfile(config, args);\n const serviceUrl = profile ? new URL(profile.service_origin) : undefined;\n const rawPort = readOption(args, '--port') || process.env.PORT || serviceUrl?.port || String(config.defaultPort);\n const port = Number(rawPort);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(`Invalid port: ${rawPort}`);\n }\n const host = readOption(args, '--host') || process.env.HOST || serviceUrl?.hostname || config.defaultHost;\n if (profile && serviceUrl && (host !== serviceUrl.hostname || port !== Number(serviceUrl.port || 80))) {\n throw new Error(`Profile ${profile.profile_id} service_origin ${profile.service_origin} conflicts with requested host/port ${host}:${port}`);\n }\n return {\n assetRoot: profile?.asset_root || resolveCliAssetRoot(args),\n dbPath: profile?.database_path || resolveCliDbPath(config, args),\n host,\n json: args.includes('--json'),\n open: args.includes('--open'),\n port,\n profile,\n };\n}\n\nfunction resolveCliAssetRoot(args: string[]): string {\n return resolve(readOption(args, '--asset-root') || process.env.LINEAGE_ASSET_ROOT || lineagePackageRoot);\n}\n\nfunction configureCliAssetRoot(args: string[]): string {\n const assetRoot = resolveCliAssetRoot(args);\n process.env.LINEAGE_ASSET_ROOT = assetRoot;\n return setLineageAssetRoot(assetRoot);\n}\n\nfunction resolveCliDbPath(config: LineageCliConfig, args: string[]): string {\n return readOption(args, '--db') || process.env.LINEAGE_DB || join(dataRoot(config.displayName), `${config.binName}.sqlite`);\n}\n\nfunction hasOption(args: string[], name: string): boolean {\n return args.includes(name) || args.some(arg => arg.startsWith(`${name}=`));\n}\n\nfunction profileSelector(args: string[]): string | undefined {\n const option = readOption(args, '--profile');\n if (option && process.env.LINEAGE_PROFILE && option !== process.env.LINEAGE_PROFILE) {\n throw new Error(`--profile ${option} conflicts with LINEAGE_PROFILE ${process.env.LINEAGE_PROFILE}`);\n }\n return option || process.env.LINEAGE_PROFILE;\n}\n\nfunction doctorFailures(result: LineageProfileDoctorResult): string {\n return result.checks.filter(check => check.status === 'fail').map(check => `${check.id}: ${check.message}`).join('; ');\n}\n\nfunction prepareCliProfile(config: LineageCliConfig, args: string[]): ResolvedLineageProfile | undefined {\n const selector = profileSelector(args);\n if (!selector) {\n assertUnselectedDatabaseIsUnbound(getLineageRuntimeInfo({ channel: config.channel, dbPath: resolveCliDbPath(config, args) }));\n return undefined;\n }\n if (hasOption(args, '--db')) throw new Error('A named profile cannot be combined with --db');\n if (hasOption(args, '--asset-root')) throw new Error('A named profile cannot be combined with --asset-root');\n const profile = resolveLineageProfile(selector);\n if (process.env.LINEAGE_DB && resolve(process.env.LINEAGE_DB) !== profile.database_path) {\n throw new Error(`Profile ${profile.profile_id} database_path conflicts with LINEAGE_DB`);\n }\n if (process.env.LINEAGE_ASSET_ROOT && resolve(process.env.LINEAGE_ASSET_ROOT) !== profile.asset_root) {\n throw new Error(`Profile ${profile.profile_id} asset_root conflicts with LINEAGE_ASSET_ROOT`);\n }\n assertProfileChannel(profile, config.channel);\n const runtime = getLineageRuntimeInfo({ channel: config.channel, dbPath: profile.database_path });\n const doctor = doctorLineageProfile(selector, { channel: config.channel, code: runtime.code, gitSha: runtime.git_sha, version: runtime.version });\n if (!doctor.ok) throw new Error(`Profile ${profile.profile_id} failed doctor: ${doctorFailures(doctor)}`);\n process.env.LINEAGE_ASSET_ROOT = profile.asset_root;\n process.env.LINEAGE_DB = profile.database_path;\n process.env.LINEAGE_PROFILE = selector;\n process.env.LINEAGE_PROFILE_ENVIRONMENT = profile.environment;\n process.env.LINEAGE_PROFILE_FINGERPRINT = profile.profile_fingerprint;\n process.env.LINEAGE_PROFILE_ID = profile.profile_id;\n process.env.LINEAGE_PROFILE_MANIFEST = profile.manifest_path;\n process.env.LINEAGE_PROFILE_SERVICE_ORIGIN = profile.service_origin;\n setLineageAssetRoot(profile.asset_root);\n return profile;\n}\n\nexport function formatLineageHelp(config: LineageCliConfig): string {\n return `${config.binName} ${packageVersion()}\n\nUsage:\n ${config.binName} start --profile <id-or-manifest> [--open] [--json]\n ${config.binName} profile init --profile <new-profile-id> [--service-origin <http-origin>] --confirm-write [--json]\n ${config.binName} profile doctor --profile <id-or-manifest> [--json]\n ${config.binName} profile bind --profile <id-or-manifest> --confirm-write [--json]\n ${config.binName} profile clone --source-db <snapshot-source> --target-profile <id-or-manifest> --confirm-write [--json]\n ${config.binName} profile clone-assets --source-asset-root <path> --target-profile <id-or-manifest> --confirm-write [--json]\n ${config.binName} profile repin-runtime --profile <development-profile> --checkout-root <path> --confirm-write [--json]\n ${config.binName} runtime info [--json]\n ${config.binName} runtime doctor [--json]\n ${config.binName} next [--project <project>] [--root <asset-id>] [--db <path>] [--json]\n ${config.binName} brief [--project <project>] [--root <asset-id>] [--db <path>] [--json]\n ${config.binName} inspect --asset-id <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} selection packet [--project <project>] [--workspace <id-or-root>|--root <asset-id>] [--channel <channel>] [--campaign <campaign>] [--context-notes <text>] [--label <label>] [--schema v2] [--out <path>] [--strict] [--db <path>] [--json]\n ${config.binName} link-child --root <asset-id> --child <asset-id> --summary \"<one-or-two-words>\" [--project <project>] [--claim-token <claim-id.secret>] [--confirm-write] [--db <path>] [--json]\n ${config.binName} generate image plan --prompt <text> --from-lineage-selection [--count <count>|--per-base-count <count>] [--project <project>] [--dry-run] [--db <path>] [--json]\n ${config.binName} generate image inspect --job-id <job-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} generate image import --job-id <job-id> --manifest <json-file> --confirm-write [--project <project>] [--db <path>] [--json]\n ${config.binName} generate image import --job-id <legacy-job-id> (--files <file,file>|--parent-files <parent=file;parent=file>) --confirm-write [--project <project>] [--db <path>] [--json]\n ${config.binName} reroll list --root <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} reroll mark --root <asset-id> --target <asset-id> [--notes <text>] [--requested-by agent|human|system] [--project <project>] [--confirm-write] [--db <path>] [--json]\n ${config.binName} reroll cancel --root <asset-id> --target <asset-id> [--project <project>] [--confirm-write] [--db <path>] [--json]\n ${config.binName} reroll plan --root <asset-id> --target <asset-id> --prompt <text> [--project <project>] [--db <path>] [--json]\n ${config.binName} reroll import --job-id <job-id> --file <scratch-file> --confirm-write [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks list --root <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks inspect --task <task-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks claim --task <task-id> --agent-name <name> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks start --task <task-id> --claim-token <claim-id.secret> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks comment --task <task-id> --message <text> [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks cancel --task <task-id> [--confirm-write] [--override] [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks override --task <task-id> --reason <text> [--instructions <text>] [--project <project>] [--db <path>] [--json]\n ${config.binName} tasks instructions --task <task-id> --instructions <text> [--project <project>] [--db <path>] [--json]\n ${config.binName} db info [--db <path>] [--json]\n ${config.binName} agent claim --project <project> --scope <scope> --target <target-id> --agent-name <name> [--channel <channel>] [--ttl 20m] [--json]\n ${config.binName} agent graph --root <asset-id> [--project <project>] [--db <path>] [--json]\n ${config.binName} agent status [--project <project>] [--json]\n ${config.binName} agent inspect --claim <claim-id> [--project <project>] [--json]\n ${config.binName} agent heartbeat --claim-token <claim-id.secret> [--json]\n ${config.binName} agent release --claim-token <claim-id.secret> [--json]\n ${config.binName} agent revoke --claim <claim-id> --project <project> --reason <text> --confirm-write [--json]\n ${config.binName} agent transfer --claim <claim-id> --to-agent-name <name> --confirm-write [--project <project>] [--json]\n ${config.binName} --help\n ${config.binName} --version\n\n${config.displayName} runs the bundled Lineage server for the ${config.channel} channel.\n\nAsset catalogs and local media default to the installed package root. Pass\n--asset-root <path> or LINEAGE_ASSET_ROOT to use an external project root.\n\nAll commands accept --profile <id-or-manifest> or LINEAGE_PROFILE. Named\nprofiles are authoritative for database, asset root, environment, and origin;\nthey cannot be combined with direct --db or --asset-root overrides. Commands\nwithout a profile run in legacy-unbound diagnostic/read-only mode.\n\nOperational commands also require an attested code origin. Stable and preview\nrun from separate lineage-channel install receipts. Dev runs only from a Git\ncheckout/worktree through npm run lineage:dev.\n\nServer startup independently verifies code origin. When --open is requested,\nthe browser opens only after /api/runtime matches the expected code, profile,\ndatabase, and unique service instance.\n\nVariation vs re-roll:\n link-child creates a new visible child variation edge.\n reroll mark -> reroll plan -> reroll import updates the same node with a new attempt.`;\n}\n\nfunction printHelp(config: LineageCliConfig): void {\n console.log(formatLineageHelp(config));\n}\n\nfunction openBrowser(url: string): void {\n const command = platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'cmd' : 'xdg-open';\n const args = platform() === 'win32' ? ['/c', 'start', '', url] : [url];\n const opener = spawn(command, args, { detached: true, stdio: 'ignore' });\n opener.unref();\n}\n\nexport function lineageServiceIdentityErrors(\n runtime: LineageRuntimeInfo,\n expected: {\n channel: LineageRuntimeInfo['channel'];\n code_fingerprint: string;\n database_path: string;\n instance_id: string;\n launcher_pid: number;\n profile?: ResolvedLineageProfile;\n },\n): string[] {\n const errors: string[] = [];\n if (runtime.channel !== expected.channel) errors.push(`channel ${runtime.channel} != ${expected.channel}`);\n if (!runtime.code?.verified) errors.push('service code identity is not verified');\n if (runtime.code?.fingerprint !== expected.code_fingerprint) errors.push(`code fingerprint ${runtime.code?.fingerprint || 'missing'} != ${expected.code_fingerprint}`);\n if (resolve(runtime.database.path) !== resolve(expected.database_path)) errors.push(`database ${runtime.database.path} != ${expected.database_path}`);\n if (runtime.service?.instance_id !== expected.instance_id) errors.push(`service instance ${runtime.service?.instance_id || 'missing'} != ${expected.instance_id}`);\n if (runtime.service?.launcher_pid !== expected.launcher_pid) errors.push(`launcher pid ${runtime.service?.launcher_pid || 'missing'} != ${expected.launcher_pid}`);\n if (expected.profile) {\n if (!runtime.profile.bound) errors.push('service profile is unbound');\n if (runtime.profile.id !== expected.profile.profile_id) errors.push(`profile ${runtime.profile.id} != ${expected.profile.profile_id}`);\n if (runtime.profile.environment !== expected.profile.environment) errors.push(`environment ${runtime.profile.environment} != ${expected.profile.environment}`);\n if (runtime.profile.fingerprint !== expected.profile.profile_fingerprint) errors.push(`profile fingerprint ${runtime.profile.fingerprint || 'missing'} != ${expected.profile.profile_fingerprint}`);\n if (runtime.schema.profile_id !== expected.profile.profile_id) errors.push(`database profile ${runtime.schema.profile_id || 'missing'} != ${expected.profile.profile_id}`);\n if (runtime.schema.profile_fingerprint !== expected.profile.profile_fingerprint) errors.push(`database fingerprint ${runtime.schema.profile_fingerprint || 'missing'} != ${expected.profile.profile_fingerprint}`);\n }\n return errors;\n}\n\nasync function openBrowserAfterReadiness(\n url: string,\n expected: Parameters<typeof lineageServiceIdentityErrors>[1],\n child: ReturnType<typeof spawn>,\n): Promise<void> {\n const deadline = Date.now() + 15_000;\n let lastError = 'service did not respond';\n while (Date.now() < deadline && child.exitCode === null) {\n try {\n const response = await fetch(`${url}/api/runtime`, { signal: AbortSignal.timeout(1_000) });\n if (response.ok) {\n const body = await response.json() as { runtime?: LineageRuntimeInfo };\n if (body.runtime) {\n const errors = lineageServiceIdentityErrors(body.runtime, expected);\n if (errors.length === 0) {\n openBrowser(url);\n return;\n }\n lastError = errors.join('; ');\n }\n } else lastError = `HTTP ${response.status}`;\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n await new Promise(resolveDelay => setTimeout(resolveDelay, 200));\n }\n throw new Error(`Service readiness failed; browser was not opened: ${lastError}`);\n}\n\nfunction positionalArgs(args: string[]): string[] {\n const values: string[] = [];\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg.startsWith('--')) {\n if (!arg.includes('=') && args[index + 1] && !args[index + 1].startsWith('--')) index += 1;\n continue;\n }\n values.push(arg);\n }\n return values;\n}\n\nfunction resolveDataCommandOptions(args: string[]): DataCommandOptions {\n configureCliAssetRoot(args);\n const positions = positionalArgs(args);\n const options = {\n assetId: readOption(args, '--asset-id') || positions[0],\n childAssetId: readOption(args, '--child'),\n claimToken: readOption(args, '--claim-token') || process.env.LINEAGE_CLAIM_TOKEN,\n confirmWrite: args.includes('--confirm-write'),\n dbPath: readOption(args, '--db'),\n json: args.includes('--json'),\n project: readOption(args, '--project') || process.env.LINEAGE_DEFAULT_PRODUCT || defaultProduct,\n rootAssetId: readOption(args, '--root'),\n summary: readOption(args, '--summary'),\n };\n if (options.dbPath) process.env.LINEAGE_DB = options.dbPath;\n return options;\n}\n\nexport function runLineageDataCommand(command: string, args: string[]): unknown {\n const options = resolveDataCommandOptions(args);\n if (command === 'next') return getLineageNextAsset(options.project, options.rootAssetId || options.assetId);\n if (command === 'brief') return getLineageBrief(options.project, options.rootAssetId || options.assetId);\n if (command === 'inspect') {\n if (!options.assetId) throw new Error('lineage inspect requires --asset-id');\n return getLineageSnapshot(options.project, options.assetId);\n }\n if (command === 'selection') {\n const subcommand = positionalArgs(args)[0] || '';\n if (subcommand !== 'packet') throw new Error(`Unknown selection command: ${subcommand}`);\n const schema = readOption(args, '--schema');\n if (schema && schema !== 'v2') throw new Error(`Unsupported selection packet schema: ${schema}. Omit --schema for v1 or pass --schema v2.`);\n const labels = readOptions(args, '--label')\n .flatMap(label => label.split(','))\n .map(label => label.trim())\n .filter(Boolean);\n const packet = getLineageSelectionPacket(options.project, {\n campaign: readOption(args, '--campaign'),\n channel: readOption(args, '--channel'),\n command: 'lineage selection packet',\n contextNotes: readOption(args, '--context-notes') || readOption(args, '--notes'),\n dbPath: options.dbPath,\n labels,\n packageVersion: packageVersion(),\n rootAssetId: options.rootAssetId,\n schema: schema === 'v2' ? 'v2' : undefined,\n strict: args.includes('--strict'),\n workspaceId: readOption(args, '--workspace') || readOption(args, '--workspace-id'),\n });\n const out = readOption(args, '--out');\n if (out) {\n const outPath = resolve(out);\n mkdirSync(dirname(outPath), { recursive: true });\n writeFileSync(outPath, `${JSON.stringify(packet, null, 2)}\\n`);\n }\n return packet;\n }\n if (command === 'link-child') {\n if (!options.childAssetId) throw new Error('lineage link-child requires --child');\n const summary = requireEdgeSummary(options.summary);\n return linkSelectedLineageChild(options.project, {\n childAssetId: options.childAssetId,\n claimToken: options.claimToken,\n confirmWrite: options.confirmWrite,\n rootAssetId: options.rootAssetId || options.assetId,\n summary,\n summaryActor: 'agent',\n });\n }\n if (command === 'generate') {\n const [resource, subcommand] = positionalArgs(args);\n if (resource !== 'image') throw new Error(`Unknown generate command: ${resource}`);\n if (subcommand === 'plan') {\n const prompt = readOption(args, '--prompt');\n const rawCount = readOption(args, '--count');\n const rawPerBaseCount = readOption(args, '--per-base-count');\n if (!prompt) throw new Error('lineage generate image plan requires --prompt');\n return planImageGeneration(options.project, {\n count: rawCount === undefined ? undefined : Number(rawCount),\n dryRun: args.includes('--dry-run'),\n fromLineageSelection: args.includes('--from-lineage-selection'),\n perBaseCount: rawPerBaseCount === undefined ? undefined : Number(rawPerBaseCount),\n prompt,\n });\n }\n if (subcommand === 'inspect') {\n const jobId = readOption(args, '--job-id');\n if (!jobId) throw new Error('lineage generate image inspect requires --job-id');\n return inspectImageGeneration(options.project, jobId);\n }\n if (subcommand === 'import') {\n const jobId = readOption(args, '--job-id');\n const manifestPath = readOption(args, '--manifest');\n const filesValue = readOption(args, '--files');\n const parentFilesValue = readOption(args, '--parent-files');\n if (!jobId) throw new Error('lineage generate image import requires --job-id');\n if (manifestPath !== undefined && (filesValue !== undefined || parentFilesValue !== undefined)) {\n throw new Error('Use --manifest or legacy --files/--parent-files, not both');\n }\n if (filesValue !== undefined && parentFilesValue !== undefined) throw new Error('Use --files or --parent-files, not both');\n return importImageGenerationOutputs(options.project, {\n confirmWrite: options.confirmWrite,\n files: filesValue === undefined ? undefined : filesValue.split(',').map(file => file.trim()).filter(Boolean),\n jobId,\n manifest: manifestPath === undefined ? undefined : readJsonFile(manifestPath, 'Generation output manifest'),\n parentFiles: parentFilesOption(parentFilesValue),\n });\n }\n throw new Error(`Unknown generate image command: ${subcommand}`);\n }\n if (command === 'reroll') {\n const subcommand = positionalArgs(args)[0] || '';\n if (subcommand === 'list') {\n if (!options.rootAssetId) throw new Error('lineage reroll list requires --root');\n return listLineageRerollRequests(options.project, options.rootAssetId);\n }\n if (subcommand === 'mark') {\n const targetAssetId = readOption(args, '--target');\n const requestedBy = rerollRequestedBy(readOption(args, '--requested-by') || 'agent');\n if (!options.rootAssetId) throw new Error('lineage reroll mark requires --root');\n if (!targetAssetId) throw new Error('lineage reroll mark requires --target');\n return markLineageRerollRequest(options.project, {\n rootAssetId: options.rootAssetId,\n nodeAssetId: targetAssetId,\n notes: readOption(args, '--notes'),\n requestedBy,\n confirmWrite: options.confirmWrite,\n });\n }\n if (subcommand === 'cancel') {\n const targetAssetId = readOption(args, '--target');\n if (!options.rootAssetId) throw new Error('lineage reroll cancel requires --root');\n if (!targetAssetId) throw new Error('lineage reroll cancel requires --target');\n return clearLineageRerollRequest(options.project, {\n rootAssetId: options.rootAssetId,\n nodeAssetId: targetAssetId,\n confirmWrite: options.confirmWrite,\n });\n }\n if (subcommand === 'plan') {\n const targetAssetId = readOption(args, '--target');\n const prompt = readOption(args, '--prompt');\n if (!options.rootAssetId) throw new Error('lineage reroll plan requires --root');\n if (!targetAssetId) throw new Error('lineage reroll plan requires --target');\n if (!prompt) throw new Error('lineage reroll plan requires --prompt');\n return planImageReroll(options.project, {\n rootAssetId: options.rootAssetId,\n targetAssetId,\n prompt,\n dryRun: args.includes('--dry-run'),\n });\n }\n if (subcommand === 'import') {\n const jobId = readOption(args, '--job-id');\n const file = readOption(args, '--file');\n if (!jobId) throw new Error('lineage reroll import requires --job-id');\n if (!file) throw new Error('lineage reroll import requires --file');\n return importImageRerollOutput(options.project, { jobId, file, confirmWrite: options.confirmWrite });\n }\n throw new Error(`Unknown reroll command: ${subcommand}`);\n }\n if (command === 'tasks') {\n const subcommand = positionalArgs(args)[0] || '';\n const taskId = readOption(args, '--task');\n if (subcommand === 'list') {\n if (!options.rootAssetId) throw new Error('lineage tasks list requires --root');\n return listLineageTasks(options.project, options.rootAssetId);\n }\n if (subcommand === 'inspect') {\n if (!taskId) throw new Error('lineage tasks inspect requires --task');\n return getLineageTask(options.project, taskId);\n }\n if (subcommand === 'claim') {\n const agentName = readOption(args, '--agent-name');\n if (!taskId) throw new Error('lineage tasks claim requires --task');\n if (!agentName) throw new Error('lineage tasks claim requires --agent-name');\n return claimLineageTask(options.project, { taskId, agentName });\n }\n if (subcommand === 'start') {\n if (!taskId) throw new Error('lineage tasks start requires --task');\n if (!options.claimToken) throw new Error('lineage tasks start requires --claim-token');\n return startLineageTask(options.project, { taskId, claimToken: options.claimToken });\n }\n if (subcommand === 'comment') {\n const message = readOption(args, '--message');\n if (!taskId) throw new Error('lineage tasks comment requires --task');\n if (!message) throw new Error('lineage tasks comment requires --message');\n return addLineageTaskComment(options.project, {\n actor: readOption(args, '--actor') || 'human',\n message,\n taskId,\n });\n }\n if (subcommand === 'cancel') {\n if (!taskId) throw new Error('lineage tasks cancel requires --task');\n return cancelLineageTask(options.project, {\n actor: readOption(args, '--actor') || 'human',\n confirmWrite: options.confirmWrite,\n override: args.includes('--override'),\n taskId,\n });\n }\n if (subcommand === 'override') {\n const reason = readOption(args, '--reason');\n if (!taskId) throw new Error('lineage tasks override requires --task');\n if (!reason) throw new Error('lineage tasks override requires --reason');\n return overrideLineageTask(options.project, {\n actor: readOption(args, '--actor') || 'human',\n instructions: readOption(args, '--instructions'),\n reason,\n taskId,\n });\n }\n if (subcommand === 'instructions') {\n const instructions = readOption(args, '--instructions');\n if (!taskId) throw new Error('lineage tasks instructions requires --task');\n if (instructions === undefined) throw new Error('lineage tasks instructions requires --instructions');\n return updateLineageTaskInstructions(options.project, { instructions, taskId });\n }\n throw new Error(`Unknown tasks command: ${subcommand}`);\n }\n throw new Error(`Unknown command: ${command}`);\n}\n\nfunction rerollRequestedBy(value: string): 'agent' | 'human' | 'system' {\n if (value === 'agent' || value === 'human' || value === 'system') return value;\n throw new Error(`Invalid re-roll requester: ${value}`);\n}\n\nexport function printDataResult(command: string, result: unknown, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (command === 'next' && result && typeof result === 'object' && 'reason' in result) {\n const next = result as { next_asset?: { asset_id: string; title: string } | null; reason: string; root_asset_id: string };\n console.log(next.next_asset ? `${next.next_asset.asset_id}: ${next.next_asset.title}` : `No next asset: ${next.reason}`);\n console.log(`Root: ${next.root_asset_id}`);\n return;\n }\n if (command === 'brief' && result && typeof result === 'object' && 'brief' in result) {\n const brief = result as { brief: { title: string; prompt: string } };\n console.log(brief.brief.title);\n console.log(brief.brief.prompt);\n return;\n }\n if (command === 'inspect' && result && typeof result === 'object' && 'nodes' in result) {\n const snapshot = result as { active_asset_id: string; edges: unknown[]; nodes: unknown[]; root_asset_id: string };\n console.log(`${snapshot.root_asset_id}: ${snapshot.nodes.length} node(s), ${snapshot.edges.length} edge(s)`);\n console.log(`Active: ${snapshot.active_asset_id}`);\n return;\n }\n if (command === 'selection' && result && typeof result === 'object' && 'packet_id' in result) {\n const packet = result as { assets?: unknown[]; packet_id: string; selection?: { count: number }; warnings?: string[]; workspace?: { root_asset_id: string } };\n console.log(`${packet.packet_id}: ${packet.selection?.count || packet.assets?.length || 0} selected asset(s)`);\n if (packet.workspace?.root_asset_id) console.log(`Root: ${packet.workspace.root_asset_id}`);\n for (const warning of packet.warnings || []) console.log(`Warning: ${warning}`);\n return;\n }\n if (command === 'link-child' && result && typeof result === 'object') {\n const link = result as { dryRun?: boolean; edge?: { child_asset_id: string; parent_asset_id: string }; message?: string; warning?: string };\n console.log(link.message || `${link.dryRun ? 'Dry run: ' : ''}Link ${link.edge?.child_asset_id || 'child'} from ${link.edge?.parent_asset_id || 'parent'}`);\n if (link.warning) console.log(`Warning: ${link.warning}`);\n return;\n }\n if (command === 'generate' && result && typeof result === 'object' && 'job' in result) {\n const generation = result as { idempotent?: boolean; imported?: unknown[]; job?: { id: string; status: string } };\n if (generation.imported) {\n console.log(`${generation.idempotent ? 'Already imported' : 'Imported'} ${generation.imported.length} output(s) for ${generation.job?.id || 'job'}`);\n } else {\n console.log(`Generation job ${generation.job?.id || 'job'} ${generation.job?.status || 'unknown'}`);\n }\n return;\n }\n if (command === 'reroll' && result && typeof result === 'object') {\n if ('requests' in result) {\n const listed = result as { requests: Array<{ node_asset_id: string; notes?: string }> };\n console.log(`${listed.requests.length} pending re-roll target(s)`);\n for (const request of listed.requests) console.log(`${request.node_asset_id}${request.notes ? `: ${request.notes}` : ''}`);\n return;\n }\n if ('job' in result) {\n const planned = result as { imported?: unknown[]; job?: { id: string; status: string } };\n console.log(planned.imported ? `Imported re-roll for ${planned.job?.id || 'job'}` : `Planned re-roll ${planned.job?.id || 'job'}`);\n return;\n }\n if ('request' in result) {\n const mutation = result as { dryRun?: boolean; request?: { node_asset_id: string; status: string } };\n console.log(`${mutation.dryRun ? 'Dry run: ' : ''}Re-roll ${mutation.request?.status || 'request'} for ${mutation.request?.node_asset_id || 'target'}`);\n return;\n }\n }\n if (command === 'tasks' && result && typeof result === 'object') {\n if ('tasks' in result) {\n const listed = result as { tasks: Array<{ id: string; status: string; target_asset_id: string; task_type: string }> };\n console.log(`${listed.tasks.length} lineage task(s)`);\n for (const task of listed.tasks) console.log(`${task.id} ${task.task_type} ${task.status} ${task.target_asset_id}`);\n return;\n }\n if ('task' in result) {\n const mutation = result as {\n dryRun?: boolean;\n events?: Array<{ event_type: string }>;\n task?: { id: string; status: string; target_asset_id: string; task_type: string };\n };\n const prefix = mutation.dryRun ? 'Dry run: ' : '';\n console.log(`${prefix}${mutation.task?.id || 'task'} ${mutation.task?.task_type || 'task'} ${mutation.task?.status || 'unknown'} ${mutation.task?.target_asset_id || ''}`.trim());\n if ('claim_token' in mutation && typeof mutation.claim_token === 'string') console.log(`Token: ${mutation.claim_token}`);\n if (mutation.events && mutation.events.length > 0) console.log(`Events: ${mutation.events.map(event => event.event_type).join(', ')}`);\n return;\n }\n }\n console.log(String(result));\n}\n\nexport function runLineageDbCommand(config: LineageCliConfig, command: string, args: string[]): unknown {\n configureCliAssetRoot(args);\n const dbPath = resolveCliDbPath(config, args);\n process.env.LINEAGE_DB = dbPath;\n if (command === 'info') return getLineageRuntimeInfo({ channel: config.channel, dbPath });\n throw new Error(`Unknown db command: ${command}`);\n}\n\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'doctor', args: string[]): LineageProfileDoctorResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'init', args: string[]): LineageProfileInitResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'bind', args: string[]): LineageProfileBindResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'clone', args: string[]): Promise<LineageProfileCloneResult>;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'clone-assets', args: string[]): LineageProfileAssetsCloneResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: 'repin-runtime', args: string[]): LineageProfileRuntimeRepinResult;\nexport function runLineageProfileCommand(config: LineageCliConfig, command: string, args: string[]): LineageProfileDoctorResult | LineageProfileInitResult | LineageProfileBindResult | LineageProfileAssetsCloneResult | LineageProfileRuntimeRepinResult | Promise<LineageProfileCloneResult>;\nexport function runLineageProfileCommand(\n config: LineageCliConfig,\n command: string,\n args: string[],\n): LineageProfileDoctorResult | LineageProfileInitResult | LineageProfileBindResult | LineageProfileAssetsCloneResult | LineageProfileRuntimeRepinResult | Promise<LineageProfileCloneResult> {\n const runtime = getLineageRuntimeInfo({ channel: config.channel });\n const runtimeIdentity = { channel: config.channel, code: runtime.code, gitSha: runtime.git_sha, version: runtime.version };\n if (command === 'init') {\n if (hasOption(args, '--db')) throw new Error('Profile init cannot be combined with --db');\n if (hasOption(args, '--asset-root')) throw new Error('Profile init cannot be combined with --asset-root');\n if (!args.includes('--confirm-write')) throw new Error('Profile init requires --confirm-write');\n const profileId = readOption(args, '--profile');\n if (!profileId) throw new Error('lineage profile init requires --profile');\n if (process.env.LINEAGE_PROFILE && process.env.LINEAGE_PROFILE !== profileId) {\n throw new Error('Profile init requires an explicit --profile that does not conflict with LINEAGE_PROFILE');\n }\n const serviceOrigin = readOption(args, '--service-origin') || `http://${config.defaultHost}:${config.defaultPort}`;\n return initializeLineageProfile(profileId, serviceOrigin, runtimeIdentity, true, (profile, initialize) => {\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n try {\n return initialize();\n } finally {\n writerLease.release();\n }\n });\n }\n if (command === 'clone') {\n const source = readOption(args, '--source-db');\n const target = readOption(args, '--target-profile');\n if (!source || !target) throw new Error('lineage profile clone requires --source-db and --target-profile');\n if (hasOption(args, '--profile')) throw new Error('Profile clone uses --target-profile, not --profile');\n if (!args.includes('--confirm-write')) throw new Error('Profile clone requires --confirm-write');\n const targetProfile = resolveLineageProfile(target);\n const writerLease = acquireProfileWriterLease(targetProfile, config.channel, 'cli');\n return cloneLineageProfileDatabase(source, target, runtimeIdentity, true)\n .finally(writerLease.release);\n }\n if (command === 'clone-assets') {\n const source = readOption(args, '--source-asset-root');\n const target = readOption(args, '--target-profile');\n if (!source || !target) throw new Error('lineage profile clone-assets requires --source-asset-root and --target-profile');\n if (hasOption(args, '--profile')) throw new Error('Profile asset clone uses --target-profile, not --profile');\n if (!args.includes('--confirm-write')) throw new Error('Profile asset clone requires --confirm-write');\n const targetProfile = resolveLineageProfile(target);\n const writerLease = acquireProfileWriterLease(targetProfile, config.channel, 'cli');\n try {\n return cloneLineageProfileAssets(source, target, runtimeIdentity, true);\n } finally {\n writerLease.release();\n }\n }\n if (hasOption(args, '--db')) throw new Error(`Profile ${command} cannot be combined with --db`);\n if (hasOption(args, '--asset-root')) throw new Error(`Profile ${command} cannot be combined with --asset-root`);\n const selector = profileSelector(args);\n if (!selector) throw new Error(`lineage profile ${command} requires --profile or LINEAGE_PROFILE`);\n if (command === 'doctor') return doctorLineageProfile(selector, runtimeIdentity);\n if (command === 'repin-runtime') {\n const checkoutRoot = readOption(args, '--checkout-root');\n if (!checkoutRoot) throw new Error('Profile runtime repin requires --checkout-root');\n if (!args.includes('--confirm-write')) throw new Error('Profile runtime repin requires --confirm-write');\n const profile = resolveLineageProfile(selector);\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n try {\n return repinLineageDevelopmentProfileRuntime(selector, checkoutRoot, runtimeIdentity, true);\n } finally {\n writerLease.release();\n }\n }\n if (command === 'bind') {\n if (!args.includes('--confirm-write')) throw new Error('Profile bind requires --confirm-write');\n const profile = resolveLineageProfile(selector);\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n try {\n return bindLineageProfileDatabase(selector, runtimeIdentity, true);\n } finally {\n writerLease.release();\n }\n }\n throw new Error(`Unknown profile command: ${command}`);\n}\n\nfunction printProfileResult(result: LineageProfileDoctorResult | LineageProfileInitResult | LineageProfileBindResult | LineageProfileCloneResult | LineageProfileAssetsCloneResult | LineageProfileRuntimeRepinResult, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (result.schema_version === 'lineage.profile_init.v1') {\n console.log(`Initialized ${result.profile_id} at ${result.manifest_path}`);\n console.log(`Service: ${result.service_origin}`);\n } else if (result.schema_version === 'lineage.profile_doctor.v1') {\n console.log(`Profile doctor: ${result.ok ? 'ok' : 'failed'}`);\n for (const check of result.checks) console.log(`${check.status.toUpperCase()} ${check.id}: ${check.message}`);\n } else if (result.schema_version === 'lineage.profile_bind.v1') {\n console.log(`${result.already_bound ? 'Already bound' : 'Bound'} ${result.database_path} to ${result.identity.profile_id}`);\n } else if (result.schema_version === 'lineage.profile_clone_receipt.v1') {\n console.log(`Cloned ${result.source_database_path} to ${result.database_path} for ${result.target_identity.profile_id}`);\n console.log(`Receipt: ${result.receipt_path}`);\n } else if (result.schema_version === 'lineage.profile_runtime_repin_receipt.v1') {\n console.log(`${result.changed ? 'Repinned' : 'Already pinned'} ${result.profile_id} to checkout ${result.checkout_root}`);\n console.log(`Code fingerprint: ${result.new_code_fingerprint}`);\n } else {\n console.log(`Cloned ${result.files_copied} referenced asset file(s) into ${result.asset_root}`);\n console.log(`Receipt: ${result.receipt_path}`);\n }\n}\n\nexport function lineageProfileDoctorExitCode(result: LineageProfileDoctorResult): 0 | 1 {\n return result.ok ? 0 : 1;\n}\n\nexport function runLineageRuntimeCommand(config: LineageCliConfig, command: string): LineageRuntimeCodeIdentity {\n if (command === 'info') return getLineageCodeIdentity(config.channel);\n if (command === 'doctor') return assertLineageCodeOrigin(config.channel);\n throw new Error(`Unknown runtime command: ${command}`);\n}\n\nfunction printRuntimeResult(result: LineageRuntimeCodeIdentity, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n console.log(`Code origin: ${result.origin}`);\n console.log(`Code root: ${result.root}`);\n console.log(`Channel: ${result.channel}`);\n console.log(`Version: ${result.package_version}`);\n if (result.git_sha) console.log(`Git: ${result.git_sha}`);\n if (result.dirty !== undefined) console.log(`Dirty: ${result.dirty ? 'yes' : 'no'}`);\n console.log(`Fingerprint: ${result.fingerprint}`);\n console.log(`Verified: ${result.verified ? 'yes' : 'no'}`);\n for (const error of result.errors) console.log(`FAIL: ${error}`);\n}\n\nexport function lineageCliRequiresWriterLease(command: string, args: string[]): boolean {\n if (command === 'next' || command === 'brief' || command === 'inspect' || command === 'selection') return false;\n const positions = positionalArgs(args);\n const subcommand = positions[0] || '';\n if (command === 'generate') return positions[0] !== 'image' || positions[1] !== 'inspect';\n if (command === 'reroll') return subcommand !== 'list';\n if (command === 'tasks') return subcommand !== 'list' && subcommand !== 'inspect';\n if (command === 'db') return subcommand !== 'info';\n if (command === 'agent') return subcommand !== 'status' && subcommand !== 'graph' && subcommand !== 'inspect';\n return true;\n}\n\nexport function lineageCliCanDelegateMutation(command: string, args: string[]): boolean {\n const positions = positionalArgs(args);\n const subcommand = positions[0] || '';\n if (command === 'link-child') return true;\n if (command === 'generate') return positions[0] === 'image' && ['plan', 'import'].includes(positions[1] || '');\n if (command === 'reroll') return ['mark', 'cancel', 'plan', 'import'].includes(subcommand);\n if (command === 'tasks') return ['claim', 'start', 'comment', 'cancel', 'override', 'instructions'].includes(subcommand);\n if (command === 'agent') return ['claim', 'heartbeat', 'release', 'revoke', 'transfer'].includes(subcommand);\n return false;\n}\n\nfunction argsWithoutProfileSelector(args: string[]): string[] {\n const filtered: string[] = [];\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === '--profile') {\n index += 1;\n continue;\n }\n if (arg.startsWith('--profile=')) continue;\n filtered.push(arg);\n }\n return filtered;\n}\n\nexport function executeDelegatedLineageMutation(command: string, args: string[]): unknown {\n if (!lineageCliCanDelegateMutation(command, args)) throw new Error(`Unsupported managed writer command: ${command}`);\n if (command === 'agent') {\n const agentCommand = args[0] || '';\n return runLineageAgentCommand(agentCommand, args.slice(1));\n }\n return runLineageDataCommand(command, args);\n}\n\nfunction printDbResult(command: string, result: unknown, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (command === 'info' && result && typeof result === 'object' && 'database' in result) {\n const runtime = result as {\n asset_root: string;\n channel: string;\n code?: LineageRuntimeCodeIdentity;\n database: { error?: string; exists: boolean; modified_at?: string; path: string; projects?: number; size_bytes?: number; workspaces?: number };\n git_sha?: string;\n node_env?: string;\n version: string;\n };\n console.log(`Channel: ${runtime.channel}`);\n console.log(`Version: ${runtime.version}`);\n if (runtime.code) {\n console.log(`Code: ${runtime.code.origin} ${runtime.code.verified ? 'verified' : 'unverified'} ${runtime.code.fingerprint}`);\n console.log(`Code root: ${runtime.code.root}`);\n }\n if (runtime.git_sha) console.log(`Git: ${runtime.git_sha}`);\n if (runtime.node_env) console.log(`Node env: ${runtime.node_env}`);\n console.log(`Assets: ${runtime.asset_root}`);\n console.log(`SQLite: ${runtime.database.path}`);\n console.log(`Exists: ${runtime.database.exists ? 'yes' : 'no'}`);\n if (runtime.database.size_bytes !== undefined) console.log(`Size: ${runtime.database.size_bytes} bytes`);\n if (runtime.database.modified_at) console.log(`Modified: ${runtime.database.modified_at}`);\n if (runtime.database.projects !== undefined) console.log(`Projects: ${runtime.database.projects}`);\n if (runtime.database.workspaces !== undefined) console.log(`Workspaces: ${runtime.database.workspaces}`);\n if (runtime.database.error) console.log(`Warning: ${runtime.database.error}`);\n return;\n }\n console.log(String(result));\n}\n\nexport function runLineageAgentCommand(command: string, args: string[]): unknown {\n configureCliAssetRoot(args);\n const dbPath = readOption(args, '--db');\n if (dbPath) process.env.LINEAGE_DB = dbPath;\n const project = readOption(args, '--project') || process.env.LINEAGE_DEFAULT_PRODUCT || defaultProduct;\n const claimId = readOption(args, '--claim');\n const claimToken = readOption(args, '--claim-token') || process.env.LINEAGE_CLAIM_TOKEN;\n if (command === 'claim') {\n return createAgentClaim({\n agentId: readOption(args, '--agent-id'),\n agentKind: readOption(args, '--agent-kind'),\n agentName: readOption(args, '--agent-name') || '',\n channel: readOption(args, '--channel'),\n force: args.includes('--force'),\n project,\n reason: readOption(args, '--reason'),\n scopeType: (readOption(args, '--scope') || '') as AgentClaimScopeType,\n targetId: readOption(args, '--target') || '',\n targetTitle: readOption(args, '--target-title'),\n threadId: readOption(args, '--thread-id'),\n ttlSeconds: parseClaimTtl(readOption(args, '--ttl')),\n });\n }\n if (command === 'status') return listAgentClaims(project);\n if (command === 'graph') {\n const rootAssetId = readOption(args, '--root') || readOption(args, '--asset-id') || positionalArgs(args)[0];\n if (!rootAssetId) throw new Error('lineage agent graph requires --root');\n return getLineageSnapshot(project, rootAssetId);\n }\n if (command === 'inspect') {\n if (!claimId) throw new Error('lineage agent inspect requires --claim');\n return inspectAgentClaim(claimId, project);\n }\n if (command === 'heartbeat') {\n if (!claimToken) throw new Error('lineage agent heartbeat requires --claim-token');\n return heartbeatAgentClaim(claimToken, parseClaimTtl(readOption(args, '--ttl')));\n }\n if (command === 'release') {\n if (!claimToken) throw new Error('lineage agent release requires --claim-token');\n return releaseAgentClaim(claimToken);\n }\n if (command === 'revoke') {\n if (!claimId) throw new Error('lineage agent revoke requires --claim');\n return revokeAgentClaim(project, claimId, {\n actor: readOption(args, '--actor') || 'human',\n confirmWrite: args.includes('--confirm-write'),\n reason: readOption(args, '--reason'),\n });\n }\n if (command === 'transfer') {\n if (!claimId) throw new Error('lineage agent transfer requires --claim');\n return transferAgentClaim(project, claimId, {\n actor: readOption(args, '--actor') || 'human',\n confirmWrite: args.includes('--confirm-write'),\n reason: readOption(args, '--reason'),\n toAgentName: readOption(args, '--to-agent-name') || '',\n });\n }\n throw new Error(`Unknown agent command: ${command}`);\n}\n\nfunction printAgentResult(command: string, result: unknown, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (command === 'claim' && result && typeof result === 'object' && 'claim' in result) {\n const created = result as { claim?: { id: string; target_id: string }; claim_token?: string };\n console.log(`Claimed ${created.claim?.target_id || 'target'} as ${created.claim?.id || 'claim'}`);\n if (created.claim_token) console.log(`Token: ${created.claim_token}`);\n return;\n }\n if (command === 'status' && result && typeof result === 'object' && 'claims' in result) {\n const status = result as { claims: Array<{ agent_name: string; derived_state: string; target_id: string }> };\n if (status.claims.length === 0) {\n console.log('No agent claims.');\n return;\n }\n for (const claim of status.claims) console.log(`${claim.agent_name} ${claim.derived_state} ${claim.target_id}`);\n return;\n }\n if (result && typeof result === 'object' && 'claim' in result) {\n const inspected = result as { claim?: { id: string; status: string; target_id: string } };\n console.log(`${inspected.claim?.id || 'claim'} ${inspected.claim?.status || 'unknown'} ${inspected.claim?.target_id || ''}`.trim());\n return;\n }\n if (command === 'graph' && result && typeof result === 'object' && 'nodes' in result) {\n console.log(formatAgentGraphDigest(result as AgentGraphDigestSnapshot));\n return;\n }\n console.log(String(result));\n}\n\ninterface AgentGraphDigestSnapshot {\n active_asset_id: string;\n edges: Array<{ child_asset_id: string; parent_asset_id: string }>;\n latest?: string[];\n nodes: Array<{ asset_id: string; is_latest?: boolean; title?: string }>;\n root_asset_id: string;\n selected?: string[];\n}\n\nexport function formatAgentGraphDigest(snapshot: AgentGraphDigestSnapshot): string {\n const lines: string[] = [];\n const titleFor = (assetId: string) => {\n const node = snapshot.nodes.find(item => item.asset_id === assetId);\n return node?.title ? `${node.title} (${assetId})` : assetId;\n };\n const root = snapshot.nodes.find(node => node.asset_id === snapshot.root_asset_id);\n lines.push(`Lineage graph: ${root?.title || snapshot.root_asset_id}`);\n lines.push(`Root: ${snapshot.root_asset_id}`);\n lines.push(`Active: ${titleFor(snapshot.active_asset_id)}`);\n lines.push(`Nodes: ${snapshot.nodes.length} Edges: ${snapshot.edges.length}`);\n const selected = snapshot.selected || [];\n if (selected.length > 0) {\n lines.push('Next variation:');\n for (const assetId of selected) lines.push(`- ${titleFor(assetId)}`);\n }\n const latest = snapshot.latest || snapshot.nodes.filter(node => node.is_latest).map(node => node.asset_id);\n if (latest.length > 0) {\n lines.push('Latest leaves:');\n for (const assetId of latest) lines.push(`- ${titleFor(assetId)}`);\n }\n lines.push('Edges:');\n for (const edge of snapshot.edges) lines.push(`- ${titleFor(edge.parent_asset_id)} -> ${titleFor(edge.child_asset_id)}`);\n return lines.join('\\n');\n}\n\nfunction start(config: LineageCliConfig, args: string[]): void {\n let options: StartOptions;\n const json = args.includes('--json');\n try {\n options = resolveStartOptions(config, args);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n const serverPath = join(packageRoot(), 'dist', 'server.js');\n if (!existsSync(serverPath)) {\n const message = `Missing bundled server at ${serverPath}. Run npm run build before using ${config.binName} start from a source checkout.`;\n if (options.json) console.error(JSON.stringify({ ok: false, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n\n mkdirSync(dirname(options.dbPath), { recursive: true });\n const url = `http://${options.host}:${options.port}`;\n if (options.json) {\n console.log(JSON.stringify({ assetRoot: options.assetRoot, channel: config.channel, dbPath: options.dbPath, host: options.host, port: options.port, profile: options.profile ? { environment: options.profile.environment, id: options.profile.profile_id } : { bound: false, id: 'legacy-unbound' }, status: 'starting', url }, null, 2));\n } else {\n console.log(`${config.displayName} starting at ${url}`);\n if (options.profile) console.log(`Profile: ${options.profile.profile_id} (${options.profile.environment})`);\n console.log(`SQLite: ${options.dbPath}`);\n console.log(`Assets: ${options.assetRoot}`);\n }\n const code = getLineageCodeIdentity(config.channel);\n const serviceInstanceId = process.env.LINEAGE_SERVICE_INSTANCE_ID || randomUUID();\n\n const child = spawn(process.execPath, [serverPath], {\n env: {\n ...process.env,\n HOST: options.host,\n LINEAGE_ASSET_ROOT: options.assetRoot,\n LINEAGE_CHANNEL: config.channel,\n LINEAGE_DB: options.dbPath,\n LINEAGE_PROFILE: process.env.LINEAGE_PROFILE,\n LINEAGE_PROFILE_ENVIRONMENT: options.profile?.environment,\n LINEAGE_PROFILE_FINGERPRINT: options.profile?.profile_fingerprint,\n LINEAGE_PROFILE_ID: options.profile?.profile_id,\n LINEAGE_PROFILE_MANIFEST: options.profile?.manifest_path,\n LINEAGE_PROFILE_SERVICE_ORIGIN: options.profile?.service_origin,\n LINEAGE_LAUNCHER_PID: String(process.pid),\n LINEAGE_SERVICE_INSTANCE_ID: serviceInstanceId,\n LINEAGE_DB_ACCESS: undefined,\n NODE_ENV: 'production',\n PORT: String(options.port),\n },\n stdio: 'inherit',\n });\n\n if (options.open) {\n void openBrowserAfterReadiness(url, {\n channel: config.channel,\n code_fingerprint: code.fingerprint,\n database_path: options.dbPath,\n instance_id: serviceInstanceId,\n launcher_pid: process.pid,\n profile: options.profile,\n }, child).catch(error => {\n console.error(`${config.binName}: ${error instanceof Error ? error.message : String(error)}`);\n child.kill('SIGTERM');\n });\n }\n\n let forwardedSignal: NodeJS.Signals | undefined;\n const stop = (signal: NodeJS.Signals) => {\n forwardedSignal = signal;\n child.kill(signal);\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n child.on('exit', code => process.exit(code ?? (forwardedSignal ? signalExitCodes[forwardedSignal] || 1 : 0)));\n child.on('error', error => {\n console.error(`${config.binName}: failed to start server: ${error.message}`);\n process.exit(1);\n });\n}\n\nexport async function runLineageCli(config: LineageCliConfig, args = process.argv.slice(2)): Promise<void> {\n process.env.LINEAGE_CHANNEL = config.channel;\n if (args.includes('--help') || args.includes('-h') || args.length === 0) {\n printHelp(config);\n process.exit(0);\n }\n\n if (args.includes('--version') || args.includes('-v')) {\n console.log(packageVersion());\n process.exit(0);\n }\n\n const normalizedArgs = args[0] === 'lineage' ? args.slice(1) : args;\n const [command] = normalizedArgs;\n\n if (command === 'profile') {\n const commandArgs = normalizedArgs.slice(2);\n const profileCommand = normalizedArgs[1] || '';\n const json = commandArgs.includes('--json');\n try {\n const result = runLineageProfileCommand(config, profileCommand, commandArgs);\n if (result instanceof Promise) {\n result.then(value => {\n printProfileResult(value, json);\n process.exit(0);\n }).catch(error => {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `profile ${profileCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n });\n return;\n }\n printProfileResult(result, json);\n process.exit(result.schema_version === 'lineage.profile_doctor.v1' ? lineageProfileDoctorExitCode(result) : 0);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `profile ${profileCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n }\n\n if (command === 'runtime') {\n const runtimeCommand = normalizedArgs[1] || '';\n const commandArgs = normalizedArgs.slice(2);\n const json = commandArgs.includes('--json');\n try {\n printRuntimeResult(runLineageRuntimeCommand(config, runtimeCommand), json);\n process.exit(0);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `runtime ${runtimeCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n }\n\n const originDiagnosticOnly = command === 'db' && normalizedArgs[1] === 'info';\n if (!originDiagnosticOnly) {\n try {\n assertLineageCodeOrigin(config.channel);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const json = normalizedArgs.includes('--json');\n if (json) console.error(JSON.stringify({ ok: false, command, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n }\n\n if (command === 'start') {\n start(config, normalizedArgs.slice(1));\n return;\n }\n\n let managedWriterProfile: ResolvedLineageProfile | undefined;\n try {\n const profile = prepareCliProfile(config, normalizedArgs.slice(1));\n const requiresWriter = lineageCliRequiresWriterLease(command, normalizedArgs.slice(1));\n if (profile) {\n if (requiresWriter) {\n delete process.env.LINEAGE_DB_ACCESS;\n try {\n const writerLease = acquireProfileWriterLease(profile, config.channel, 'cli');\n process.once('exit', writerLease.release);\n } catch (error) {\n if (!(error instanceof ProfileWriterLeaseConflictError) || error.owner.role !== 'service') throw error;\n process.env.LINEAGE_DB_ACCESS = 'read-only';\n managedWriterProfile = profile;\n }\n } else {\n process.env.LINEAGE_DB_ACCESS = 'read-only';\n }\n } else if (requiresWriter) {\n throw new Error('Persistent writes require --profile; legacy-unbound access is read-only. Create a fresh profile with `profile init --profile <id> --confirm-write`, then pass that profile to the command');\n } else {\n process.env.LINEAGE_DB_ACCESS = 'read-only';\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const json = normalizedArgs.includes('--json');\n if (json) console.error(JSON.stringify({ ok: false, command, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n\n if (command === 'next' || command === 'brief' || command === 'inspect' || command === 'selection' || command === 'link-child' || command === 'generate' || command === 'reroll' || command === 'tasks') {\n const commandArgs = normalizedArgs.slice(1);\n const json = commandArgs.includes('--json');\n try {\n const result = managedWriterProfile\n ? await executeManagedWriterCommand(managedWriterProfile, config.channel, command, argsWithoutProfileSelector(commandArgs))\n : runLineageDataCommand(command, commandArgs);\n printDataResult(command, result, json);\n } catch (error) {\n const message = redactAgentClaimTokens(error instanceof Error ? error.message : String(error));\n if (json) {\n const output = isAgentClaimError(error)\n ? { ok: false, command, error: error.code, message, conflicts: error.conflicts }\n : { ok: false, command, error: message };\n console.error(JSON.stringify(output, null, 2));\n }\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n process.exit(0);\n }\n\n if (command === 'db') {\n const commandArgs = normalizedArgs.slice(2);\n const dbCommand = normalizedArgs[1] || '';\n const json = commandArgs.includes('--json');\n try {\n printDbResult(dbCommand, runLineageDbCommand(config, dbCommand, commandArgs), json);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (json) console.error(JSON.stringify({ ok: false, command: `db ${dbCommand}`, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n }\n process.exit(0);\n }\n\n if (command === 'agent') {\n const commandArgs = normalizedArgs.slice(2);\n const agentCommand = normalizedArgs[1] || '';\n const json = commandArgs.includes('--json');\n try {\n const result = managedWriterProfile\n ? await executeManagedWriterCommand(\n managedWriterProfile,\n config.channel,\n 'agent',\n argsWithoutProfileSelector([agentCommand, ...commandArgs]),\n )\n : runLineageAgentCommand(agentCommand, commandArgs);\n printAgentResult(agentCommand, result, json);\n } catch (error) {\n const message = redactAgentClaimTokens(error instanceof Error ? error.message : String(error));\n if (json) {\n const output = isAgentClaimError(error)\n ? { ok: false, command: `agent ${agentCommand}`, error: error.code, message, conflicts: error.conflicts }\n : { ok: false, command: `agent ${agentCommand}`, error: message };\n console.error(JSON.stringify(output, null, 2));\n } else {\n console.error(`${config.binName}: ${message}`);\n }\n process.exit(1);\n }\n process.exit(0);\n }\n\n const json = args.includes('--json');\n const message = `Unknown command: ${command}`;\n if (json) console.error(JSON.stringify({ ok: false, command, error: message }, null, 2));\n else console.error(`${config.binName}: ${message}`);\n process.exit(1);\n}\n", "export const edgeSummaryWordLimit = 2 as const;\n\nexport type EdgeSummaryValidationCode = 'not_text' | 'required' | 'too_many_words';\n\nexport class EdgeSummaryValidationError extends Error {\n constructor(\n public readonly code: EdgeSummaryValidationCode,\n message: string,\n ) {\n super(message);\n this.name = 'EdgeSummaryValidationError';\n }\n}\n\nexport function normalizeEdgeSummary(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string') throw new EdgeSummaryValidationError('not_text', 'Edge summary must be text');\n const words = value.trim().split(/\\s+/u).filter(Boolean);\n if (words.length === 0) return undefined;\n if (words.length > edgeSummaryWordLimit) {\n throw new EdgeSummaryValidationError('too_many_words', `Edge summary must contain at most ${edgeSummaryWordLimit} words`);\n }\n return words.join(' ');\n}\n\nexport function requireEdgeSummary(value: unknown): string {\n const summary = normalizeEdgeSummary(value);\n if (!summary) throw new EdgeSummaryValidationError('required', 'Edge summary is required');\n return summary;\n}\n", "import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\n\nexport type AgentClaimScopeType = 'lineage_workspace' | 'lineage_task' | 'content_post' | 'content_queue_lane' | 'selection_set' | 'project_channel';\ntype AgentClaimStatus = 'active' | 'expired' | 'released' | 'revoked' | 'transferred';\n\nexport interface AgentClaim {\n id: string;\n project: string;\n channel?: string;\n scope_type: AgentClaimScopeType;\n target_id: string;\n target_title?: string;\n agent_id?: string;\n agent_name: string;\n agent_kind: string;\n thread_id?: string;\n status: AgentClaimStatus;\n created_at: string;\n heartbeat_at: string;\n expires_at: string;\n released_at?: string;\n revoked_at?: string;\n revoked_by?: string;\n override_reason?: string;\n metadata?: Record<string, unknown>;\n heartbeat_age_seconds: number;\n derived_state: 'active' | 'idle' | 'stale' | 'expired';\n}\n\ninterface AgentClaimEvent {\n claim_id: string;\n event_type: string;\n actor?: string;\n message?: string;\n created_at: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface CreateAgentClaimFields {\n project: string;\n channel?: string;\n scopeType: AgentClaimScopeType;\n targetId: string;\n targetTitle?: string;\n agentId?: string;\n agentName: string;\n agentKind?: string;\n threadId?: string;\n ttlSeconds?: number;\n force?: boolean;\n reason?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ValidateAgentClaimForWriteFields {\n claimToken?: string;\n project: string;\n channel?: string;\n scopeType: AgentClaimScopeType;\n targetId: string;\n writeKind: string;\n dangerLevel: 'claim' | 'warn' | 'enforce' | 'danger';\n confirmWrite?: boolean;\n recordEvent?: boolean;\n}\n\nexport type AgentClaimValidationResult =\n | { ok: true; claim: AgentClaim; warnings: string[] }\n | { ok: false; code: string; message: string; conflicts: AgentClaim[] };\n\ntype Row = Record<string, unknown>;\n\nconst defaultTtlSeconds = 20 * 60;\nconst idleAfterSeconds = 5 * 60;\nconst staleAfterSeconds = 15 * 60;\nconst scopes = new Set<AgentClaimScopeType>(['lineage_workspace', 'lineage_task', 'content_post', 'content_queue_lane', 'selection_set', 'project_channel']);\nconst claimTokenPattern = /claim_[a-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\n\nexport class AgentClaimError extends Error {\n constructor(message: string, public status = 400, public code = 'agent_claim_error', public conflicts: AgentClaim[] = []) {\n super(message);\n }\n}\n\nexport function isAgentClaimError(error: unknown): error is AgentClaimError {\n return error instanceof AgentClaimError;\n}\n\nexport function redactAgentClaimTokens(input: string): string {\n return input.replace(claimTokenPattern, '[redacted-claim-token]');\n}\n\nexport function parseClaimTtl(value?: string): number {\n if (!value) return defaultTtlSeconds;\n const match = value.trim().match(/^(\\d+)(s|m|h)?$/);\n if (!match) throw new AgentClaimError(`Invalid claim ttl: ${value}`);\n const amount = Number(match[1]);\n const unit = match[2] || 's';\n const multiplier = unit === 'h' ? 3600 : unit === 'm' ? 60 : 1;\n const seconds = amount * multiplier;\n if (!Number.isInteger(seconds) || seconds < 30 || seconds > 24 * 60 * 60) {\n throw new AgentClaimError('Claim ttl must be between 30 seconds and 24 hours');\n }\n return seconds;\n}\n\nfunction randomId(prefix: string): string {\n return `${prefix}_${Date.now().toString(36)}_${randomBytes(6).toString('base64url').toLowerCase()}`;\n}\n\nfunction tokenHash(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const left = Buffer.from(a);\n const right = Buffer.from(b);\n return left.length === right.length && timingSafeEqual(left, right);\n}\n\nfunction expiresAtFrom(timestamp: string, ttlSeconds: number): string {\n return new Date(new Date(timestamp).getTime() + ttlSeconds * 1000).toISOString();\n}\n\nfunction metadataJson(metadata?: Record<string, unknown>): string | null {\n return metadata ? JSON.stringify(metadata) : null;\n}\n\nfunction parseMetadata(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string' || !value) return undefined;\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction derivedState(row: { status: AgentClaimStatus; heartbeat_at: string; expires_at: string }, now = new Date()): AgentClaim['derived_state'] {\n if (row.status !== 'active') return row.status === 'expired' ? 'expired' : 'stale';\n if (new Date(row.expires_at).getTime() <= now.getTime()) return 'expired';\n const ageSeconds = Math.max(0, Math.floor((now.getTime() - new Date(row.heartbeat_at).getTime()) / 1000));\n if (ageSeconds >= staleAfterSeconds) return 'stale';\n if (ageSeconds >= idleAfterSeconds) return 'idle';\n return 'active';\n}\n\nfunction rowToClaim(row: Row, now = new Date()): AgentClaim {\n const heartbeatAt = String(row.heartbeat_at);\n const persistedStatus = String(row.status) as AgentClaimStatus;\n const state = derivedState({\n expires_at: String(row.expires_at),\n heartbeat_at: heartbeatAt,\n status: persistedStatus,\n }, now);\n return {\n id: String(row.id),\n project: String(row.project_id),\n channel: typeof row.channel === 'string' ? row.channel : undefined,\n scope_type: String(row.scope_type) as AgentClaimScopeType,\n target_id: String(row.target_id),\n target_title: typeof row.target_title === 'string' ? row.target_title : undefined,\n agent_id: typeof row.agent_id === 'string' ? row.agent_id : undefined,\n agent_name: String(row.agent_name),\n agent_kind: String(row.agent_kind),\n thread_id: typeof row.thread_id === 'string' ? row.thread_id : undefined,\n status: persistedStatus === 'active' && state === 'expired' ? 'expired' : persistedStatus,\n created_at: String(row.created_at),\n heartbeat_at: heartbeatAt,\n expires_at: String(row.expires_at),\n released_at: typeof row.released_at === 'string' ? row.released_at : undefined,\n revoked_at: typeof row.revoked_at === 'string' ? row.revoked_at : undefined,\n revoked_by: typeof row.revoked_by === 'string' ? row.revoked_by : undefined,\n override_reason: typeof row.override_reason === 'string' ? row.override_reason : undefined,\n metadata: parseMetadata(row.metadata_json),\n heartbeat_age_seconds: Math.max(0, Math.floor((now.getTime() - new Date(heartbeatAt).getTime()) / 1000)),\n derived_state: state,\n };\n}\n\nfunction eventToRow(row: Row): AgentClaimEvent {\n return {\n claim_id: String(row.claim_id),\n event_type: String(row.event_type),\n actor: typeof row.actor === 'string' ? row.actor : undefined,\n message: typeof row.message === 'string' ? row.message : undefined,\n created_at: String(row.created_at),\n metadata: parseMetadata(row.metadata_json),\n };\n}\n\nfunction ensureProject(database: DatabaseSync, project: string): void {\n const timestamp = nowIso();\n database.prepare(`\n insert into projects (id, product, created_at, updated_at)\n values (?, ?, ?, ?)\n on conflict(id) do update set product = excluded.product, updated_at = excluded.updated_at\n `).run(project, project, timestamp, timestamp);\n}\n\nfunction recordEvent(database: DatabaseSync, claimId: string, eventType: string, actor?: string, message?: string, metadata?: Record<string, unknown>): void {\n database.prepare(`\n insert into agent_claim_events (id, claim_id, event_type, actor, message, created_at, metadata_json)\n values (?, ?, ?, ?, ?, ?, ?)\n `).run(randomId('claim_event'), claimId, eventType, actor || null, message || null, nowIso(), metadataJson(metadata));\n}\n\nfunction expireActiveClaims(database: DatabaseSync): void {\n const timestamp = nowIso();\n const expired = database.prepare(`\n select id from agent_claims where status = 'active' and expires_at <= ?\n `).all(timestamp) as Array<{ id: string }>;\n if (expired.length === 0) return;\n database.prepare(`\n update agent_claims set status = 'expired' where status = 'active' and expires_at <= ?\n `).run(timestamp);\n for (const claim of expired) recordEvent(database, claim.id, 'expired', 'system', 'Claim expired after missed heartbeat.');\n}\n\nfunction normalizeScope(scopeType: AgentClaimScopeType): AgentClaimScopeType {\n if (!scopes.has(scopeType)) throw new AgentClaimError(`Unsupported claim scope: ${scopeType}`);\n return scopeType;\n}\n\nfunction channelOverlaps(left?: string, right?: string): boolean {\n return !left || !right || left === right;\n}\n\nfunction claimOverlaps(candidate: Pick<AgentClaim, 'project' | 'channel' | 'scope_type' | 'target_id'>, existing: AgentClaim): boolean {\n if (candidate.project !== existing.project) return false;\n if (!channelOverlaps(candidate.channel, existing.channel)) return false;\n if (candidate.scope_type === existing.scope_type && candidate.target_id === existing.target_id) return true;\n return candidate.scope_type === 'project_channel' || existing.scope_type === 'project_channel';\n}\n\nfunction activeClaims(database: DatabaseSync, project?: string): AgentClaim[] {\n const rows = project\n ? database.prepare(\"select * from agent_claims where project_id = ? and status = 'active' order by heartbeat_at desc\").all(project)\n : database.prepare(\"select * from agent_claims where status = 'active' order by project_id, heartbeat_at desc\").all();\n return (rows as Row[]).map(row => rowToClaim(row));\n}\n\nfunction findClaimById(database: DatabaseSync, claimId: string, project?: string): AgentClaim | null {\n const row = project\n ? database.prepare('select * from agent_claims where project_id = ? and id = ?').get(project, claimId)\n : database.prepare('select * from agent_claims where id = ?').get(claimId);\n return row ? rowToClaim(row as Row) : null;\n}\n\nfunction findClaimRowByToken(database: DatabaseSync, claimToken: string): Row | null {\n const claimId = claimToken.split('.')[0];\n const row = database.prepare('select * from agent_claims where id = ?').get(claimId) as Row | undefined;\n if (!row) return null;\n return safeEqual(String(row.token_hash), tokenHash(claimToken)) ? row : null;\n}\n\nfunction denied(code: string, message: string, conflicts: AgentClaim[] = []): AgentClaimValidationResult {\n return { ok: false, code, message, conflicts };\n}\n\nfunction scopeAllowsWrite(claim: AgentClaim, scopeType: AgentClaimScopeType, targetId: string, writeKind: string): boolean {\n if (claim.scope_type === scopeType && claim.target_id === targetId) return true;\n if (claim.scope_type === 'project_channel') return true;\n if (claim.scope_type === 'lineage_workspace' && scopeType === 'lineage_workspace') return claim.target_id === targetId;\n if (claim.scope_type === 'content_queue_lane' && writeKind === 'content_queue_next') return true;\n return false;\n}\n\nexport function createAgentClaim(fields: CreateAgentClaimFields) {\n const project = fields.project.trim();\n const targetId = fields.targetId.trim();\n const agentName = fields.agentName.trim();\n if (!project) throw new AgentClaimError('Agent claim requires project');\n if (!targetId) throw new AgentClaimError('Agent claim requires target');\n if (!agentName) throw new AgentClaimError('Agent claim requires agent name');\n const scopeType = normalizeScope(fields.scopeType);\n const ttlSeconds = fields.ttlSeconds || defaultTtlSeconds;\n const database = lineageDb();\n try {\n ensureProject(database, project);\n expireActiveClaims(database);\n const candidate = { project, channel: fields.channel?.trim() || undefined, scope_type: scopeType, target_id: targetId };\n const conflicts = activeClaims(database, project).filter(claim => claimOverlaps(candidate, claim));\n if (conflicts.length > 0 && !fields.force) {\n throw new AgentClaimError('Target already has an active overlapping agent claim.', 409, 'target_already_claimed', conflicts);\n }\n if (conflicts.length > 0 && !fields.reason?.trim()) {\n throw new AgentClaimError('Overriding an active claim requires --reason.', 400, 'override_reason_required', conflicts);\n }\n const timestamp = nowIso();\n for (const conflict of conflicts) {\n database.prepare(`\n update agent_claims\n set status = 'revoked', revoked_at = ?, revoked_by = ?, override_reason = ?\n where id = ? and status = 'active'\n `).run(timestamp, agentName, fields.reason || null, conflict.id);\n recordEvent(database, conflict.id, 'revoked', agentName, fields.reason || 'Revoked by forced claim takeover.');\n recordEvent(database, conflict.id, 'conflict', agentName, `Overridden by ${agentName}.`, { new_claim_target: targetId });\n }\n const id = randomId('claim');\n const secret = randomBytes(24).toString('base64url');\n const claimToken = `${id}.${secret}`;\n const expiresAt = expiresAtFrom(timestamp, ttlSeconds);\n database.prepare(`\n insert into agent_claims (\n id, token_hash, project_id, channel, scope_type, target_id, target_title, agent_id, agent_name,\n agent_kind, thread_id, status, created_at, heartbeat_at, expires_at, metadata_json\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?)\n `).run(\n id,\n tokenHash(claimToken),\n project,\n candidate.channel || null,\n scopeType,\n targetId,\n fields.targetTitle?.trim() || null,\n fields.agentId?.trim() || null,\n agentName,\n fields.agentKind?.trim() || 'codex',\n fields.threadId?.trim() || null,\n timestamp,\n timestamp,\n expiresAt,\n metadataJson(fields.metadata)\n );\n recordEvent(database, id, 'created', agentName, `Claimed ${scopeType} ${targetId}.`, { ttl_seconds: ttlSeconds });\n const claim = findClaimById(database, id);\n return { ok: true as const, claim, claim_token: claimToken, conflicts_revoked: conflicts.map(conflict => conflict.id) };\n } finally {\n database.close();\n }\n}\n\nexport function listAgentClaims(project?: string) {\n const database = lineageDb();\n try {\n if (process.env.LINEAGE_DB_ACCESS !== 'read-only') expireActiveClaims(database);\n const rows = project\n ? database.prepare('select * from agent_claims where project_id = ? order by status, heartbeat_at desc').all(project)\n : database.prepare('select * from agent_claims order by project_id, status, heartbeat_at desc').all();\n return { ok: true as const, claims: (rows as Row[]).map(row => rowToClaim(row)), fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function inspectAgentClaim(claimId: string, project?: string) {\n const database = lineageDb();\n try {\n if (process.env.LINEAGE_DB_ACCESS !== 'read-only') expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n const events = database.prepare('select * from agent_claim_events where claim_id = ? order by created_at').all(claim.id) as Row[];\n return { ok: true as const, claim, events: events.map(eventToRow) };\n } finally {\n database.close();\n }\n}\n\nexport function heartbeatAgentClaim(claimToken: string, ttlSeconds = defaultTtlSeconds) {\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const row = findClaimRowByToken(database, claimToken);\n if (!row) throw new AgentClaimError('Unknown or invalid agent claim token.', 401, 'claim_token_invalid');\n const claim = rowToClaim(row);\n if (claim.status !== 'active') throw new AgentClaimError(`Agent claim is ${claim.status}.`, 409, 'claim_not_active');\n const timestamp = nowIso();\n database.prepare('update agent_claims set heartbeat_at = ?, expires_at = ? where id = ?').run(timestamp, expiresAtFrom(timestamp, ttlSeconds), claim.id);\n recordEvent(database, claim.id, 'heartbeat', claim.agent_name, 'Claim heartbeat received.');\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function releaseAgentClaim(claimToken: string) {\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const row = findClaimRowByToken(database, claimToken);\n if (!row) throw new AgentClaimError('Unknown or invalid agent claim token.', 401, 'claim_token_invalid');\n const claim = rowToClaim(row);\n if (claim.status !== 'active') throw new AgentClaimError(`Agent claim is ${claim.status}.`, 409, 'claim_not_active');\n const timestamp = nowIso();\n database.prepare(\"update agent_claims set status = 'released', released_at = ? where id = ?\").run(timestamp, claim.id);\n recordEvent(database, claim.id, 'released', claim.agent_name, 'Claim released by token holder.');\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function releaseStaleAgentClaim(project: string, claimId: string, fields: { actor?: string; confirmWrite: boolean; reason?: string }) {\n if (!fields.confirmWrite) throw new AgentClaimError('Releasing a stale agent claim requires confirmWrite=true.', 400, 'confirm_write_required');\n if (!fields.reason?.trim()) throw new AgentClaimError('Releasing a stale agent claim requires a reason.', 400, 'reason_required');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n if (claim.status !== 'active' || claim.derived_state !== 'stale') {\n throw new AgentClaimError('Only stale active claims can be released without the claim token.', 409, 'claim_not_stale', [claim]);\n }\n const timestamp = nowIso();\n database.prepare(\"update agent_claims set status = 'released', released_at = ?, revoked_by = ?, override_reason = ? where id = ?\").run(timestamp, fields.actor || 'human', fields.reason, claim.id);\n recordEvent(database, claim.id, 'released', fields.actor || 'human', fields.reason);\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function revokeAgentClaim(project: string, claimId: string, fields: { actor?: string; confirmWrite: boolean; reason?: string }) {\n if (!fields.confirmWrite) throw new AgentClaimError('Revoking an agent claim requires confirmWrite=true.', 400, 'confirm_write_required');\n if (!fields.reason?.trim()) throw new AgentClaimError('Revoking an agent claim requires a reason.', 400, 'reason_required');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n const timestamp = nowIso();\n database.prepare(`\n update agent_claims set status = 'revoked', revoked_at = ?, revoked_by = ?, override_reason = ?\n where id = ?\n `).run(timestamp, fields.actor || 'human', fields.reason, claim.id);\n recordEvent(database, claim.id, 'revoked', fields.actor || 'human', fields.reason);\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function revokeAgentClaimInDatabase(database: DatabaseSync, project: string, claimId: string, fields: { actor?: string; reason?: string }) {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n if (claim.status !== 'active') return claim;\n const timestamp = nowIso();\n database.prepare(`\n update agent_claims set status = 'revoked', revoked_at = ?, revoked_by = ?, override_reason = ?\n where id = ? and status = 'active'\n `).run(timestamp, fields.actor || 'human', fields.reason || null, claim.id);\n recordEvent(database, claim.id, 'revoked', fields.actor || 'human', fields.reason);\n return findClaimById(database, claim.id, project);\n}\n\nexport function transferAgentClaim(project: string, claimId: string, fields: { confirmWrite: boolean; toAgentName: string; actor?: string; reason?: string }) {\n if (!fields.confirmWrite) throw new AgentClaimError('Transferring an agent claim requires confirmWrite=true.', 400, 'confirm_write_required');\n const toAgentName = fields.toAgentName.trim();\n if (!toAgentName) throw new AgentClaimError('Transfer requires toAgentName.', 400, 'agent_name_required');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const claim = findClaimById(database, claimId, project);\n if (!claim) throw new AgentClaimError(`Unknown agent claim: ${claimId}`, 404, 'claim_not_found');\n if (claim.status !== 'active') throw new AgentClaimError(`Agent claim is ${claim.status}.`, 409, 'claim_not_active');\n database.prepare('update agent_claims set agent_name = ? where id = ?').run(toAgentName, claim.id);\n recordEvent(database, claim.id, 'transferred', fields.actor || 'human', fields.reason || `Transferred claim to ${toAgentName}.`, { to_agent_name: toAgentName });\n return { ok: true as const, claim: findClaimById(database, claim.id) };\n } finally {\n database.close();\n }\n}\n\nexport function recordAgentClaimWriteAllowed(claim: Pick<AgentClaim, 'id' | 'agent_name'>, fields: Pick<ValidateAgentClaimForWriteFields, 'dangerLevel' | 'targetId' | 'writeKind'>) {\n const database = lineageDb();\n try {\n recordEvent(database, claim.id, 'write_allowed', claim.agent_name, `${fields.writeKind} allowed.`, {\n danger_level: fields.dangerLevel,\n target_id: fields.targetId,\n write_kind: fields.writeKind,\n });\n return { ok: true as const };\n } finally {\n database.close();\n }\n}\n\nexport function validateAgentClaimForWrite(fields: ValidateAgentClaimForWriteFields): AgentClaimValidationResult {\n if (fields.dangerLevel === 'danger' && !fields.confirmWrite) {\n return denied('human_confirmation_required', 'Dangerous write requires explicit human confirmation.');\n }\n if (!fields.claimToken) return denied('claim_required', 'Mutating agent write requires a matching claim token.');\n const database = lineageDb();\n try {\n expireActiveClaims(database);\n const row = findClaimRowByToken(database, fields.claimToken);\n if (!row) return denied('claim_token_invalid', 'Unknown or invalid claim token.');\n const claim = rowToClaim(row);\n if (claim.status !== 'active') return denied('claim_not_active', `Agent claim is ${claim.status}.`);\n if (new Date(claim.expires_at).getTime() <= Date.now()) return denied('claim_expired', 'Agent claim has expired.');\n if (claim.project !== fields.project) return denied('claim_project_mismatch', `Claim project ${claim.project} does not match ${fields.project}.`, [claim]);\n if (fields.channel && claim.channel && claim.channel !== fields.channel) {\n return denied('claim_channel_mismatch', `Claim channel ${claim.channel} does not match ${fields.channel}.`, [claim]);\n }\n if (!scopeAllowsWrite(claim, fields.scopeType, fields.targetId, fields.writeKind)) {\n return denied('claim_scope_mismatch', `Claim does not cover ${fields.scopeType} ${fields.targetId}.`, [claim]);\n }\n if (fields.recordEvent !== false) {\n recordEvent(database, claim.id, 'write_allowed', claim.agent_name, `${fields.writeKind} allowed.`, {\n danger_level: fields.dangerLevel,\n target_id: fields.targetId,\n write_kind: fields.writeKind,\n });\n }\n return { ok: true, claim, warnings: [] };\n } finally {\n database.close();\n }\n}\n", "import type { DatabaseSync as DatabaseSyncType } from 'node:sqlite';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { packageRoot } from './assetCore';\nimport { assertProfileWriterLeaseHeld, assertSelectedProfileDatabaseIdentity } from './profileWriterLease';\nimport { loadNodeSqlite } from './nodeSqlite';\n\nexport type DatabaseSync = DatabaseSyncType;\n\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n\nexport function lineageDbPath(): string {\n return process.env.LINEAGE_DB || join(packageRoot, '.lineage', 'asset-lineage.sqlite');\n}\n\nexport function lineageDb(): DatabaseSync {\n const readOnly = process.env.LINEAGE_DB_ACCESS === 'read-only';\n if (!readOnly) assertProfileWriterLeaseHeld();\n if (!readOnly && !existsSync(lineageDbPath())) {\n throw new Error(`Refusing writable open of missing profile database ${lineageDbPath()}; bind an existing database or create a non-production clone first`);\n }\n if (!readOnly) mkdirSync(join(lineageDbPath(), '..'), { recursive: true });\n const { DatabaseSync } = loadNodeSqlite();\n const database = readOnly ? new DatabaseSync(lineageDbPath(), { readOnly: true }) : new DatabaseSync(lineageDbPath());\n if (process.env.LINEAGE_PROFILE) assertSelectedProfileDatabaseIdentity(database);\n database.exec('PRAGMA foreign_keys = ON');\n database.exec('PRAGMA busy_timeout = 5000');\n if (readOnly) return database;\n database.exec('PRAGMA journal_mode = WAL');\n database.exec(`\n create table if not exists projects (\n id text primary key,\n product text not null,\n catalog_path text,\n created_at text not null,\n updated_at text not null\n );\n create table if not exists assets (\n id text primary key,\n project_id text not null references projects(id),\n source text not null check (source in ('local', 'catalog')),\n local_path text,\n s3_key text,\n checksum_sha256 text,\n media_type text not null,\n title text not null,\n status text not null,\n channel text,\n campaign text,\n audience text,\n size_bytes integer,\n content_type text,\n created_at text not null,\n updated_at text not null,\n last_seen_at text not null\n );\n create index if not exists assets_project_source_seen on assets(project_id, source, last_seen_at);\n create index if not exists assets_project_checksum on assets(project_id, checksum_sha256);\n create index if not exists assets_project_channel_campaign on assets(project_id, channel, campaign);\n create table if not exists lineage_schema_migrations (\n key text primary key,\n applied_at text not null\n );\n create table if not exists asset_edges (\n id text primary key,\n project_id text not null references projects(id),\n parent_asset_id text not null references assets(id),\n child_asset_id text not null references assets(id),\n relation_type text not null check (relation_type in ('derived_from')),\n created_at text not null,\n summary text,\n summary_created_by text check (summary_created_by in ('human', 'agent', 'system')),\n summary_updated_by text check (summary_updated_by in ('human', 'agent', 'system')),\n summary_updated_at text,\n unique (project_id, parent_asset_id, child_asset_id, relation_type)\n );\n create index if not exists edges_parent on asset_edges(project_id, parent_asset_id);\n create index if not exists edges_child on asset_edges(project_id, child_asset_id);\n create table if not exists asset_attempts (\n id text primary key,\n project_id text not null references projects(id),\n node_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n attempt_index integer not null check (attempt_index > 0),\n source text not null check (source in ('initial', 'generated_child', 'reroll')),\n prompt text,\n generation_job_id text,\n file_path text,\n checksum_sha256 text,\n created_at text not null,\n promoted_at text,\n is_current integer not null check (is_current in (0, 1)),\n unique(project_id, node_asset_id, attempt_index),\n unique(project_id, node_asset_id, asset_id, source)\n );\n create unique index if not exists asset_attempts_one_current\n on asset_attempts(project_id, node_asset_id)\n where is_current = 1;\n create index if not exists asset_attempts_node_created\n on asset_attempts(project_id, node_asset_id, created_at);\n create table if not exists asset_reroll_requests (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n node_asset_id text not null references assets(id),\n status text not null check (status in ('pending', 'resolved', 'cancelled')),\n requested_by text not null check (requested_by in ('human', 'agent', 'system')),\n notes text,\n created_at text not null,\n resolved_at text\n );\n create unique index if not exists asset_reroll_requests_one_pending\n on asset_reroll_requests(project_id, root_asset_id, node_asset_id)\n where status = 'pending';\n create index if not exists asset_reroll_requests_root_status\n on asset_reroll_requests(project_id, root_asset_id, status, created_at);\n create table if not exists asset_reviews (\n asset_id text primary key references assets(id),\n review_state text not null check (review_state in ('unreviewed', 'approved', 'needs_revision', 'rejected', 'ignored')),\n reviewed_at text,\n ignored_at text,\n notes text,\n updated_at text not null\n );\n create table if not exists asset_selections (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n notes text,\n selected_at text not null,\n unique(project_id, root_asset_id)\n );\n create table if not exists asset_layouts (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n x real not null,\n y real not null,\n updated_at text not null,\n unique(project_id, root_asset_id, asset_id)\n );\n create table if not exists lineage_workspaces (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n title text not null,\n status text not null check (status in ('active', 'paused', 'archived')),\n notes text,\n created_by text not null check (created_by in ('human', 'agent', 'system')),\n active_at text,\n created_at text not null,\n updated_at text not null,\n unique(project_id, root_asset_id)\n );\n create index if not exists lineage_workspaces_project_status on lineage_workspaces(project_id, status, updated_at);\n create index if not exists lineage_workspaces_project_active on lineage_workspaces(project_id, active_at);\n create table if not exists asset_ledger_records (\n id text primary key,\n project_id text not null references projects(id),\n canonical_asset_id text not null,\n checksum_sha256 text,\n media_type text not null,\n title text not null,\n status text not null,\n channel text,\n campaign text,\n audience text,\n created_at text not null,\n updated_at text not null,\n first_seen_at text not null default (datetime('now')),\n last_seen_at text not null\n );\n create index if not exists asset_ledger_records_project_seen on asset_ledger_records(project_id, last_seen_at);\n create index if not exists asset_ledger_records_project_checksum on asset_ledger_records(project_id, checksum_sha256);\n create table if not exists asset_ledger_sources (\n id text primary key,\n project_id text not null references projects(id),\n record_id text not null references asset_ledger_records(id) on delete cascade,\n source_type text not null check (source_type in ('local', 'catalog', 's3')),\n asset_id text,\n local_path text,\n s3_bucket text,\n s3_region text,\n s3_key text,\n s3_version_id text,\n etag text,\n size_bytes integer,\n content_type text,\n updated_at text,\n first_seen_at text not null default (datetime('now')),\n last_seen_at text not null\n );\n create index if not exists asset_ledger_sources_project_type on asset_ledger_sources(project_id, source_type);\n create index if not exists asset_ledger_sources_record on asset_ledger_sources(project_id, record_id);\n create index if not exists asset_ledger_sources_s3_key on asset_ledger_sources(project_id, s3_key);\n create table if not exists asset_ledger_placements (\n id text primary key,\n project_id text not null references projects(id),\n asset_id text not null,\n channel text not null,\n status text not null,\n scheduled_at text,\n posted_at text,\n url text,\n notes text,\n updated_at text not null,\n synced_at text not null,\n unique(project_id, asset_id, channel)\n );\n create index if not exists asset_ledger_placements_project_status on asset_ledger_placements(project_id, status);\n create index if not exists asset_ledger_placements_asset on asset_ledger_placements(project_id, asset_id);\n create table if not exists asset_ledger_index_runs (\n id text primary key,\n project_id text not null references projects(id),\n source_mode text not null check (source_mode in ('all', 'catalog', 'local')),\n include_live_s3 integer not null default 0,\n status text not null check (status in ('running', 'complete', 'failed')),\n started_at text not null,\n completed_at text,\n assets_indexed integer not null default 0,\n records_after integer not null default 0,\n catalog_sources_after integer not null default 0,\n local_sources_after integer not null default 0,\n s3_sources_after integer not null default 0,\n error text\n );\n create index if not exists asset_ledger_index_runs_project_started on asset_ledger_index_runs(project_id, started_at);\n create table if not exists content_batches (\n id text not null,\n project_id text not null references projects(id),\n title text not null,\n campaign text,\n channel text,\n status text not null check (status in ('active', 'archived')),\n notes text,\n created_at text not null,\n updated_at text not null,\n primary key(project_id, id)\n );\n create index if not exists content_batches_project_updated on content_batches(project_id, updated_at);\n create table if not exists content_posts (\n id text not null,\n project_id text not null references projects(id),\n batch_id text not null,\n channel text not null,\n title text not null,\n phase text not null check (phase in ('draft', 'review', 'scheduled', 'posted', 'skipped', 'archived')),\n campaign text,\n body text,\n cta text,\n scheduled_at text,\n posted_at text,\n url text,\n notes text,\n source_path text,\n created_at text not null,\n updated_at text not null,\n primary key(project_id, id),\n foreign key(project_id, batch_id) references content_batches(project_id, id) on delete cascade\n );\n create index if not exists content_posts_project_phase on content_posts(project_id, phase);\n create index if not exists content_posts_batch on content_posts(project_id, batch_id);\n create table if not exists content_post_assets (\n id text primary key,\n project_id text not null references projects(id),\n post_id text not null,\n asset_id text not null,\n role text not null,\n notes text,\n attached_at text not null,\n unique(project_id, post_id, asset_id, role),\n foreign key(project_id, post_id) references content_posts(project_id, id) on delete cascade\n );\n create index if not exists content_post_assets_post on content_post_assets(project_id, post_id);\n create index if not exists content_post_assets_asset on content_post_assets(project_id, asset_id);\n create table if not exists content_targets (\n project_id text primary key references projects(id),\n post_id text not null,\n notes text,\n selected_at text not null,\n updated_at text not null,\n foreign key(project_id, post_id) references content_posts(project_id, id) on delete cascade\n );\n create table if not exists selection_sets (\n id text primary key,\n project_id text not null references projects(id),\n kind text not null check (kind in ('current', 'review')),\n key text not null,\n label text not null,\n status text not null check (status in ('active', 'archived')),\n created_by text not null check (created_by in ('human', 'agent', 'system')),\n created_at text not null,\n updated_at text not null,\n unique(project_id, kind, key)\n );\n create index if not exists selection_sets_project_kind on selection_sets(project_id, kind, updated_at);\n create table if not exists selection_items (\n id text primary key,\n set_id text not null references selection_sets(id) on delete cascade,\n asset_id text not null,\n role text not null check (role in ('primary', 'candidate', 'next_base')),\n variation_label text,\n position integer not null default 0,\n selected_by text check (selected_by in ('human', 'agent', 'system')),\n selected_at text,\n deselected_at text,\n notes text,\n created_at text not null,\n updated_at text not null,\n unique(set_id, asset_id)\n );\n create index if not exists selection_items_set_position on selection_items(set_id, position);\n create unique index if not exists selection_items_set_label on selection_items(set_id, variation_label) where variation_label is not null;\n create table if not exists generation_jobs (\n id text primary key,\n project_id text not null references projects(id),\n provider text not null default 'codex-handoff',\n adapter_version text not null,\n source_mode text not null check (source_mode in ('lineage_selection', 'lineage_reroll')),\n root_asset_id text not null references assets(id),\n prompt text not null,\n expected_output_count integer not null check (expected_output_count > 0),\n status text not null check (status in ('planned', 'imported', 'failed', 'cancelled')),\n output_dir text,\n handoff_json text,\n created_at text not null,\n updated_at text not null,\n imported_at text\n );\n create index if not exists generation_jobs_project_created on generation_jobs(project_id, created_at);\n create table if not exists generation_job_inputs (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n project_id text not null references projects(id),\n asset_id text not null references assets(id),\n root_asset_id text not null references assets(id),\n role text not null check (role in ('lineage_next_base', 'reference', 'reroll_target')),\n position integer not null,\n selection_strategy text not null,\n selection_snapshot_json text not null,\n unique(job_id, asset_id, role)\n );\n create index if not exists generation_job_inputs_job on generation_job_inputs(job_id, position);\n create table if not exists generation_job_outputs (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n project_id text not null references projects(id),\n output_index integer not null,\n file_path text not null,\n checksum_sha256 text not null,\n size_bytes integer not null,\n content_type text not null,\n imported_asset_id text not null references assets(id),\n parent_asset_id text not null references assets(id),\n imported_at text not null,\n edge_summary text,\n unique(job_id, output_index),\n unique(job_id, file_path)\n );\n create index if not exists generation_job_outputs_job on generation_job_outputs(job_id, output_index);\n create table if not exists generation_job_receipts (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n receipt_type text not null check (receipt_type in ('plan', 'import', 'error')),\n status text not null check (status in ('ok', 'error')),\n command text not null,\n payload_json text not null,\n created_at text not null\n );\n create index if not exists generation_job_receipts_job on generation_job_receipts(job_id, created_at);\n create table if not exists adapter_settings (project_id text not null references projects(id), adapter_type text not null check (adapter_type in ('cloud', 'scheduler', 'image_generator')), provider text not null, enabled integer not null check (enabled in (0, 1)), secret_ref text, safe_config_json text not null, created_at text not null, updated_at text not null, primary key(project_id, adapter_type, provider)); create index if not exists adapter_settings_project_type on adapter_settings(project_id, adapter_type);\n create table if not exists lineage_tasks (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n target_asset_id text not null references assets(id),\n task_type text not null check (task_type in ('iterate', 'reroll')),\n status text not null check (status in ('pending', 'claimed', 'in_progress', 'resolved', 'cancelled')),\n instructions text,\n created_by text not null check (created_by in ('human', 'agent', 'system')),\n created_at text not null,\n updated_at text not null,\n claimed_at text,\n started_at text,\n resolved_at text,\n cancelled_at text,\n resolved_generation_job_id text,\n resolved_asset_id text references assets(id),\n metadata_json text\n );\n create unique index if not exists lineage_tasks_one_open\n on lineage_tasks(project_id, root_asset_id, target_asset_id, task_type)\n where status in ('pending', 'claimed', 'in_progress');\n create index if not exists lineage_tasks_root_status\n on lineage_tasks(project_id, root_asset_id, status, updated_at);\n create index if not exists lineage_tasks_target\n on lineage_tasks(project_id, root_asset_id, target_asset_id, task_type, status);\n create table if not exists lineage_task_events (\n id text primary key,\n task_id text not null references lineage_tasks(id) on delete cascade,\n event_type text not null,\n actor text,\n message text,\n created_at text not null,\n metadata_json text\n );\n create index if not exists lineage_task_events_task_created\n on lineage_task_events(task_id, created_at);\n create table if not exists agent_claims (\n id text primary key,\n token_hash text not null,\n project_id text not null references projects(id),\n channel text,\n scope_type text not null check (scope_type in ('lineage_workspace', 'lineage_task', 'content_post', 'content_queue_lane', 'selection_set', 'project_channel')),\n target_id text not null,\n target_title text,\n agent_id text,\n agent_name text not null,\n agent_kind text not null,\n thread_id text,\n status text not null check (status in ('active', 'expired', 'released', 'revoked', 'transferred')),\n created_at text not null,\n heartbeat_at text not null,\n expires_at text not null,\n released_at text,\n revoked_at text,\n revoked_by text,\n override_reason text,\n metadata_json text\n );\n create unique index if not exists agent_claims_token_hash on agent_claims(token_hash);\n create index if not exists agent_claims_project_status on agent_claims(project_id, status, heartbeat_at);\n create index if not exists agent_claims_target on agent_claims(project_id, channel, scope_type, target_id, status);\n create table if not exists agent_claim_events (\n id text primary key,\n claim_id text not null references agent_claims(id) on delete cascade,\n event_type text not null,\n actor text,\n message text,\n created_at text not null,\n metadata_json text\n );\n create index if not exists agent_claim_events_claim_created on agent_claim_events(claim_id, created_at);\n `);\n ensureColumn(database, 'asset_edges', 'summary', 'text');\n ensureColumn(database, 'asset_edges', 'summary_created_by', \"text check (summary_created_by in ('human', 'agent', 'system'))\");\n ensureColumn(database, 'asset_edges', 'summary_updated_by', \"text check (summary_updated_by in ('human', 'agent', 'system'))\");\n ensureColumn(database, 'asset_edges', 'summary_updated_at', 'text');\n ensureColumn(database, 'generation_job_outputs', 'edge_summary', 'text');\n migrateAssetSelections(database);\n dropLegacyAssetSelectionRootUnique(database);\n ensureColumn(database, 'asset_selections', 'notes', 'text');\n backfillLineageTasks(database);\n ensureColumn(database, 'asset_ledger_records', 'first_seen_at', 'text');\n ensureColumn(database, 'asset_ledger_records', 'indexed_by_run_id', 'text');\n ensureColumn(database, 'asset_ledger_sources', 'first_seen_at', 'text');\n ensureColumn(database, 'asset_ledger_sources', 'indexed_by_run_id', 'text');\n ensureReviewStateValues(database);\n ensureAgentClaimScopeValues(database);\n ensureGenerationReceiptCheckValues(database);\n return database;\n}\n\nexport function backfillLineageTasks(database: DatabaseSync): void {\n database.exec(`\n create table if not exists lineage_schema_migrations (\n key text primary key,\n applied_at text not null\n )\n `);\n const marker = database.prepare(\"select key from lineage_schema_migrations where key = 'lineage_tasks_backfilled_v1'\").get();\n if (marker) return;\n\n database.exec('BEGIN IMMEDIATE');\n try {\n database.exec(`\n insert or ignore into lineage_tasks (\n id, project_id, root_asset_id, target_asset_id, task_type, status, instructions,\n created_by, created_at, updated_at, metadata_json\n )\n select\n s.project_id || ':' || s.root_asset_id || ':lineage-task:iterate:' || s.asset_id,\n s.project_id,\n s.root_asset_id,\n s.asset_id,\n 'iterate',\n 'pending',\n s.notes,\n 'human',\n s.selected_at,\n s.selected_at,\n null\n from asset_selections s;\n\n insert or ignore into lineage_tasks (\n id, project_id, root_asset_id, target_asset_id, task_type, status, instructions,\n created_by, created_at, updated_at, metadata_json\n )\n select\n r.project_id || ':' || r.root_asset_id || ':lineage-task:reroll:' || r.node_asset_id,\n r.project_id,\n r.root_asset_id,\n r.node_asset_id,\n 'reroll',\n 'pending',\n r.notes,\n r.requested_by,\n r.created_at,\n r.created_at,\n null\n from asset_reroll_requests r\n where r.status = 'pending';\n `);\n database.prepare(`\n insert into lineage_schema_migrations (key, applied_at)\n values ('lineage_tasks_backfilled_v1', ?)\n on conflict(key) do nothing\n `).run(nowIso());\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n}\n\nfunction ensureColumn(database: DatabaseSync, table: string, column: string, definition: string): void {\n const rows = database.prepare(`pragma table_info(${table})`).all() as Array<{ name: string }>;\n if (!rows.some(row => row.name === column)) database.exec(`alter table ${table} add column ${column} ${definition}`);\n}\n\nfunction migrateAssetSelections(database: DatabaseSync): void {\n const rows = database.prepare('pragma table_info(asset_selections)').all() as Array<{ name: string }>;\n if (rows.some(row => row.name === 'position')) return;\n const notesSelect = rows.some(row => row.name === 'notes') ? 'notes' : 'null';\n\n database.exec(`\n create table if not exists asset_selections_v2 (\n id text primary key,\n project_id text not null references projects(id),\n root_asset_id text not null references assets(id),\n asset_id text not null references assets(id),\n position integer not null default 0,\n notes text,\n selected_at text not null,\n unique(project_id, root_asset_id, asset_id)\n );\n insert or ignore into asset_selections_v2 (id, project_id, root_asset_id, asset_id, position, notes, selected_at)\n select\n project_id || ':' || root_asset_id || ':selected:' || asset_id,\n project_id,\n root_asset_id,\n asset_id,\n 0,\n ${notesSelect},\n selected_at\n from asset_selections;\n drop table asset_selections;\n alter table asset_selections_v2 rename to asset_selections;\n create index if not exists asset_selections_project_root_position\n on asset_selections(project_id, root_asset_id, position, selected_at);\n `);\n}\n\nfunction dropLegacyAssetSelectionRootUnique(database: DatabaseSync): void {\n const indexes = database.prepare('pragma index_list(asset_selections)').all() as Array<{ name: string; unique: number }>;\n for (const index of indexes) {\n if (!index.unique) continue;\n const columns = database.prepare(`pragma index_info(${index.name})`).all() as Array<{ name: string }>;\n const columnNames = columns.map(column => column.name).join(',');\n if (columnNames === 'project_id,root_asset_id') database.exec(`drop index if exists ${index.name}`);\n }\n}\n\nfunction ensureReviewStateValues(database: DatabaseSync): void {\n const createSql = database.prepare(\"select sql from sqlite_master where type = 'table' and name = 'asset_reviews'\").get() as { sql?: string } | undefined;\n if (createSql?.sql?.includes('needs_revision')) return;\n\n database.exec(`\n alter table asset_reviews rename to asset_reviews_old;\n create table asset_reviews (\n asset_id text primary key references assets(id),\n review_state text not null check (review_state in ('unreviewed', 'approved', 'needs_revision', 'rejected', 'ignored')),\n reviewed_at text,\n ignored_at text,\n notes text,\n updated_at text not null\n );\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n select asset_id, review_state, reviewed_at, ignored_at, notes, updated_at\n from asset_reviews_old;\n drop table asset_reviews_old;\n `);\n}\n\nfunction ensureAgentClaimScopeValues(database: DatabaseSync): void {\n const createSql = database.prepare(\"select sql from sqlite_master where type = 'table' and name = 'agent_claims'\").get() as { sql?: string } | undefined;\n if (createSql?.sql?.includes(\"'lineage_task'\")) return;\n\n database.exec('PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON; BEGIN IMMEDIATE');\n try {\n database.exec(`\n alter table agent_claims rename to agent_claims_old;\n create table agent_claims (\n id text primary key,\n token_hash text not null,\n project_id text not null references projects(id),\n channel text,\n scope_type text not null check (scope_type in ('lineage_workspace', 'lineage_task', 'content_post', 'content_queue_lane', 'selection_set', 'project_channel')),\n target_id text not null,\n target_title text,\n agent_id text,\n agent_name text not null,\n agent_kind text not null,\n thread_id text,\n status text not null check (status in ('active', 'expired', 'released', 'revoked', 'transferred')),\n created_at text not null,\n heartbeat_at text not null,\n expires_at text not null,\n released_at text,\n revoked_at text,\n revoked_by text,\n override_reason text,\n metadata_json text\n );\n insert into agent_claims\n select * from agent_claims_old;\n drop table agent_claims_old;\n create unique index if not exists agent_claims_token_hash on agent_claims(token_hash);\n create index if not exists agent_claims_project_status on agent_claims(project_id, status, heartbeat_at);\n create index if not exists agent_claims_target on agent_claims(project_id, channel, scope_type, target_id, status);\n `);\n const violations = database.prepare('pragma foreign_key_check').all();\n if (violations.length > 0) throw new Error(`Agent claim scope migration failed foreign key check: ${JSON.stringify(violations)}`);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n } finally {\n database.exec('PRAGMA legacy_alter_table = OFF; PRAGMA foreign_keys = ON');\n }\n}\n\nfunction tableCreateSql(database: DatabaseSync, table: string): string {\n const row = database.prepare(\"select sql from sqlite_master where type = 'table' and name = ?\").get(table) as { sql?: string } | undefined;\n return row?.sql || '';\n}\n\nfunction ensureGenerationReceiptCheckValues(database: DatabaseSync): void {\n const jobsSql = tableCreateSql(database, 'generation_jobs');\n const inputsSql = tableCreateSql(database, 'generation_job_inputs');\n const needsJobsMigration = Boolean(jobsSql && !jobsSql.includes(\"'lineage_reroll'\"));\n const needsInputsMigration = Boolean(inputsSql && !inputsSql.includes(\"'reroll_target'\"));\n if (!needsJobsMigration && !needsInputsMigration) return;\n\n database.exec('PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON; BEGIN IMMEDIATE');\n try {\n if (needsJobsMigration) migrateGenerationJobsCheck(database);\n if (needsInputsMigration) migrateGenerationJobInputsCheck(database);\n const violations = database.prepare('pragma foreign_key_check').all();\n if (violations.length > 0) throw new Error(`Generation receipt migration failed foreign key check: ${JSON.stringify(violations)}`);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n } finally {\n database.exec('PRAGMA legacy_alter_table = OFF; PRAGMA foreign_keys = ON');\n }\n}\n\nfunction migrateGenerationJobsCheck(database: DatabaseSync): void {\n database.exec(`\n alter table generation_jobs rename to generation_jobs_legacy_check;\n create table generation_jobs (\n id text primary key,\n project_id text not null references projects(id),\n provider text not null default 'codex-handoff',\n adapter_version text not null,\n source_mode text not null check (source_mode in ('lineage_selection', 'lineage_reroll')),\n root_asset_id text not null references assets(id),\n prompt text not null,\n expected_output_count integer not null check (expected_output_count > 0),\n status text not null check (status in ('planned', 'imported', 'failed', 'cancelled')),\n output_dir text,\n handoff_json text,\n created_at text not null,\n updated_at text not null,\n imported_at text\n );\n insert into generation_jobs (\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at, imported_at\n )\n select\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at, imported_at\n from generation_jobs_legacy_check;\n drop table generation_jobs_legacy_check;\n create index if not exists generation_jobs_project_created on generation_jobs(project_id, created_at);\n `);\n}\n\nfunction migrateGenerationJobInputsCheck(database: DatabaseSync): void {\n database.exec(`\n alter table generation_job_inputs rename to generation_job_inputs_legacy_check;\n create table generation_job_inputs (\n id text primary key,\n job_id text not null references generation_jobs(id) on delete cascade,\n project_id text not null references projects(id),\n asset_id text not null references assets(id),\n root_asset_id text not null references assets(id),\n role text not null check (role in ('lineage_next_base', 'reference', 'reroll_target')),\n position integer not null,\n selection_strategy text not null,\n selection_snapshot_json text not null,\n unique(job_id, asset_id, role)\n );\n insert into generation_job_inputs (\n id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json\n )\n select\n id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json\n from generation_job_inputs_legacy_check;\n drop table generation_job_inputs_legacy_check;\n create index if not exists generation_job_inputs_job on generation_job_inputs(job_id, position);\n `);\n}\n", "import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { createS3StorageAdapter } from './adapters/storage';\nimport { listLocalReviewAssets, localPreviewPath as resolveLocalPreviewPath } from './localReview';\nimport { syncLedgerPlacement } from './assetLedgerWorkflow';\nimport { appName } from '../shared/appConstants';\nimport type {\n AssetCatalog,\n AssetContentType,\n AssetFacets,\n DoctorReport,\n AssetLibrarySnapshot,\n GrowthAsset,\n ListAssetsOptions,\n LiveS3Object,\n MutationResponse,\n PlacementFields,\n PlacementStatus,\n PresignResponse,\n ProjectSummary,\n UploadFields,\n} from '../shared/types';\n\nfunction isPackageRoot(path: string): boolean {\n const packageJson = join(path, 'package.json');\n if (!existsSync(packageJson)) return false;\n try {\n const packageInfo = JSON.parse(readFileSync(packageJson, 'utf8')) as { name?: string };\n return packageInfo.name === '@mean-weasel/lineage';\n } catch {\n return false;\n }\n}\n\nfunction resolvePackageRoot(): string {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n process.env.LINEAGE_REPO_ROOT,\n resolve(moduleDir, '..'),\n resolve(moduleDir, '../..'),\n process.cwd(),\n ].filter((candidate): candidate is string => Boolean(candidate));\n const root = candidates.find(isPackageRoot);\n if (!root) throw new Error('Unable to locate Lineage package root');\n return root;\n}\n\nexport const packageRoot = resolvePackageRoot();\nexport let repoRoot = resolve(process.env.LINEAGE_ASSET_ROOT || packageRoot);\n\nexport function setLineageAssetRoot(path?: string): string {\n repoRoot = resolve(path || packageRoot);\n return repoRoot;\n}\nexport const defaultProject = 'demo-project';\nexport const defaultProduct = process.env.LINEAGE_DEFAULT_PRODUCT || defaultProject;\nconst publicFallbackBucket = 'lineage-demo-assets';\nconst publicFallbackRegion = 'us-east-1';\nconst contentTypes = new Set<AssetContentType>(['image', 'video', 'gif', 'audio', 'doc', 'other']);\nconst baseChannels = ['linkedin', 'meta', 'tiktok', 'x-twitter', 'youtube'];\nconst placementStatuses = new Set<PlacementStatus>(['planned', 'scheduled', 'posted', 'skipped']);\nconst projectNamePattern = /^[a-z0-9][a-z0-9-]*$/;\n\ninterface CommandResult {\n stdout: string;\n stderr: string;\n}\n\nclass LineageAssetError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageAssetError(error: unknown): error is LineageAssetError {\n return error instanceof LineageAssetError;\n}\n\nexport function cleanProject(project = defaultProject): string {\n if (!projectNamePattern.test(project)) {\n throw new LineageAssetError('Project must be lowercase kebab-case');\n }\n return project;\n}\n\nexport function catalogPath(project = defaultProject): string {\n return join(repoRoot, cleanProject(project), 'assets', 'catalog.json');\n}\n\nfunction fixtureCatalogPath(project = defaultProject): string {\n return join(packageRoot, 'fixtures', cleanProject(project), 'assets', 'catalog.json');\n}\n\nfunction resolvedCatalogPath(project = defaultProject): string {\n const path = catalogPath(project);\n if (existsSync(path)) return path;\n const clean = cleanProject(project);\n if (clean === defaultProject && existsSync(fixtureCatalogPath(clean))) return fixtureCatalogPath(clean);\n return path;\n}\n\nexport function normalizeCatalog(catalog: Partial<AssetCatalog>, fallbackProject = defaultProject): AssetCatalog {\n const project = cleanProject(catalog.project || catalog.product || fallbackProject);\n const product = catalog.product || project;\n return {\n ...catalog,\n project,\n product,\n default_bucket: catalog.default_bucket || '',\n default_region: catalog.default_region || '',\n assets: (catalog.assets || []).map(asset => ({\n ...asset,\n source: asset.source || 'catalog',\n project: asset.project || asset.product || project,\n product: asset.product || asset.project || project,\n })),\n };\n}\n\nfunction fallbackS3(assetId: string, channel: string, status = 'working') {\n return {\n bucket: publicFallbackBucket,\n checksum_sha256: undefined,\n content_type: 'image/png',\n key: `products/${defaultProject}/campaigns/2026-06-public-demo/channels/${channel}/audiences/creators/statuses/${status}/types/image/assets/${assetId}/${assetId}.png`,\n region: publicFallbackRegion,\n size_bytes: 2048,\n updated_at: '2026-06-24T12:00:00.000Z',\n version_id: 'public-demo-version',\n };\n}\n\nfunction fallbackAsset(fields: Omit<GrowthAsset, 'audience' | 'campaign' | 'content_type' | 'cta' | 'hook' | 'product' | 'project' | 'source' | 'utm_content'> & {\n audience?: string;\n campaign?: string;\n cta?: string;\n hook?: string;\n utm_content?: string;\n}): GrowthAsset {\n return {\n audience: fields.audience || 'creators',\n campaign: fields.campaign || '2026-06-public-demo',\n content_type: 'image',\n cta: fields.cta || 'Save the idea',\n hook: fields.hook || 'Public demo creative for local review.',\n product: defaultProject,\n project: defaultProject,\n source: 'catalog',\n utm_content: fields.utm_content || fields.asset_id.replace(/-/g, '_'),\n ...fields,\n };\n}\n\nfunction defaultFallbackCatalog(): AssetCatalog {\n return normalizeCatalog({\n assets: [\n fallbackAsset({\n asset_id: 'demo-meta-short-form-upload-demo-post-static',\n channel: 'meta',\n s3: fallbackS3('demo-meta-short-form-upload-demo-post-static', 'meta'),\n status: 'working',\n title: 'Meta short-form demo post static',\n }),\n fallbackAsset({\n asset_id: 'demo-linkedin-ledger-catalog-shared',\n channel: 'linkedin',\n hook: 'Shared ledger creative with catalog metadata.',\n s3: fallbackS3('demo-linkedin-ledger-catalog-shared', 'linkedin'),\n status: 'working',\n title: 'LinkedIn ledger catalog shared',\n }),\n fallbackAsset({\n asset_id: 'demo-linkedin-upload-demo-done-static-grounded-v2',\n channel: 'linkedin',\n placements: [{\n channel: 'linkedin',\n notes: 'Synthetic public scheduled placement.',\n scheduled_at: '2026-06-24T16:00:00-07:00',\n status: 'scheduled',\n updated_at: '2026-06-24T12:30:00.000Z',\n }],\n s3: fallbackS3('demo-linkedin-upload-demo-done-static-grounded-v2', 'linkedin', 'approved'),\n status: 'approved',\n title: 'LinkedIn upload demo scheduled static',\n }),\n fallbackAsset({\n asset_id: 'demo-tiktok-upload-demo-export-vertical',\n channel: 'tiktok',\n format: 'vertical',\n hook: 'Fast vertical demo export for content queue tests.',\n s3: fallbackS3('demo-tiktok-upload-demo-export-vertical', 'tiktok'),\n status: 'working',\n title: 'TikTok upload demo export vertical',\n }),\n fallbackAsset({\n asset_id: 'demo-youtube-short-demo-posted-cut',\n channel: 'youtube',\n placements: [{\n channel: 'youtube',\n notes: 'Synthetic public posted placement.',\n posted_at: '2026-06-25T16:00:00-07:00',\n status: 'posted',\n updated_at: '2026-06-25T17:00:00.000Z',\n }],\n s3: fallbackS3('demo-youtube-short-demo-posted-cut', 'youtube', 'published'),\n status: 'published',\n title: 'YouTube short demo posted cut',\n }),\n fallbackAsset({\n asset_id: 'demo-x-twitter-carousel-demo-working-static',\n channel: 'x-twitter',\n format: 'static',\n s3: fallbackS3('demo-x-twitter-carousel-demo-working-static', 'x-twitter'),\n status: 'working',\n title: 'X Twitter carousel demo working static',\n }),\n ],\n default_bucket: '',\n default_region: '',\n product: defaultProject,\n project: defaultProject,\n }, defaultProject);\n}\n\nfunction isDefaultFallbackCatalog(catalog: AssetCatalog): boolean {\n return catalog.project === defaultProject && !existsSync(catalogPath(defaultProject));\n}\n\nfunction fallbackPreviewDataUrl(asset: GrowthAsset): string {\n const label = `${asset.title}\\n${asset.channel} / ${asset.status}`;\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"675\" viewBox=\"0 0 1200 675\"><rect width=\"1200\" height=\"675\" fill=\"#f7f5ef\"/><rect x=\"56\" y=\"56\" width=\"1088\" height=\"563\" rx=\"18\" fill=\"#10201c\"/><text x=\"96\" y=\"145\" fill=\"#9fe6c8\" font-family=\"Arial, sans-serif\" font-size=\"34\" font-weight=\"700\">Lineage public demo preview</text><text x=\"96\" y=\"230\" fill=\"#fff8e6\" font-family=\"Arial, sans-serif\" font-size=\"56\" font-weight=\"700\">${escapeSvgText(asset.asset_id)}</text><text x=\"96\" y=\"330\" fill=\"#d9e8df\" font-family=\"Arial, sans-serif\" font-size=\"34\">${escapeSvgText(label)}</text><text x=\"96\" y=\"500\" fill=\"#9fb7ae\" font-family=\"Arial, sans-serif\" font-size=\"26\">Synthetic local placeholder. No external storage requested.</text></svg>`;\n return `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;\n}\n\nfunction escapeSvgText(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\nexport function loadCatalog(project = defaultProject): AssetCatalog {\n const path = catalogPath(project);\n if (existsSync(path)) {\n try {\n return normalizeCatalog(JSON.parse(readFileSync(path, 'utf8')) as Partial<AssetCatalog>, project);\n } catch (error) {\n if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {\n throw new LineageAssetError(`Missing catalog: ${path}`, 404);\n }\n throw error;\n }\n }\n const clean = cleanProject(project);\n if (clean === defaultProject) {\n const fixturePath = fixtureCatalogPath(clean);\n if (existsSync(fixturePath)) {\n return normalizeCatalog(JSON.parse(readFileSync(fixturePath, 'utf8')) as Partial<AssetCatalog>, project);\n }\n return defaultFallbackCatalog();\n }\n throw new LineageAssetError(`Missing catalog: ${path}`, 404);\n}\n\nfunction saveCatalog(project: string, catalog: AssetCatalog): AssetCatalog {\n const normalized = normalizeCatalog(catalog, project);\n mkdirSync(dirname(catalogPath(project)), { recursive: true });\n writeFileSync(catalogPath(project), `${JSON.stringify(normalized, null, 2)}\\n`);\n return normalized;\n}\n\nfunction run(command: string, args: string[]): CommandResult {\n const result = spawnSync(command, args, {\n cwd: repoRoot,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n env: {\n ...process.env,\n AWS_REGION: process.env.AWS_REGION || 'us-east-1',\n AWS_DEFAULT_REGION: process.env.AWS_DEFAULT_REGION || 'us-east-1',\n },\n });\n\n if (result.status !== 0) {\n const detail = result.stderr.trim() || result.stdout.trim();\n throw new LineageAssetError(`${command} ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`, 502);\n }\n\n return { stdout: result.stdout, stderr: result.stderr };\n}\n\nfunction runAws(args: string[]): CommandResult {\n return run('aws', args);\n}\n\nexport function listProjects(): ProjectSummary[] {\n const projects = readdirSync(repoRoot, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && projectNamePattern.test(entry.name) && existsSync(catalogPath(entry.name)))\n .flatMap(entry => {\n try {\n const catalog = loadCatalog(entry.name);\n return [{ project: catalog.project, product: catalog.product, catalogPath: resolvedCatalogPath(entry.name), default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length }];\n } catch (error) {\n if (error instanceof LineageAssetError && error.status === 404) return [];\n throw error;\n }\n })\n .sort((a, b) => a.project.localeCompare(b.project));\n if (!projects.some(item => item.project === defaultProject)) {\n const catalog = loadCatalog(defaultProject);\n projects.push({ project: catalog.project, product: catalog.product, catalogPath: resolvedCatalogPath(defaultProject), default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length });\n projects.sort((a, b) => a.project.localeCompare(b.project));\n }\n return projects;\n}\n\nfunction assetById(catalog: AssetCatalog, assetId: string): GrowthAsset {\n const asset = catalog.assets.find(item => item.asset_id === assetId);\n if (!asset) throw new LineageAssetError(`Unknown asset: ${assetId}`, 404);\n return asset;\n}\n\nconst storageAdapter = createS3StorageAdapter({\n assetById,\n cleanProject,\n createError: (message, status) => new LineageAssetError(message, status),\n defaultProject,\n loadCatalog,\n runAws,\n repoRoot,\n saveCatalog,\n supportedContentTypes: contentTypes,\n});\n\nfunction uniqueSorted<T extends string>(values: Array<T | undefined>): T[] {\n return Array.from(new Set(values.filter(Boolean) as T[])).sort();\n}\n\nfunction facetsFor(assets: GrowthAsset[]): AssetFacets {\n return {\n audiences: uniqueSorted(assets.map(asset => asset.audience)),\n campaigns: uniqueSorted(assets.map(asset => asset.campaign)),\n channels: uniqueSorted([...baseChannels, ...assets.map(asset => asset.channel)]),\n contentTypes: uniqueSorted(assets.map(asset => asset.content_type)),\n placementStatuses: uniqueSorted(assets.flatMap(asset => asset.placements?.map(placement => placement.status) || [])),\n statuses: uniqueSorted(assets.map(asset => asset.status)),\n totalSizeBytes: assets.reduce((sum, asset) => sum + (asset.s3?.size_bytes || 0), 0),\n };\n}\n\nfunction filteredAssets(assets: GrowthAsset[], options: ListAssetsOptions): GrowthAsset[] {\n const query = options.query?.trim().toLowerCase();\n return assets.filter(asset => {\n if (options.status && options.status !== 'all' && asset.status !== options.status) return false;\n if (options.channel && options.channel !== 'all' && asset.channel !== options.channel) return false;\n if (options.type && options.type !== 'all' && asset.content_type !== options.type) return false;\n if (options.placementStatus === 'not-posted' && asset.placements?.some(placement => placement.status === 'posted')) return false;\n if (options.placementStatus && !['all', 'not-posted'].includes(options.placementStatus) && !asset.placements?.some(placement => placement.status === options.placementStatus)) return false;\n if (options.campaign && options.campaign !== 'all' && asset.campaign !== options.campaign) return false;\n if (options.audience && options.audience !== 'all' && asset.audience !== options.audience) return false;\n if (!query) return true;\n return [asset.asset_id, asset.title, asset.campaign, asset.channel, asset.audience, asset.hook, asset.cta]\n .join(' ')\n .toLowerCase()\n .includes(query);\n });\n}\n\nexport function listAssets(project = defaultProject, options: ListAssetsOptions = {}): AssetLibrarySnapshot {\n const catalog = loadCatalog(project);\n const pageSize = Math.min(Math.max(Number(options.pageSize || 10), 1), 100);\n const page = Math.max(Number(options.page || 1), 1);\n const localAssets = listLocalReviewAssets(repoRoot, catalog.project, catalog);\n const source = options.source || 'catalog';\n const sourceAssets = source === 'local' ? localAssets : source === 'all' ? [...localAssets, ...catalog.assets] : catalog.assets;\n const filtered = filteredAssets(sourceAssets, options);\n const totalPages = Math.max(Math.ceil(filtered.length / pageSize), 1);\n const safePage = Math.min(page, totalPages);\n const start = (safePage - 1) * pageSize;\n const pageAssets = filtered.slice(start, start + pageSize);\n let liveObjects: LiveS3Object[] = [];\n let error: string | undefined;\n if (options.includeLive && !isDefaultFallbackCatalog(catalog)) {\n try {\n liveObjects = storageAdapter.listLiveObjects(catalog);\n } catch (err) {\n error = err instanceof Error ? err.message : String(err);\n }\n }\n return {\n catalog: { project: catalog.project, product: catalog.product, default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length },\n assets: pageAssets,\n facets: facetsFor(catalog.assets),\n pagination: { page: safePage, pageSize, total: filtered.length, totalPages },\n liveObjects,\n orphanObjects: liveObjects.filter(object => !object.cataloged),\n identity: options.includeLive && !isDefaultFallbackCatalog(catalog) ? storageAdapter.getIdentity() : undefined,\n fetchedAt: new Date().toISOString(),\n error,\n };\n}\n\nexport function inspectAsset(project: string, assetId: string): GrowthAsset {\n return assetById(loadCatalog(project), assetId);\n}\n\nexport function validateProject(project = defaultProject): ProjectSummary {\n const catalog = loadCatalog(project);\n return { project: catalog.project, product: catalog.product, catalogPath: resolvedCatalogPath(project), default_bucket: catalog.default_bucket, default_region: catalog.default_region, asset_count: catalog.assets.length };\n}\n\nexport function doctorProject(project = defaultProject, options: { includeLive?: boolean } = {}): DoctorReport {\n const summary = validateProject(project);\n let liveCheck: DoctorReport['liveCheck'] = 'skipped';\n let liveError: string | undefined;\n if (options.includeLive && isDefaultFallbackCatalog(loadCatalog(project))) {\n liveCheck = 'skipped';\n liveError = `${appName} public fallback uses local catalog data only.`;\n } else if (options.includeLive) {\n try {\n storageAdapter.listLiveObjects(loadCatalog(project));\n liveCheck = 'ok';\n } catch (error) {\n liveCheck = 'error';\n liveError = error instanceof Error ? error.message : String(error);\n }\n }\n return { catalogExists: true, deleteEnabled: process.env.LINEAGE_ENABLE_CLOUD_DELETE === 'true', project: summary, liveCheck, liveError };\n}\n\nexport function pullAsset(project: string, assetId: string, out = '.asset-scratch'): MutationResponse {\n return storageAdapter.pullAsset(project, assetId, out);\n}\n\nfunction placementFromFields(fields: PlacementFields) {\n if (!fields.channel) throw new LineageAssetError('Placement requires channel');\n if (!placementStatuses.has(fields.status)) throw new LineageAssetError(`Unsupported placement status: ${fields.status}`);\n const now = new Date().toISOString();\n return {\n channel: fields.channel,\n status: fields.status,\n ...(fields.scheduledAt ? { scheduled_at: fields.scheduledAt } : {}),\n ...(fields.postedAt ? { posted_at: fields.postedAt } : {}),\n ...(fields.url ? { url: fields.url } : {}),\n ...(fields.notes ? { notes: fields.notes } : {}),\n updated_at: now,\n };\n}\n\nexport function previewPlacement(project: string, fields: PlacementFields) {\n const asset = inspectAsset(project, fields.assetId);\n return { asset_id: asset.asset_id, placement: placementFromFields(fields) };\n}\n\nexport function updatePlacement(project: string, fields: PlacementFields): MutationResponse {\n if (!fields.confirmWrite) throw new LineageAssetError('Placement updates require confirmWrite=true');\n const catalog = loadCatalog(project);\n const asset = assetById(catalog, fields.assetId);\n const placement = placementFromFields(fields);\n const existing = asset.placements?.findIndex(item => item.channel === placement.channel);\n if (existing !== undefined && existing >= 0) asset.placements![existing] = placement;\n else asset.placements = [...(asset.placements || []), placement];\n saveCatalog(project, catalog);\n syncLedgerPlacement(project, asset.asset_id, placement);\n return { ok: true, message: `Marked ${asset.asset_id} ${placement.status} for ${placement.channel}`, catalog };\n}\n\nexport function presignAsset(project: string, assetId: string, expiresIn = 900): PresignResponse {\n const catalog = loadCatalog(project);\n if (isDefaultFallbackCatalog(catalog)) {\n const asset = assetById(catalog, assetId);\n return { assetId: asset.asset_id, expiresIn, url: fallbackPreviewDataUrl(asset) };\n }\n return storageAdapter.presignAsset(project, assetId, expiresIn);\n}\n\nexport function localPreviewPath(relativePath: string): string {\n try {\n return resolveLocalPreviewPath(repoRoot, relativePath);\n } catch (error) {\n throw new LineageAssetError(error instanceof Error ? error.message : 'Unknown local review asset', 404);\n }\n}\n\nexport function promoteAsset(project: string, assetId: string, confirmWrite: boolean): MutationResponse {\n return storageAdapter.promoteAsset(project, assetId, confirmWrite);\n}\n\nexport function archiveAsset(project: string, assetId: string, confirmArchive: boolean): MutationResponse {\n if (!confirmArchive) throw new LineageAssetError('Archive requires confirmArchive=true');\n const catalog = loadCatalog(project);\n const asset = assetById(catalog, assetId);\n asset.status = 'archived';\n saveCatalog(project, catalog);\n return { ok: true, message: `Archived ${assetId}`, catalog };\n}\n\nexport function uploadAsset(file: string, fields: UploadFields): MutationResponse {\n return storageAdapter.uploadAsset(file, fields);\n}\n\nexport function deleteObjectGuarded(project: string, assetId: string, confirmation: string): MutationResponse {\n return storageAdapter.deleteObjectGuarded(project, assetId, confirmation);\n}\n\nexport function ensureUploadDir(): string {\n const dir = join(repoRoot, '.asset-scratch', 'studio-uploads');\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n return dir;\n}\n\nexport function cleanupUploadedTemp(file?: string): void {\n if (!file) return;\n const uploadRoot = ensureUploadDir();\n const resolved = resolve(file);\n if (resolved.startsWith(`${uploadRoot}/`) && existsSync(resolved)) {\n unlinkSync(resolved);\n }\n}\n", "import { copyFileSync, existsSync, mkdirSync, statSync } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport { contentTypeFor, fileSha256 } from '../../localReview';\nimport type { AssetCatalog, LiveS3Object, MutationResponse, PresignResponse } from '../../../shared/types';\nimport type { StorageAdapter, StorageAdapterDependencies } from './types';\n\nexport function parseAssetIdFromS3Key(key: string): string | undefined {\n const marker = '/assets/';\n const index = key.indexOf(marker);\n if (index === -1) return undefined;\n return key.slice(index + marker.length).split('/')[0];\n}\n\nfunction previewDataUrl(asset: { asset_id: string; channel?: string; status?: string; title?: string }): string {\n const title = asset.title || asset.asset_id;\n const label = `${asset.channel || 'catalog'} / ${asset.status || 'working'}`;\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"675\" viewBox=\"0 0 1200 675\"><rect width=\"1200\" height=\"675\" fill=\"#f7f5ef\"/><rect x=\"56\" y=\"56\" width=\"1088\" height=\"563\" rx=\"18\" fill=\"#10201c\"/><text x=\"96\" y=\"145\" fill=\"#9fe6c8\" font-family=\"Arial, sans-serif\" font-size=\"34\" font-weight=\"700\">Lineage catalog preview</text><text x=\"96\" y=\"230\" fill=\"#fff8e6\" font-family=\"Arial, sans-serif\" font-size=\"56\" font-weight=\"700\">${escapeSvgText(asset.asset_id)}</text><text x=\"96\" y=\"330\" fill=\"#d9e8df\" font-family=\"Arial, sans-serif\" font-size=\"34\">${escapeSvgText(title)}</text><text x=\"96\" y=\"500\" fill=\"#9fb7ae\" font-family=\"Arial, sans-serif\" font-size=\"26\">${escapeSvgText(label)}. No external storage requested.</text></svg>`;\n return `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;\n}\n\nfunction escapeSvgText(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\nexport function createS3StorageAdapter(deps: StorageAdapterDependencies): StorageAdapter {\n return {\n deleteObjectGuarded(project, assetId, confirmation): MutationResponse {\n const enabled = process.env.LINEAGE_ENABLE_CLOUD_DELETE === 'true';\n if (!enabled) {\n throw deps.createError('S3 delete is disabled. Use archive unless a human enables LINEAGE_ENABLE_CLOUD_DELETE.', 403);\n }\n if (confirmation !== `delete ${assetId}`) {\n throw deps.createError(`Delete confirmation must exactly equal: delete ${assetId}`);\n }\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n if (!asset.s3) throw deps.createError(`Asset has no S3 object: ${assetId}`);\n deps.runAws(['s3api', 'delete-object', '--bucket', asset.s3.bucket, '--key', asset.s3.key, '--region', asset.s3.region]);\n asset.status = 'archived';\n deps.saveCatalog(project, catalog);\n return { ok: true, message: `Deleted current S3 object and archived ${assetId}`, catalog };\n },\n\n getIdentity() {\n try {\n const output = deps.runAws(['sts', 'get-caller-identity', '--query', '{Account:Account,Arn:Arn}', '--output', 'json']);\n const parsed = JSON.parse(output.stdout) as { Account: string; Arn: string };\n return { account: parsed.Account, arn: parsed.Arn };\n } catch {\n return undefined;\n }\n },\n\n listLiveObjects(catalog: AssetCatalog): LiveS3Object[] {\n const bucket = catalog.default_bucket;\n const region = catalog.default_region;\n // Existing uploaded objects live under products/<project>; do not rewrite keys during project migration.\n const prefix = `products/${catalog.product}/`;\n const output = deps.runAws(['s3api', 'list-objects-v2', '--bucket', bucket, '--prefix', prefix, '--region', region, '--output', 'json']);\n const parsed = JSON.parse(output.stdout) as {\n Contents?: Array<{ Key: string; Size: number; LastModified: string; StorageClass?: string }>;\n };\n const catalogKeys = new Set(catalog.assets.map(asset => asset.s3?.key).filter(Boolean));\n return (parsed.Contents || []).map(item => ({\n key: item.Key,\n size: item.Size,\n lastModified: item.LastModified,\n storageClass: item.StorageClass,\n cataloged: catalogKeys.has(item.Key),\n assetId: parseAssetIdFromS3Key(item.Key),\n }));\n },\n\n presignAsset(project, assetId, expiresIn = 900): PresignResponse {\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n return { assetId, expiresIn, url: previewDataUrl(asset) };\n },\n\n promoteAsset(project, assetId, confirmWrite): MutationResponse {\n if (!confirmWrite) throw deps.createError('Promote requires confirmWrite=true');\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n asset.status = 'published';\n deps.saveCatalog(project, catalog);\n return {\n ok: true,\n message: `Promoted ${assetId}`,\n catalog,\n };\n },\n\n pullAsset(project, assetId, out = '.asset-scratch'): MutationResponse {\n const catalog = deps.loadCatalog(project);\n const asset = deps.assetById(catalog, assetId);\n return {\n ok: true,\n message: `Prepared ${assetId} for local review`,\n output: {\n assetId: asset.asset_id,\n out,\n storage: asset.local ? 'local' : asset.s3 ? 'catalog-s3-metadata' : 'catalog',\n note: 'Lineage public package does not pull cloud objects automatically.',\n },\n };\n },\n\n uploadAsset(file, fields): MutationResponse {\n if (!fields.confirmWrite) throw deps.createError('Upload requires confirmWrite=true');\n if (!existsSync(file)) throw deps.createError(`Upload file missing: ${file}`, 404);\n if (!['working', 'published'].includes(fields.status)) throw deps.createError('Upload status must be working or published');\n if (!deps.supportedContentTypes.has(fields.type)) throw deps.createError(`Unsupported asset type: ${fields.type}`);\n\n const project = deps.cleanProject(fields.project || fields.product || deps.defaultProject);\n const catalog = deps.loadCatalog(project);\n const relativePath = join('uploads', project, fields.assetId, basename(file));\n const absolutePath = join(deps.repoRoot, '.asset-scratch', relativePath);\n mkdirSync(dirname(absolutePath), { recursive: true });\n copyFileSync(file, absolutePath);\n const stats = statSync(absolutePath);\n const contentType = contentTypeFor(absolutePath);\n const checksumSha256 = fileSha256(absolutePath);\n const now = new Date().toISOString();\n const nextAsset = {\n asset_id: fields.assetId,\n audience: fields.audience,\n campaign: fields.campaign,\n channel: fields.channel,\n content_type: fields.type,\n cta: fields.cta,\n hook: fields.hook,\n ...(fields.format ? { format: fields.format } : {}),\n local: {\n absolute_path: absolutePath,\n checksum_sha256: checksumSha256,\n content_type: contentType,\n relative_path: relativePath,\n size_bytes: stats.size,\n updated_at: now,\n },\n ...(fields.messageFamily ? { message_family: fields.messageFamily } : {}),\n ...(fields.notes ? { notes: fields.notes } : {}),\n product: project,\n project,\n source: 'catalog' as const,\n status: fields.status,\n title: fields.title,\n utm_content: fields.utmContent,\n };\n const existing = catalog.assets.findIndex(asset => asset.asset_id === fields.assetId);\n if (existing >= 0) catalog.assets[existing] = { ...catalog.assets[existing], ...nextAsset };\n else catalog.assets.push(nextAsset);\n deps.saveCatalog(project, catalog);\n return {\n ok: true,\n message: `Recorded ${fields.assetId} locally`,\n output: {\n file: basename(absolutePath),\n relativePath,\n sizeBytes: stats.size,\n contentType,\n checksumSha256,\n },\n catalog,\n };\n },\n };\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, extname, join, relative, resolve } from 'node:path';\nimport type { AssetCatalog, AssetContentType, GrowthAsset } from '../shared/types';\n\nconst mimeByExt: Record<string, string> = {\n '.gif': 'image/gif',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.mov': 'video/quicktime',\n '.mp4': 'video/mp4',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.webp': 'image/webp',\n};\nconst localReviewExts = new Set(Object.keys(mimeByExt));\nconst channelFromName = /\\b(linkedin|meta|tiktok|youtube|x-twitter|x)\\b/i;\nconst campaignFromPath = /\\b(20\\d{2}-\\d{2}-[a-z0-9-]+)\\b/i;\n\nclass LocalReviewError extends Error {\n status = 400;\n}\n\nfunction localReviewRoot(repoRoot: string): string {\n return join(repoRoot, '.asset-scratch');\n}\n\nexport function contentTypeFor(file: string): string {\n return mimeByExt[extname(file).toLowerCase()] || 'application/octet-stream';\n}\n\nexport function fileSha256(file: string): string {\n return createHash('sha256').update(readFileSync(file)).digest('hex');\n}\n\nfunction isPathInside(child: string, parent: string): boolean {\n const relativePath = relative(parent, child);\n return Boolean(relativePath) && !relativePath.startsWith('..') && !relativePath.startsWith('/');\n}\n\nfunction walkLocalReviewFiles(dir: string, files: string[] = []): string[] {\n if (!existsSync(dir)) return files;\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return files;\n throw error;\n }\n for (const entry of entries) {\n if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'studio-uploads' || entry.name === 'playwright-results' || entry.name === 'lineage-demo') continue;\n if (process.env.NODE_ENV !== 'test' && /^vitest-/.test(entry.name)) continue;\n const path = join(dir, entry.name);\n if (entry.isDirectory()) walkLocalReviewFiles(path, files);\n else if (entry.isFile() && localReviewExts.has(extname(entry.name).toLowerCase())) files.push(path);\n }\n return files;\n}\n\nfunction inferCampaign(relativePath: string): string {\n return campaignFromPath.exec(relativePath)?.[1] || 'local-review';\n}\n\nfunction inferChannel(relativePath: string): string {\n const match = channelFromName.exec(relativePath);\n if (!match) return 'local';\n return match[1].toLowerCase() === 'x' ? 'x-twitter' : match[1].toLowerCase();\n}\n\nfunction inferContentType(file: string): AssetContentType {\n const mime = contentTypeFor(file);\n if (mime.startsWith('image/gif')) return 'gif';\n if (mime.startsWith('image/')) return 'image';\n if (mime.startsWith('video/')) return 'video';\n return 'other';\n}\n\nexport function listLocalReviewAssets(repoRoot: string, project: string, catalog: AssetCatalog): GrowthAsset[] {\n const catalogChecksums = new Set(catalog.assets.map(asset => asset.s3?.checksum_sha256).filter(Boolean));\n const root = localReviewRoot(repoRoot);\n return walkLocalReviewFiles(root)\n .flatMap(file => {\n try {\n const stats = statSync(file);\n const checksum = fileSha256(file);\n const relativePath = relative(root, file);\n return [{ checksum, file, relativePath, stats }];\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n })\n .filter(item => !catalogChecksums.has(item.checksum))\n .map(item => {\n const fileSlug = basename(item.file, extname(item.file));\n const channel = inferChannel(item.relativePath);\n return {\n asset_id: `local-${item.checksum.slice(0, 12)}`,\n project,\n product: project,\n source: 'local',\n campaign: inferCampaign(item.relativePath),\n channel,\n audience: 'local-review',\n status: 'planned',\n content_type: inferContentType(item.file),\n title: fileSlug.replace(/[-_]+/g, ' '),\n hook: item.relativePath,\n cta: 'Review before upload',\n utm_content: fileSlug.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').toLowerCase() || 'local_review',\n notes: 'Local pre-push asset. Review and refine before uploading to S3.',\n local: {\n relative_path: item.relativePath,\n absolute_path: item.file,\n size_bytes: item.stats.size,\n content_type: contentTypeFor(item.file),\n checksum_sha256: item.checksum,\n updated_at: item.stats.mtime.toISOString(),\n },\n };\n });\n}\n\nexport function localPreviewPath(repoRoot: string, relativePath: string): string {\n const root = localReviewRoot(repoRoot);\n const resolved = resolve(root, relativePath);\n if (!isPathInside(resolved, root) || !existsSync(resolved)) throw new LocalReviewError('Unknown local review asset');\n if (!localReviewExts.has(extname(resolved).toLowerCase())) throw new LocalReviewError('Local preview type is not supported');\n return resolved;\n}\n", "import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';\nimport { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport type { LineageRuntimeChannel } from '../shared/runtimeInfoTypes';\nimport type { ResolvedLineageProfile } from '../shared/lineageProfileTypes';\nimport type { DatabaseSync } from './assetLineageDb';\nimport { assertProfileChannel } from './lineageProfiles';\n\nconst writerLeaseSchemaVersion = 'lineage.profile_writer_lease.v1' as const;\nconst ownerFileName = 'owner.json';\n\ninterface WriterLeaseOwner {\n acquired_at: string;\n environment: ResolvedLineageProfile['environment'];\n pid: number;\n profile_fingerprint: string;\n profile_id: string;\n role: 'service' | 'cli';\n schema_version: typeof writerLeaseSchemaVersion;\n service_origin?: string;\n token: string;\n}\n\nexport interface ProfileWriterLease {\n authenticate: (token: string | undefined) => boolean;\n lock_path: string;\n owner: Omit<WriterLeaseOwner, 'token'>;\n release: () => void;\n}\n\nexport interface ProfileWriterDelegation {\n owner: Omit<WriterLeaseOwner, 'token'>;\n service_origin: string;\n token: string;\n}\n\nexport class ProfileWriterLeaseConflictError extends Error {\n constructor(\n message: string,\n public readonly owner: Omit<WriterLeaseOwner, 'token'>,\n ) {\n super(message);\n this.name = 'ProfileWriterLeaseConflictError';\n }\n}\n\nexport function profileWriterLockPath(profile: Pick<ResolvedLineageProfile, 'manifest_path'>): string {\n return join(dirname(profile.manifest_path), 'writer.lock');\n}\n\nfunction ownerPath(lockPath: string): string {\n return join(lockPath, ownerFileName);\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error && typeof error === 'object' && 'code' in error ? String((error as NodeJS.ErrnoException).code) : undefined;\n}\n\nfunction readOwner(lockPath: string): WriterLeaseOwner {\n const stat = lstatSync(lockPath);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new Error(`Writer lease path is not a safe directory: ${lockPath}; manual inspection is required`);\n }\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(ownerPath(lockPath), 'utf8'));\n } catch (error) {\n throw new Error(`Writer lease metadata is unreadable at ${lockPath}; refusing automatic recovery`, { cause: error });\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error(`Writer lease metadata is invalid at ${lockPath}; refusing automatic recovery`);\n }\n const owner = raw as Partial<WriterLeaseOwner>;\n if (\n owner.schema_version !== writerLeaseSchemaVersion\n || typeof owner.profile_id !== 'string'\n || typeof owner.profile_fingerprint !== 'string'\n || !/^[a-f0-9]{64}$/i.test(owner.profile_fingerprint)\n || (owner.environment !== 'production' && owner.environment !== 'preview' && owner.environment !== 'development')\n || (owner.role !== 'service' && owner.role !== 'cli')\n || !Number.isSafeInteger(owner.pid)\n || Number(owner.pid) <= 0\n || typeof owner.acquired_at !== 'string'\n || Number.isNaN(Date.parse(owner.acquired_at))\n || (owner.role === 'service' && (typeof owner.service_origin !== 'string' || !owner.service_origin))\n || (owner.role === 'cli' && owner.service_origin !== undefined)\n || typeof owner.token !== 'string'\n || owner.token.length < 16\n ) {\n throw new Error(`Writer lease metadata is invalid at ${lockPath}; refusing automatic recovery`);\n }\n return owner as WriterLeaseOwner;\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n if (errorCode(error) === 'ESRCH') return false;\n return true;\n }\n}\n\nfunction createLeaseDirectory(lockPath: string, owner: WriterLeaseOwner): void {\n mkdirSync(lockPath, { mode: 0o700 });\n try {\n writeFileSync(ownerPath(lockPath), `${JSON.stringify(owner, null, 2)}\\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n } catch (error) {\n rmSync(lockPath, { force: true, recursive: true });\n throw error;\n }\n}\n\nfunction reclaimDeadOwner(lockPath: string, owner: WriterLeaseOwner): void {\n if (processIsAlive(owner.pid)) {\n const { token: _token, ...publicOwner } = owner;\n throw new ProfileWriterLeaseConflictError(\n `Lineage profile ${owner.profile_id} already has an active ${owner.role} writer (pid ${owner.pid}); use that managed service or stop it before starting another writer`,\n publicOwner,\n );\n }\n const tokenFence = createHash('sha256').update(owner.token).digest('hex').slice(0, 24);\n const tombstone = `${lockPath}.stale-${owner.pid}-${tokenFence}`;\n try {\n renameSync(lockPath, tombstone);\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return;\n throw error;\n }\n rmSync(tombstone, { force: true, recursive: true });\n}\n\nexport function acquireProfileWriterLease(\n profile: ResolvedLineageProfile,\n channel: LineageRuntimeChannel,\n role: WriterLeaseOwner['role'] = 'service'\n): ProfileWriterLease {\n assertProfileChannel(profile, channel);\n const lockPath = profileWriterLockPath(profile);\n const owner: WriterLeaseOwner = {\n acquired_at: new Date().toISOString(),\n environment: profile.environment,\n pid: process.pid,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n role,\n schema_version: writerLeaseSchemaVersion,\n ...(role === 'service' ? { service_origin: profile.service_origin } : {}),\n token: randomUUID(),\n };\n\n for (let attempt = 0; attempt < 4; attempt += 1) {\n try {\n createLeaseDirectory(lockPath, owner);\n process.env.LINEAGE_WRITER_LEASE_TOKEN = owner.token;\n process.env.LINEAGE_WRITER_LOCK_PATH = lockPath;\n const { token: _token, ...publicOwner } = owner;\n let released = false;\n return {\n authenticate: candidate => {\n if (!candidate) return false;\n const expected = Buffer.from(owner.token);\n const actual = Buffer.from(candidate);\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n },\n lock_path: lockPath,\n owner: publicOwner,\n release: () => {\n if (released) return;\n released = true;\n try {\n const current = readOwner(lockPath);\n if (current.token === owner.token && current.pid === owner.pid) rmSync(lockPath, { force: true, recursive: true });\n } catch {\n // Never remove a lock whose ownership cannot be proven.\n }\n if (process.env.LINEAGE_WRITER_LEASE_TOKEN === owner.token) delete process.env.LINEAGE_WRITER_LEASE_TOKEN;\n if (process.env.LINEAGE_WRITER_LOCK_PATH === lockPath) delete process.env.LINEAGE_WRITER_LOCK_PATH;\n },\n };\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') throw error;\n let existing: WriterLeaseOwner;\n try {\n existing = readOwner(lockPath);\n } catch (readError) {\n if (errorCode(readError) === 'ENOENT') continue;\n throw readError;\n }\n if (\n existing.profile_id !== profile.profile_id\n || existing.environment !== profile.environment\n || existing.profile_fingerprint !== profile.profile_fingerprint\n ) {\n throw new Error(`Writer lease identity at ${lockPath} does not match ${profile.profile_id}/${profile.environment}; manual inspection is required`, { cause: error });\n }\n reclaimDeadOwner(lockPath, existing);\n }\n }\n throw new Error(`Could not acquire writer lease for Lineage profile ${profile.profile_id}; another writer is racing for ownership`);\n}\n\nexport function assertProfileWriterLeaseHeld(): void {\n if (!process.env.LINEAGE_PROFILE) {\n throw new Error('Persistent writes require a selected named Lineage profile and its writer lease; legacy-unbound access is read-only. Create a fresh profile with `profile init --profile <id> --confirm-write`, then pass that profile to the command');\n }\n const profileId = process.env.LINEAGE_PROFILE_ID;\n const profileFingerprint = process.env.LINEAGE_PROFILE_FINGERPRINT;\n const environment = process.env.LINEAGE_PROFILE_ENVIRONMENT;\n const manifestPath = process.env.LINEAGE_PROFILE_MANIFEST;\n const lockPath = process.env.LINEAGE_WRITER_LOCK_PATH;\n const token = process.env.LINEAGE_WRITER_LEASE_TOKEN;\n if (!profileId || !profileFingerprint || !environment || !manifestPath || !lockPath || !token) {\n throw new Error('Named Lineage profiles may write only through a process holding the profile writer lease');\n }\n const expectedLockPath = join(dirname(resolve(manifestPath)), 'writer.lock');\n if (resolve(lockPath) !== expectedLockPath) throw new Error('Profile writer lease path does not match the selected profile manifest');\n const owner = readOwner(lockPath);\n if (\n owner.pid !== process.pid\n || owner.token !== token\n || owner.profile_id !== profileId\n || owner.profile_fingerprint !== profileFingerprint\n || owner.environment !== environment\n ) {\n throw new Error('Current process does not own the selected Lineage profile writer lease');\n }\n}\n\nexport function assertSelectedProfileDatabaseIdentity(database: DatabaseSync): void {\n const profileId = process.env.LINEAGE_PROFILE_ID;\n const environment = process.env.LINEAGE_PROFILE_ENVIRONMENT;\n const profileFingerprint = process.env.LINEAGE_PROFILE_FINGERPRINT;\n if (!process.env.LINEAGE_PROFILE || !profileId || !environment || !profileFingerprint) {\n throw new Error('Writable SQLite identity validation requires a fully resolved named Lineage profile');\n }\n const table = database.prepare(\"select name from sqlite_master where type = 'table' and name = 'lineage_profile_identity'\").get();\n if (!table) throw new Error(`Refusing writable open: database is not bound to Lineage profile ${profileId}`);\n const columns = new Set((database.prepare('pragma table_info(lineage_profile_identity)').all() as Array<{ name: string }>).map(row => row.name));\n if (!columns.has('profile_id') || !columns.has('environment') || !columns.has('profile_fingerprint')) {\n throw new Error(`Refusing writable open: database identity for ${profileId} is missing required fingerprint fields`);\n }\n const rows = database.prepare('select profile_id, environment, profile_fingerprint from lineage_profile_identity').all() as Array<Record<string, unknown>>;\n if (rows.length !== 1) throw new Error(`Refusing writable open: expected exactly one database profile identity, found ${rows.length}`);\n const identity = rows[0];\n if (\n identity.profile_id !== profileId\n || identity.environment !== environment\n || identity.profile_fingerprint !== profileFingerprint\n ) {\n throw new Error(\n `Refusing writable open: database identity ${String(identity.profile_id)}/${String(identity.environment)}/${String(identity.profile_fingerprint)} does not match selected profile ${profileId}/${environment}/${profileFingerprint}`\n );\n }\n}\n\nexport function inspectProfileWriterLease(profile: ResolvedLineageProfile): Omit<WriterLeaseOwner, 'token'> | undefined {\n const lockPath = profileWriterLockPath(profile);\n if (!existsSync(lockPath)) return undefined;\n const { token: _token, ...owner } = readOwner(lockPath);\n return owner;\n}\n\nexport function getProfileWriterDelegation(profile: ResolvedLineageProfile): ProfileWriterDelegation {\n const lockPath = profileWriterLockPath(profile);\n if (!existsSync(lockPath)) {\n throw new Error(\n `Lineage profile ${profile.profile_id} mutating commands require its managed service at ${profile.service_origin}; no active service writer lease was found`\n );\n }\n const owner = readOwner(lockPath);\n if (\n owner.profile_id !== profile.profile_id\n || owner.environment !== profile.environment\n || owner.profile_fingerprint !== profile.profile_fingerprint\n ) {\n throw new Error(`Writer lease identity at ${lockPath} does not match ${profile.profile_id}/${profile.environment}; refusing delegation`);\n }\n if (owner.role !== 'service' || owner.service_origin !== profile.service_origin) {\n throw new Error(`Writer lease for Lineage profile ${profile.profile_id} is not the configured managed service at ${profile.service_origin}`);\n }\n if (!processIsAlive(owner.pid)) {\n throw new Error(`Managed service writer lease for Lineage profile ${profile.profile_id} is stale; refusing delegation`);\n }\n const { token, ...publicOwner } = owner;\n return { owner: publicOwner, service_origin: owner.service_origin, token };\n}\n", "import { createHash, randomUUID } from 'node:crypto';\nimport {\n chmodSync,\n closeSync,\n constants as fsConstants,\n copyFileSync,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n type Stats,\n writeFileSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport {\n lineageProfileAssetsCloneReceiptSchemaVersion,\n lineageProfileCloneReceiptSchemaVersion,\n lineageProfileDoctorSchemaVersion,\n lineageProfileInitSchemaVersion,\n lineageProfileRuntimeRepinReceiptSchemaVersion,\n lineageProfileSchemaVersion,\n type LineageProfileBindResult,\n type LineageProfileAssetsCloneResult,\n type LineageProfileCloneResult,\n type LineageProfileDoctorCheck,\n type LineageProfileDoctorResult,\n type LineageProfileEnvironment,\n type LineageProfileIdentity,\n type LineageProfileInitResult,\n type LineageProfileManifest,\n type LineageProfileRuntimeRepinResult,\n type ResolvedLineageProfile,\n} from '../shared/lineageProfileTypes';\nimport type { LineageRuntimeChannel, LineageRuntimeCodeIdentity, LineageRuntimeInfo } from '../shared/runtimeInfoTypes';\nimport type { DatabaseSync } from './assetLineageDb';\nimport { loadNodeSqlite } from './nodeSqlite';\n\nconst profileIdPattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;\n\nfunction lineageDataRoot(): string {\n if (process.env.LINEAGE_HOME) return resolve(process.env.LINEAGE_HOME);\n if (platform() === 'darwin') return join(homedir(), 'Library', 'Application Support', 'Lineage');\n if (platform() === 'win32') return join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Lineage');\n return join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'lineage');\n}\n\nfunction lineageProfileRoot(): string {\n return resolve(process.env.LINEAGE_PROFILE_ROOT || join(lineageDataRoot(), 'profiles'));\n}\n\nfunction environmentChannel(environment: LineageProfileEnvironment): LineageRuntimeChannel {\n if (environment === 'production') return 'stable';\n if (environment === 'preview') return 'preview';\n return 'dev';\n}\n\nfunction channelEnvironment(channel: LineageRuntimeChannel): LineageProfileEnvironment {\n if (channel === 'stable') return 'production';\n if (channel === 'preview') return 'preview';\n return 'development';\n}\n\nfunction profileManifestPath(selector: string): { manifestPath: string; namedProfileId?: string } {\n const value = selector.trim();\n if (!value) throw new Error('Profile selector must not be empty');\n const looksLikePath = isAbsolute(value) || value.includes('/') || value.includes('\\\\') || value.endsWith('.json');\n if (looksLikePath) return { manifestPath: resolve(value) };\n if (!profileIdPattern.test(value)) throw new Error(`Invalid profile ID: ${value}`);\n return { manifestPath: join(lineageProfileRoot(), value, 'profile.json'), namedProfileId: value };\n}\n\nfunction requiredString(record: Record<string, unknown>, key: string): string {\n const value = record[key];\n if (typeof value !== 'string' || !value.trim()) throw new Error(`Profile manifest requires a non-empty ${key}`);\n return value.trim();\n}\n\nfunction optionalString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n if (value === undefined) return undefined;\n if (typeof value !== 'string' || !value.trim()) throw new Error(`Profile manifest ${key} must be a non-empty string`);\n return value.trim();\n}\n\nfunction validateEnvironment(value: string): LineageProfileEnvironment {\n if (value === 'production' || value === 'preview' || value === 'development') return value;\n throw new Error(`Invalid profile environment: ${value}`);\n}\n\nfunction validateChannel(value: unknown): LineageRuntimeChannel | undefined {\n if (value === undefined) return undefined;\n if (value === 'stable' || value === 'preview' || value === 'dev') return value;\n throw new Error(`Invalid expected runtime channel: ${String(value)}`);\n}\n\nfunction validateCodeOrigin(value: unknown): 'checkout' | 'package' | undefined {\n if (value === undefined) return undefined;\n if (value === 'checkout' || value === 'package') return value;\n throw new Error(`Invalid expected runtime code_origin: ${String(value)}`);\n}\n\nfunction validateFingerprint(value: string | undefined, field: string): string | undefined {\n if (value === undefined) return undefined;\n if (!/^[a-f0-9]{64}$/i.test(value)) throw new Error(`Profile ${field} must be a 64-character SHA-256 fingerprint`);\n return value.toLowerCase();\n}\n\nfunction resolveManifestPath(manifestPath: string, value: string): string {\n return resolve(dirname(manifestPath), value);\n}\n\nfunction validateServiceOrigin(value: string): string {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(`Invalid profile service_origin: ${value}`);\n }\n if (parsed.protocol !== 'http:') throw new Error('Profile service_origin must use http for the local Lineage service');\n if (!parsed.port) throw new Error('Profile service_origin must include an explicit port');\n if (parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash) {\n throw new Error('Profile service_origin must contain only scheme, host, and port');\n }\n return parsed.origin;\n}\n\nexport function resolveLineageProfile(selector: string): ResolvedLineageProfile {\n const { manifestPath, namedProfileId } = profileManifestPath(selector);\n if (!existsSync(manifestPath)) throw new Error(`Profile manifest does not exist: ${manifestPath}`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Could not parse profile manifest ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Profile manifest must be a JSON object');\n const record = raw as Record<string, unknown>;\n const schemaVersion = requiredString(record, 'schema_version');\n if (schemaVersion !== lineageProfileSchemaVersion) throw new Error(`Unsupported profile schema_version: ${schemaVersion}`);\n const profileId = requiredString(record, 'profile_id');\n if (!profileIdPattern.test(profileId)) throw new Error(`Invalid profile ID: ${profileId}`);\n if (namedProfileId && namedProfileId !== profileId) {\n throw new Error(`Named profile ${namedProfileId} does not match immutable manifest profile_id ${profileId}`);\n }\n const expectedRaw = record.expected_runtime;\n if (expectedRaw !== undefined && (!expectedRaw || typeof expectedRaw !== 'object' || Array.isArray(expectedRaw))) {\n throw new Error('Profile expected_runtime must be an object');\n }\n const expected = expectedRaw as Record<string, unknown> | undefined;\n const expectedGitSha = expected ? optionalString(expected, 'git_sha') : undefined;\n const expectedVersion = expected ? optionalString(expected, 'version') : undefined;\n const expectedCodeFingerprint = validateFingerprint(expected ? optionalString(expected, 'code_fingerprint') : undefined, 'expected_runtime.code_fingerprint');\n const expectedCodeOrigin = validateCodeOrigin(expected?.code_origin);\n const migrationsRaw = record.required_schema_migrations;\n if (migrationsRaw !== undefined && (!Array.isArray(migrationsRaw) || migrationsRaw.some(value => typeof value !== 'string' || !value.trim()))) {\n throw new Error('Profile required_schema_migrations must be an array of non-empty strings');\n }\n const environment = validateEnvironment(requiredString(record, 'environment'));\n const expectedChannel = validateChannel(expected?.channel);\n if (expectedChannel && expectedChannel !== environmentChannel(environment)) {\n throw new Error(`Profile environment ${environment} conflicts with expected runtime channel ${expectedChannel}`);\n }\n const manifest: LineageProfileManifest = {\n asset_root: resolveManifestPath(manifestPath, requiredString(record, 'asset_root')),\n database_path: resolveManifestPath(manifestPath, requiredString(record, 'database_path')),\n environment,\n ...(expected ? {\n expected_runtime: {\n ...(expectedChannel ? { channel: expectedChannel } : {}),\n ...(expectedCodeFingerprint ? { code_fingerprint: expectedCodeFingerprint } : {}),\n ...(expectedCodeOrigin ? { code_origin: expectedCodeOrigin } : {}),\n ...(expectedGitSha ? { git_sha: expectedGitSha } : {}),\n ...(expectedVersion ? { version: expectedVersion } : {}),\n },\n } : {}),\n profile_id: profileId,\n ...(migrationsRaw ? { required_schema_migrations: (migrationsRaw as string[]).map(value => value.trim()) } : {}),\n schema_version: lineageProfileSchemaVersion,\n service_origin: validateServiceOrigin(requiredString(record, 'service_origin')),\n };\n return { ...manifest, manifest_path: manifestPath, profile_fingerprint: lineageProfileFingerprint(manifest) };\n}\n\nexport function lineageProfileFingerprint(profile: LineageProfileManifest): string {\n return createHash('sha256').update(JSON.stringify({\n asset_root: resolve(profile.asset_root),\n database_path: resolve(profile.database_path),\n environment: profile.environment,\n profile_id: profile.profile_id,\n schema_version: profile.schema_version,\n service_origin: profile.service_origin,\n })).digest('hex');\n}\n\ntype ProfileRuntime = {\n channel: LineageRuntimeChannel;\n code?: LineageRuntimeCodeIdentity;\n gitSha?: string;\n version: string;\n};\n\ntype ProfileInitializationLease = (\n profile: ResolvedLineageProfile,\n initialize: () => LineageProfileIdentity,\n) => LineageProfileIdentity;\n\nexport function initializeLineageProfile(\n profileId: string,\n serviceOrigin: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n withWriterLease: ProfileInitializationLease,\n): LineageProfileInitResult {\n if (!confirmWrite) throw new Error('Profile init requires --confirm-write');\n if (!profileIdPattern.test(profileId)) throw new Error(`Invalid profile ID: ${profileId}`);\n if (!runtime.code?.verified) throw new Error('Profile init requires a verified runtime code identity');\n if (runtime.code.origin !== 'checkout' && runtime.code.origin !== 'package') {\n throw new Error(`Profile init requires checkout or package code, not ${runtime.code.origin}`);\n }\n if (!runtime.code.fingerprint || !/^[a-f0-9]{64}$/i.test(runtime.code.fingerprint)) {\n throw new Error('Profile init requires a valid executing code fingerprint');\n }\n const validatedServiceOrigin = validateServiceOrigin(serviceOrigin);\n\n const root = lineageProfileRoot();\n mkdirSync(root, { recursive: true, mode: 0o700 });\n const profileDirectory = join(root, profileId);\n try {\n mkdirSync(profileDirectory, { mode: 0o700 });\n } catch (error) {\n if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {\n const doctor = doctorLineageProfile(profileId, runtime);\n if (doctor.ok) {\n throw new Error(`Profile ${profileId} already exists and passes doctor. No files were changed. Reuse it with \\`start --profile ${profileId}\\`; verify it first with \\`profile doctor --profile ${profileId} --json\\`.`, { cause: error });\n }\n const failures = doctor.checks.filter(check => check.status === 'fail').map(check => `${check.id}: ${check.message}`).join('; ');\n throw new Error(`Profile ${profileId} already exists but did not pass doctor. No files were changed. Run \\`profile doctor --profile ${profileId} --json\\`, then inspect ${profileDirectory} manually before retrying. ${failures}`, { cause: error });\n }\n throw error;\n }\n\n const manifestPath = join(profileDirectory, 'profile.json');\n const databasePath = join(profileDirectory, 'lineage.sqlite');\n const assetRoot = join(profileDirectory, 'media');\n const environment = channelEnvironment(runtime.channel);\n const manifest: LineageProfileManifest = {\n asset_root: assetRoot,\n database_path: databasePath,\n environment,\n expected_runtime: {\n channel: runtime.channel,\n code_fingerprint: runtime.code.fingerprint.toLowerCase(),\n code_origin: runtime.code.origin,\n },\n profile_id: profileId,\n schema_version: lineageProfileSchemaVersion,\n service_origin: validatedServiceOrigin,\n };\n const profile: ResolvedLineageProfile = {\n ...manifest,\n manifest_path: manifestPath,\n profile_fingerprint: lineageProfileFingerprint(manifest),\n };\n\n try {\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n const identity = withWriterLease(profile, () => {\n mkdirSync(assetRoot, { mode: 0o700 });\n const databaseFd = openSync(databasePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR, 0o600);\n closeSync(databaseFd);\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(databasePath);\n let boundIdentity: LineageProfileIdentity;\n try {\n boundIdentity = bindOpenDatabase(database, profile, false);\n } finally {\n database.close();\n }\n const manifestPayload = {\n asset_root: './media',\n database_path: './lineage.sqlite',\n environment: profile.environment,\n expected_runtime: profile.expected_runtime,\n profile_id: profile.profile_id,\n schema_version: profile.schema_version,\n service_origin: profile.service_origin,\n };\n writeFileSync(manifestPath, `${JSON.stringify(manifestPayload, null, 2)}\\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n const manifestFd = openSync(manifestPath, 'r');\n try { fsyncSync(manifestFd); } finally { closeSync(manifestFd); }\n const directoryFd = openSync(profileDirectory, 'r');\n try { fsyncSync(directoryFd); } finally { closeSync(directoryFd); }\n const published = resolveLineageProfile(profileId);\n if (published.profile_fingerprint !== profile.profile_fingerprint) {\n throw new Error('Initialized profile fingerprint does not match its published manifest');\n }\n return boundIdentity;\n });\n return {\n asset_root: profile.asset_root,\n database_path: profile.database_path,\n environment: profile.environment,\n identity,\n manifest_path: profile.manifest_path,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n runtime: {\n channel: runtime.channel,\n code_fingerprint: runtime.code.fingerprint,\n code_origin: runtime.code.origin,\n },\n schema_version: lineageProfileInitSchemaVersion,\n service_origin: profile.service_origin,\n };\n } catch (error) {\n rmSync(profileDirectory, { force: true, recursive: true });\n throw error;\n }\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction assertOwnerOnlyPath(path: string, kind: 'manifest' | 'profile directory'): Stats {\n const stats = lstatSync(path);\n const expectedType = kind === 'manifest' ? stats.isFile() : stats.isDirectory();\n if (!expectedType || stats.isSymbolicLink()) throw new Error(`Profile ${kind} must be a nonsymlink ${kind === 'manifest' ? 'regular file' : 'directory'}: ${path}`);\n if ((stats.mode & 0o077) !== 0) throw new Error(`Profile ${kind} must be owner-only: ${path}`);\n if (typeof process.getuid === 'function' && stats.uid !== process.getuid()) throw new Error(`Profile ${kind} must be owned by the current user: ${path}`);\n return stats;\n}\n\nfunction runtimeRepinInvariant(profile: ResolvedLineageProfile): string {\n return JSON.stringify({\n asset_root: profile.asset_root,\n database_path: profile.database_path,\n environment: profile.environment,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n required_schema_migrations: profile.required_schema_migrations || [],\n schema_version: profile.schema_version,\n service_origin: profile.service_origin,\n });\n}\n\nfunction sameFileIdentity(left: Stats, right: Stats): boolean {\n return left.dev === right.dev\n && left.ino === right.ino\n && left.size === right.size\n && left.mtimeMs === right.mtimeMs\n && left.ctimeMs === right.ctimeMs;\n}\n\nexport function repinLineageDevelopmentProfileRuntime(\n selector: string,\n checkoutRoot: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): LineageProfileRuntimeRepinResult {\n if (!confirmWrite) throw new Error('Profile runtime repin requires --confirm-write');\n if (runtime.channel !== 'dev') throw new Error(`Profile runtime repin requires dev code, not ${runtime.channel}`);\n if (!runtime.code?.verified) throw new Error('Profile runtime repin requires a verified checkout runtime');\n if (runtime.code.origin !== 'checkout') throw new Error(`Profile runtime repin requires checkout code, not ${runtime.code.origin}`);\n if (!runtime.code.fingerprint || !/^[a-f0-9]{64}$/i.test(runtime.code.fingerprint)) {\n throw new Error('Profile runtime repin requires a valid executing code fingerprint');\n }\n if (!checkoutRoot.trim()) throw new Error('Profile runtime repin requires --checkout-root');\n const intendedRoot = realpathSync(resolve(checkoutRoot));\n if (!statSync(intendedRoot).isDirectory()) throw new Error(`Profile runtime repin checkout root is not a directory: ${intendedRoot}`);\n const executingRoot = realpathSync(runtime.code.root);\n if (intendedRoot !== executingRoot) {\n throw new Error(`Profile runtime repin checkout root ${intendedRoot} does not match executing code root ${executingRoot}`);\n }\n\n const profile = resolveLineageProfile(selector);\n if (profile.environment !== 'development') throw new Error(`Profile runtime repin requires a development profile, not ${profile.environment}`);\n if (profile.expected_runtime?.channel !== 'dev') throw new Error('Development profile runtime repin requires an existing dev channel pin');\n if (profile.expected_runtime.code_origin !== 'checkout') throw new Error('Development profile runtime repin requires an existing checkout origin pin');\n if (!profile.expected_runtime.code_fingerprint) throw new Error('Development profile runtime repin requires an existing code fingerprint pin');\n\n const manifestPath = profile.manifest_path;\n assertOwnerOnlyPath(dirname(manifestPath), 'profile directory');\n const beforeStats = assertOwnerOnlyPath(manifestPath, 'manifest');\n const beforeText = readFileSync(manifestPath, 'utf8');\n const beforeHash = sha256(beforeText);\n let raw: unknown;\n try {\n raw = JSON.parse(beforeText);\n } catch (error) {\n throw new Error(`Could not parse profile manifest ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Profile manifest must be a JSON object');\n const previousFingerprint = profile.expected_runtime.code_fingerprint;\n const nextExpectedRuntime = {\n channel: 'dev' as const,\n code_fingerprint: runtime.code.fingerprint,\n code_origin: 'checkout' as const,\n ...(runtime.gitSha ? { git_sha: runtime.gitSha } : {}),\n version: runtime.version,\n };\n const updated = { ...(raw as Record<string, unknown>), expected_runtime: nextExpectedRuntime };\n const afterText = `${JSON.stringify(updated, null, 2)}\\n`;\n const afterHash = sha256(afterText);\n const result: LineageProfileRuntimeRepinResult = {\n changed: beforeText !== afterText,\n checkout_root: intendedRoot,\n manifest_after_sha256: afterHash,\n manifest_before_sha256: beforeHash,\n manifest_path: manifestPath,\n new_code_fingerprint: runtime.code.fingerprint,\n previous_code_fingerprint: previousFingerprint,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n schema_version: lineageProfileRuntimeRepinReceiptSchemaVersion,\n };\n if (!result.changed) return result;\n\n const temporaryPath = join(dirname(manifestPath), `.profile.runtime-repin-${randomUUID()}.tmp`);\n let temporaryExists = false;\n try {\n writeFileSync(temporaryPath, afterText, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n temporaryExists = true;\n chmodSync(temporaryPath, 0o600);\n const temporaryFd = openSync(temporaryPath, 'r');\n try { fsyncSync(temporaryFd); } finally { closeSync(temporaryFd); }\n const preparedReplacement = resolveLineageProfile(temporaryPath);\n if (runtimeRepinInvariant(preparedReplacement) !== runtimeRepinInvariant(profile)) {\n throw new Error('Profile runtime repin would change immutable profile routing identity');\n }\n\n const currentStats = assertOwnerOnlyPath(manifestPath, 'manifest');\n const currentText = readFileSync(manifestPath, 'utf8');\n if (!sameFileIdentity(beforeStats, currentStats) || sha256(currentText) !== beforeHash) {\n throw new Error('Profile manifest changed while runtime repin was being prepared; refusing replacement');\n }\n renameSync(temporaryPath, manifestPath);\n temporaryExists = false;\n chmodSync(manifestPath, 0o600);\n const directoryFd = openSync(dirname(manifestPath), 'r');\n try { fsyncSync(directoryFd); } finally { closeSync(directoryFd); }\n\n const replacement = resolveLineageProfile(manifestPath);\n if (runtimeRepinInvariant(replacement) !== runtimeRepinInvariant(profile)) {\n throw new Error('Profile runtime repin changed immutable profile routing identity');\n }\n if (readFileSync(manifestPath, 'utf8') !== afterText) throw new Error('Profile runtime repin replacement bytes do not match the prepared manifest');\n return result;\n } finally {\n if (temporaryExists) rmSync(temporaryPath, { force: true });\n }\n}\n\ntype ProfileAssetReferenceKind = 'root' | 'scratch';\n\ninterface ProfileAssetReference {\n kind: ProfileAssetReferenceKind;\n value: string;\n}\n\nfunction assertProfileRuntimePin(profile: ResolvedLineageProfile, runtime?: ProfileRuntime): void {\n if (!profile.expected_runtime?.code_fingerprint || !profile.expected_runtime.code_origin) {\n throw new Error(`Profile ${profile.profile_id} must pin expected_runtime.code_fingerprint and expected_runtime.code_origin before binding or writing`);\n }\n if (!runtime?.code?.verified) {\n throw new Error(`Profile ${profile.profile_id} requires a verified runtime code identity before binding or writing`);\n }\n if (runtime.code.fingerprint !== profile.expected_runtime.code_fingerprint) {\n throw new Error(`Profile ${profile.profile_id} expects code fingerprint ${profile.expected_runtime.code_fingerprint}, found ${runtime.code.fingerprint}`);\n }\n if (runtime.code.origin !== profile.expected_runtime.code_origin) {\n throw new Error(`Profile ${profile.profile_id} expects code origin ${profile.expected_runtime.code_origin}, found ${runtime.code.origin}`);\n }\n}\n\nexport function assertProfileChannel(profile: ResolvedLineageProfile, channel: LineageRuntimeChannel): void {\n const requiredChannel = environmentChannel(profile.environment);\n if (channel === requiredChannel) return;\n if (profile.environment === 'production') {\n throw new Error(`Refusing to open production profile ${profile.profile_id} from ${channel} code; use the stable channel`);\n }\n throw new Error(`Profile ${profile.profile_id} requires the ${requiredChannel} channel, not ${channel}`);\n}\n\nfunction tableExists(database: DatabaseSync, table: string): boolean {\n return Boolean(database.prepare(\"select name from sqlite_master where type = 'table' and name = ?\").get(table));\n}\n\nfunction tableColumns(database: DatabaseSync, table: string): Set<string> {\n if (!tableExists(database, table)) return new Set();\n return new Set((database.prepare(`pragma table_info(${table})`).all() as Array<{ name: string }>).map(row => row.name));\n}\n\nfunction inspectDatabase(profile: ResolvedLineageProfile): NonNullable<LineageProfileDoctorResult['database']> {\n const result: NonNullable<LineageProfileDoctorResult['database']> = {\n exists: existsSync(profile.database_path),\n migration_keys: [],\n path: profile.database_path,\n };\n if (!result.exists) return result;\n try {\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(profile.database_path, { readOnly: true });\n try {\n if (tableExists(database, 'lineage_profile_identity')) {\n const columns = tableColumns(database, 'lineage_profile_identity');\n const fingerprintExpression = columns.has('profile_fingerprint') ? 'profile_fingerprint' : \"'' as profile_fingerprint\";\n const rows = database.prepare(`select profile_id, environment, bound_at, ${fingerprintExpression} from lineage_profile_identity`).all() as Array<Record<string, unknown>>;\n if (rows.length === 1) {\n const identity: LineageProfileIdentity = {\n bound_at: typeof rows[0].bound_at === 'string' ? rows[0].bound_at : undefined,\n environment: String(rows[0].environment) as LineageProfileEnvironment,\n profile_fingerprint: typeof rows[0].profile_fingerprint === 'string' ? rows[0].profile_fingerprint : '',\n profile_id: String(rows[0].profile_id),\n };\n result.identity = identity;\n } else {\n result.error = `Expected exactly one lineage_profile_identity row, found ${rows.length}`;\n }\n }\n if (tableExists(database, 'lineage_schema_migrations')) {\n result.migration_keys = (database.prepare('select key from lineage_schema_migrations order by key').all() as Array<{ key: string }>).map(row => row.key);\n }\n } finally {\n database.close();\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n }\n return result;\n}\n\nexport function doctorLineageProfile(\n selector: string,\n runtime: ProfileRuntime\n): LineageProfileDoctorResult {\n const checks: LineageProfileDoctorCheck[] = [];\n const result: LineageProfileDoctorResult = {\n checks,\n ok: false,\n runtime: {\n channel: runtime.channel,\n code_fingerprint: runtime.code?.fingerprint,\n code_origin: runtime.code?.origin,\n code_verified: runtime.code?.verified,\n git_sha: runtime.gitSha,\n version: runtime.version,\n },\n schema_version: lineageProfileDoctorSchemaVersion,\n };\n let profile: ResolvedLineageProfile;\n try {\n profile = resolveLineageProfile(selector);\n result.profile = profile;\n result.manifest_path = profile.manifest_path;\n checks.push({ id: 'manifest', message: `Loaded ${profile.profile_id}`, status: 'pass' });\n } catch (error) {\n checks.push({ id: 'manifest', message: error instanceof Error ? error.message : String(error), status: 'fail' });\n return result;\n }\n\n try {\n assertProfileChannel(profile, runtime.channel);\n checks.push({ id: 'runtime_channel', message: `${runtime.channel} code matches ${profile.environment}`, status: 'pass' });\n } catch (error) {\n checks.push({ id: 'runtime_channel', message: error instanceof Error ? error.message : String(error), status: 'fail' });\n }\n try {\n assertProfileRuntimePin(profile, runtime);\n checks.push({ id: 'runtime_code', message: `Verified ${runtime.code!.origin} code ${runtime.code!.fingerprint}`, status: 'pass' });\n } catch (error) {\n checks.push({ id: 'runtime_code', message: error instanceof Error ? error.message : String(error), status: 'fail' });\n }\n if (profile.expected_runtime?.version && profile.expected_runtime.version !== runtime.version) {\n checks.push({ id: 'runtime_version', message: `Expected version ${profile.expected_runtime.version}, found ${runtime.version}`, status: 'fail' });\n } else {\n checks.push({ id: 'runtime_version', message: `Runtime version ${runtime.version}`, status: 'pass' });\n }\n if (profile.expected_runtime?.git_sha && profile.expected_runtime.git_sha !== runtime.gitSha) {\n checks.push({ id: 'runtime_git_sha', message: `Expected Git SHA ${profile.expected_runtime.git_sha}, found ${runtime.gitSha || 'unavailable'}`, status: 'fail' });\n } else if (profile.expected_runtime?.git_sha) {\n checks.push({ id: 'runtime_git_sha', message: `Git SHA ${runtime.gitSha}`, status: 'pass' });\n }\n\n const assetExists = existsSync(profile.asset_root);\n const assetIsDirectory = assetExists && statSync(profile.asset_root).isDirectory();\n result.asset_root = { exists: assetExists, is_directory: assetIsDirectory, path: profile.asset_root };\n checks.push({\n id: 'asset_root',\n message: assetIsDirectory ? `Asset root exists: ${profile.asset_root}` : `Asset root is missing or not a directory: ${profile.asset_root}`,\n status: assetIsDirectory ? 'pass' : 'fail',\n });\n\n const database = inspectDatabase(profile);\n result.database = database;\n checks.push({\n id: 'database_exists',\n message: database.exists ? `Database exists: ${profile.database_path}` : `Database does not exist: ${profile.database_path}`,\n status: database.exists ? 'pass' : 'fail',\n });\n if (database.error) checks.push({ id: 'database_read', message: database.error, status: 'fail' });\n if (!database.identity) {\n checks.push({ id: 'database_identity', message: 'Database is not bound to a Lineage profile', status: 'fail' });\n } else if (\n database.identity.profile_id !== profile.profile_id\n || database.identity.environment !== profile.environment\n || database.identity.profile_fingerprint !== profile.profile_fingerprint\n ) {\n checks.push({\n id: 'database_identity',\n message: `Database identity ${database.identity.profile_id}/${database.identity.environment}/${database.identity.profile_fingerprint || 'no-fingerprint'} does not match ${profile.profile_id}/${profile.environment}/${profile.profile_fingerprint}`,\n status: 'fail',\n });\n } else {\n checks.push({ id: 'database_identity', message: `Database is bound to ${profile.profile_id}`, status: 'pass' });\n }\n const missingMigrations = (profile.required_schema_migrations || []).filter(key => !database.migration_keys.includes(key));\n checks.push({\n id: 'database_schema',\n message: missingMigrations.length ? `Missing required schema migrations: ${missingMigrations.join(', ')}` : `${database.migration_keys.length} schema migration marker(s) available`,\n status: missingMigrations.length ? 'fail' : 'pass',\n });\n result.ok = checks.every(check => check.status !== 'fail');\n return result;\n}\n\nexport function runtimeProfileIdentity(channel: LineageRuntimeChannel): {\n bound: boolean;\n environment: LineageProfileEnvironment;\n fingerprint?: string;\n id: string;\n manifest_path?: string;\n service_origin?: string;\n warning?: string;\n} {\n const selector = process.env.LINEAGE_PROFILE;\n const id = process.env.LINEAGE_PROFILE_ID;\n const environment = process.env.LINEAGE_PROFILE_ENVIRONMENT as LineageProfileEnvironment | undefined;\n if (selector && id && environment) {\n return {\n bound: true,\n environment,\n fingerprint: process.env.LINEAGE_PROFILE_FINGERPRINT,\n id,\n manifest_path: process.env.LINEAGE_PROFILE_MANIFEST,\n service_origin: process.env.LINEAGE_PROFILE_SERVICE_ORIGIN,\n };\n }\n return {\n bound: false,\n environment: channelEnvironment(channel),\n id: 'legacy-unbound',\n warning: id || environment || process.env.LINEAGE_PROFILE_FINGERPRINT || process.env.LINEAGE_PROFILE_MANIFEST\n ? 'Invalid unbound runtime: derived profile identity was supplied without a resolved LINEAGE_PROFILE selector.'\n : 'Legacy unbound runtime: database and asset paths are not protected by a named profile.',\n };\n}\n\nexport function assertRuntimeProfileSafety(channel: LineageRuntimeChannel): void {\n const hasDerivedIdentity = Boolean(\n process.env.LINEAGE_PROFILE_ID\n || process.env.LINEAGE_PROFILE_ENVIRONMENT\n || process.env.LINEAGE_PROFILE_FINGERPRINT\n || process.env.LINEAGE_PROFILE_MANIFEST\n || process.env.LINEAGE_PROFILE_SERVICE_ORIGIN\n );\n if (hasDerivedIdentity && !process.env.LINEAGE_PROFILE) {\n throw new Error('Derived Lineage profile identity requires LINEAGE_PROFILE; start through the Lineage CLI with --profile');\n }\n const profile = runtimeProfileIdentity(channel);\n if (profile.bound && profile.environment === 'production' && channel !== 'stable') {\n throw new Error(`Refusing to open production profile ${profile.id} from ${channel} code; use the stable channel`);\n }\n}\n\nexport function assertUnselectedDatabaseIsUnbound(runtime: LineageRuntimeInfo): void {\n if (!runtime.schema.profile_id) return;\n const environment = runtime.schema.profile_environment || 'unknown';\n throw new Error(\n `Database ${runtime.database.path} is bound to Lineage profile ${runtime.schema.profile_id}/${environment}; select that profile with --profile`\n );\n}\n\nexport function assertResolvedRuntimeProfileEnvironment(profile: ResolvedLineageProfile): void {\n const serviceUrl = new URL(profile.service_origin);\n const expected = new Map<string, string>([\n ['LINEAGE_PROFILE_ID', profile.profile_id],\n ['LINEAGE_PROFILE_ENVIRONMENT', profile.environment],\n ['LINEAGE_PROFILE_FINGERPRINT', profile.profile_fingerprint],\n ['LINEAGE_PROFILE_MANIFEST', profile.manifest_path],\n ['LINEAGE_PROFILE_SERVICE_ORIGIN', profile.service_origin],\n ['LINEAGE_DB', profile.database_path],\n ['LINEAGE_ASSET_ROOT', profile.asset_root],\n ['HOST', serviceUrl.hostname],\n ['PORT', serviceUrl.port],\n ]);\n const conflicts: string[] = [];\n for (const [key, expectedValue] of expected) {\n const actual = process.env[key];\n const pathValue = key === 'LINEAGE_PROFILE_MANIFEST' || key === 'LINEAGE_DB' || key === 'LINEAGE_ASSET_ROOT';\n const matches = actual && (pathValue ? resolve(actual) === resolve(expectedValue) : actual === expectedValue);\n if (!matches) conflicts.push(`${key}=${actual || '(missing)'}`);\n }\n if (conflicts.length > 0) {\n throw new Error(`Resolved profile environment conflicts with ${profile.profile_id}: ${conflicts.join(', ')}`);\n }\n}\n\nfunction ensureProfileIdentityTable(database: DatabaseSync): void {\n if (!tableExists(database, 'lineage_profile_identity')) {\n database.exec(`\n create table lineage_profile_identity (\n profile_id text primary key,\n environment text not null,\n profile_fingerprint text not null,\n bound_at text not null\n )\n `);\n return;\n }\n const columns = tableColumns(database, 'lineage_profile_identity');\n if (!columns.has('profile_id') || !columns.has('environment') || !columns.has('bound_at')) {\n throw new Error('Existing lineage_profile_identity table has an unsupported shape');\n }\n if (!columns.has('profile_fingerprint')) {\n database.exec(\"alter table lineage_profile_identity add column profile_fingerprint text not null default ''\");\n }\n}\n\nfunction assertRequiredMigrations(database: DatabaseSync, profile: ResolvedLineageProfile): void {\n const required = profile.required_schema_migrations || [];\n if (required.length === 0) return;\n if (!tableExists(database, 'lineage_schema_migrations')) {\n throw new Error(`Database is missing required schema migrations: ${required.join(', ')}`);\n }\n const available = new Set((database.prepare('select key from lineage_schema_migrations').all() as Array<{ key: string }>).map(row => row.key));\n const missing = required.filter(key => !available.has(key));\n if (missing.length > 0) throw new Error(`Database is missing required schema migrations: ${missing.join(', ')}`);\n}\n\nfunction profileIdentity(profile: ResolvedLineageProfile): LineageProfileIdentity {\n return {\n bound_at: new Date().toISOString(),\n environment: profile.environment,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n };\n}\n\nfunction bindOpenDatabase(database: DatabaseSync, profile: ResolvedLineageProfile, replace: boolean): LineageProfileIdentity {\n database.exec('begin immediate');\n try {\n ensureProfileIdentityTable(database);\n assertRequiredMigrations(database, profile);\n const rows = database.prepare('select profile_id, environment, profile_fingerprint, bound_at from lineage_profile_identity').all() as unknown as LineageProfileIdentity[];\n if (!replace && rows.length > 0) {\n if (rows.length !== 1) throw new Error(`Expected at most one lineage_profile_identity row, found ${rows.length}`);\n const existing = rows[0];\n const sameBaseIdentity = existing.profile_id === profile.profile_id && existing.environment === profile.environment;\n const migratableLegacyIdentity = sameBaseIdentity && !existing.profile_fingerprint;\n if (!migratableLegacyIdentity && existing.profile_fingerprint !== profile.profile_fingerprint) {\n throw new Error(`Database is already bound to ${existing.profile_id}/${existing.environment}/${existing.profile_fingerprint || 'no-fingerprint'}`);\n }\n if (!migratableLegacyIdentity) {\n database.exec('commit');\n return existing;\n }\n }\n const identity = profileIdentity(profile);\n database.exec('delete from lineage_profile_identity');\n database.prepare('insert into lineage_profile_identity (profile_id, environment, profile_fingerprint, bound_at) values (?, ?, ?, ?)')\n .run(identity.profile_id, identity.environment, identity.profile_fingerprint, identity.bound_at!);\n const integrity = database.prepare('pragma integrity_check').get() as { integrity_check?: string } | undefined;\n if (integrity?.integrity_check !== 'ok') throw new Error(`SQLite integrity check failed: ${integrity?.integrity_check || 'unknown result'}`);\n database.exec('commit');\n return identity;\n } catch (error) {\n try { database.exec('rollback'); } catch { /* best effort */ }\n throw error;\n }\n}\n\nexport function bindLineageProfileDatabase(\n selector: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): LineageProfileBindResult {\n if (!confirmWrite) throw new Error('Profile bind requires --confirm-write');\n const profile = resolveLineageProfile(selector);\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n if (!existsSync(profile.database_path)) throw new Error(`Profile database does not exist: ${profile.database_path}`);\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(profile.database_path);\n try {\n const before = inspectDatabase(profile).identity;\n const identity = bindOpenDatabase(database, profile, false);\n return {\n already_bound: Boolean(before?.profile_fingerprint === profile.profile_fingerprint),\n database_path: profile.database_path,\n identity,\n schema_version: 'lineage.profile_bind.v1',\n };\n } finally {\n database.close();\n }\n}\n\nexport async function cloneLineageProfileDatabase(\n sourceDatabasePath: string,\n targetSelector: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): Promise<LineageProfileCloneResult> {\n if (!confirmWrite) throw new Error('Profile clone requires --confirm-write');\n const profile = resolveLineageProfile(targetSelector);\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n if (profile.environment === 'production') throw new Error('Profile clone target must be preview or development, never production');\n const sourcePath = resolve(sourceDatabasePath);\n const targetPath = resolve(profile.database_path);\n if (sourcePath === targetPath) throw new Error('Profile clone source and target database paths must be different');\n if (!existsSync(sourcePath)) throw new Error(`Profile clone source database does not exist: ${sourcePath}`);\n if (existsSync(targetPath)) throw new Error(`Profile clone target database already exists: ${targetPath}`);\n mkdirSync(dirname(targetPath), { recursive: true });\n const temporaryPath = `${targetPath}.clone-${randomUUID()}.tmp`;\n const receiptDirectory = join(dirname(profile.manifest_path), 'clone-receipts');\n let targetCreated = false;\n const { DatabaseSync, backup } = loadNodeSqlite();\n const source = new DatabaseSync(sourcePath, { readOnly: true });\n try {\n const pagesCopied = await backup(source, temporaryPath);\n chmodSync(temporaryPath, 0o600);\n const cloned = new DatabaseSync(temporaryPath);\n let identity: LineageProfileIdentity;\n try {\n identity = bindOpenDatabase(cloned, profile, true);\n } finally {\n cloned.close();\n }\n // Both paths share a directory. Linking is atomic and fails with EEXIST,\n // unlike rename(), which may silently replace a target created by a racer.\n linkSync(temporaryPath, targetPath);\n targetCreated = true;\n rmSync(temporaryPath, { force: true });\n mkdirSync(receiptDirectory, { recursive: true, mode: 0o700 });\n const receiptPath = join(receiptDirectory, `${Date.now()}-${randomUUID()}.json`);\n const result: LineageProfileCloneResult = {\n database_path: targetPath,\n pages_copied: pagesCopied,\n receipt_path: receiptPath,\n schema_version: lineageProfileCloneReceiptSchemaVersion,\n source_database_path: sourcePath,\n target_identity: identity,\n };\n writeFileSync(receiptPath, `${JSON.stringify({ ...result, created_at: new Date().toISOString() }, null, 2)}\\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n return result;\n } catch (error) {\n rmSync(temporaryPath, { force: true });\n if (targetCreated) rmSync(targetPath, { force: true });\n throw error;\n } finally {\n source.close();\n }\n}\n\nfunction pathIsInside(path: string, parent: string): boolean {\n const child = relative(parent, path);\n return child !== '' && !child.startsWith('..') && !isAbsolute(child);\n}\n\nfunction fileSha256(path: string): string {\n return createHash('sha256').update(readFileSync(path)).digest('hex');\n}\n\nfunction profileAssetReferences(database: DatabaseSync): ProfileAssetReference[] {\n const references: ProfileAssetReference[] = [];\n const addColumn = (table: string, column: string, kind: ProfileAssetReferenceKind) => {\n if (!tableColumns(database, table).has(column)) return;\n const rows = database.prepare(`select ${column} value from ${table} where ${column} is not null and ${column} <> ''`).all() as Array<{ value: string }>;\n for (const row of rows) references.push({ kind, value: row.value });\n };\n addColumn('assets', 'local_path', 'scratch');\n addColumn('asset_attempts', 'file_path', 'scratch');\n addColumn('generation_job_outputs', 'file_path', 'scratch');\n addColumn('asset_ledger_sources', 'local_path', 'scratch');\n addColumn('content_posts', 'source_path', 'root');\n if (tableColumns(database, 'projects').has('id')) {\n const projects = database.prepare(\"select id from projects where id is not null and id <> ''\").all() as Array<{ id: string }>;\n for (const project of projects) {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(project.id)) throw new Error('A project ID cannot be mapped safely into the source asset root');\n references.push({ kind: 'root', value: join(project.id, 'assets', 'catalog.json') });\n }\n }\n return references;\n}\n\nfunction resolveProfileAssetReference(sourceRoot: string, reference: ProfileAssetReference): { path: string; relative_path: string } {\n if (reference.value.includes('\\0')) throw new Error('A referenced asset path contains a null byte');\n const sourceScratch = join(sourceRoot, '.asset-scratch');\n const base = reference.kind === 'scratch' ? sourceScratch : sourceRoot;\n const value = reference.kind === 'scratch' && reference.value.startsWith('.asset-scratch/')\n ? reference.value.slice('.asset-scratch/'.length)\n : reference.value;\n const candidate = isAbsolute(value) ? resolve(value) : resolve(base, value);\n if (!pathIsInside(candidate, base)) throw new Error('A referenced asset path escapes the declared source asset root');\n return { path: candidate, relative_path: relative(sourceRoot, candidate) };\n}\n\nexport function cloneLineageProfileAssets(\n sourceAssetRoot: string,\n targetSelector: string,\n runtime: ProfileRuntime,\n confirmWrite: boolean,\n): LineageProfileAssetsCloneResult {\n if (!confirmWrite) throw new Error('Profile asset clone requires --confirm-write');\n const profile = resolveLineageProfile(targetSelector);\n assertProfileChannel(profile, runtime.channel);\n assertProfileRuntimePin(profile, runtime);\n if (!existsSync(profile.database_path)) throw new Error(`Profile database does not exist: ${profile.database_path}`);\n const sourceRoot = resolve(sourceAssetRoot);\n const targetRoot = resolve(profile.asset_root);\n if (!existsSync(sourceRoot) || !statSync(sourceRoot).isDirectory()) throw new Error(`Source asset root does not exist: ${sourceRoot}`);\n if (sourceRoot === targetRoot || pathIsInside(targetRoot, sourceRoot) || pathIsInside(sourceRoot, targetRoot)) {\n throw new Error('Source and target asset roots must be disjoint');\n }\n if (pathIsInside(profile.database_path, targetRoot)) throw new Error('Profile database must not be stored inside its asset root');\n if (existsSync(targetRoot)) throw new Error(`Profile asset clone target already exists: ${targetRoot}`);\n const databaseIdentity = inspectDatabase(profile).identity;\n if (databaseIdentity && (\n databaseIdentity.profile_id !== profile.profile_id\n || databaseIdentity.environment !== profile.environment\n || (databaseIdentity.profile_fingerprint && databaseIdentity.profile_fingerprint !== profile.profile_fingerprint)\n )) {\n throw new Error(`Profile database is already bound to ${databaseIdentity.profile_id}/${databaseIdentity.environment}`);\n }\n\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(profile.database_path, { readOnly: true });\n let references: ProfileAssetReference[];\n try {\n database.exec('begin');\n references = profileAssetReferences(database);\n database.exec('commit');\n } catch (error) {\n try { database.exec('rollback'); } catch { /* best effort */ }\n throw error;\n } finally {\n database.close();\n }\n\n const sourceRealRoot = realpathSync(sourceRoot);\n const files = new Map<string, string>();\n let missingReferences = 0;\n let duplicateReferences = 0;\n for (const reference of references) {\n const resolved = resolveProfileAssetReference(sourceRoot, reference);\n if (!existsSync(resolved.path)) {\n missingReferences += 1;\n continue;\n }\n const stats = statSync(resolved.path);\n if (!stats.isFile()) {\n missingReferences += 1;\n continue;\n }\n const realSource = realpathSync(resolved.path);\n if (!pathIsInside(realSource, sourceRealRoot)) throw new Error('A referenced asset symlink escapes the declared source asset root');\n const existing = files.get(resolved.relative_path);\n if (existing) {\n if (realpathSync(existing) !== realSource) throw new Error('Two source assets map to the same target path');\n duplicateReferences += 1;\n continue;\n }\n files.set(resolved.relative_path, resolved.path);\n }\n\n mkdirSync(dirname(targetRoot), { recursive: true, mode: 0o700 });\n mkdirSync(targetRoot, { mode: 0o700 });\n try {\n let bytesCopied = 0;\n const treeHash = createHash('sha256');\n for (const relativePath of [...files.keys()].sort()) {\n const sourcePath = files.get(relativePath)!;\n const destinationPath = join(targetRoot, relativePath);\n mkdirSync(dirname(destinationPath), { recursive: true, mode: 0o700 });\n copyFileSync(sourcePath, destinationPath, fsConstants.COPYFILE_EXCL);\n chmodSync(destinationPath, 0o600);\n const sourceHash = fileSha256(sourcePath);\n const destinationHash = fileSha256(destinationPath);\n if (sourceHash !== destinationHash) throw new Error('A source asset changed or failed checksum verification during clone');\n bytesCopied += statSync(destinationPath).size;\n treeHash.update(relativePath.replaceAll('\\\\', '/'));\n treeHash.update('\\0');\n treeHash.update(destinationHash);\n treeHash.update('\\0');\n }\n chmodSync(targetRoot, 0o700);\n const receiptPath = join(targetRoot, '.lineage-profile-assets.json');\n const result: LineageProfileAssetsCloneResult = {\n asset_root: targetRoot,\n bytes_copied: bytesCopied,\n code_fingerprint: runtime.code!.fingerprint,\n database_path: profile.database_path,\n duplicate_references: duplicateReferences,\n files_copied: files.size,\n missing_references: missingReferences,\n profile_fingerprint: profile.profile_fingerprint,\n profile_id: profile.profile_id,\n receipt_path: receiptPath,\n references_discovered: references.length,\n runtime_channel: runtime.channel,\n schema_version: lineageProfileAssetsCloneReceiptSchemaVersion,\n source_asset_root: sourceRoot,\n tree_sha256: treeHash.digest('hex'),\n };\n writeFileSync(receiptPath, `${JSON.stringify({ ...result, created_at: new Date().toISOString() }, null, 2)}\\n`, {\n encoding: 'utf8',\n flag: 'wx',\n mode: 0o600,\n });\n return result;\n } catch (error) {\n rmSync(targetRoot, { force: true, recursive: true });\n throw error;\n }\n}\n", "import type { LineageRuntimeChannel } from './runtimeInfoTypes';\n\nexport const lineageProfileSchemaVersion = 'lineage.profile.v1' as const;\nexport const lineageProfileInitSchemaVersion = 'lineage.profile_init.v1' as const;\nexport const lineageProfileDoctorSchemaVersion = 'lineage.profile_doctor.v1' as const;\nexport const lineageProfileCloneReceiptSchemaVersion = 'lineage.profile_clone_receipt.v1' as const;\nexport const lineageProfileAssetsCloneReceiptSchemaVersion = 'lineage.profile_assets_clone_receipt.v1' as const;\nexport const lineageProfileRuntimeRepinReceiptSchemaVersion = 'lineage.profile_runtime_repin_receipt.v1' as const;\n\nexport type LineageProfileEnvironment = 'production' | 'preview' | 'development';\n\ninterface LineageProfileExpectedRuntime {\n channel?: LineageRuntimeChannel;\n code_fingerprint?: string;\n code_origin?: 'checkout' | 'package';\n git_sha?: string;\n version?: string;\n}\n\nexport interface LineageProfileManifest {\n asset_root: string;\n database_path: string;\n environment: LineageProfileEnvironment;\n expected_runtime?: LineageProfileExpectedRuntime;\n profile_id: string;\n required_schema_migrations?: string[];\n schema_version: typeof lineageProfileSchemaVersion;\n service_origin: string;\n}\n\nexport interface ResolvedLineageProfile extends LineageProfileManifest {\n manifest_path: string;\n profile_fingerprint: string;\n}\n\nexport interface LineageProfileIdentity {\n bound_at?: string;\n environment: LineageProfileEnvironment;\n profile_fingerprint: string;\n profile_id: string;\n}\n\nexport interface LineageProfileBindResult {\n already_bound: boolean;\n database_path: string;\n identity: LineageProfileIdentity;\n schema_version: 'lineage.profile_bind.v1';\n}\n\nexport interface LineageProfileInitResult {\n asset_root: string;\n database_path: string;\n environment: LineageProfileEnvironment;\n identity: LineageProfileIdentity;\n manifest_path: string;\n profile_fingerprint: string;\n profile_id: string;\n runtime: {\n channel: LineageRuntimeChannel;\n code_fingerprint: string;\n code_origin: 'checkout' | 'package';\n };\n schema_version: typeof lineageProfileInitSchemaVersion;\n service_origin: string;\n}\n\nexport interface LineageProfileCloneResult {\n database_path: string;\n pages_copied: number;\n receipt_path: string;\n schema_version: typeof lineageProfileCloneReceiptSchemaVersion;\n source_database_path: string;\n target_identity: LineageProfileIdentity;\n}\n\nexport interface LineageProfileAssetsCloneResult {\n asset_root: string;\n bytes_copied: number;\n code_fingerprint: string;\n database_path: string;\n duplicate_references: number;\n files_copied: number;\n missing_references: number;\n profile_fingerprint: string;\n profile_id: string;\n receipt_path: string;\n references_discovered: number;\n runtime_channel: LineageRuntimeChannel;\n schema_version: typeof lineageProfileAssetsCloneReceiptSchemaVersion;\n source_asset_root: string;\n tree_sha256: string;\n}\n\nexport interface LineageProfileRuntimeRepinResult {\n changed: boolean;\n checkout_root: string;\n manifest_after_sha256: string;\n manifest_before_sha256: string;\n manifest_path: string;\n new_code_fingerprint: string;\n previous_code_fingerprint: string;\n profile_fingerprint: string;\n profile_id: string;\n schema_version: typeof lineageProfileRuntimeRepinReceiptSchemaVersion;\n}\n\ntype LineageProfileDoctorCheckStatus = 'pass' | 'fail' | 'warning';\n\nexport interface LineageProfileDoctorCheck {\n id: string;\n message: string;\n status: LineageProfileDoctorCheckStatus;\n}\n\nexport interface LineageProfileDoctorResult {\n asset_root?: {\n exists: boolean;\n is_directory: boolean;\n path: string;\n };\n checks: LineageProfileDoctorCheck[];\n database?: {\n error?: string;\n exists: boolean;\n identity?: LineageProfileIdentity;\n migration_keys: string[];\n path: string;\n };\n manifest_path?: string;\n ok: boolean;\n profile?: ResolvedLineageProfile;\n runtime: {\n channel: LineageRuntimeChannel;\n code_fingerprint?: string;\n code_origin?: 'checkout' | 'package' | 'unknown';\n code_verified?: boolean;\n git_sha?: string;\n version: string;\n };\n schema_version: typeof lineageProfileDoctorSchemaVersion;\n}\n", "import { createRequire } from 'node:module';\n\nconst require = createRequire(import.meta.url);\nconst sqliteExperimentalWarning = 'SQLite is an experimental feature and might change at any time';\n\nexport function loadNodeSqlite(): typeof import('node:sqlite') {\n const emitWarning = process.emitWarning;\n process.emitWarning = ((warning: string | Error, ...args: unknown[]) => {\n const message = warning instanceof Error ? warning.message : warning;\n const type = typeof args[0] === 'string' ? args[0] : warning instanceof Error ? warning.name : undefined;\n if (message === sqliteExperimentalWarning && type === 'ExperimentalWarning') return;\n return Reflect.apply(emitWarning, process, [warning, ...args]);\n }) as typeof process.emitWarning;\n try {\n return require('node:sqlite') as typeof import('node:sqlite');\n } finally {\n process.emitWarning = emitWarning;\n }\n}\n", "import { isAbsolute, join, resolve } from 'node:path';\nimport { EdgeSummaryValidationError, normalizeEdgeSummary, requireEdgeSummary } from '../shared/edgeSummary';\nimport { defaultProject, listAssets, repoRoot } from './assetCore';\nimport { lineageDb as db, lineageDbPath, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { LINEAGE_NEXT_VARIATION_LIMIT, normalizeSelectionInput, selectedRows, selectionId } from './assetLineageSelection';\nimport { cancelLineageTask, listLineageTasks, upsertLineageTask } from './assetLineageTasks';\nimport { activeLineageWorkspaceRoot } from './assetLineageWorkspaces';\nimport { requireLineageWorkspaceClaimForWrite } from './lineageClaimGuards';\nimport type {\n AssetReviewState,\n GrowthAsset,\n LineageAttempt,\n LineageAttemptPromotionResponse,\n LineageAttemptsResponse,\n LineageEdge,\n LineageChildrenResponse,\n LineageEdgeSummaryFields,\n LineageEdgeSummaryMutationResponse,\n LineageIndexSummary,\n LineageLayoutFields,\n LineageLinkFields,\n LineageNode,\n LineageNextResponse,\n LineagePosition,\n LineageRerollRequest,\n LineageRerollRequestMutationResponse,\n LineageRerollRequestsResponse,\n LineageSnapshot,\n LineageTask,\n ReviewFields,\n SelectionFields,\n} from '../shared/types';\n\nexport class LineageError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageError(error: unknown): error is LineageError {\n return error instanceof LineageError;\n}\n\nfunction collectAssets(project: string, source: 'catalog' | 'local'): GrowthAsset[] {\n const first = listAssets(project, { source, page: 1, pageSize: 100 });\n const assets = [...first.assets];\n for (let page = 2; page <= first.pagination.totalPages; page += 1) {\n assets.push(...listAssets(project, { source, page, pageSize: 100 }).assets);\n }\n return assets;\n}\n\nfunction absoluteLocalPath(localPath?: string): string | undefined {\n if (!localPath) return undefined;\n if (isAbsolute(localPath)) return localPath;\n return resolve(repoRoot, '.asset-scratch', localPath);\n}\n\nfunction upsertProject(database: DatabaseSync, project: string): void {\n const timestamp = nowIso();\n database.prepare(`\n insert into projects (id, product, catalog_path, created_at, updated_at)\n values (?, ?, ?, ?, ?)\n on conflict(id) do update set product = excluded.product, updated_at = excluded.updated_at\n `).run(project, project, join(repoRoot, project, 'assets', 'catalog.json'), timestamp, timestamp);\n}\n\nfunction upsertAsset(database: DatabaseSync, project: string, asset: GrowthAsset): void {\n const timestamp = nowIso();\n const source = asset.source === 'local' ? 'local' : 'catalog';\n database.prepare(`\n insert into assets (\n id, project_id, source, local_path, s3_key, checksum_sha256, media_type, title, status,\n channel, campaign, audience, size_bytes, content_type, created_at, updated_at, last_seen_at\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n on conflict(id) do update set\n source = excluded.source, local_path = excluded.local_path, s3_key = excluded.s3_key,\n checksum_sha256 = excluded.checksum_sha256, media_type = excluded.media_type,\n title = excluded.title, status = excluded.status, channel = excluded.channel,\n campaign = excluded.campaign, audience = excluded.audience, size_bytes = excluded.size_bytes,\n content_type = excluded.content_type, updated_at = excluded.updated_at, last_seen_at = excluded.last_seen_at\n `).run(\n asset.asset_id, project, source, asset.local?.relative_path || null, asset.s3?.key || null,\n asset.local?.checksum_sha256 || asset.s3?.checksum_sha256 || null, asset.content_type, asset.title,\n asset.status, asset.channel || null, asset.campaign || null, asset.audience || null,\n asset.local?.size_bytes || asset.s3?.size_bytes || null, asset.local?.content_type || asset.s3?.content_type || null,\n timestamp, timestamp, timestamp\n );\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, updated_at)\n values (?, 'unreviewed', ?)\n on conflict(asset_id) do nothing\n `).run(asset.asset_id, timestamp);\n}\n\nexport function indexLineageAssets(project = defaultProject): LineageIndexSummary {\n const database = db();\n const catalog = collectAssets(project, 'catalog');\n const local = collectAssets(project, 'local');\n upsertProject(database, project);\n for (const asset of [...catalog, ...local]) upsertAsset(database, project, asset);\n database.close();\n return { catalog: catalog.length, local: local.length, total: catalog.length + local.length, database: lineageDbPath() };\n}\n\nfunction requireAsset(database: DatabaseSync, project: string, assetId: string): void {\n const row = database.prepare('select id from assets where project_id = ? and id = ?').get(project, assetId);\n if (!row) throw new LineageError(`Unknown indexed asset: ${assetId}`, 404);\n}\n\nfunction parentOf(database: DatabaseSync, project: string, assetId: string): string | undefined {\n const row = database.prepare('select parent_asset_id from asset_edges where project_id = ? and child_asset_id = ? order by created_at limit 1').get(project, assetId) as { parent_asset_id?: string } | undefined;\n return row?.parent_asset_id;\n}\n\nfunction rootFor(database: DatabaseSync, project: string, assetId: string): string {\n let root = assetId;\n const seen = new Set<string>();\n while (!seen.has(root)) {\n seen.add(root);\n const parent = parentOf(database, project, root);\n if (!parent) return root;\n root = parent;\n }\n return assetId;\n}\n\nfunction assertCanonicalRoot(database: DatabaseSync, project: string, root: string): void {\n requireAsset(database, project, root);\n const canonicalRoot = rootFor(database, project, root);\n if (canonicalRoot !== root) throw new LineageError(`Asset ${root} is not a lineage root`, 400);\n}\n\nfunction explicitWorkspaceRoot(database: DatabaseSync, project: string, assetId: string): string | undefined {\n const row = database.prepare(`\n select root_asset_id from lineage_workspaces\n where project_id = ? and root_asset_id = ? and status != 'archived'\n `).get(project, assetId) as { root_asset_id?: string } | undefined;\n return row?.root_asset_id;\n}\n\nfunction nearestWorkspaceRoot(database: DatabaseSync, project: string, assetId: string): string {\n let current = assetId;\n const seen = new Set<string>();\n while (!seen.has(current)) {\n seen.add(current);\n const explicit = explicitWorkspaceRoot(database, project, current);\n if (explicit) return explicit;\n const parent = parentOf(database, project, current);\n if (!parent) return current;\n current = parent;\n }\n return assetId;\n}\n\nfunction assetChannel(database: DatabaseSync, project: string, assetId: string): string | undefined {\n const row = database.prepare('select channel from assets where project_id = ? and id = ?').get(project, assetId) as { channel?: string } | undefined;\n return row?.channel;\n}\n\nfunction lineageWriteClaimContext(database: DatabaseSync, project: string, assetId: string): { channel?: string; rootAssetId: string } {\n return {\n channel: assetChannel(database, project, assetId),\n rootAssetId: nearestWorkspaceRoot(database, project, assetId),\n };\n}\n\nexport function getLineageWriteClaimContext(project: string, assetId: string): { channel?: string; rootAssetId: string } {\n const database = db();\n try {\n requireAsset(database, project, assetId);\n return lineageWriteClaimContext(database, project, assetId);\n } finally {\n database.close();\n }\n}\n\nfunction latestSelectedRoot(database: DatabaseSync, project: string): string | undefined {\n const row = database.prepare('select root_asset_id from asset_selections where project_id = ? order by selected_at desc limit 1').get(project) as { root_asset_id?: string } | undefined;\n return row?.root_asset_id;\n}\n\nfunction resolveRoot(database: DatabaseSync, project: string, rootAssetId?: string): string {\n if (rootAssetId) {\n requireAsset(database, project, rootAssetId);\n return rootAssetId;\n }\n const root = activeLineageWorkspaceRoot(project) || latestSelectedRoot(database, project);\n if (!root) throw new LineageError('Lineage command requires --root unless a project selection exists');\n requireAsset(database, project, root);\n return root;\n}\n\nfunction edgeId(project: string, parent: string, child: string): string {\n return `${project}:${parent}:derived_from:${child}`;\n}\n\nfunction rerollRequestId(project: string, root: string, node: string, timestamp: string): string {\n return `${project}:${root}:reroll:${node}:${Date.parse(timestamp) || Date.now()}`;\n}\n\nfunction rowString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction lineageEdgeFromRow(row: Record<string, unknown>): LineageEdge {\n const summary = rowString(row.summary);\n const summaryCreatedBy = rowString(row.summary_created_by) as LineageEdge['summary_created_by'];\n const summaryUpdatedBy = rowString(row.summary_updated_by) as LineageEdge['summary_updated_by'];\n const summaryUpdatedAt = rowString(row.summary_updated_at);\n return {\n id: String(row.id),\n parent_asset_id: String(row.parent_asset_id),\n child_asset_id: String(row.child_asset_id),\n relation_type: row.relation_type as LineageEdge['relation_type'],\n created_at: String(row.created_at),\n ...(summary ? { summary } : {}),\n ...(summaryCreatedBy ? { summary_created_by: summaryCreatedBy } : {}),\n ...(summaryUpdatedBy ? { summary_updated_by: summaryUpdatedBy } : {}),\n ...(summaryUpdatedAt ? { summary_updated_at: summaryUpdatedAt } : {}),\n };\n}\n\nfunction nextEdgeSummaryTimestamp(current?: string): string {\n const currentMillis = current ? Date.parse(current) : Number.NaN;\n const nextMillis = Number.isFinite(currentMillis) ? Math.max(Date.now(), currentMillis + 1) : Date.now();\n return new Date(nextMillis).toISOString();\n}\n\nfunction expectedEdgeSummaryTimestamp(value: unknown): string | null {\n if (value === null) return null;\n if (typeof value === 'string' && value.length > 0) return value;\n throw new LineageError('Edge summary update requires expectedSummaryUpdatedAt as a timestamp or null');\n}\n\nfunction validatedHumanEdgeSummary(value: unknown): string {\n try {\n return requireEdgeSummary(value);\n } catch (error) {\n if (error instanceof EdgeSummaryValidationError) throw new LineageError(error.message);\n throw error;\n }\n}\n\nfunction rerollRequestFrom(row: Record<string, unknown>): LineageRerollRequest {\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n root_asset_id: String(row.root_asset_id),\n node_asset_id: String(row.node_asset_id),\n status: row.status as LineageRerollRequest['status'],\n requested_by: row.requested_by as LineageRerollRequest['requested_by'],\n notes: rowString(row.notes),\n created_at: String(row.created_at),\n resolved_at: rowString(row.resolved_at),\n };\n}\n\nfunction tasksByTarget(tasks: LineageTask[]): Map<string, Partial<Record<'iterate' | 'reroll', LineageTask>>> {\n const byTarget = new Map<string, Partial<Record<'iterate' | 'reroll', LineageTask>>>();\n for (const task of tasks) {\n if (task.task_type !== 'iterate' && task.task_type !== 'reroll') continue;\n const existing = byTarget.get(task.target_asset_id) || {};\n existing[task.task_type] = task;\n byTarget.set(task.target_asset_id, existing);\n }\n return byTarget;\n}\n\nfunction withRerollTask(request: LineageRerollRequest, task?: LineageTask): LineageRerollRequest {\n return task ? { ...request, task_id: task.id, task } : request;\n}\n\nfunction taskBackedRerollRequest(project: string, rootAssetId: string, task: LineageTask): LineageRerollRequest {\n return {\n id: `${task.id}:request`,\n project_id: project,\n root_asset_id: rootAssetId,\n node_asset_id: task.target_asset_id,\n status: 'pending',\n requested_by: task.created_by,\n notes: task.instructions,\n created_at: task.created_at,\n task_id: task.id,\n task,\n };\n}\n\nfunction attemptFrom(row: Record<string, unknown>): LineageAttempt {\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n node_asset_id: String(row.node_asset_id),\n asset_id: String(row.asset_id),\n attempt_index: Number(row.attempt_index),\n source: row.source as LineageAttempt['source'],\n prompt: rowString(row.prompt),\n generation_job_id: rowString(row.generation_job_id),\n file_path: rowString(row.file_path),\n checksum_sha256: rowString(row.checksum_sha256),\n created_at: String(row.created_at),\n promoted_at: rowString(row.promoted_at),\n is_current: Boolean(Number(row.is_current)),\n };\n}\n\nfunction implicitAttempt(row: { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string }, isCurrent = true): LineageAttempt {\n const createdAt = row.asset_created_at || nowIso();\n return {\n id: `${row.project}:${row.asset_id}:attempt:implicit`,\n project_id: row.project,\n node_asset_id: row.asset_id,\n asset_id: row.asset_id,\n attempt_index: 1,\n source: 'initial',\n file_path: row.local_path,\n checksum_sha256: row.checksum_sha256,\n created_at: createdAt,\n promoted_at: createdAt,\n is_current: isCurrent,\n };\n}\n\nfunction withImplicitAttempt(physicalAttempts: LineageAttempt[], row: { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string }): LineageAttempt[] {\n if (physicalAttempts.some(attempt => attempt.source === 'initial')) return physicalAttempts;\n return [...physicalAttempts, implicitAttempt(row, !physicalAttempts.some(attempt => attempt.is_current))];\n}\n\nfunction assertNodeInRoot(database: DatabaseSync, project: string, root: string, node: string): void {\n assertCanonicalRoot(database, project, root);\n requireAsset(database, project, node);\n const nodeRoot = rootFor(database, project, node);\n if (nodeRoot !== root) throw new LineageError(`Asset ${node} is not in lineage rooted at ${root}`);\n}\n\nfunction assertAttemptAssetNotVisibleLineageNode(database: DatabaseSync, project: string, root: string, assetId: string): void {\n const visibleNodeIds = new Set([\n root,\n ...descendants(database, project, root).flatMap(edge => [edge.parent_asset_id, edge.child_asset_id]),\n ]);\n if (visibleNodeIds.has(assetId)) throw new LineageError(`Attempt asset ${assetId} is already a visible lineage node in ${root}`, 400);\n}\n\nfunction canPreviewLocally(mediaType: string, localPath?: string): boolean {\n return Boolean(localPath && ['image', 'video', 'gif'].includes(mediaType));\n}\n\nfunction localPreviewUrl(project: string, localPath?: string): string | undefined {\n if (!localPath) return undefined;\n const params = new URLSearchParams({ project, path: localPath });\n return `/api/assets/local-preview?${params.toString()}`;\n}\n\nexport function linkLineageAssets(project: string, fields: LineageLinkFields) {\n const summary = normalizeEdgeSummary(fields.summary);\n if (summary && !fields.summaryActor) throw new LineageError('Lineage edge summary requires an explicit author');\n if (!summary && fields.summaryActor) throw new LineageError('Lineage edge summary author requires a summary');\n const database = db();\n requireAsset(database, project, fields.parentAssetId);\n requireAsset(database, project, fields.childAssetId);\n if (fields.parentAssetId === fields.childAssetId) throw new LineageError('Lineage link cannot point to itself');\n const claimContext = lineageWriteClaimContext(database, project, fields.parentAssetId);\n try {\n requireLineageWorkspaceClaimForWrite({\n channel: claimContext.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n project,\n rootAssetId: claimContext.rootAssetId,\n writeKind: 'lineage_link',\n });\n } catch (error) {\n database.close();\n throw error;\n }\n const createdAt = nowIso();\n const edge: LineageEdge = {\n id: edgeId(project, fields.parentAssetId, fields.childAssetId), parent_asset_id: fields.parentAssetId,\n child_asset_id: fields.childAssetId, relation_type: 'derived_from' as const, created_at: createdAt,\n ...(summary ? {\n summary,\n summary_created_by: fields.summaryActor!,\n summary_updated_by: fields.summaryActor!,\n summary_updated_at: createdAt,\n } : {}),\n };\n if (!fields.confirmWrite) {\n database.close();\n return { ok: true as const, dryRun: true, edge };\n }\n const inserted = database.prepare(`\n insert into asset_edges (\n id, project_id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n )\n values (?, ?, ?, ?, 'derived_from', ?, ?, ?, ?, ?)\n on conflict(project_id, parent_asset_id, child_asset_id, relation_type) do nothing\n `).run(\n edge.id,\n project,\n edge.parent_asset_id,\n edge.child_asset_id,\n edge.created_at,\n edge.summary || null,\n edge.summary_created_by || null,\n edge.summary_updated_by || null,\n edge.summary_updated_at || null,\n );\n if (inserted.changes === 0) {\n const existingRow = database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ? and child_asset_id = ? and relation_type = 'derived_from'\n `).get(project, edge.parent_asset_id, edge.child_asset_id) as Record<string, unknown> | undefined;\n if (!existingRow) {\n database.close();\n throw new LineageError('Lineage edge conflict could not be resolved', 409);\n }\n const existingEdge = lineageEdgeFromRow(existingRow);\n if (summary && (\n existingEdge.summary !== summary\n || existingEdge.summary_created_by !== fields.summaryActor\n || existingEdge.summary_updated_by !== fields.summaryActor\n || !existingEdge.summary_updated_at\n )) {\n database.close();\n throw new LineageError('Lineage edge already exists with a different summary or provenance', 409);\n }\n database.close();\n return {\n ok: true as const,\n idempotent: true as const,\n message: `Already linked ${existingEdge.child_asset_id} from ${existingEdge.parent_asset_id}`,\n edge: existingEdge,\n };\n }\n database.close();\n return { ok: true as const, message: `Linked ${edge.child_asset_id} from ${edge.parent_asset_id}`, edge };\n}\n\nexport function updateLineageEdgeSummary(project: string, fields: LineageEdgeSummaryFields): LineageEdgeSummaryMutationResponse {\n if (!fields.confirmWrite) throw new LineageError('Edge summary updates require confirmWrite=true');\n if (fields.action !== 'set' && fields.action !== 'clear') throw new LineageError('Edge summary action must be set or clear');\n const expectedUpdatedAt = expectedEdgeSummaryTimestamp(fields.expectedSummaryUpdatedAt);\n const summary = fields.action === 'set' ? validatedHumanEdgeSummary(fields.summary) : undefined;\n if (fields.action === 'clear' && fields.summary !== undefined) throw new LineageError('Clear edge summary must not include summary text');\n\n const database = db();\n try {\n const row = database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and id = ?\n `).get(project, fields.edgeId) as Record<string, unknown> | undefined;\n if (!row) throw new LineageError(`Unknown lineage edge: ${fields.edgeId}`, 404);\n const current = lineageEdgeFromRow(row);\n const currentUpdatedAt = current.summary_updated_at || null;\n if (currentUpdatedAt !== expectedUpdatedAt) {\n throw new LineageError('Edge summary changed since it was opened; refresh and retry', 409);\n }\n if (fields.action === 'clear' && !current.summary) throw new LineageError('Edge summary is already clear');\n if (fields.action === 'set' && summary === current.summary) throw new LineageError('Edge summary is unchanged');\n\n const claimContext = lineageWriteClaimContext(database, project, current.parent_asset_id);\n requireLineageWorkspaceClaimForWrite({\n channel: claimContext.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n project,\n rootAssetId: claimContext.rootAssetId,\n writeKind: 'lineage_edge_summary',\n });\n\n const updatedAt = nextEdgeSummaryTimestamp(current.summary_updated_at);\n const createdBy = fields.action === 'set'\n ? (current.summary ? current.summary_created_by || 'human' : 'human')\n : current.summary_created_by || 'human';\n const result = database.prepare(`\n update asset_edges\n set summary = ?, summary_created_by = ?, summary_updated_by = 'human', summary_updated_at = ?\n where project_id = ? and id = ?\n and ((summary_updated_at is null and ? is null) or summary_updated_at = ?)\n `).run(\n summary || null,\n createdBy,\n updatedAt,\n project,\n fields.edgeId,\n expectedUpdatedAt,\n expectedUpdatedAt,\n );\n if (Number(result.changes) !== 1) {\n throw new LineageError('Edge summary changed since it was opened; refresh and retry', 409);\n }\n const updatedRow = database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and id = ?\n `).get(project, fields.edgeId) as Record<string, unknown>;\n const edge = lineageEdgeFromRow(updatedRow);\n return {\n ok: true,\n edge,\n message: fields.action === 'clear' ? 'Cleared edge label' : `Saved edge label \u201C${edge.summary}\u201D`,\n };\n } finally {\n database.close();\n }\n}\n\nfunction descendants(database: DatabaseSync, project: string, root: string): LineageEdge[] {\n const edges: LineageEdge[] = [];\n const queue = [root];\n const seen = new Set<string>();\n while (queue.length > 0) {\n const parent = queue.shift()!;\n if (seen.has(parent)) continue;\n seen.add(parent);\n const rows = (database.prepare(`\n select id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ?\n order by created_at\n `).all(project, parent) as Array<Record<string, unknown>>).map(lineageEdgeFromRow);\n edges.push(...rows);\n queue.push(...rows.map(row => row.child_asset_id));\n }\n return edges;\n}\n\nexport function getLineageSnapshot(project: string, assetId: string): LineageSnapshot {\n const database = db();\n requireAsset(database, project, assetId);\n const root = explicitWorkspaceRoot(database, project, assetId) || rootFor(database, project, assetId);\n const edges = descendants(database, project, root);\n const selected = selectedRows(database, project, root);\n const tasks = listLineageTasks(project, root).tasks;\n const ids = [...new Set([\n root,\n ...edges.flatMap(edge => [edge.parent_asset_id, edge.child_asset_id]),\n ...selected.map(row => row.asset_id),\n ...tasks.map(task => task.target_asset_id),\n ])];\n const placeholders = ids.map(() => '?').join(',');\n const rows = database.prepare(`\n select a.id asset_id, a.project_id project, a.source, a.title, a.media_type, a.status, a.channel, a.campaign,\n a.local_path, a.s3_key, a.checksum_sha256, coalesce(r.review_state, 'unreviewed') review_state,\n r.notes review_notes, a.created_at asset_created_at, l.x layout_x, l.y layout_y\n from assets a left join asset_reviews r on r.asset_id = a.id\n left join asset_layouts l on l.project_id = a.project_id and l.root_asset_id = ? and l.asset_id = a.id\n where a.project_id = ? and a.id in (${placeholders})\n `).all(root, project, ...ids) as unknown as Array<Omit<LineageNode, 'attempt_count' | 'current_attempt' | 'is_latest' | 'lineage_tasks' | 'position' | 'preview_url' | 'reroll_request' | 'selection_note' | 'user_selected'> & { asset_created_at?: string; layout_x?: number; layout_y?: number }>;\n const attemptRows = ids.length > 0\n ? database.prepare(`select * from asset_attempts where project_id = ? and node_asset_id in (${placeholders}) order by node_asset_id, attempt_index desc`).all(project, ...ids) as Array<Record<string, unknown>>\n : [];\n const attemptsByNode = new Map<string, LineageAttempt[]>();\n for (const attempt of attemptRows.map(attemptFrom)) {\n attemptsByNode.set(attempt.node_asset_id, [...(attemptsByNode.get(attempt.node_asset_id) || []), attempt]);\n }\n const lineageTasksByNode = tasksByTarget(tasks);\n const rerollRows = ids.length > 0\n ? database.prepare(`select * from asset_reroll_requests where project_id = ? and root_asset_id = ? and status = 'pending' and node_asset_id in (${placeholders}) order by created_at`).all(project, root, ...ids) as Array<Record<string, unknown>>\n : [];\n const rerollsByNode = new Map(rerollRows.map(row => {\n const request = rerollRequestFrom(row);\n return [request.node_asset_id, withRerollTask(request, lineageTasksByNode.get(request.node_asset_id)?.reroll)] as const;\n }));\n const childIds = new Set(edges.map(edge => edge.parent_asset_id));\n const selectedIds = new Set(selected.map(row => row.asset_id));\n const selections = selected.map(row => ({\n asset_id: row.asset_id, notes: row.notes || undefined,\n position: Number(row.position || 0), selected_at: row.selected_at,\n }));\n const selection = selections[0] || null;\n const nodes = rows.map(row => {\n const position: LineagePosition | undefined = typeof row.layout_x === 'number' && typeof row.layout_y === 'number' ? { x: row.layout_x, y: row.layout_y } : undefined;\n const { asset_created_at: _assetCreatedAt, layout_x: _layoutX, layout_y: _layoutY, ...node } = row;\n const nodeSelection = selections.find(item => item.asset_id === row.asset_id);\n const attempts = withImplicitAttempt(attemptsByNode.get(row.asset_id) || [], row);\n const currentAttempt = attempts.find(attempt => attempt.is_current) || attempts[0];\n const previewPath = currentAttempt?.file_path || row.local_path;\n const lineageTasks = lineageTasksByNode.get(row.asset_id);\n return {\n ...node,\n absolute_path: absoluteLocalPath(row.local_path),\n attempt_count: attempts.length,\n current_attempt: currentAttempt,\n is_latest: !childIds.has(row.asset_id),\n lineage_tasks: lineageTasks && Object.keys(lineageTasks).length > 0 ? lineageTasks : undefined,\n position,\n preview_url: canPreviewLocally(row.media_type, previewPath) ? localPreviewUrl(project, previewPath) : undefined,\n reroll_request: rerollsByNode.get(row.asset_id),\n selection_note: nodeSelection?.notes,\n user_selected: selectedIds.has(row.asset_id),\n };\n });\n database.close();\n return {\n project,\n root_asset_id: root,\n active_asset_id: assetId,\n selected: selections.map(row => row.asset_id),\n selection,\n selections,\n tasks,\n latest: nodes.filter(node => node.is_latest).map(node => node.asset_id),\n nodes,\n edges,\n fetchedAt: nowIso(),\n };\n}\n\nexport function updateLineageLayout(project: string, fields: LineageLayoutFields) {\n if (fields.positions.length === 0) throw new LineageError('Lineage layout requires at least one position');\n const database = db();\n requireAsset(database, project, fields.rootAssetId);\n for (const position of fields.positions) requireAsset(database, project, position.assetId);\n try {\n requireLineageWorkspaceClaimForWrite({\n channel: assetChannel(database, project, fields.rootAssetId),\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n project,\n rootAssetId: fields.rootAssetId,\n writeKind: 'lineage_layout',\n });\n } catch (error) {\n database.close();\n throw error;\n }\n if (!fields.confirmWrite) {\n database.close();\n return { ok: true as const, dryRun: true, root_asset_id: fields.rootAssetId, positions: fields.positions };\n }\n const timestamp = nowIso();\n const statement = database.prepare(`\n insert into asset_layouts (id, project_id, root_asset_id, asset_id, x, y, updated_at)\n values (?, ?, ?, ?, ?, ?, ?)\n on conflict(project_id, root_asset_id, asset_id) do update set\n x = excluded.x, y = excluded.y, updated_at = excluded.updated_at\n `);\n for (const position of fields.positions) {\n statement.run(`${project}:${fields.rootAssetId}:layout:${position.assetId}`, project, fields.rootAssetId, position.assetId, position.x, position.y, timestamp);\n }\n database.close();\n return { ok: true as const, message: `Saved ${fields.positions.length} lineage positions`, root_asset_id: fields.rootAssetId, positions: fields.positions };\n}\n\nexport function getLineageNextAsset(project: string, rootAssetId?: string): LineageNextResponse {\n const database = db();\n const root = resolveRoot(database, project, rootAssetId);\n database.close();\n const snapshot = getLineageSnapshot(project, root);\n const pendingIterateTasks = (snapshot.tasks || []).filter(task => task.task_type === 'iterate' && task.status === 'pending');\n const taskIdsInSelectionOrder = [\n ...snapshot.selections\n .map(selection => selection.asset_id)\n .filter(assetId => pendingIterateTasks.some(task => task.target_asset_id === assetId)),\n ...pendingIterateTasks\n .map(task => task.target_asset_id)\n .filter(assetId => !snapshot.selections.some(selection => selection.asset_id === assetId)),\n ];\n const taskSelectedIds = [...new Set(taskIdsInSelectionOrder)];\n const selectedIds = taskSelectedIds.length > 0 ? taskSelectedIds : snapshot.selected;\n const selectedNodes = selectedIds\n .map(assetId => snapshot.nodes.find(node => node.asset_id === assetId))\n .filter((node): node is LineageNode => Boolean(node));\n const taskSelections = taskSelectedIds.map((assetId, position) => {\n const task = pendingIterateTasks.find(item => item.target_asset_id === assetId);\n return {\n asset_id: assetId,\n notes: task?.instructions,\n position,\n selected_at: task?.created_at || nowIso(),\n };\n });\n const selectedSelection = taskSelections.length > 0 ? taskSelections[0] : snapshot.selection;\n const selectedSelections = taskSelections.length > 0 ? taskSelections : snapshot.selections;\n const latestNodes = snapshot.nodes.filter(node => snapshot.latest.includes(node.asset_id));\n const warnings: string[] = [];\n for (const selectedNode of selectedNodes) {\n if (selectedNode.is_latest) continue;\n warnings.push('Selected asset is not a latest leaf; agents should treat this as an intentional branch choice.');\n }\n if (selectedNodes.length > 0) {\n return {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: 'selected',\n selection_mode: selectedNodes.length > 1 ? 'multiple' : 'single',\n recommended_action: 'evolve_variations',\n reason: 'user_selected',\n next_asset: selectedNodes[0],\n next_assets: selectedNodes,\n latest: snapshot.latest,\n selected: selectedIds,\n selection: selectedSelection,\n selections: selectedSelections,\n candidates: latestNodes,\n warnings,\n fetchedAt: nowIso(),\n };\n }\n if (latestNodes.length === 1) {\n return {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: 'single_latest',\n selection_mode: 'fallback',\n recommended_action: 'evolve_variations',\n reason: 'single_latest_fallback',\n next_asset: latestNodes[0],\n next_assets: [latestNodes[0]],\n latest: snapshot.latest,\n selected: selectedIds,\n selection: selectedSelection,\n selections: selectedSelections,\n candidates: latestNodes,\n warnings,\n fetchedAt: nowIso(),\n };\n }\n return {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: latestNodes.length > 1 ? 'ambiguous_latest' : 'empty',\n selection_mode: 'none',\n recommended_action: latestNodes.length > 1 ? 'choose_next_base' : 'none',\n reason: latestNodes.length > 1 ? 'multiple_latest_no_selection' : 'no_lineage_candidates',\n next_asset: null,\n next_assets: [],\n latest: snapshot.latest,\n selected: selectedIds,\n selection: selectedSelection,\n selections: selectedSelections,\n candidates: latestNodes,\n warnings,\n fetchedAt: nowIso(),\n };\n}\n\nexport function getLineageChildren(project: string, parentAssetId: string): LineageChildrenResponse {\n const snapshot = getLineageSnapshot(project, parentAssetId);\n const edges = snapshot.edges.filter(edge => edge.parent_asset_id === parentAssetId);\n const childIds = new Set(edges.map(edge => edge.child_asset_id));\n return {\n project, parent_asset_id: parentAssetId,\n children: snapshot.nodes.filter(node => childIds.has(node.asset_id)),\n edges, fetchedAt: nowIso(),\n };\n}\n\nexport function listLineageRerollRequests(project: string, rootAssetId: string): LineageRerollRequestsResponse {\n const database = db();\n try {\n assertCanonicalRoot(database, project, rootAssetId);\n const rerollTasks = listLineageTasks(project, rootAssetId).tasks.filter(task => task.task_type === 'reroll');\n const pendingRerollTasks = listLineageTasks(project, rootAssetId, ['pending']).tasks.filter(task => task.task_type === 'reroll');\n const rerollTaskByTarget = new Map(rerollTasks.map(task => [task.target_asset_id, task]));\n const rows = database.prepare(`\n select * from asset_reroll_requests\n where project_id = ? and root_asset_id = ? and status = 'pending'\n order by created_at, id\n `).all(project, rootAssetId) as Array<Record<string, unknown>>;\n const requests = rows.map(row => {\n const request = rerollRequestFrom(row);\n return withRerollTask(request, rerollTaskByTarget.get(request.node_asset_id));\n });\n const legacyTargets = new Set(requests.map(request => request.node_asset_id));\n for (const task of pendingRerollTasks) {\n if (!legacyTargets.has(task.target_asset_id)) requests.push(taskBackedRerollRequest(project, rootAssetId, task));\n }\n return { project, root_asset_id: rootAssetId, requests, fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function getLineageAttempts(project: string, rootAssetId: string, nodeAssetId: string): LineageAttemptsResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, rootAssetId, nodeAssetId);\n const rows = database.prepare(`\n select * from asset_attempts\n where project_id = ? and node_asset_id = ?\n order by attempt_index desc, created_at desc\n `).all(project, nodeAssetId) as Array<Record<string, unknown>>;\n const asset = database.prepare('select id asset_id, project_id project, local_path, checksum_sha256, created_at asset_created_at from assets where project_id = ? and id = ?').get(project, nodeAssetId) as { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string };\n return { project, root_asset_id: rootAssetId, node_asset_id: nodeAssetId, attempts: withImplicitAttempt(rows.map(attemptFrom), asset), fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function promoteLineageAttempt(project: string, fields: {\n rootAssetId: string;\n nodeAssetId: string;\n attemptId: string;\n confirmWrite: boolean;\n}): LineageAttemptPromotionResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n const asset = database.prepare('select id asset_id, project_id project, local_path, checksum_sha256, created_at asset_created_at from assets where project_id = ? and id = ?').get(project, fields.nodeAssetId) as { asset_id: string; project: string; local_path?: string; checksum_sha256?: string; asset_created_at?: string };\n const rows = database.prepare(`\n select * from asset_attempts\n where project_id = ? and node_asset_id = ?\n order by attempt_index desc, created_at desc\n `).all(project, fields.nodeAssetId) as Array<Record<string, unknown>>;\n const attempts = withImplicitAttempt(rows.map(attemptFrom), asset);\n const target = attempts.find(attempt => attempt.id === fields.attemptId);\n if (!target) throw new LineageError(`Attempt ${fields.attemptId} is not in ${fields.nodeAssetId}`, 404);\n const timestamp = nowIso();\n const promotedAttempt = { ...target, is_current: true, promoted_at: timestamp };\n if (!fields.confirmWrite) {\n return {\n ok: true,\n dryRun: true,\n project,\n root_asset_id: fields.rootAssetId,\n node_asset_id: fields.nodeAssetId,\n attempt: promotedAttempt,\n attempts: attempts.map(attempt => ({ ...attempt, is_current: attempt.id === target.id, promoted_at: attempt.id === target.id ? timestamp : attempt.promoted_at })),\n fetchedAt: timestamp,\n };\n }\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare('update asset_attempts set is_current = 0 where project_id = ? and node_asset_id = ?').run(project, fields.nodeAssetId);\n if (target.source !== 'initial') {\n const result = database.prepare(`\n update asset_attempts\n set is_current = 1, promoted_at = ?\n where project_id = ? and node_asset_id = ? and id = ?\n `).run(timestamp, project, fields.nodeAssetId, target.id);\n if (result.changes !== 1) throw new LineageError(`Attempt ${fields.attemptId} is not in ${fields.nodeAssetId}`, 404);\n }\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n const refreshedRows = database.prepare(`\n select * from asset_attempts\n where project_id = ? and node_asset_id = ?\n order by attempt_index desc, created_at desc\n `).all(project, fields.nodeAssetId) as Array<Record<string, unknown>>;\n const refreshedAttempts = withImplicitAttempt(refreshedRows.map(attemptFrom), asset);\n const attempt = refreshedAttempts.find(item => item.id === target.id) || promotedAttempt;\n return {\n ok: true,\n project,\n root_asset_id: fields.rootAssetId,\n node_asset_id: fields.nodeAssetId,\n attempt,\n attempts: refreshedAttempts,\n fetchedAt: nowIso(),\n };\n } finally {\n database.close();\n }\n}\n\nexport function recordLineageRerollAttempt(project: string, fields: {\n rootAssetId: string;\n nodeAssetId: string;\n assetId: string;\n prompt: string;\n generationJobId: string;\n filePath: string;\n checksumSha256: string;\n confirmWrite: boolean;\n}): { ok: true; attempt: LineageAttempt; dryRun?: true } {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n requireAsset(database, project, fields.assetId);\n assertAttemptAssetNotVisibleLineageNode(database, project, fields.rootAssetId, fields.assetId);\n const timestamp = nowIso();\n const maxRow = database.prepare('select max(attempt_index) max_index from asset_attempts where project_id = ? and node_asset_id = ?').get(project, fields.nodeAssetId) as { max_index?: number | null };\n const attemptIndex = Number(maxRow.max_index || 1) + 1;\n const attempt: LineageAttempt = {\n id: `${project}:${fields.nodeAssetId}:attempt:${attemptIndex}`,\n project_id: project,\n node_asset_id: fields.nodeAssetId,\n asset_id: fields.assetId,\n attempt_index: attemptIndex,\n source: 'reroll',\n prompt: fields.prompt,\n generation_job_id: fields.generationJobId,\n file_path: fields.filePath,\n checksum_sha256: fields.checksumSha256,\n created_at: timestamp,\n promoted_at: timestamp,\n is_current: true,\n };\n if (!fields.confirmWrite) return { ok: true, dryRun: true, attempt };\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare('update asset_attempts set is_current = 0 where project_id = ? and node_asset_id = ?').run(project, fields.nodeAssetId);\n database.prepare(`\n insert into asset_attempts (\n id, project_id, node_asset_id, asset_id, attempt_index, source, prompt, generation_job_id,\n file_path, checksum_sha256, created_at, promoted_at, is_current\n ) values (?, ?, ?, ?, ?, 'reroll', ?, ?, ?, ?, ?, ?, 1)\n `).run(\n attempt.id, project, fields.nodeAssetId, fields.assetId, attempt.attempt_index, fields.prompt,\n fields.generationJobId, fields.filePath, fields.checksumSha256, timestamp, timestamp\n );\n database.prepare(`\n update asset_reroll_requests\n set status = 'resolved', resolved_at = ?\n where project_id = ? and root_asset_id = ? and node_asset_id = ? and status = 'pending'\n `).run(timestamp, project, fields.rootAssetId, fields.nodeAssetId);\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n values (?, 'unreviewed', ?, null, null, ?)\n on conflict(asset_id) do update set\n review_state = excluded.review_state, reviewed_at = excluded.reviewed_at,\n ignored_at = excluded.ignored_at, updated_at = excluded.updated_at\n `).run(fields.nodeAssetId, timestamp, timestamp);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n return { ok: true, attempt };\n } finally {\n database.close();\n }\n}\n\nexport function markLineageRerollRequest(project: string, fields: { rootAssetId: string; nodeAssetId: string; notes?: string; requestedBy?: 'agent' | 'human' | 'system'; confirmWrite: boolean }): LineageRerollRequestMutationResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n const existing = database.prepare(`\n select * from asset_reroll_requests\n where project_id = ? and root_asset_id = ? and node_asset_id = ? and status = 'pending'\n order by created_at desc limit 1\n `).get(project, fields.rootAssetId, fields.nodeAssetId) as Record<string, unknown> | undefined;\n const timestamp = nowIso();\n const request: LineageRerollRequest = existing ? {\n ...rerollRequestFrom(existing),\n notes: fields.notes || rerollRequestFrom(existing).notes,\n requested_by: fields.requestedBy || rerollRequestFrom(existing).requested_by,\n } : {\n id: rerollRequestId(project, fields.rootAssetId, fields.nodeAssetId, timestamp),\n project_id: project,\n root_asset_id: fields.rootAssetId,\n node_asset_id: fields.nodeAssetId,\n status: 'pending',\n requested_by: fields.requestedBy || 'human',\n notes: fields.notes,\n created_at: timestamp,\n };\n if (!fields.confirmWrite) return { ok: true, dryRun: true, request };\n const taskResult = upsertLineageTask(project, {\n createdBy: request.requested_by,\n instructions: request.notes,\n rootAssetId: fields.rootAssetId,\n targetAssetId: fields.nodeAssetId,\n taskType: 'reroll',\n });\n if (existing) {\n database.prepare(`\n update asset_reroll_requests\n set requested_by = ?, notes = ?\n where id = ?\n `).run(request.requested_by, request.notes || null, request.id);\n } else {\n database.prepare(`\n insert into asset_reroll_requests (id, project_id, root_asset_id, node_asset_id, status, requested_by, notes, created_at, resolved_at)\n values (?, ?, ?, ?, 'pending', ?, ?, ?, null)\n `).run(request.id, project, fields.rootAssetId, fields.nodeAssetId, request.requested_by, request.notes || null, request.created_at);\n }\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n values (?, 'needs_revision', ?, null, ?, ?)\n on conflict(asset_id) do update set\n review_state = excluded.review_state, reviewed_at = excluded.reviewed_at,\n ignored_at = excluded.ignored_at, notes = coalesce(excluded.notes, asset_reviews.notes), updated_at = excluded.updated_at\n `).run(fields.nodeAssetId, timestamp, request.notes || null, timestamp);\n return {\n ok: true,\n request: withRerollTask(rerollRequestFrom(database.prepare('select * from asset_reroll_requests where id = ?').get(request.id) as Record<string, unknown>), taskResult.task),\n task_id: taskResult.task.id,\n task: taskResult.task,\n };\n } finally {\n database.close();\n }\n}\n\nexport function clearLineageRerollRequest(project: string, fields: { rootAssetId: string; nodeAssetId: string; confirmWrite: boolean }): LineageRerollRequestMutationResponse {\n const database = db();\n try {\n assertNodeInRoot(database, project, fields.rootAssetId, fields.nodeAssetId);\n const existing = database.prepare(`\n select * from asset_reroll_requests\n where project_id = ? and root_asset_id = ? and node_asset_id = ? and status = 'pending'\n order by created_at desc limit 1\n `).get(project, fields.rootAssetId, fields.nodeAssetId) as Record<string, unknown> | undefined;\n if (!existing) throw new LineageError(`No pending re-roll request for ${fields.nodeAssetId}`, 404);\n const timestamp = nowIso();\n const request = { ...rerollRequestFrom(existing), status: 'cancelled' as const, resolved_at: timestamp };\n if (!fields.confirmWrite) return { ok: true, dryRun: true, request };\n const task = listLineageTasks(project, fields.rootAssetId, ['pending']).tasks.find(item => item.task_type === 'reroll' && item.target_asset_id === fields.nodeAssetId);\n const cancelledTask = task ? cancelLineageTask(project, {\n actor: 'human',\n confirmWrite: true,\n taskId: task.id,\n }).task : undefined;\n database.prepare(`\n update asset_reroll_requests\n set status = 'cancelled', resolved_at = ?\n where id = ?\n `).run(timestamp, request.id);\n return {\n ok: true,\n request: withRerollTask(request, cancelledTask),\n task_id: cancelledTask?.id,\n task: cancelledTask,\n };\n } finally {\n database.close();\n }\n}\n\nexport function updateSelectedAsset(project: string, fields: SelectionFields) {\n const database = db();\n let root: string;\n let current: ReturnType<typeof selectedRows>;\n let inputAssetIds: string[];\n let mode: NonNullable<SelectionFields['mode']>;\n let limit: number;\n let nextIds: string[];\n const notesByAsset = new Map<string, string | undefined>();\n try {\n inputAssetIds = normalizeSelectionInput(fields);\n root = fields.rootAssetId || (inputAssetIds[0] ? rootFor(database, project, inputAssetIds[0]) : '');\n if (!root) throw new LineageError('Selection requires rootAssetId or assetId');\n requireAsset(database, project, root);\n for (const assetId of inputAssetIds) requireAsset(database, project, assetId);\n mode = fields.mode || 'replace';\n limit = fields.maxSelections || LINEAGE_NEXT_VARIATION_LIMIT;\n if (!fields.confirmWrite) {\n return { ok: true as const, dryRun: true, root_asset_id: root, asset_ids: inputAssetIds, mode, clear: Boolean(fields.clear), max_selections: limit };\n }\n current = selectedRows(database, project, root);\n nextIds = current.map(row => row.asset_id);\n if (fields.clear) {\n nextIds = [];\n } else if (mode === 'replace') {\n nextIds = inputAssetIds;\n } else if (mode === 'add') {\n nextIds = [...nextIds, ...inputAssetIds];\n } else if (mode === 'remove') {\n nextIds = nextIds.filter(assetId => !inputAssetIds.includes(assetId));\n } else if (mode === 'toggle') {\n for (const assetId of inputAssetIds) {\n nextIds = nextIds.includes(assetId) ? nextIds.filter(id => id !== assetId) : [...nextIds, assetId];\n }\n }\n nextIds = [...new Set(nextIds)];\n if (!fields.clear && inputAssetIds.length === 0) throw new LineageError('Selection set requires assetId or assetIds');\n if (nextIds.length > limit) throw new LineageError(`Select at most ${limit} assets for next variation`);\n for (const assetId of nextIds) {\n const existing = current.find(row => row.asset_id === assetId);\n notesByAsset.set(assetId, inputAssetIds.includes(assetId) ? fields.notes || existing?.notes : existing?.notes);\n }\n } finally {\n database.close();\n }\n\n const removedIds = current.map(row => row.asset_id).filter(assetId => !nextIds.includes(assetId));\n const openIterateTasks = listLineageTasks(project, root, ['pending']).tasks.filter(task => task.task_type === 'iterate');\n for (const assetId of removedIds) {\n const task = openIterateTasks.find(item => item.target_asset_id === assetId);\n if (task) {\n cancelLineageTask(project, {\n actor: 'human',\n confirmWrite: true,\n taskId: task.id,\n });\n }\n }\n for (const assetId of nextIds) {\n upsertLineageTask(project, {\n createdBy: 'human',\n instructions: notesByAsset.get(assetId),\n rootAssetId: root,\n targetAssetId: assetId,\n taskType: 'iterate',\n });\n }\n\n const writeDatabase = db();\n writeDatabase.prepare('delete from asset_selections where project_id = ? and root_asset_id = ?').run(project, root);\n const timestamp = nowIso();\n const insert = writeDatabase.prepare(`\n insert into asset_selections (id, project_id, root_asset_id, asset_id, position, notes, selected_at)\n values (?, ?, ?, ?, ?, ?, ?)\n `);\n nextIds.forEach((assetId, position) => {\n insert.run(selectionId(project, root, assetId), project, root, assetId, position, notesByAsset.get(assetId) || null, timestamp);\n });\n writeDatabase.close();\n const message = nextIds.length === 0 ? `Cleared selected assets for ${root}` : `Selected ${nextIds.length} asset${nextIds.length === 1 ? '' : 's'} for ${root}`;\n return { ok: true as const, message, root_asset_id: root, asset_id: nextIds[0] || null, asset_ids: nextIds, mode };\n}\n\nexport function updateAssetReview(project: string, fields: ReviewFields) {\n const allowed = new Set<AssetReviewState>(['unreviewed', 'approved', 'needs_revision', 'rejected', 'ignored']);\n if (!allowed.has(fields.reviewState)) throw new LineageError(`Unsupported review state: ${fields.reviewState}`);\n const database = db();\n requireAsset(database, project, fields.assetId);\n if (!fields.confirmWrite) {\n database.close();\n return { ok: true as const, dryRun: true, asset_id: fields.assetId, review_state: fields.reviewState, notes: fields.notes };\n }\n const timestamp = nowIso();\n database.prepare(`\n insert into asset_reviews (asset_id, review_state, reviewed_at, ignored_at, notes, updated_at)\n values (?, ?, ?, ?, ?, ?)\n on conflict(asset_id) do update set\n review_state = excluded.review_state, reviewed_at = excluded.reviewed_at,\n ignored_at = excluded.ignored_at, notes = excluded.notes, updated_at = excluded.updated_at\n `).run(fields.assetId, fields.reviewState, timestamp, fields.reviewState === 'ignored' ? timestamp : null, fields.notes || null, timestamp);\n database.close();\n return { ok: true as const, message: `Marked ${fields.assetId} ${fields.reviewState}`, asset_id: fields.assetId, review_state: fields.reviewState };\n}\n", "import type { SelectionFields } from '../shared/types';\nimport type { DatabaseSync } from './assetLineageDb';\n\nexport const LINEAGE_NEXT_VARIATION_LIMIT = 3;\n\nexport interface LineageSelectionRow {\n asset_id: string;\n notes?: string;\n position: number;\n selected_at: string;\n}\n\nexport function selectionId(project: string, root: string, assetId: string): string {\n return `${project}:${root}:selected:${assetId}`;\n}\n\nexport function selectedRows(database: DatabaseSync, project: string, root: string): LineageSelectionRow[] {\n return database.prepare(`\n select asset_id, notes, position, selected_at\n from asset_selections\n where project_id = ? and root_asset_id = ?\n order by position, selected_at, asset_id\n `).all(project, root) as unknown as LineageSelectionRow[];\n}\n\nexport function normalizeSelectionInput(fields: SelectionFields): string[] {\n return [...new Set([...(fields.assetIds || []), fields.assetId || ''].map(assetId => assetId.trim()).filter(Boolean))];\n}\n", "import { randomBytes } from 'node:crypto';\nimport { createAgentClaim, recordAgentClaimWriteAllowed, releaseAgentClaim, revokeAgentClaimInDatabase, validateAgentClaimForWrite, type AgentClaim } from './agentClaims';\nimport { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\nimport type {\n LineageTask,\n LineageTaskActor,\n LineageTaskEvent,\n LineageTaskMutationResponse,\n LineageTaskStatus,\n LineageTasksResponse,\n LineageTaskType,\n} from '../shared/types';\n\nclass LineageTaskError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageTaskError(error: unknown): error is LineageTaskError {\n return error instanceof LineageTaskError;\n}\n\ntype Row = Record<string, unknown>;\ntype LineageTaskMutationResult = Omit<LineageTaskMutationResponse, 'events'> & { project: string; events: LineageTaskEvent[] };\ntype LineageTaskClaimResult = LineageTaskMutationResult & { claim: AgentClaim; claim_token: string };\n\nconst activeStatuses: LineageTaskStatus[] = ['pending', 'claimed', 'in_progress'];\nconst taskTypes = new Set<LineageTaskType>(['iterate', 'reroll']);\nconst taskStatuses = new Set<LineageTaskStatus>(['pending', 'claimed', 'in_progress', 'resolved', 'cancelled']);\n\nexport function taskIdFor(project: string, rootAssetId: string, targetAssetId: string, taskType: LineageTaskType): string {\n return `${project}:${rootAssetId}:lineage-task:${taskType}:${targetAssetId}`;\n}\n\nfunction randomId(prefix: string): string {\n return `${prefix}_${Date.now().toString(36)}_${randomBytes(6).toString('base64url').toLowerCase()}`;\n}\n\nfunction metadataJson(metadata?: Record<string, unknown>): string | null {\n return metadata ? JSON.stringify(metadata) : null;\n}\n\nfunction metadataWithoutClaim(metadata?: Record<string, unknown>): Record<string, unknown> | undefined {\n if (!metadata) return undefined;\n const next = { ...metadata };\n delete next.claim_id;\n return Object.keys(next).length > 0 ? next : undefined;\n}\n\nfunction parseMetadata(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string' || !value) return undefined;\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeProject(project: string): string {\n const trimmed = project.trim();\n if (!trimmed) throw new LineageTaskError('Lineage task requires project');\n return trimmed;\n}\n\nfunction normalizeTaskType(taskType: LineageTaskType): LineageTaskType {\n if (!taskTypes.has(taskType)) throw new LineageTaskError(`Unsupported lineage task type: ${taskType}`);\n return taskType;\n}\n\nfunction normalizeStatus(status: LineageTaskStatus): LineageTaskStatus {\n if (!taskStatuses.has(status)) throw new LineageTaskError(`Unsupported lineage task status: ${status}`);\n return status;\n}\n\nfunction normalizeActor(actor: string, label: string): string {\n const trimmed = actor.trim();\n if (!trimmed) throw new LineageTaskError(`${label} is required`);\n return trimmed;\n}\n\nfunction requireAsset(database: DatabaseSync, project: string, assetId: string): void {\n const row = database.prepare('select id from assets where project_id = ? and id = ?').get(project, assetId);\n if (!row) throw new LineageTaskError(`Unknown indexed asset: ${assetId}`, 404);\n}\n\nfunction taskFromRow(row: Row): LineageTask {\n const metadata = parseMetadata(row.metadata_json);\n const claimId = typeof metadata?.claim_id === 'string' ? metadata.claim_id : undefined;\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n root_asset_id: String(row.root_asset_id),\n target_asset_id: String(row.target_asset_id),\n task_type: String(row.task_type) as LineageTaskType,\n status: String(row.status) as LineageTaskStatus,\n instructions: typeof row.instructions === 'string' ? row.instructions : undefined,\n created_by: String(row.created_by) as LineageTaskActor,\n created_at: String(row.created_at),\n updated_at: String(row.updated_at),\n claimed_at: typeof row.claimed_at === 'string' ? row.claimed_at : undefined,\n started_at: typeof row.started_at === 'string' ? row.started_at : undefined,\n resolved_at: typeof row.resolved_at === 'string' ? row.resolved_at : undefined,\n cancelled_at: typeof row.cancelled_at === 'string' ? row.cancelled_at : undefined,\n resolved_generation_job_id: typeof row.resolved_generation_job_id === 'string' ? row.resolved_generation_job_id : undefined,\n resolved_asset_id: typeof row.resolved_asset_id === 'string' ? row.resolved_asset_id : undefined,\n claimed_by_claim_id: claimId,\n metadata,\n };\n}\n\nfunction eventFromRow(row: Row): LineageTaskEvent {\n return {\n id: String(row.id),\n task_id: String(row.task_id),\n event_type: String(row.event_type) as LineageTaskEvent['event_type'],\n actor: typeof row.actor === 'string' ? row.actor : undefined,\n message: typeof row.message === 'string' ? row.message : undefined,\n created_at: String(row.created_at),\n metadata: parseMetadata(row.metadata_json),\n };\n}\n\nfunction findTask(database: DatabaseSync, project: string, taskId: string): LineageTask | null {\n const row = database.prepare('select * from lineage_tasks where project_id = ? and id = ?').get(project, taskId) as Row | undefined;\n return row ? taskFromRow(row) : null;\n}\n\nfunction requireTask(database: DatabaseSync, project: string, taskId: string): LineageTask {\n const task = findTask(database, project, taskId);\n if (!task) throw new LineageTaskError(`Unknown lineage task: ${taskId}`, 404);\n return task;\n}\n\nfunction taskEvents(database: DatabaseSync, taskId: string): LineageTaskEvent[] {\n const rows = database.prepare('select * from lineage_task_events where task_id = ? order by created_at, rowid').all(taskId) as Row[];\n return rows.map(eventFromRow);\n}\n\nfunction recordEvent(database: DatabaseSync, taskId: string, eventType: string, actor?: string, message?: string, metadata?: Record<string, unknown>): void {\n database.prepare(`\n insert into lineage_task_events (id, task_id, event_type, actor, message, created_at, metadata_json)\n values (?, ?, ?, ?, ?, ?, ?)\n `).run(randomId('lineage_task_event'), taskId, eventType, actor || null, message || null, nowIso(), metadataJson(metadata));\n}\n\nfunction taskWithEvents(database: DatabaseSync, project: string, taskId: string): LineageTaskMutationResult {\n return { project, ok: true, task: requireTask(database, project, taskId), events: taskEvents(database, taskId) };\n}\n\nfunction assertChanged(result: { changes: number | bigint }, message: string): void {\n if (Number(result.changes) !== 1) throw new LineageTaskError(message, 409);\n}\n\nfunction transaction<T>(database: DatabaseSync, callback: () => T): T {\n database.exec('BEGIN IMMEDIATE');\n try {\n const value = callback();\n database.exec('COMMIT');\n return value;\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n}\n\nfunction taskReadWithEvents(database: DatabaseSync, project: string, taskId: string) {\n return { task: requireTask(database, project, taskId), events: taskEvents(database, taskId) };\n}\n\nexport function listLineageTasks(project: string, rootAssetId: string, statuses: LineageTaskStatus[] = activeStatuses): LineageTasksResponse {\n const normalizedProject = normalizeProject(project);\n const normalizedStatuses = statuses.map(normalizeStatus);\n const database = lineageDb();\n try {\n requireAsset(database, normalizedProject, rootAssetId);\n if (normalizedStatuses.length === 0) {\n return { project: normalizedProject, root_asset_id: rootAssetId, tasks: [], fetchedAt: nowIso() };\n }\n const placeholders = normalizedStatuses.map(() => '?').join(',');\n const rows = database.prepare(`\n select * from lineage_tasks\n where project_id = ? and root_asset_id = ? and status in (${placeholders})\n order by updated_at desc, created_at desc, id\n `).all(normalizedProject, rootAssetId, ...normalizedStatuses) as Row[];\n return { project: normalizedProject, root_asset_id: rootAssetId, tasks: rows.map(taskFromRow), fetchedAt: nowIso() };\n } finally {\n database.close();\n }\n}\n\nexport function getLineageTask(project: string, taskId: string) {\n const normalizedProject = normalizeProject(project);\n const database = lineageDb();\n try {\n return { project: normalizedProject, ...taskReadWithEvents(database, normalizedProject, taskId) };\n } finally {\n database.close();\n }\n}\n\nexport function upsertLineageTask(project: string, fields: {\n createdBy: LineageTaskActor;\n instructions?: string;\n rootAssetId: string;\n targetAssetId: string;\n taskType: LineageTaskType;\n}): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const taskType = normalizeTaskType(fields.taskType);\n const taskId = taskIdFor(normalizedProject, fields.rootAssetId, fields.targetAssetId, taskType);\n const database = lineageDb();\n try {\n requireAsset(database, normalizedProject, fields.rootAssetId);\n requireAsset(database, normalizedProject, fields.targetAssetId);\n const existing = database.prepare(`\n select * from lineage_tasks\n where project_id = ? and root_asset_id = ? and target_asset_id = ? and task_type = ?\n and status in ('pending', 'claimed', 'in_progress')\n order by created_at desc limit 1\n `).get(normalizedProject, fields.rootAssetId, fields.targetAssetId, taskType) as Row | undefined;\n const instructions = fields.instructions?.trim() || undefined;\n if (existing) {\n const task = taskFromRow(existing);\n if (task.status !== 'pending' && instructions !== undefined && instructions !== task.instructions) {\n throw new LineageTaskError('Only pending lineage tasks can update instructions.', 409);\n }\n if (task.status === 'pending' && instructions !== undefined && instructions !== task.instructions) {\n const timestamp = nowIso();\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set instructions = ?, updated_at = ?\n where id = ? and status = 'pending'\n `).run(instructions, timestamp, task.id);\n assertChanged(result, 'Only pending lineage tasks can update instructions.');\n recordEvent(database, task.id, 'instructions_updated', fields.createdBy, 'Instructions updated.');\n });\n }\n return taskWithEvents(database, normalizedProject, task.id);\n }\n const closedTask = findTask(database, normalizedProject, taskId);\n if (closedTask) {\n const timestamp = nowIso();\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'pending', instructions = ?, created_by = ?, updated_at = ?,\n claimed_at = null, started_at = null, resolved_at = null, cancelled_at = null,\n resolved_generation_job_id = null, resolved_asset_id = null, metadata_json = null\n where id = ? and status not in ('pending', 'claimed', 'in_progress')\n `).run(instructions || null, fields.createdBy, timestamp, taskId);\n assertChanged(result, 'Lineage task changed while reopening.');\n recordEvent(database, taskId, 'created', fields.createdBy, 'Lineage task created.');\n });\n return taskWithEvents(database, normalizedProject, taskId);\n }\n const timestamp = nowIso();\n transaction(database, () => {\n database.prepare(`\n insert into lineage_tasks (\n id, project_id, root_asset_id, target_asset_id, task_type, status, instructions,\n created_by, created_at, updated_at, metadata_json\n ) values (?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, null)\n `).run(taskId, normalizedProject, fields.rootAssetId, fields.targetAssetId, taskType, instructions || null, fields.createdBy, timestamp, timestamp);\n recordEvent(database, taskId, 'created', fields.createdBy, 'Lineage task created.');\n });\n return taskWithEvents(database, normalizedProject, taskId);\n } finally {\n database.close();\n }\n}\n\nexport function updateLineageTaskInstructions(project: string, fields: { taskId: string; instructions: string }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const instructions = fields.instructions.trim();\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status !== 'pending') throw new LineageTaskError('Only pending lineage tasks can update instructions.', 409);\n const timestamp = nowIso();\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set instructions = ?, updated_at = ?\n where id = ? and status = 'pending'\n `).run(instructions || null, timestamp, task.id);\n assertChanged(result, 'Only pending lineage tasks can update instructions.');\n recordEvent(database, task.id, 'instructions_updated', 'human', 'Instructions updated.');\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function addLineageTaskComment(project: string, fields: { taskId: string; actor: string; message: string }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Comment actor');\n const message = fields.message.trim();\n if (!message) throw new LineageTaskError('Comment message is required');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n transaction(database, () => {\n recordEvent(database, task.id, 'comment_added', actor, message);\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function claimLineageTask(project: string, fields: { taskId: string; agentName: string }): LineageTaskClaimResult {\n const normalizedProject = normalizeProject(project);\n const agentName = normalizeActor(fields.agentName, 'Agent name');\n const beforeClaimDb = lineageDb();\n try {\n const task = requireTask(beforeClaimDb, normalizedProject, fields.taskId);\n if (task.status !== 'pending') throw new LineageTaskError('Only pending lineage tasks can be claimed.', 409);\n } finally {\n beforeClaimDb.close();\n }\n\n const claimResult = createAgentClaim({\n agentName,\n project: normalizedProject,\n scopeType: 'lineage_task',\n targetId: fields.taskId,\n targetTitle: fields.taskId,\n });\n if (!claimResult.claim) throw new LineageTaskError('Unable to create lineage task claim.', 500);\n const claim = claimResult.claim;\n\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status !== 'pending') {\n releaseAgentClaim(claimResult.claim_token);\n throw new LineageTaskError('Only pending lineage tasks can be claimed.', 409);\n }\n const timestamp = nowIso();\n const metadata = { ...(task.metadata || {}), claim_id: claim.id };\n try {\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'claimed', claimed_at = ?, updated_at = ?, metadata_json = ?\n where id = ? and status = 'pending'\n `).run(timestamp, timestamp, metadataJson(metadata), task.id);\n assertChanged(result, 'Only pending lineage tasks can be claimed.');\n recordEvent(database, task.id, 'claimed', agentName, 'Lineage task claimed.', { claim_id: claim.id });\n });\n } catch (error) {\n releaseAgentClaim(claimResult.claim_token);\n throw error;\n }\n return {\n ...taskWithEvents(database, normalizedProject, task.id),\n claim,\n claim_token: claimResult.claim_token,\n };\n } finally {\n database.close();\n }\n}\n\nexport function startLineageTask(project: string, fields: { taskId: string; claimToken: string }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const precheckDatabase = lineageDb();\n try {\n const task = requireTask(precheckDatabase, normalizedProject, fields.taskId);\n if (task.status !== 'claimed') throw new LineageTaskError('Only claimed lineage tasks can be started.', 409);\n } finally {\n precheckDatabase.close();\n }\n const validation = validateAgentClaimForWrite({\n claimToken: fields.claimToken,\n dangerLevel: 'enforce',\n project: normalizedProject,\n recordEvent: false,\n scopeType: 'lineage_task',\n targetId: fields.taskId,\n writeKind: 'lineage_task_start',\n });\n if (!validation.ok) throw new LineageTaskError(validation.message, 409);\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status !== 'claimed') throw new LineageTaskError('Only claimed lineage tasks can be started.', 409);\n if (task.claimed_by_claim_id && task.claimed_by_claim_id !== validation.claim.id) {\n throw new LineageTaskError('Claim token does not match the task claim.', 409);\n }\n const timestamp = nowIso();\n const metadata = { ...(task.metadata || {}), claim_id: validation.claim.id };\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'in_progress', started_at = ?, updated_at = ?, metadata_json = ?\n where id = ? and status = 'claimed'\n `).run(timestamp, timestamp, metadataJson(metadata), task.id);\n assertChanged(result, 'Only claimed lineage tasks can be started.');\n recordEvent(database, task.id, 'started', validation.claim.agent_name, 'Lineage task started.', { claim_id: validation.claim.id });\n });\n recordAgentClaimWriteAllowed(validation.claim, {\n dangerLevel: 'enforce',\n targetId: fields.taskId,\n writeKind: 'lineage_task_start',\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function overrideLineageTask(project: string, fields: {\n actor: string;\n instructions?: string;\n reason: string;\n taskId: string;\n}): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Override actor');\n const reason = fields.reason.trim();\n if (!reason) throw new LineageTaskError('Override reason is required');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (!['claimed', 'in_progress'].includes(task.status)) {\n throw new LineageTaskError(`Only claimed or in-progress lineage tasks can be overridden; task is ${task.status}.`, 409);\n }\n const timestamp = nowIso();\n const instructions = fields.instructions === undefined ? task.instructions : (fields.instructions.trim() || undefined);\n const metadata = metadataWithoutClaim(task.metadata);\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'pending', instructions = ?, claimed_at = null, started_at = null,\n updated_at = ?, metadata_json = ?\n where project_id = ? and id = ? and status in ('claimed', 'in_progress')\n `).run(instructions || null, timestamp, metadataJson(metadata), normalizedProject, task.id);\n assertChanged(result, `Only active lineage task ${task.id} could be overridden.`);\n if (task.claimed_by_claim_id) {\n revokeAgentClaimInDatabase(database, normalizedProject, task.claimed_by_claim_id, {\n actor,\n reason,\n });\n }\n recordEvent(database, task.id, 'human_override', actor, reason, {\n previous_claim_id: task.claimed_by_claim_id,\n previous_status: task.status,\n });\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function cancelLineageTask(project: string, fields: { taskId: string; actor: string; confirmWrite: boolean; override?: boolean }): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Cancel actor');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (task.status === 'cancelled') return { project: normalizedProject, ok: true, task, events: taskEvents(database, task.id) };\n if (!['pending', 'claimed', 'in_progress'].includes(task.status)) {\n throw new LineageTaskError(`Only open lineage tasks can be cancelled; task is ${task.status}.`, 409);\n }\n if (task.status !== 'pending' && !fields.override) {\n throw new LineageTaskError('Cancelling an active lineage task requires override=true.', 409);\n }\n const overridingActiveTask = fields.override === true && task.status !== 'pending';\n const metadata = overridingActiveTask ? metadataWithoutClaim(task.metadata) : task.metadata;\n const timestamp = nowIso();\n const cancelledTask = {\n ...task,\n cancelled_at: timestamp,\n claimed_at: overridingActiveTask ? undefined : task.claimed_at,\n claimed_by_claim_id: overridingActiveTask ? undefined : task.claimed_by_claim_id,\n started_at: overridingActiveTask ? undefined : task.started_at,\n status: 'cancelled' as const,\n updated_at: timestamp,\n metadata,\n };\n if (!fields.confirmWrite) return { project: normalizedProject, ok: true, dryRun: true as const, task: cancelledTask, events: taskEvents(database, task.id) };\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'cancelled', cancelled_at = ?, claimed_at = ?, started_at = ?,\n updated_at = ?, metadata_json = ?\n where id = ? and status = ?\n `).run(\n timestamp,\n overridingActiveTask ? null : task.claimed_at || null,\n overridingActiveTask ? null : task.started_at || null,\n timestamp,\n metadataJson(metadata),\n task.id,\n task.status\n );\n assertChanged(result, `Only ${task.status} lineage task ${task.id} could be cancelled.`);\n if (overridingActiveTask) {\n if (task.claimed_by_claim_id) {\n revokeAgentClaimInDatabase(database, normalizedProject, task.claimed_by_claim_id, {\n actor,\n reason: 'Lineage task cancelled by human override.',\n });\n }\n recordEvent(database, task.id, 'human_override', actor, 'Lineage task cancelled by human override.', {\n previous_claim_id: task.claimed_by_claim_id,\n previous_status: task.status,\n });\n }\n recordEvent(database, task.id, 'cancelled', actor, 'Lineage task cancelled.');\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n\nexport function cancelLineageIterateTasksForAssets(project: string, fields: {\n actor: string;\n assetIds?: string[];\n confirmWrite: boolean;\n rootAssetId: string;\n}): LineageTaskMutationResult[] {\n const targetIds = fields.assetIds ? new Set(fields.assetIds) : undefined;\n return listLineageTasks(project, fields.rootAssetId, ['pending']).tasks\n .filter(task => task.task_type === 'iterate')\n .filter(task => !targetIds || targetIds.has(task.target_asset_id))\n .map(task => cancelLineageTask(project, {\n actor: fields.actor,\n confirmWrite: fields.confirmWrite,\n taskId: task.id,\n }));\n}\n\nexport function resolveLineageTask(project: string, fields: {\n actor: string;\n confirmWrite: boolean;\n resolvedAssetId?: string;\n resolvedGenerationJobId?: string;\n taskId: string;\n}): LineageTaskMutationResult {\n const normalizedProject = normalizeProject(project);\n const actor = normalizeActor(fields.actor, 'Resolve actor');\n const database = lineageDb();\n try {\n const task = requireTask(database, normalizedProject, fields.taskId);\n if (fields.resolvedAssetId) requireAsset(database, normalizedProject, fields.resolvedAssetId);\n if (task.status === 'resolved') return { project: normalizedProject, ok: true, task, events: taskEvents(database, task.id) };\n if (!['pending', 'claimed', 'in_progress'].includes(task.status)) {\n throw new LineageTaskError(`Only open lineage tasks can be resolved; task is ${task.status}.`, 409);\n }\n const timestamp = nowIso();\n const resolvedTask = {\n ...task,\n status: 'resolved' as const,\n resolved_asset_id: fields.resolvedAssetId,\n resolved_at: timestamp,\n resolved_generation_job_id: fields.resolvedGenerationJobId,\n updated_at: timestamp,\n };\n if (!fields.confirmWrite) return { project: normalizedProject, ok: true, dryRun: true as const, task: resolvedTask, events: taskEvents(database, task.id) };\n transaction(database, () => {\n const result = database.prepare(`\n update lineage_tasks\n set status = 'resolved', resolved_at = ?, resolved_generation_job_id = ?, resolved_asset_id = ?, updated_at = ?\n where id = ? and status = ?\n `).run(timestamp, fields.resolvedGenerationJobId || null, fields.resolvedAssetId || null, timestamp, task.id, task.status);\n assertChanged(result, `Only ${task.status} lineage task ${task.id} could be resolved.`);\n recordEvent(database, task.id, 'resolved', actor, 'Lineage task resolved.', {\n resolved_asset_id: fields.resolvedAssetId,\n resolved_generation_job_id: fields.resolvedGenerationJobId,\n });\n });\n return taskWithEvents(database, normalizedProject, task.id);\n } finally {\n database.close();\n }\n}\n", "import { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { cancelLineageIterateTasksForAssets } from './assetLineageTasks';\nimport type {\n LineageWorkspace,\n LineageWorkspaceActor,\n LineageWorkspaceFields,\n LineageWorkspaceSnapshot,\n LineageWorkspaceStatus,\n LineageWorkspaceUpdateFields,\n} from '../shared/types';\n\ntype Row = Record<string, unknown>;\n\nconst actors = new Set<LineageWorkspaceActor>(['human', 'agent', 'system']);\nconst statuses = new Set<LineageWorkspaceStatus>(['active', 'paused', 'archived']);\n\nexport class LineageWorkspaceError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isLineageWorkspaceError(error: unknown): error is LineageWorkspaceError {\n return error instanceof LineageWorkspaceError;\n}\n\nexport function lineageWorkspaceId(project: string, rootAssetId: string): string {\n return `${project}:lineage-workspace:${rootAssetId}`;\n}\n\nfunction ensureProject(database: DatabaseSync, project: string): void {\n const timestamp = nowIso();\n database.prepare(`\n insert into projects (id, product, created_at, updated_at)\n values (?, ?, ?, ?)\n on conflict(id) do update set product = excluded.product, updated_at = excluded.updated_at\n `).run(project, project, timestamp, timestamp);\n}\n\nfunction normalizeStatus(value: LineageWorkspaceStatus | undefined, fallback: LineageWorkspaceStatus): LineageWorkspaceStatus {\n const status = value || fallback;\n if (!statuses.has(status)) throw new LineageWorkspaceError(`Unsupported lineage workspace status: ${status}`);\n return status;\n}\n\nfunction normalizeActor(value: LineageWorkspaceActor | undefined): LineageWorkspaceActor {\n const actor = value || 'human';\n if (!actors.has(actor)) throw new LineageWorkspaceError(`Unsupported lineage workspace actor: ${actor}`);\n return actor;\n}\n\nfunction requireAsset(database: DatabaseSync, project: string, assetId: string): { id: string; title: string } {\n const row = database.prepare('select id, title from assets where project_id = ? and id = ?').get(project, assetId) as { id: string; title: string } | undefined;\n if (!row) throw new LineageWorkspaceError(`Unknown indexed asset: ${assetId}`, 404);\n return row;\n}\n\nfunction rowToWorkspace(row: Row): LineageWorkspace {\n return {\n id: String(row.id),\n project: String(row.project_id),\n root_asset_id: String(row.root_asset_id),\n title: String(row.title),\n status: String(row.status) as LineageWorkspaceStatus,\n notes: typeof row.notes === 'string' ? row.notes : undefined,\n created_by: String(row.created_by) as LineageWorkspaceActor,\n active_at: typeof row.active_at === 'string' ? row.active_at : undefined,\n created_at: String(row.created_at),\n updated_at: String(row.updated_at),\n };\n}\n\nfunction workspaceById(database: DatabaseSync, project: string, id: string): LineageWorkspace | null {\n const row = database.prepare('select * from lineage_workspaces where project_id = ? and id = ?').get(project, id) as Row | undefined;\n return row ? rowToWorkspace(row) : null;\n}\n\nfunction workspaceByRoot(database: DatabaseSync, project: string, rootAssetId: string): LineageWorkspace | null {\n const row = database.prepare('select * from lineage_workspaces where project_id = ? and root_asset_id = ?').get(project, rootAssetId) as Row | undefined;\n return row ? rowToWorkspace(row) : null;\n}\n\nfunction knownRoots(database: DatabaseSync, project: string): Array<{ root_asset_id: string; selected_at?: string }> {\n const rows = database.prepare(`\n select root_asset_id, max(selected_at) selected_at from asset_selections where project_id = ? group by root_asset_id\n union\n select root_asset_id, null selected_at from asset_layouts where project_id = ? group by root_asset_id\n union\n select parent_asset_id root_asset_id, null selected_at\n from asset_edges\n where project_id = ?\n and parent_asset_id not in (select child_asset_id from asset_edges where project_id = ?)\n group by parent_asset_id\n `).all(project, project, project, project) as Array<{ root_asset_id: string; selected_at?: string | null }>;\n const roots = new Map<string, { root_asset_id: string; selected_at?: string }>();\n for (const row of rows) {\n const existing = roots.get(row.root_asset_id);\n roots.set(row.root_asset_id, {\n root_asset_id: row.root_asset_id,\n selected_at: row.selected_at || existing?.selected_at,\n });\n }\n return [...roots.values()];\n}\n\nfunction seedLegacyWorkspaces(database: DatabaseSync, project: string): void {\n if (process.env.LINEAGE_DB_ACCESS === 'read-only') return;\n ensureProject(database, project);\n const timestamp = nowIso();\n const statement = database.prepare(`\n insert into lineage_workspaces (\n id, project_id, root_asset_id, title, status, notes, created_by, active_at, created_at, updated_at\n )\n select ?, ?, a.id, a.title || ' lineage', 'active', null, 'system', ?, ?, ?\n from assets a\n where a.project_id = ? and a.id = ?\n on conflict(project_id, root_asset_id) do nothing\n `);\n for (const root of knownRoots(database, project)) {\n statement.run(\n lineageWorkspaceId(project, root.root_asset_id),\n project,\n root.selected_at || null,\n timestamp,\n timestamp,\n project,\n root.root_asset_id\n );\n }\n}\n\nfunction inferredLegacyWorkspaces(database: DatabaseSync, project: string): LineageWorkspace[] {\n if (process.env.LINEAGE_DB_ACCESS !== 'read-only') return [];\n const persistedRoots = new Set(\n (database.prepare('select root_asset_id from lineage_workspaces where project_id = ?').all(project) as Array<{ root_asset_id: string }>)\n .map(row => row.root_asset_id),\n );\n const asset = database.prepare('select id, title from assets where project_id = ? and id = ?');\n return knownRoots(database, project).flatMap(root => {\n if (persistedRoots.has(root.root_asset_id)) return [];\n const row = asset.get(project, root.root_asset_id) as { id: string; title: string } | undefined;\n if (!row) return [];\n const timestamp = root.selected_at || nowIso();\n return [{\n active_at: root.selected_at,\n created_at: timestamp,\n created_by: 'system' as const,\n id: lineageWorkspaceId(project, root.root_asset_id),\n project,\n root_asset_id: root.root_asset_id,\n status: 'active' as const,\n title: `${row.title} lineage`,\n updated_at: timestamp,\n }];\n });\n}\n\nfunction sortWorkspaces(workspaces: LineageWorkspace[]): LineageWorkspace[] {\n const statusRank: Record<LineageWorkspaceStatus, number> = { active: 0, paused: 1, archived: 2 };\n return workspaces.sort((left, right) => statusRank[left.status] - statusRank[right.status]\n || (right.active_at || '').localeCompare(left.active_at || '')\n || right.updated_at.localeCompare(left.updated_at)\n || left.title.localeCompare(right.title));\n}\n\nfunction listRows(database: DatabaseSync, project: string): LineageWorkspace[] {\n return (database.prepare(`\n select * from lineage_workspaces\n where project_id = ?\n order by\n case status when 'active' then 0 when 'paused' then 1 else 2 end,\n active_at desc nulls last,\n updated_at desc,\n title\n `).all(project) as Row[]).map(rowToWorkspace);\n}\n\nexport function listLineageWorkspaces(project: string): LineageWorkspaceSnapshot {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const workspaces = sortWorkspaces([...listRows(database, project), ...inferredLegacyWorkspaces(database, project)]);\n return {\n project,\n active_workspace: workspaces.find(workspace => workspace.status !== 'archived') || null,\n workspaces,\n fetchedAt: nowIso(),\n };\n } finally {\n database.close();\n }\n}\n\nexport function inspectLineageWorkspace(project: string, workspaceId: string): LineageWorkspace {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const workspace = workspaceById(database, project, workspaceId)\n || workspaceByRoot(database, project, workspaceId)\n || inferredLegacyWorkspaces(database, project).find(item => item.id === workspaceId || item.root_asset_id === workspaceId);\n if (!workspace) throw new LineageWorkspaceError(`Unknown lineage workspace: ${workspaceId}`, 404);\n return workspace;\n } finally {\n database.close();\n }\n}\n\nexport function createLineageWorkspace(project: string, fields: LineageWorkspaceFields) {\n const rootAssetId = fields.rootAssetId.trim();\n if (!rootAssetId) throw new LineageWorkspaceError('Lineage workspace requires rootAssetId');\n const status = normalizeStatus(fields.status, 'active');\n const actor = normalizeActor(fields.createdBy);\n const database = lineageDb();\n try {\n const root = requireAsset(database, project, rootAssetId);\n const timestamp = nowIso();\n const workspace: LineageWorkspace = {\n id: lineageWorkspaceId(project, rootAssetId),\n project,\n root_asset_id: rootAssetId,\n title: fields.title?.trim() || `${root.title} lineage`,\n status,\n notes: fields.notes?.trim() || undefined,\n created_by: actor,\n active_at: fields.activate !== false && status !== 'archived' ? timestamp : undefined,\n created_at: timestamp,\n updated_at: timestamp,\n };\n if (!fields.confirmWrite) return { ok: true as const, dryRun: true as const, workspace };\n ensureProject(database, project);\n database.prepare(`\n insert into lineage_workspaces (\n id, project_id, root_asset_id, title, status, notes, created_by, active_at, created_at, updated_at\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n on conflict(project_id, root_asset_id) do update set\n title = excluded.title,\n status = excluded.status,\n notes = excluded.notes,\n active_at = coalesce(excluded.active_at, lineage_workspaces.active_at),\n updated_at = excluded.updated_at\n `).run(\n workspace.id,\n project,\n workspace.root_asset_id,\n workspace.title,\n workspace.status,\n workspace.notes || null,\n workspace.created_by,\n workspace.active_at || null,\n workspace.created_at,\n workspace.updated_at\n );\n return {\n ok: true as const,\n message: `Saved lineage workspace ${workspace.title}`,\n workspace: workspaceById(database, project, workspace.id),\n };\n } finally {\n database.close();\n }\n}\n\nexport function updateLineageWorkspace(project: string, workspaceId: string, fields: LineageWorkspaceUpdateFields) {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const current = workspaceById(database, project, workspaceId) || workspaceByRoot(database, project, workspaceId);\n if (!current) throw new LineageWorkspaceError(`Unknown lineage workspace: ${workspaceId}`, 404);\n const timestamp = nowIso();\n const next: LineageWorkspace = {\n ...current,\n title: fields.title?.trim() || current.title,\n status: normalizeStatus(fields.status, current.status),\n notes: fields.notes === undefined ? current.notes : fields.notes.trim() || undefined,\n active_at: fields.activate ? timestamp : current.active_at,\n updated_at: timestamp,\n };\n if (!fields.confirmWrite) return { ok: true as const, dryRun: true as const, workspace: next };\n database.prepare(`\n update lineage_workspaces\n set title = ?, status = ?, notes = ?, active_at = ?, updated_at = ?\n where project_id = ? and id = ?\n `).run(next.title, next.status, next.notes || null, next.active_at || null, timestamp, project, current.id);\n return {\n ok: true as const,\n message: `Updated lineage workspace ${next.title}`,\n workspace: workspaceById(database, project, current.id),\n };\n } finally {\n database.close();\n }\n}\n\nexport function activateLineageWorkspace(project: string, workspaceId: string, confirmWrite: boolean) {\n return updateLineageWorkspace(project, workspaceId, { activate: true, status: 'active', confirmWrite });\n}\n\nexport function archiveLineageWorkspace(project: string, workspaceId: string, confirmWrite: boolean) {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n const current = workspaceById(database, project, workspaceId) || workspaceByRoot(database, project, workspaceId);\n if (!current) throw new LineageWorkspaceError(`Unknown lineage workspace: ${workspaceId}`, 404);\n const timestamp = nowIso();\n const next: LineageWorkspace = {\n ...current,\n status: 'archived',\n active_at: undefined,\n updated_at: timestamp,\n };\n if (!confirmWrite) return { ok: true as const, dryRun: true as const, workspace: next };\n cancelLineageIterateTasksForAssets(project, {\n actor: 'human',\n confirmWrite: true,\n rootAssetId: current.root_asset_id,\n });\n database.prepare(`\n update lineage_workspaces\n set status = 'archived', active_at = null, updated_at = ?\n where project_id = ? and id = ?\n `).run(timestamp, project, current.id);\n database.prepare('delete from asset_selections where project_id = ? and root_asset_id = ?').run(project, current.root_asset_id);\n return {\n ok: true as const,\n message: `Archived lineage workspace ${current.title}`,\n workspace: workspaceById(database, project, current.id),\n };\n } finally {\n database.close();\n }\n}\n\nexport function activeLineageWorkspaceRoot(project: string): string | undefined {\n const database = lineageDb();\n try {\n seedLegacyWorkspaces(database, project);\n return sortWorkspaces([...listRows(database, project), ...inferredLegacyWorkspaces(database, project)])\n .find(workspace => workspace.status !== 'archived')?.root_asset_id;\n } finally {\n database.close();\n }\n}\n", "import { AgentClaimError, listAgentClaims, validateAgentClaimForWrite } from './agentClaims';\nimport { lineageWorkspaceId } from './assetLineageWorkspaces';\n\nfunction channelOverlaps(left?: string, right?: string): boolean {\n return !left || !right || left === right;\n}\n\nfunction hasActiveLineageWorkspaceClaim(project: string, targetId: string, channel?: string): boolean {\n return listAgentClaims(project).claims.some(claim => {\n if (claim.project !== project || claim.status !== 'active' || claim.derived_state === 'expired') return false;\n if (claim.scope_type === 'lineage_workspace') return claim.target_id === targetId;\n return claim.scope_type === 'project_channel' && channelOverlaps(channel, claim.channel);\n });\n}\n\nexport function requireLineageWorkspaceClaimForWrite(fields: {\n channel?: string;\n claimToken?: string;\n confirmWrite: boolean;\n project: string;\n rootAssetId: string;\n writeKind: string;\n}): void {\n if (!fields.confirmWrite) return;\n const targetId = lineageWorkspaceId(fields.project, fields.rootAssetId);\n if (!fields.claimToken && !hasActiveLineageWorkspaceClaim(fields.project, targetId, fields.channel)) return;\n const validation = validateAgentClaimForWrite({\n channel: fields.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n dangerLevel: 'enforce',\n project: fields.project,\n scopeType: 'lineage_workspace',\n targetId,\n writeKind: fields.writeKind,\n });\n if (!validation.ok) {\n const status = validation.code === 'claim_required' || validation.code === 'claim_token_invalid' ? 401 : 409;\n throw new AgentClaimError(validation.message, status, validation.code, validation.conflicts);\n }\n}\n", "import { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { packageRoot } from './assetCore';\n\nconst require = createRequire(import.meta.url);\n\nexport function lineageCliLauncher(channel = process.env.LINEAGE_CHANNEL): string {\n if (channel === 'dev') {\n const sourceCli = join(packageRoot, 'src', 'cli', 'lineage-dev.ts');\n const builtCli = join(packageRoot, 'dist', 'cli', 'lineage-dev.js');\n return existsSync(sourceCli)\n ? `${shellQuote(process.execPath)} --import ${shellQuote(require.resolve('tsx'))} ${shellQuote(sourceCli)}`\n : `${shellQuote(process.execPath)} ${shellQuote(builtCli)}`;\n }\n if (channel === 'preview') return 'lineage-preview';\n if (channel === 'stable') return 'lineage-stable';\n throw new Error('LINEAGE_CHANNEL must be stable, preview, or dev before generating a Lineage command');\n}\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nexport function lineageRuntimeSelector(databasePath?: string): string {\n const manifest = process.env.LINEAGE_PROFILE_MANIFEST?.trim();\n const database = databasePath || process.env.LINEAGE_DB || join(packageRoot, '.lineage', 'asset-lineage.sqlite');\n return manifest ? `--profile ${shellQuote(manifest)}` : `--db ${shellQuote(database)}`;\n}\n\nexport function lineageCliCommand(command: string): string {\n const normalized = command.trim().replace(/\\s+--json$/, '');\n return `${lineageCliLauncher()} ${normalized} ${lineageRuntimeSelector()} --json`;\n}\n", "import type { LineageBriefResponse, LineageSelectedChildFields } from '../shared/types';\nimport { requireEdgeSummary } from '../shared/edgeSummary';\nimport { AgentClaimError, validateAgentClaimForWrite } from './agentClaims';\nimport { getLineageNextAsset, getLineageWriteClaimContext, LineageError, linkLineageAssets, listLineageRerollRequests } from './assetLineage';\nimport { nowIso } from './assetLineageDb';\nimport { lineageWorkspaceId } from './assetLineageWorkspaces';\nimport { lineageCliCommand, shellQuote } from './lineageRuntimeCommand';\n\nfunction lineageCommand(command: string, project: string, rootAssetId: string): string {\n return lineageCliCommand(`${command} --project ${shellQuote(project)} --root ${shellQuote(rootAssetId)}`);\n}\n\nfunction linkChildCommand(project: string, rootAssetId: string): string {\n return lineageCliCommand(`link-child --project ${shellQuote(project)} --root ${shellQuote(rootAssetId)} --child <asset-id> --summary \"<one-or-two-words>\" --confirm-write`);\n}\n\nfunction rerollImportGuidance(rootAssetId: string, targetAssetId: string): string {\n return `Use lineage reroll plan --root ${rootAssetId} --target ${targetAssetId} and lineage reroll import instead.`;\n}\n\nexport function getLineageBrief(project: string, rootAssetId?: string): LineageBriefResponse {\n const next = getLineageNextAsset(project, rootAssetId);\n const assets = next.next_assets;\n const asset = next.next_asset;\n const referenceAssetIds = assets.map(item => item.asset_id);\n const rationale = next.selections.map(selection => selection.notes).find(Boolean) || asset?.selection_note || next.selection?.notes;\n const channels = [...new Set(assets.map(item => item.channel || 'unknown'))];\n const campaigns = [...new Set(assets.map(item => item.campaign || 'unknown'))];\n const prompt = assets.length > 0\n ? [\n assets.length === 1\n ? `Create 3-4 variations from asset ${assets[0].asset_id} (${assets[0].title}).`\n : `Create 3-4 variations using these ${assets.length} selected references: ${referenceAssetIds.join(', ')}.`,\n rationale ? `Preserve this selection rationale: ${rationale}` : 'Preserve the strongest visible ideas while exploring distinct alternatives.',\n `Keep project=${project}, root=${next.root_asset_id}, channels=${channels.join(',')}, campaigns=${campaigns.join(',')}.`,\n 'After generation, index outputs and link chosen children with lineage link-child.',\n ].join(' ')\n : 'Select one to three latest lineage candidates before generating variations.';\n return {\n project,\n root_asset_id: next.root_asset_id,\n strategy: next.strategy,\n selection_mode: next.selection_mode,\n recommended_action: next.recommended_action,\n reason: next.reason,\n next_asset: asset,\n next_assets: assets,\n selection: next.selection,\n selections: next.selections,\n latest: next.latest,\n warnings: next.warnings,\n brief: {\n title: asset ? `Evolve ${assets.length > 1 ? `${assets.length} selected bases` : asset.title}` : 'Choose next lineage base',\n objective: asset ? 'Generate the next branch of visual variations from the selected lineage base or bases.' : 'Resolve the next base before generation.',\n prompt,\n reference_asset_id: asset?.asset_id,\n reference_asset_ids: referenceAssetIds,\n rationale,\n },\n handoff: {\n next_command: lineageCommand('next', project, next.root_asset_id),\n inspect_command: asset ? lineageCliCommand(`inspect --project ${shellQuote(project)} --asset-id ${shellQuote(asset.asset_id)}`) : undefined,\n link_child_command: asset ? linkChildCommand(project, next.root_asset_id) : undefined,\n },\n fetchedAt: nowIso(),\n };\n}\n\nexport function linkSelectedLineageChild(project: string, fields: LineageSelectedChildFields) {\n const summary = fields.summaryActor ? requireEdgeSummary(fields.summary) : fields.summary;\n const next = getLineageNextAsset(project, fields.rootAssetId);\n if (!next.next_asset) throw new LineageError('Cannot link child until a next base is selected or unambiguous');\n const rerollRequests = listLineageRerollRequests(project, next.root_asset_id).requests;\n const pendingRerollForParent = rerollRequests.find(request => request.node_asset_id === next.next_asset?.asset_id);\n if (pendingRerollForParent && fields.confirmWrite) {\n throw new LineageError(\n `Pending re-roll exists for ${pendingRerollForParent.node_asset_id}. lineage link-child creates a visible child variation edge; it does not re-roll the same node. ${rerollImportGuidance(next.root_asset_id, pendingRerollForParent.node_asset_id)} Cancel the re-roll first if you intentionally want a new child variation.`,\n 409\n );\n }\n if (fields.confirmWrite) {\n const claimContext = getLineageWriteClaimContext(project, next.next_asset.asset_id);\n const validation = validateAgentClaimForWrite({\n channel: claimContext.channel,\n claimToken: fields.claimToken,\n confirmWrite: fields.confirmWrite,\n dangerLevel: 'enforce',\n project,\n scopeType: 'lineage_workspace',\n targetId: lineageWorkspaceId(project, claimContext.rootAssetId),\n writeKind: 'link_child',\n });\n if (!validation.ok) throw new AgentClaimError(validation.message, validation.code === 'claim_required' ? 401 : 403, validation.code, validation.conflicts);\n }\n const result = linkLineageAssets(project, {\n childAssetId: fields.childAssetId,\n confirmWrite: fields.confirmWrite,\n claimToken: fields.claimToken,\n parentAssetId: next.next_asset.asset_id,\n summary,\n summaryActor: fields.summaryActor,\n });\n return {\n ...result,\n root_asset_id: next.root_asset_id,\n parent_asset_id: next.next_asset.asset_id,\n child_asset_id: fields.childAssetId,\n reference_asset_ids: next.next_assets.map(asset => asset.asset_id),\n warning: [\n pendingRerollForParent\n ? `Pending re-roll exists for ${pendingRerollForParent.node_asset_id}. link-child would create a visible child variation; use reroll plan/import to update the same node attempt.`\n : undefined,\n rerollRequests.length > 0 && !pendingRerollForParent\n ? `This lineage has ${rerollRequests.length} pending re-roll target(s). link-child is only for new visible child variations, not re-roll attempts.`\n : undefined,\n next.next_assets.length > 1\n ? 'Linked child to the primary selected base; add explicit edges to other selected references if the child derives from them too.'\n : undefined,\n ].filter(Boolean).join(' ') || undefined,\n };\n}\n", "import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { defaultProject, repoRoot } from './assetCore';\nimport { getLineageNextAsset, getLineageSnapshot, indexLineageAssets, listLineageRerollRequests, recordLineageRerollAttempt } from './assetLineage';\nimport { lineageDb, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { cancelLineageIterateTasksForAssets, listLineageTasks, resolveLineageTask } from './assetLineageTasks';\nimport { activeLineageWorkspaceRoot } from './assetLineageWorkspaces';\nimport { contentTypeFor, fileSha256 } from './localReview';\nimport { lineageCliCommand } from './lineageRuntimeCommand';\nimport { createGenerationOutputManifestDraft, parseGenerationOutputManifest, type GenerationOutputManifest } from '../shared/generationOutputManifest';\nimport type {\n GenerationHandoffPacket,\n GenerationImportResponse,\n GenerationInspectResponse,\n GenerationJob,\n GenerationJobInput,\n GenerationJobOutput,\n GenerationJobReceipt,\n GenerationPlanResponse,\n GenerationProvider,\n GenerationSourceMode,\n LineageNextResponse,\n LineageRerollRequest,\n} from '../shared/types';\n\nconst legacyAdapterVersion = 'generation-receipts-v1';\nconst manifestAdapterVersion = 'generation-receipts-v2';\nconst provider: GenerationProvider = 'codex-handoff';\n\nclass GenerationReceiptError extends Error {\n constructor(message: string, public status = 400) {\n super(message);\n }\n}\n\nexport function isGenerationReceiptError(error: unknown): error is GenerationReceiptError {\n return error instanceof GenerationReceiptError;\n}\n\nfunction jobId(): string {\n return `gen-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;\n}\n\nfunction quote(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction parseJson<T>(value: string | null | undefined, fallback: T): T {\n if (!value) return fallback;\n return JSON.parse(value) as T;\n}\n\nfunction positiveInteger(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) > 0;\n}\n\nfunction resolveLineageSelection(project: string): LineageNextResponse {\n const rootAssetId = activeLineageWorkspaceRoot(project);\n if (!rootAssetId) throw new GenerationReceiptError('No active lineage workspace for generation planning');\n const next = getLineageNextAsset(project, rootAssetId);\n if (!next.next_asset) throw new GenerationReceiptError(`No clear lineage next asset: ${next.reason}`);\n if (next.strategy !== 'selected') throw new GenerationReceiptError('Generation v1 requires an explicit selected lineage next base');\n if (next.selection_mode !== 'multiple' && next.selection?.asset_id !== next.next_asset.asset_id) throw new GenerationReceiptError('Generation v1 requires one explicit selected lineage next base');\n return next;\n}\n\nfunction selectedParents(next: LineageNextResponse) {\n const parents = next.next_assets.length > 0 ? next.next_assets : next.next_asset ? [next.next_asset] : [];\n if (parents.length === 0) throw new GenerationReceiptError('Missing lineage next base');\n return parents;\n}\n\nfunction parentMappings(next: LineageNextResponse, perBaseCount: number) {\n return selectedParents(next).map((parent, parentIndex) => ({\n parent,\n output_indexes: Array.from({ length: perBaseCount }, (_value, index) => parentIndex * perBaseCount + index),\n }));\n}\n\nfunction buildHandoff(\n project: string,\n id: string,\n prompt: string,\n count: number,\n perBaseCount: number,\n next: LineageNextResponse,\n inputs: GenerationJobInput[],\n): GenerationHandoffPacket {\n const parent = next.next_asset;\n if (!parent) throw new GenerationReceiptError('Missing lineage next base');\n const parents = parentMappings(next, perBaseCount);\n const outputManifest = createGenerationOutputManifestDraft({ id, expected_output_count: count, inputs });\n const importCommand = lineageCliCommand(`generate image import --project ${quote(project)} --job-id ${quote(id)} --manifest ${quote('.asset-scratch/generation-output-manifest.json')} --confirm-write`);\n return {\n schema_version: 'lineage.generation_handoff.v2', provider, project, job_id: id, prompt, expected_output_count: count,\n per_base_count: next.selection_mode === 'multiple' ? perBaseCount : undefined,\n lineage: {\n root_asset_id: next.root_asset_id, parent_asset_id: parent.asset_id, selection_strategy: next.strategy,\n parent_title: parent.title, parent_local_path: parent.local_path, parent_s3_key: parent.s3_key,\n parents: parents.length > 1 ? parents.map(mapping => ({\n parent_asset_id: mapping.parent.asset_id, parent_title: mapping.parent.title,\n parent_local_path: mapping.parent.local_path, parent_s3_key: mapping.parent.s3_key, output_indexes: mapping.output_indexes,\n })) : undefined,\n },\n instructions: [\n 'Use Codex image generation outside Lineage server code.',\n 'Write generated output files under .asset-scratch before import.',\n 'Do not call live provider APIs from the CLI or server.',\n 'Fill every output_manifest entry with its generated file path and a one- or two-word edge summary.',\n 'Import the completed manifest with --confirm-write to persist every lineage child.',\n ],\n import_command: importCommand,\n output_manifest: outputManifest,\n guardrails: { live_generation: false, external_services: false, output_root: '.asset-scratch', confirm_write_required: true },\n };\n}\n\nfunction buildRerollHandoff(project: string, id: string, prompt: string, rootAssetId: string, target: { asset_id: string; title: string; local_path?: string; s3_key?: string }, request: LineageRerollRequest): GenerationHandoffPacket {\n const importCommand = lineageCliCommand(`reroll import --project ${quote(project)} --job-id ${quote(id)} --file <.asset-scratch-file> --confirm-write`);\n return {\n schema_version: 'lineage.generation_handoff.v1',\n provider,\n project,\n job_id: id,\n prompt,\n expected_output_count: 1,\n lineage: {\n root_asset_id: rootAssetId,\n parent_asset_id: target.asset_id,\n selection_strategy: 'reroll_request',\n parent_title: target.title,\n parent_local_path: target.local_path,\n parent_s3_key: target.s3_key,\n },\n instructions: [\n 'Use Codex image generation outside Lineage server code.',\n 'Write the regenerated output file under .asset-scratch before import.',\n 'Do not call live provider APIs from the CLI or server.',\n 'Import exactly one output with reroll import, not link-child or generate image import.',\n `Resolve re-roll request ${request.id}; do not create a visible lineage child edge.`,\n ],\n import_command: importCommand,\n guardrails: { live_generation: false, external_services: false, output_root: '.asset-scratch', confirm_write_required: true },\n };\n}\n\nfunction inputsFrom(jobIdValue: string, project: string, next: LineageNextResponse): GenerationJobInput[] {\n return selectedParents(next).map((parent, position) => ({\n id: `${jobIdValue}:input:${position}`,\n job_id: jobIdValue,\n project_id: project,\n asset_id: parent.asset_id,\n root_asset_id: next.root_asset_id,\n role: 'lineage_next_base',\n position,\n selection_strategy: next.strategy,\n selection_snapshot: next,\n }));\n}\n\nfunction receiptFrom(row: Record<string, unknown>): GenerationJobReceipt {\n return {\n id: String(row.id),\n job_id: String(row.job_id),\n receipt_type: row.receipt_type as GenerationJobReceipt['receipt_type'],\n status: row.status as GenerationJobReceipt['status'],\n command: String(row.command),\n payload: parseJson(String(row.payload_json), null),\n created_at: String(row.created_at),\n };\n}\n\nfunction outputFrom(row: Record<string, unknown>): GenerationJobOutput {\n const edgeSummary = typeof row.edge_summary === 'string' && row.edge_summary.length > 0 ? row.edge_summary : undefined;\n return {\n id: String(row.id),\n job_id: String(row.job_id),\n project_id: String(row.project_id),\n output_index: Number(row.output_index),\n file_path: String(row.file_path),\n checksum_sha256: String(row.checksum_sha256),\n size_bytes: Number(row.size_bytes),\n content_type: String(row.content_type),\n imported_asset_id: String(row.imported_asset_id),\n parent_asset_id: String(row.parent_asset_id),\n imported_at: String(row.imported_at),\n ...(edgeSummary ? { edge_summary: edgeSummary } : {}),\n };\n}\n\nexport function loadGenerationJob(database: DatabaseSync, project: string, id: string): GenerationJob {\n const row = database.prepare('select * from generation_jobs where project_id = ? and id = ?').get(project, id) as Record<string, unknown> | undefined;\n if (!row) throw new GenerationReceiptError(`Unknown generation job: ${id}`, 404);\n const inputRows = database.prepare('select * from generation_job_inputs where job_id = ? order by position').all(id) as Array<Record<string, unknown>>;\n const inputs = inputRows.map(input => ({\n id: String(input.id),\n job_id: String(input.job_id),\n project_id: String(input.project_id),\n asset_id: String(input.asset_id),\n root_asset_id: String(input.root_asset_id),\n role: input.role as GenerationJobInput['role'],\n position: Number(input.position),\n selection_strategy: String(input.selection_strategy),\n selection_snapshot: parseJson<LineageNextResponse>(String(input.selection_snapshot_json), {} as LineageNextResponse),\n }));\n const outputs = (database.prepare('select * from generation_job_outputs where job_id = ? order by output_index').all(id) as Array<Record<string, unknown>>).map(outputFrom);\n const receipts = (database.prepare('select * from generation_job_receipts where job_id = ? order by created_at, id').all(id) as Array<Record<string, unknown>>).map(receiptFrom);\n return {\n id: String(row.id),\n project_id: String(row.project_id),\n provider: row.provider as GenerationProvider,\n adapter_version: String(row.adapter_version) as GenerationJob['adapter_version'],\n source_mode: String(row.source_mode) as GenerationSourceMode,\n root_asset_id: String(row.root_asset_id),\n prompt: String(row.prompt),\n expected_output_count: Number(row.expected_output_count),\n status: row.status as GenerationJob['status'],\n output_dir: typeof row.output_dir === 'string' ? row.output_dir : undefined,\n handoff: parseJson<GenerationHandoffPacket>(String(row.handoff_json), {} as GenerationHandoffPacket),\n created_at: String(row.created_at),\n updated_at: String(row.updated_at),\n imported_at: typeof row.imported_at === 'string' ? row.imported_at : undefined,\n inputs,\n outputs,\n receipts,\n };\n}\n\nfunction insertReceipt(database: DatabaseSync, id: string, type: 'plan' | 'import' | 'error', command: string, payload: unknown): void {\n database.prepare(`\n insert into generation_job_receipts (id, job_id, receipt_type, status, command, payload_json, created_at)\n values (?, ?, ?, 'ok', ?, ?, ?)\n `).run(`${id}:receipt:${type}:${Date.now()}`, id, type, command, JSON.stringify(payload), nowIso());\n}\n\nexport function planImageGeneration(project = defaultProject, fields: { prompt: string; count?: number; dryRun?: boolean; fromLineageSelection: boolean; perBaseCount?: number }): GenerationPlanResponse {\n const prompt = fields.prompt.trim();\n if (!prompt) throw new GenerationReceiptError('Missing --prompt');\n if (!fields.fromLineageSelection) throw new GenerationReceiptError('Generation v1 requires --from-lineage-selection');\n const next = resolveLineageSelection(project);\n const parentCount = selectedParents(next).length;\n if (parentCount > 1 && !positiveInteger(fields.perBaseCount)) throw new GenerationReceiptError('Multi-parent generation requires --per-base-count');\n const perBaseCount = parentCount > 1 ? Number(fields.perBaseCount) : Number(fields.count ?? fields.perBaseCount);\n const count = parentCount * perBaseCount;\n if (!positiveInteger(perBaseCount)) throw new GenerationReceiptError('Generation count must be a positive integer');\n if (fields.count !== undefined && fields.count !== count) throw new GenerationReceiptError(`Generation count mismatch: expected ${count} from selected bases, received ${fields.count}`);\n const id = jobId();\n const inputs = inputsFrom(id, project, next);\n const handoff = buildHandoff(project, id, prompt, count, perBaseCount, next, inputs);\n const mappings = parentMappings(next, perBaseCount).map(mapping => ({ parent_asset_id: mapping.parent.asset_id, output_indexes: mapping.output_indexes }));\n const timestamp = nowIso();\n const preview: GenerationJob = {\n id,\n project_id: project,\n provider,\n adapter_version: manifestAdapterVersion,\n source_mode: 'lineage_selection',\n root_asset_id: next.root_asset_id,\n prompt,\n expected_output_count: count,\n status: 'planned',\n output_dir: '.asset-scratch',\n handoff,\n created_at: timestamp,\n updated_at: timestamp,\n inputs,\n outputs: [],\n receipts: [{\n id: `${id}:receipt:plan:preview`,\n job_id: id,\n receipt_type: 'plan',\n status: 'ok',\n command: 'generate image plan',\n payload: { prompt, expected_output_count: count, per_base_count: parentCount > 1 ? perBaseCount : undefined, lineage: handoff.lineage, parent_mappings: mappings },\n created_at: timestamp,\n }],\n };\n if (fields.dryRun) return { ok: true, command: 'generate image plan', project, dryRun: true, wouldWrite: true, job: preview };\n\n const database = lineageDb();\n try {\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare(`\n insert into generation_jobs (\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at\n ) values (?, ?, ?, ?, 'lineage_selection', ?, ?, ?, 'planned', ?, ?, ?, ?)\n `).run(id, project, provider, manifestAdapterVersion, next.root_asset_id, prompt, count, '.asset-scratch', JSON.stringify(handoff), timestamp, timestamp);\n const insertInput = database.prepare('insert into generation_job_inputs (id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json) values (?, ?, ?, ?, ?, ?, ?, ?, ?)');\n for (const input of inputs) insertInput.run(input.id, id, project, input.asset_id, input.root_asset_id, input.role, input.position, input.selection_strategy, JSON.stringify(next));\n insertReceipt(database, id, 'plan', 'generate image plan', preview.receipts[0].payload);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n return { ok: true, command: 'generate image plan', project, job: loadGenerationJob(database, project, id) };\n } finally {\n database.close();\n }\n}\n\nexport function planImageReroll(project = defaultProject, fields: { rootAssetId: string; targetAssetId: string; prompt: string; dryRun?: boolean }): GenerationPlanResponse {\n const prompt = fields.prompt.trim();\n if (!prompt) throw new GenerationReceiptError('Missing --prompt');\n if (!fields.rootAssetId) throw new GenerationReceiptError('Missing --root');\n if (!fields.targetAssetId) throw new GenerationReceiptError('Missing --target');\n const snapshot = getLineageSnapshot(project, fields.rootAssetId);\n const target = snapshot.nodes.find(node => node.asset_id === fields.targetAssetId);\n if (!target) throw new GenerationReceiptError(`Re-roll target is not in lineage: ${fields.targetAssetId}`, 404);\n const request = listLineageRerollRequests(project, snapshot.root_asset_id).requests.find(item => item.node_asset_id === fields.targetAssetId);\n if (!request) throw new GenerationReceiptError(`No pending re-roll request for ${fields.targetAssetId}`);\n const id = jobId();\n const timestamp = nowIso();\n const handoff = buildRerollHandoff(project, id, prompt, snapshot.root_asset_id, target, request);\n const input: GenerationJobInput = {\n id: `${id}:input:0`,\n job_id: id,\n project_id: project,\n asset_id: target.asset_id,\n root_asset_id: snapshot.root_asset_id,\n role: 'reroll_target',\n position: 0,\n selection_strategy: 'reroll_request',\n selection_snapshot: {\n project,\n root_asset_id: snapshot.root_asset_id,\n strategy: 'selected',\n selection_mode: 'single',\n recommended_action: 'evolve_variations',\n reason: 'user_selected',\n next_asset: target,\n next_assets: [target],\n latest: snapshot.latest,\n selected: [target.asset_id],\n selection: null,\n selections: [],\n candidates: snapshot.nodes,\n warnings: ['Re-roll target: import output as an attempt, not a lineage child.'],\n fetchedAt: timestamp,\n },\n };\n const preview: GenerationJob = {\n id,\n project_id: project,\n provider,\n adapter_version: legacyAdapterVersion,\n source_mode: 'lineage_reroll',\n root_asset_id: snapshot.root_asset_id,\n prompt,\n expected_output_count: 1,\n status: 'planned',\n output_dir: '.asset-scratch',\n handoff,\n created_at: timestamp,\n updated_at: timestamp,\n inputs: [input],\n outputs: [],\n receipts: [{\n id: `${id}:receipt:plan:preview`,\n job_id: id,\n receipt_type: 'plan',\n status: 'ok',\n command: 'reroll plan',\n payload: { prompt, expected_output_count: 1, lineage: handoff.lineage, reroll_request_id: request.id },\n created_at: timestamp,\n }],\n };\n if (fields.dryRun) return { ok: true, command: 'reroll plan', project, dryRun: true, wouldWrite: true, job: preview };\n const database = lineageDb();\n try {\n database.exec('BEGIN IMMEDIATE');\n try {\n database.prepare(`\n insert into generation_jobs (\n id, project_id, provider, adapter_version, source_mode, root_asset_id, prompt,\n expected_output_count, status, output_dir, handoff_json, created_at, updated_at\n ) values (?, ?, ?, ?, 'lineage_reroll', ?, ?, 1, 'planned', ?, ?, ?, ?)\n `).run(id, project, provider, legacyAdapterVersion, snapshot.root_asset_id, prompt, '.asset-scratch', JSON.stringify(handoff), timestamp, timestamp);\n database.prepare('insert into generation_job_inputs (id, job_id, project_id, asset_id, root_asset_id, role, position, selection_strategy, selection_snapshot_json) values (?, ?, ?, ?, ?, ?, ?, ?, ?)')\n .run(input.id, id, project, input.asset_id, input.root_asset_id, input.role, input.position, input.selection_strategy, JSON.stringify(input.selection_snapshot));\n insertReceipt(database, id, 'plan', 'reroll plan', preview.receipts[0].payload);\n database.exec('COMMIT');\n } catch (error) {\n database.exec('ROLLBACK');\n throw error;\n }\n return { ok: true, command: 'reroll plan', project, job: loadGenerationJob(database, project, id) };\n } finally {\n database.close();\n }\n}\n\nfunction parentForOutput(job: GenerationJob, outputIndex: number): string {\n const inputs = job.inputs.filter(input => input.role === 'lineage_next_base');\n if (inputs.length === 0) throw new GenerationReceiptError('Generation job has no lineage_next_base input');\n if (inputs.length === 1) return inputs[0].asset_id;\n if (job.expected_output_count % inputs.length !== 0) throw new GenerationReceiptError('Generation job has invalid parent mapping');\n return inputs[Math.floor(outputIndex / (job.expected_output_count / inputs.length))]?.asset_id || inputs[inputs.length - 1].asset_id;\n}\n\nfunction parentInputs(job: GenerationJob): GenerationJobInput[] {\n const inputs = job.inputs.filter(input => input.role === 'lineage_next_base');\n if (inputs.length === 0) throw new GenerationReceiptError('Generation job has no lineage_next_base input');\n return inputs;\n}\n\nfunction parentFilesFor(job: GenerationJob, parentFiles: Record<string, string[]>): Array<{ file: string; parentAssetId: string }> {\n const inputs = parentInputs(job);\n const expectedPerParent = job.expected_output_count / inputs.length;\n if (!Number.isInteger(expectedPerParent)) throw new GenerationReceiptError('Generation job has invalid parent mapping');\n const allowedParents = new Set(inputs.map(input => input.asset_id));\n const seenParents = new Set<string>();\n const mapped: Array<{ file: string; parentAssetId: string }> = [];\n for (const parentAssetId of Object.keys(parentFiles)) {\n if (!allowedParents.has(parentAssetId)) throw new GenerationReceiptError(`Unknown generation parent mapping: ${parentAssetId}`);\n if (seenParents.has(parentAssetId)) throw new GenerationReceiptError(`Duplicate generation parent mapping: ${parentAssetId}`);\n seenParents.add(parentAssetId);\n }\n for (const input of inputs) {\n const files = (parentFiles[input.asset_id] || []).map(file => file.trim()).filter(Boolean);\n if (files.length === 0) throw new GenerationReceiptError(`Missing generation parent mapping for ${input.asset_id}`);\n if (files.length !== expectedPerParent) throw new GenerationReceiptError(`Parent ${input.asset_id} requires ${expectedPerParent} output file${expectedPerParent === 1 ? '' : 's'}, received ${files.length}`);\n for (const file of files) mapped.push({ file, parentAssetId: input.asset_id });\n }\n return mapped;\n}\n\nfunction orderedFilesFor(job: GenerationJob, files: string[]): Array<{ file: string; parentAssetId: string }> {\n return files.map((file, index) => ({ file, parentAssetId: parentForOutput(job, index) }));\n}\n\nexport function inspectImageGeneration(project = defaultProject, jobIdValue: string): GenerationInspectResponse {\n if (!jobIdValue) throw new GenerationReceiptError('Missing --job-id');\n const database = lineageDb();\n try {\n return { ok: true, command: 'generate image inspect', project, job: loadGenerationJob(database, project, jobIdValue) };\n } finally {\n database.close();\n }\n}\n\nfunction isPathInside(child: string, parent: string): boolean {\n const rel = relative(parent, child);\n return Boolean(rel) && !rel.startsWith('..') && !rel.startsWith('/');\n}\n\nfunction scratchCandidate(file: string): { candidate: string; scratchRoot: string } {\n const scratchRoot = resolve(repoRoot, '.asset-scratch');\n const candidate = file.startsWith('.asset-scratch/') || resolve(file).startsWith(scratchRoot)\n ? resolve(repoRoot, file)\n : resolve(scratchRoot, file);\n if (!isPathInside(candidate, scratchRoot)) throw new GenerationReceiptError(`Import file must be under .asset-scratch: ${file}`);\n return { candidate, scratchRoot };\n}\n\nfunction resolveScratchManifestPath(file: string): string {\n const { candidate, scratchRoot } = scratchCandidate(file);\n return relative(scratchRoot, candidate);\n}\n\nfunction resolveScratchFile(file: string): { relativePath: string; checksum: string; size: number; contentType: string; assetId: string } {\n const { candidate, scratchRoot } = scratchCandidate(file);\n if (!existsSync(candidate)) throw new GenerationReceiptError(`Missing import file: ${file}`, 404);\n const realScratchRoot = realpathSync(scratchRoot);\n const realCandidate = realpathSync(candidate);\n if (!isPathInside(realCandidate, realScratchRoot)) throw new GenerationReceiptError(`Import file must be under .asset-scratch: ${file}`);\n const stats = statSync(candidate);\n if (!stats.isFile()) throw new GenerationReceiptError(`Import path is not a file: ${file}`);\n const checksum = fileSha256(candidate);\n return {\n relativePath: relative(scratchRoot, candidate),\n checksum,\n size: stats.size,\n contentType: contentTypeFor(candidate),\n assetId: `local-${checksum.slice(0, 12)}`,\n };\n}\n\ninterface GenerationImportRow {\n edgeSummary?: string;\n file: string;\n parentAssetId: string;\n}\n\nfunction generationManifestConflict(): never {\n throw new GenerationReceiptError('Generation import already exists with different output, summary, or provenance', 409);\n}\n\nfunction confirmManifestRetry(project: string, job: GenerationJob, manifest: GenerationOutputManifest): GenerationImportResponse {\n if (job.outputs.length !== manifest.outputs.length) generationManifestConflict();\n const database = lineageDb();\n try {\n for (const expected of manifest.outputs) {\n const recorded = job.outputs.find(output => output.output_index === expected.output_index);\n if (\n !recorded\n || recorded.file_path !== expected.file_path\n || recorded.parent_asset_id !== expected.parent_asset_id\n || recorded.edge_summary !== expected.edge_summary\n ) generationManifestConflict();\n const edge = database.prepare(`\n select summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ? and child_asset_id = ? and relation_type = 'derived_from'\n `).get(project, recorded.parent_asset_id, recorded.imported_asset_id) as Record<string, unknown> | undefined;\n if (\n !edge\n || edge.summary !== expected.edge_summary\n || edge.summary_created_by !== 'agent'\n || edge.summary_updated_by !== 'agent'\n || typeof edge.summary_updated_at !== 'string'\n || edge.summary_updated_at.length === 0\n ) generationManifestConflict();\n }\n return { ok: true, command: 'generate image import', project, job, imported: job.outputs, idempotent: true };\n } finally {\n database.close();\n }\n}\n\nexport function importImageGenerationOutputs(\n project = defaultProject,\n fields: { jobId: string; files?: string[]; parentFiles?: Record<string, string[]>; manifest?: unknown; confirmWrite: boolean },\n): GenerationImportResponse {\n if (!fields.jobId) throw new GenerationReceiptError('Missing --job-id');\n if (!fields.confirmWrite) throw new GenerationReceiptError('Generation import requires --confirm-write');\n const database = lineageDb();\n let job: GenerationJob;\n try {\n job = loadGenerationJob(database, project, fields.jobId);\n } finally {\n database.close();\n }\n if (job.source_mode !== 'lineage_selection') throw new GenerationReceiptError(`Generation job is not an image-selection job: ${job.source_mode}`);\n\n const hasManifestInput = fields.manifest !== undefined;\n const hasParentFilesInput = fields.parentFiles !== undefined;\n const hasFilesInput = fields.files !== undefined;\n if (hasManifestInput && (hasParentFilesInput || hasFilesInput)) {\n throw new GenerationReceiptError('Use --manifest or legacy --files/--parent-files, not both');\n }\n if (hasParentFilesInput && hasFilesInput) throw new GenerationReceiptError('Use --files or --parent-files, not both');\n\n let manifest: GenerationOutputManifest | undefined;\n let parentFileRows: GenerationImportRow[];\n let mappingStrategy: 'generation_output_manifest_v1' | 'explicit_parent_files' | 'ordered_per_base';\n if (job.adapter_version === manifestAdapterVersion) {\n if (!hasManifestInput) throw new GenerationReceiptError('New generation jobs require --manifest');\n manifest = parseGenerationOutputManifest(fields.manifest, job, { resolveFilePath: resolveScratchManifestPath });\n if (job.status === 'imported') return confirmManifestRetry(project, job, manifest);\n if (job.status !== 'planned') throw new GenerationReceiptError(`Generation job is not importable from status: ${job.status}`);\n parentFileRows = manifest.outputs.map(output => ({\n edgeSummary: output.edge_summary,\n file: output.file_path,\n parentAssetId: output.parent_asset_id,\n }));\n mappingStrategy = 'generation_output_manifest_v1';\n } else if (job.adapter_version === legacyAdapterVersion) {\n if (hasManifestInput) throw new GenerationReceiptError('Already-planned legacy generation jobs require --files or --parent-files');\n if (job.status !== 'planned') throw new GenerationReceiptError(`Generation job is not importable from status: ${job.status}`);\n const hasExplicitParentFiles = Boolean(fields.parentFiles && Object.keys(fields.parentFiles).length > 0);\n parentFileRows = hasExplicitParentFiles\n ? parentFilesFor(job, fields.parentFiles || {})\n : orderedFilesFor(job, (fields.files || []).map(file => file.trim()).filter(Boolean));\n mappingStrategy = hasExplicitParentFiles ? 'explicit_parent_files' : 'ordered_per_base';\n } else {\n throw new GenerationReceiptError(`Unsupported generation adapter version: ${job.adapter_version}`);\n }\n if (parentFileRows.length === 0) throw new GenerationReceiptError('Generation import requires --files or --parent-files');\n if (parentFileRows.length !== job.expected_output_count) {\n throw new GenerationReceiptError(`Output count mismatch: expected ${job.expected_output_count}, received ${parentFileRows.length}`);\n }\n const resolved = parentFileRows.map(row => ({ ...resolveScratchFile(row.file), edgeSummary: row.edgeSummary, parentAssetId: row.parentAssetId }));\n const uniquePaths = new Set(resolved.map(file => file.relativePath));\n if (uniquePaths.size !== resolved.length) throw new GenerationReceiptError('Generation import files must be unique');\n cancelLineageIterateTasksForAssets(project, {\n actor: 'system',\n confirmWrite: false,\n rootAssetId: job.root_asset_id,\n });\n indexLineageAssets(project);\n const writeDb = lineageDb();\n try {\n const timestamp = nowIso();\n writeDb.exec('BEGIN IMMEDIATE');\n try {\n for (const [index, file] of resolved.entries()) {\n const assetRow = writeDb.prepare('select id from assets where project_id = ? and id = ?').get(project, file.assetId);\n if (!assetRow) throw new GenerationReceiptError(`Indexed local asset was not found: ${file.relativePath}`);\n const outputId = `${fields.jobId}:output:${index}`;\n writeDb.prepare(`insert into generation_job_outputs (\n id, job_id, project_id, output_index, file_path, checksum_sha256, size_bytes, content_type,\n imported_asset_id, parent_asset_id, imported_at, edge_summary\n ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n outputId, fields.jobId, project, index, file.relativePath, file.checksum, file.size,\n file.contentType, file.assetId, file.parentAssetId, timestamp, file.edgeSummary || null,\n );\n const insertedEdge = writeDb.prepare(`insert into asset_edges (\n id, project_id, parent_asset_id, child_asset_id, relation_type, created_at,\n summary, summary_created_by, summary_updated_by, summary_updated_at\n ) values (?, ?, ?, ?, 'derived_from', ?, ?, ?, ?, ?)\n on conflict(project_id, parent_asset_id, child_asset_id, relation_type) do nothing`).run(\n `${project}:${file.parentAssetId}:derived_from:${file.assetId}`,\n project,\n file.parentAssetId,\n file.assetId,\n timestamp,\n file.edgeSummary || null,\n file.edgeSummary ? 'agent' : null,\n file.edgeSummary ? 'agent' : null,\n file.edgeSummary ? timestamp : null,\n );\n if (file.edgeSummary && insertedEdge.changes === 0) {\n const edge = writeDb.prepare(`\n select summary, summary_created_by, summary_updated_by, summary_updated_at\n from asset_edges\n where project_id = ? and parent_asset_id = ? and child_asset_id = ? and relation_type = 'derived_from'\n `).get(project, file.parentAssetId, file.assetId) as Record<string, unknown> | undefined;\n if (\n !edge\n || edge.summary !== file.edgeSummary\n || edge.summary_created_by !== 'agent'\n || edge.summary_updated_by !== 'agent'\n || typeof edge.summary_updated_at !== 'string'\n || edge.summary_updated_at.length === 0\n ) generationManifestConflict();\n }\n }\n writeDb.prepare(`\n update generation_jobs\n set status = 'imported', imported_at = ?, updated_at = ?\n where project_id = ? and id = ?\n `).run(timestamp, timestamp, project, fields.jobId);\n insertReceipt(writeDb, fields.jobId, 'import', 'generate image import', {\n mapping_strategy: mappingStrategy,\n files: resolved.map((file, index) => ({\n output_index: index,\n file_path: file.relativePath,\n imported_asset_id: file.assetId,\n parent_asset_id: file.parentAssetId,\n ...(file.edgeSummary ? { edge_summary: file.edgeSummary } : {}),\n })),\n selection_reset: { root_asset_id: job.root_asset_id, cleared: true },\n });\n writeDb.prepare('delete from asset_selections where project_id = ? and root_asset_id = ?').run(project, job.root_asset_id);\n writeDb.exec('COMMIT');\n } catch (error) {\n writeDb.exec('ROLLBACK');\n throw error;\n }\n cancelLineageIterateTasksForAssets(project, {\n actor: 'system',\n confirmWrite: true,\n rootAssetId: job.root_asset_id,\n });\n const importedJob = loadGenerationJob(writeDb, project, fields.jobId);\n return { ok: true, command: 'generate image import', project, job: importedJob, imported: importedJob.outputs };\n } finally {\n writeDb.close();\n }\n}\n\nexport function importImageRerollOutput(project = defaultProject, fields: { jobId: string; file: string; confirmWrite: boolean }): GenerationImportResponse {\n if (!fields.jobId) throw new GenerationReceiptError('Missing --job-id');\n if (!fields.confirmWrite) throw new GenerationReceiptError('Generation import requires --confirm-write');\n const database = lineageDb();\n let job: GenerationJob;\n try {\n job = loadGenerationJob(database, project, fields.jobId);\n } finally {\n database.close();\n }\n if (job.status !== 'planned') throw new GenerationReceiptError(`Generation job is not importable from status: ${job.status}`);\n if (job.source_mode !== 'lineage_reroll') throw new GenerationReceiptError(`Generation job is not a re-roll job: ${job.source_mode}`);\n const target = job.inputs.filter(input => input.role === 'reroll_target');\n if (target.length !== 1) throw new GenerationReceiptError('Re-roll import requires exactly one reroll_target input');\n const resolved = resolveScratchFile(fields.file);\n indexLineageAssets(project);\n const writeDb = lineageDb();\n try {\n const timestamp = nowIso();\n writeDb.exec('BEGIN IMMEDIATE');\n try {\n const assetRow = writeDb.prepare('select id from assets where project_id = ? and id = ?').get(project, resolved.assetId);\n if (!assetRow) throw new GenerationReceiptError(`Indexed local asset was not found: ${resolved.relativePath}`);\n const outputId = `${fields.jobId}:output:0`;\n writeDb.prepare(`insert into generation_job_outputs (\n id, job_id, project_id, output_index, file_path, checksum_sha256, size_bytes, content_type, imported_asset_id, parent_asset_id, imported_at\n ) values (?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?)`).run(outputId, fields.jobId, project, resolved.relativePath, resolved.checksum, resolved.size, resolved.contentType, resolved.assetId, target[0].asset_id, timestamp);\n writeDb.prepare(`\n update generation_jobs\n set status = 'imported', imported_at = ?, updated_at = ?\n where project_id = ? and id = ?\n `).run(timestamp, timestamp, project, fields.jobId);\n insertReceipt(writeDb, fields.jobId, 'import', 'reroll import', {\n file: { output_index: 0, file_path: resolved.relativePath, imported_asset_id: resolved.assetId, parent_asset_id: target[0].asset_id },\n reroll: { root_asset_id: job.root_asset_id, node_asset_id: target[0].asset_id },\n });\n writeDb.exec('COMMIT');\n } catch (error) {\n writeDb.exec('ROLLBACK');\n throw error;\n }\n recordLineageRerollAttempt(project, {\n rootAssetId: job.root_asset_id,\n nodeAssetId: target[0].asset_id,\n assetId: resolved.assetId,\n prompt: job.prompt,\n generationJobId: fields.jobId,\n filePath: resolved.relativePath,\n checksumSha256: resolved.checksum,\n confirmWrite: true,\n });\n const rerollTask = listLineageTasks(project, job.root_asset_id).tasks.find(task => task.task_type === 'reroll' && task.target_asset_id === target[0].asset_id);\n if (rerollTask) {\n resolveLineageTask(project, {\n actor: 'agent',\n confirmWrite: true,\n resolvedAssetId: resolved.assetId,\n resolvedGenerationJobId: fields.jobId,\n taskId: rerollTask.id,\n });\n }\n const importedJob = loadGenerationJob(writeDb, project, fields.jobId);\n return { ok: true, command: 'reroll import', project, job: importedJob, imported: importedJob.outputs };\n } finally {\n writeDb.close();\n }\n}\n", "import { EdgeSummaryValidationError, requireEdgeSummary } from './edgeSummary';\nimport type { GenerationJob, GenerationJobInput } from './generationTypes';\n\nexport const generationOutputManifestSchemaVersion = 'lineage.generation_output_manifest.v1' as const;\n\ninterface GenerationOutputManifestEntry {\n output_index: number;\n file_path: string;\n parent_asset_id: string;\n edge_summary: string;\n}\n\nexport interface GenerationOutputManifest {\n schema_version: typeof generationOutputManifestSchemaVersion;\n job_id: string;\n outputs: GenerationOutputManifestEntry[];\n}\n\ninterface GenerationOutputManifestDraftEntry {\n output_index: number;\n file_path: '';\n parent_asset_id: string;\n edge_summary: '';\n}\n\nexport interface GenerationOutputManifestDraft {\n schema_version: typeof generationOutputManifestSchemaVersion;\n job_id: string;\n outputs: GenerationOutputManifestDraftEntry[];\n}\n\nexport type GenerationOutputManifestJob = Pick<GenerationJob, 'id' | 'expected_output_count'> & {\n inputs: Array<Pick<GenerationJobInput, 'asset_id' | 'position' | 'role'>>;\n};\n\nexport interface GenerationOutputManifestParseOptions {\n resolveFilePath: (filePath: string) => string;\n}\n\nclass GenerationOutputManifestError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GenerationOutputManifestError';\n }\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new GenerationOutputManifestError(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction exactKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {\n const allowedKeys = new Set(allowed);\n const unsupported = Object.keys(value).filter(key => !allowedKeys.has(key)).sort();\n if (unsupported.length > 0) {\n throw new GenerationOutputManifestError(`${label} contains unsupported field: ${unsupported[0]}`);\n }\n}\n\nfunction nonEmptyText(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new GenerationOutputManifestError(`${label} is required`);\n return value.trim();\n}\n\nexport function expectedGenerationOutputParents(job: GenerationOutputManifestJob): string[] {\n if (!Number.isInteger(job.expected_output_count) || job.expected_output_count <= 0) {\n throw new GenerationOutputManifestError('Generation job expected output count must be a positive integer');\n }\n const parents = job.inputs\n .filter(input => input.role === 'lineage_next_base')\n .sort((left, right) => left.position - right.position);\n if (parents.length === 0) throw new GenerationOutputManifestError('Generation job has no lineage_next_base input');\n const parentIds = new Set<string>();\n const parentPositions = new Set<number>();\n for (const parent of parents) {\n if (typeof parent.asset_id !== 'string' || !parent.asset_id || parent.asset_id.trim() !== parent.asset_id) {\n throw new GenerationOutputManifestError('Generation job has invalid lineage parent asset id');\n }\n if (!Number.isInteger(parent.position) || parent.position < 0 || parentPositions.has(parent.position)) {\n throw new GenerationOutputManifestError('Generation job has invalid lineage parent positions');\n }\n if (parentIds.has(parent.asset_id)) throw new GenerationOutputManifestError(`Generation job has duplicate lineage parent: ${parent.asset_id}`);\n parentIds.add(parent.asset_id);\n parentPositions.add(parent.position);\n }\n if (job.expected_output_count % parents.length !== 0) {\n throw new GenerationOutputManifestError('Generation job has invalid parent mapping');\n }\n const outputsPerParent = job.expected_output_count / parents.length;\n return Array.from({ length: job.expected_output_count }, (_value, outputIndex) => {\n return parents[Math.floor(outputIndex / outputsPerParent)].asset_id;\n });\n}\n\nexport function createGenerationOutputManifestDraft(job: GenerationOutputManifestJob): GenerationOutputManifestDraft {\n return {\n schema_version: generationOutputManifestSchemaVersion,\n job_id: job.id,\n outputs: expectedGenerationOutputParents(job).map((parentAssetId, outputIndex) => ({\n output_index: outputIndex,\n file_path: '',\n parent_asset_id: parentAssetId,\n edge_summary: '',\n })),\n };\n}\n\nexport function parseGenerationOutputManifest(\n value: unknown,\n job: GenerationOutputManifestJob,\n options: GenerationOutputManifestParseOptions,\n): GenerationOutputManifest {\n if (!options || typeof options.resolveFilePath !== 'function') {\n throw new GenerationOutputManifestError('Generation output manifest requires a file-path resolver');\n }\n const manifest = record(value, 'Generation output manifest');\n exactKeys(manifest, ['schema_version', 'job_id', 'outputs'], 'Generation output manifest');\n if (manifest.schema_version !== generationOutputManifestSchemaVersion) {\n throw new GenerationOutputManifestError(`Generation output manifest schema_version must be ${generationOutputManifestSchemaVersion}`);\n }\n if (manifest.job_id !== job.id) throw new GenerationOutputManifestError(`Generation output manifest job_id must be ${job.id}`);\n if (!Array.isArray(manifest.outputs)) throw new GenerationOutputManifestError('Generation output manifest outputs must be an array');\n\n const expectedParents = expectedGenerationOutputParents(job);\n if (manifest.outputs.length !== expectedParents.length) {\n throw new GenerationOutputManifestError(`Generation output manifest requires ${expectedParents.length} outputs, received ${manifest.outputs.length}`);\n }\n\n const seenIndexes = new Set<number>();\n const outputs = manifest.outputs.map((value, position): GenerationOutputManifestEntry => {\n const output = record(value, `Generation output at position ${position}`);\n exactKeys(output, ['output_index', 'file_path', 'parent_asset_id', 'edge_summary'], `Generation output at position ${position}`);\n const outputIndex = output.output_index;\n if (!Number.isInteger(outputIndex) || Number(outputIndex) < 0) {\n throw new GenerationOutputManifestError(`Generation output at position ${position} requires a non-negative integer output_index`);\n }\n const normalizedIndex = Number(outputIndex);\n if (seenIndexes.has(normalizedIndex)) throw new GenerationOutputManifestError(`Duplicate generation output_index: ${normalizedIndex}`);\n seenIndexes.add(normalizedIndex);\n const expectedParent = expectedParents[normalizedIndex];\n if (!expectedParent) throw new GenerationOutputManifestError(`Unknown generation output_index: ${normalizedIndex}`);\n\n const filePath = nonEmptyText(output.file_path, `Generation output ${normalizedIndex} file_path`);\n const parentAssetId = nonEmptyText(output.parent_asset_id, `Generation output ${normalizedIndex} parent_asset_id`);\n if (parentAssetId !== expectedParent) {\n throw new GenerationOutputManifestError(`Generation output ${normalizedIndex} must use parent_asset_id ${expectedParent}`);\n }\n let edgeSummary: string;\n try {\n edgeSummary = requireEdgeSummary(output.edge_summary);\n } catch (error) {\n if (error instanceof EdgeSummaryValidationError) {\n throw new GenerationOutputManifestError(`Generation output ${normalizedIndex}: ${error.message}`);\n }\n throw error;\n }\n return {\n output_index: normalizedIndex,\n file_path: filePath,\n parent_asset_id: parentAssetId,\n edge_summary: edgeSummary,\n };\n });\n\n for (const outputIndex of expectedParents.keys()) {\n if (!seenIndexes.has(outputIndex)) throw new GenerationOutputManifestError(`Missing generation output_index: ${outputIndex}`);\n }\n outputs.sort((left, right) => left.output_index - right.output_index);\n const seenPaths = new Set<string>();\n const resolvedOutputs = outputs.map(output => {\n const filePath = nonEmptyText(options.resolveFilePath(output.file_path), `Generation output ${output.output_index} resolved file_path`);\n if (seenPaths.has(filePath)) throw new GenerationOutputManifestError(`Duplicate generation output file_path: ${filePath}`);\n seenPaths.add(filePath);\n return { ...output, file_path: filePath };\n });\n return {\n schema_version: generationOutputManifestSchemaVersion,\n job_id: job.id,\n outputs: resolvedOutputs,\n };\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, statSync } from 'node:fs';\nimport { isAbsolute, resolve } from 'node:path';\nimport { listAssets, repoRoot, validateProject } from './assetCore';\nimport { getLineageSnapshot } from './assetLineage';\nimport { lineageDbPath } from './assetLineageDb';\nimport { lineageWorkspaceId, listLineageWorkspaces } from './assetLineageWorkspaces';\nimport { contentTypeFor, fileSha256 } from './localReview';\nimport type {\n GrowthAsset,\n LineageNode,\n LineageSelectionPacket,\n LineageSelectionPacketAsset,\n LineageSelectionPacketDiagnostic,\n LineageSelectionPacketStorageState,\n LineageSelectionPacketV1,\n LineageSelectionPacketV2,\n LineageSelectionPacketV2Asset,\n LineageSelectionPacketV2Attempt,\n LineageSelectionPacketV2IdentityProjection,\n LineageWorkspace,\n} from '../shared/types';\n\nexport interface LineageSelectionPacketOptions {\n campaign?: string;\n channel?: string;\n command?: string;\n contextNotes?: string;\n dbPath?: string;\n labels?: string[];\n packageVersion?: string;\n rootAssetId?: string;\n schema?: 'v2';\n strict?: boolean;\n workspaceId?: string;\n}\n\nexport class LineageSelectionPacketError extends Error {\n constructor(\n message: string,\n public warnings: string[] = [],\n public errors: string[] = [],\n public diagnostics: LineageSelectionPacketDiagnostic[] = [],\n ) {\n super(message);\n }\n}\n\nfunction listAllAssets(project: string): GrowthAsset[] {\n const pageSize = 100;\n const first = listAssets(project, { page: 1, pageSize, source: 'all' });\n const assets = [...first.assets];\n for (let page = 2; page <= first.pagination.totalPages; page += 1) {\n assets.push(...listAssets(project, { page, pageSize, source: 'all' }).assets);\n }\n return assets;\n}\n\nfunction resolveWorkspace(project: string, options: LineageSelectionPacketOptions): LineageWorkspace {\n if (options.rootAssetId && options.workspaceId) {\n throw new LineageSelectionPacketError('Use either --root or --workspace, not both.', [], ['ambiguous_workspace']);\n }\n const snapshot = listLineageWorkspaces(project);\n const target = options.workspaceId || options.rootAssetId;\n const workspace = target\n ? snapshot.workspaces.find(item => item.id === target || item.root_asset_id === target)\n : snapshot.active_workspace;\n if (workspace) return workspace;\n if (options.rootAssetId) {\n return {\n id: lineageWorkspaceId(project, options.rootAssetId),\n project,\n root_asset_id: options.rootAssetId,\n title: `${options.rootAssetId} lineage`,\n status: 'active',\n created_by: 'system',\n created_at: '',\n updated_at: '',\n };\n }\n const message = options.workspaceId\n ? `Unknown lineage workspace: ${options.workspaceId}`\n : 'No active lineage workspace. Pass --root or activate a workspace first.';\n throw new LineageSelectionPacketError(message, [], [options.workspaceId ? 'unknown_workspace' : 'missing_active_workspace']);\n}\n\nfunction resolveLocalReference(reference?: string): string | undefined {\n if (!reference) return undefined;\n if (isAbsolute(reference)) return reference;\n const repoRelative = resolve(repoRoot, reference);\n if (existsSync(repoRelative)) return repoRelative;\n return resolve(repoRoot, '.asset-scratch', reference);\n}\n\nfunction fileSize(path?: string): number | undefined {\n if (!path || !existsSync(path)) return undefined;\n try {\n return statSync(path).size;\n } catch {\n return undefined;\n }\n}\n\nfunction storageState(hasLocal: boolean, hasS3: boolean): LineageSelectionPacketStorageState {\n if (hasLocal && hasS3) return 'local_and_s3';\n if (hasLocal) return 'local_only';\n if (hasS3) return 's3_backed';\n return 'unresolved';\n}\n\nfunction currentAttemptFor(node: LineageNode): LineageSelectionPacketAsset['current_attempt'] {\n if (!node.current_attempt) return undefined;\n return {\n asset_id: node.current_attempt.asset_id,\n checksum_sha256: node.current_attempt.checksum_sha256,\n file_path: node.current_attempt.file_path,\n generation_job_id: node.current_attempt.generation_job_id,\n id: node.current_attempt.id,\n is_current: node.current_attempt.is_current,\n source: node.current_attempt.source,\n };\n}\n\nfunction assetForNode(node: LineageNode, catalogAsset: GrowthAsset | undefined, warnings: string[]): LineageSelectionPacketAsset {\n const localReference = catalogAsset?.local?.absolute_path || node.current_attempt?.file_path || node.local_path || catalogAsset?.local?.relative_path;\n const absolutePath = catalogAsset?.local?.absolute_path || resolveLocalReference(localReference);\n const localExists = absolutePath ? existsSync(absolutePath) : false;\n const hasLocalClaim = Boolean(absolutePath || node.local_path || catalogAsset?.local?.relative_path);\n const s3Key = catalogAsset?.s3?.key || node.s3_key;\n const hasS3 = Boolean(s3Key);\n const checksum = catalogAsset?.local?.checksum_sha256 || node.current_attempt?.checksum_sha256 || node.checksum_sha256 || catalogAsset?.s3?.checksum_sha256;\n const mimeType = catalogAsset?.local?.content_type || catalogAsset?.s3?.content_type;\n const mediaType = catalogAsset?.content_type || node.media_type;\n\n if (hasLocalClaim && !localExists) warnings.push(`Selected asset ${node.asset_id} has a local path but the file is missing: ${absolutePath || node.local_path}`);\n if (!hasLocalClaim && !hasS3) warnings.push(`Selected asset ${node.asset_id} has neither a local file nor S3 key.`);\n if (mediaType && mediaType !== 'image' && mediaType !== 'gif') warnings.push(`Selected asset ${node.asset_id} is ${mediaType}, not an image/gif asset.`);\n\n return {\n asset_id: node.asset_id,\n campaign: catalogAsset?.campaign || node.campaign,\n channel: catalogAsset?.channel || node.channel,\n checksum_sha256: checksum,\n current_attempt: currentAttemptFor(node),\n local: {\n absolute_path: absolutePath,\n content_type: catalogAsset?.local?.content_type,\n exists: localExists,\n relative_path: catalogAsset?.local?.relative_path || node.local_path || node.current_attempt?.file_path,\n size_bytes: catalogAsset?.local?.size_bytes || fileSize(absolutePath),\n },\n media_type: mediaType,\n mime_type: mimeType,\n review_notes: node.review_notes,\n review_state: node.review_state,\n s3: {\n bucket: catalogAsset?.s3?.bucket,\n checksum_sha256: catalogAsset?.s3?.checksum_sha256,\n content_type: catalogAsset?.s3?.content_type,\n etag: catalogAsset?.s3?.etag,\n key: s3Key,\n region: catalogAsset?.s3?.region,\n size_bytes: catalogAsset?.s3?.size_bytes,\n version_id: catalogAsset?.s3?.version_id,\n },\n selection_note: node.selection_note,\n source: catalogAsset?.source || node.source,\n status: catalogAsset?.status || node.status,\n storage_state: storageState(hasLocalClaim, hasS3),\n title: catalogAsset?.title || node.title || node.asset_id,\n };\n}\n\nfunction packetId(packetIdentity: unknown): string {\n const digest = createHash('sha256').update(JSON.stringify(packetIdentity)).digest('hex').slice(0, 24);\n return `lineage_packet_${digest}`;\n}\n\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/;\n\nfunction canonicalValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(item => canonicalValue(item));\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)\n .map(([key, item]) => [key, canonicalValue(item)]),\n );\n }\n return value;\n}\n\nexport function canonicalLineageSelectionPacketIdentityJson(projection: LineageSelectionPacketV2IdentityProjection): string {\n return JSON.stringify(canonicalValue(projection));\n}\n\nexport function lineageSelectionPacketV2IdentityProjection(packet: LineageSelectionPacketV2): LineageSelectionPacketV2IdentityProjection {\n const assetsById = new Map(packet.assets.map(asset => [asset.asset_id, asset]));\n const selection = packet.selection.items.map(item => {\n const asset = assetsById.get(item.asset_id);\n if (!asset) {\n const diagnostics: LineageSelectionPacketDiagnostic[] = [{ asset_id: item.asset_id, code: 'selected_asset_missing', severity: 'error' }];\n throw new LineageSelectionPacketError(\n `Selected asset ${item.asset_id} is absent from the v2 packet asset envelope.`,\n [],\n ['selected_asset_missing'],\n diagnostics,\n );\n }\n return {\n asset_id: item.asset_id,\n campaign: asset.campaign,\n channel: asset.channel,\n current_attempt: {\n asset_id: asset.current_attempt.asset_id,\n attempt_index: asset.current_attempt.attempt_index,\n checksum_sha256: asset.current_attempt.checksum_sha256,\n id: asset.current_attempt.id,\n source: asset.current_attempt.source,\n },\n media_type: asset.media_type,\n mime_type: asset.mime_type,\n position: item.position,\n selection_note: item.selection_note,\n title: asset.title,\n };\n });\n return {\n schema_version: 'lineage.selection_packet.v2',\n project: packet.project,\n product: packet.product,\n workspace: {\n id: packet.workspace.id,\n root_asset_id: packet.workspace.root_asset_id,\n },\n context: {\n campaign: packet.context.campaign,\n channel: packet.context.channel,\n labels: packet.context.labels,\n notes: packet.context.notes,\n },\n selection,\n diagnostics: packet.diagnostics.map(diagnostic => ({\n code: diagnostic.code,\n severity: diagnostic.severity,\n ...(diagnostic.asset_id ? { asset_id: diagnostic.asset_id } : {}),\n })),\n };\n}\n\nexport function lineageSelectionPacketV2IdentitySha256(packet: LineageSelectionPacketV2): string {\n const projection = lineageSelectionPacketV2IdentityProjection(packet);\n return createHash('sha256').update(canonicalLineageSelectionPacketIdentityJson(projection)).digest('hex');\n}\n\nfunction addDiagnostic(diagnostics: LineageSelectionPacketDiagnostic[], diagnostic: LineageSelectionPacketDiagnostic): void {\n if (diagnostics.some(item => item.code === diagnostic.code && item.severity === diagnostic.severity && item.asset_id === diagnostic.asset_id)) return;\n diagnostics.push(diagnostic);\n}\n\nfunction requireV2CurrentAttempt(\n node: LineageNode,\n warnings: string[],\n diagnostics: LineageSelectionPacketDiagnostic[],\n): LineageSelectionPacketV2Attempt {\n const attempt = node.current_attempt;\n if (!attempt) {\n const message = `Selected asset ${node.asset_id} has no current attempt identity.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_missing', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, warnings, ['current_attempt_missing'], [...diagnostics, diagnostic]);\n }\n if (!attempt.id || !attempt.asset_id || !Number.isInteger(attempt.attempt_index) || attempt.attempt_index <= 0 || !attempt.source || attempt.is_current !== true) {\n const message = `Selected asset ${node.asset_id} has malformed current attempt identity.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_invalid_identity', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, warnings, ['current_attempt_invalid_identity'], [...diagnostics, diagnostic]);\n }\n if (!attempt.checksum_sha256 || !SHA256_PATTERN.test(attempt.checksum_sha256)) {\n const message = `Selected asset ${node.asset_id} current attempt does not have a valid lowercase SHA-256 checksum.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_invalid_checksum', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, warnings, ['current_attempt_invalid_checksum'], [...diagnostics, diagnostic]);\n }\n return {\n asset_id: attempt.asset_id,\n attempt_index: attempt.attempt_index,\n checksum_sha256: attempt.checksum_sha256,\n file_path: attempt.file_path,\n generation_job_id: attempt.generation_job_id,\n id: attempt.id,\n is_current: attempt.is_current,\n source: attempt.source,\n };\n}\n\nfunction assetForNodeV2(\n node: LineageNode,\n visibleCatalogAsset: GrowthAsset | undefined,\n catalogById: Map<string, GrowthAsset>,\n warnings: string[],\n errors: string[],\n diagnostics: LineageSelectionPacketDiagnostic[],\n): LineageSelectionPacketV2Asset {\n const currentAttempt = requireV2CurrentAttempt(node, warnings, diagnostics);\n const currentAttemptCatalogAsset = catalogById.get(currentAttempt.asset_id);\n const isVisibleNodeAttempt = currentAttempt.asset_id === node.asset_id;\n const mediaCatalogAsset = currentAttemptCatalogAsset || (isVisibleNodeAttempt ? visibleCatalogAsset : undefined);\n const localReference = currentAttempt.file_path\n || mediaCatalogAsset?.local?.absolute_path\n || mediaCatalogAsset?.local?.relative_path\n || (isVisibleNodeAttempt ? node.local_path : undefined);\n const absolutePath = resolveLocalReference(localReference);\n const localExists = absolutePath ? existsSync(absolutePath) : false;\n const hasLocalClaim = Boolean(localReference);\n const s3Key = mediaCatalogAsset?.s3?.key || (isVisibleNodeAttempt ? node.s3_key : undefined);\n const hasS3 = Boolean(s3Key);\n const mimeType = mediaCatalogAsset?.local?.content_type\n || mediaCatalogAsset?.s3?.content_type\n || visibleCatalogAsset?.local?.content_type\n || visibleCatalogAsset?.s3?.content_type\n || (localReference ? contentTypeFor(localReference) : undefined);\n const mediaType = mediaCatalogAsset?.content_type || visibleCatalogAsset?.content_type || node.media_type;\n\n if (localExists && absolutePath && fileSha256(absolutePath) !== currentAttempt.checksum_sha256) {\n const message = `Selected asset ${node.asset_id} current attempt checksum does not match its local file.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_checksum_mismatch', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, [...warnings, message], ['current_attempt_checksum_mismatch'], [...diagnostics, diagnostic]);\n }\n const s3Checksum = mediaCatalogAsset?.s3?.checksum_sha256;\n if (hasS3 && s3Checksum && s3Checksum !== currentAttempt.checksum_sha256) {\n const message = `Selected asset ${node.asset_id} current attempt checksum does not match its S3 media envelope.`;\n const diagnostic = { asset_id: node.asset_id, code: 'current_attempt_checksum_mismatch', severity: 'error' } as const;\n throw new LineageSelectionPacketError(message, [...warnings, message], ['current_attempt_checksum_mismatch'], [...diagnostics, diagnostic]);\n }\n\n if (hasLocalClaim && !localExists) {\n warnings.push(`Selected asset ${node.asset_id} current attempt has a local path but the file is missing: ${absolutePath || localReference}`);\n }\n if (!hasLocalClaim && !hasS3) {\n const message = `Selected asset ${node.asset_id} current attempt has neither a local file nor S3 key.`;\n warnings.push(message);\n errors.push(message);\n }\n if (mediaType && mediaType !== 'image' && mediaType !== 'gif') {\n warnings.push(`Selected asset ${node.asset_id} is ${mediaType}, not an image/gif asset.`);\n addDiagnostic(diagnostics, { asset_id: node.asset_id, code: 'unsupported_media_type', severity: 'warning' });\n }\n\n const conflictingChecksums = [\n currentAttemptCatalogAsset?.local?.checksum_sha256,\n currentAttemptCatalogAsset?.s3?.checksum_sha256,\n visibleCatalogAsset?.local?.checksum_sha256,\n visibleCatalogAsset?.s3?.checksum_sha256,\n node.checksum_sha256,\n ].filter((checksum): checksum is string => Boolean(checksum && checksum !== currentAttempt.checksum_sha256));\n if (conflictingChecksums.length > 0) {\n warnings.push(`Selected asset ${node.asset_id} catalog or visible-node checksum differs from its current attempt; current attempt checksum is authoritative.`);\n }\n\n return {\n asset_id: node.asset_id,\n campaign: visibleCatalogAsset?.campaign || node.campaign,\n channel: visibleCatalogAsset?.channel || node.channel,\n checksum_sha256: currentAttempt.checksum_sha256,\n current_attempt: currentAttempt,\n local: {\n absolute_path: absolutePath,\n content_type: mediaCatalogAsset?.local?.content_type,\n exists: localExists,\n relative_path: mediaCatalogAsset?.local?.relative_path || currentAttempt.file_path || (isVisibleNodeAttempt ? node.local_path : undefined),\n size_bytes: mediaCatalogAsset?.local?.size_bytes || fileSize(absolutePath),\n },\n media_type: mediaType,\n mime_type: mimeType,\n review_notes: node.review_notes,\n review_state: node.review_state,\n s3: {\n bucket: mediaCatalogAsset?.s3?.bucket,\n checksum_sha256: mediaCatalogAsset?.s3?.checksum_sha256,\n content_type: mediaCatalogAsset?.s3?.content_type,\n etag: mediaCatalogAsset?.s3?.etag,\n key: s3Key,\n region: mediaCatalogAsset?.s3?.region,\n size_bytes: mediaCatalogAsset?.s3?.size_bytes,\n version_id: mediaCatalogAsset?.s3?.version_id,\n },\n selection_note: node.selection_note,\n source: mediaCatalogAsset?.source || visibleCatalogAsset?.source || node.source,\n status: visibleCatalogAsset?.status || node.status,\n storage_state: storageState(hasLocalClaim, hasS3),\n title: visibleCatalogAsset?.title || node.title || node.asset_id,\n };\n}\n\nfunction getLineageSelectionPacketV1(project: string, options: LineageSelectionPacketOptions = {}): LineageSelectionPacketV1 {\n const workspace = resolveWorkspace(project, options);\n const snapshot = getLineageSnapshot(project, workspace.root_asset_id);\n const catalogSummary = validateProject(project);\n const catalogAssets = listAllAssets(project);\n const catalogById = new Map(catalogAssets.map(asset => [asset.asset_id, asset]));\n const warnings: string[] = [];\n const errors: string[] = [];\n const nodeById = new Map(snapshot.nodes.map(node => [node.asset_id, node]));\n const selectedItems = snapshot.selections.map(selection => ({\n asset_id: selection.asset_id,\n position: selection.position,\n selected_at: selection.selected_at,\n selection_note: selection.notes,\n }));\n\n if (selectedItems.length === 0) warnings.push(`Lineage workspace ${workspace.id} has no selected assets.`);\n\n const assets = selectedItems.flatMap(item => {\n const node = nodeById.get(item.asset_id);\n if (!node) {\n const message = `Selected asset ${item.asset_id} is not present in the resolved workspace snapshot.`;\n warnings.push(message);\n errors.push('selected_asset_outside_workspace');\n return [];\n }\n return [assetForNode(node, catalogById.get(item.asset_id), warnings)];\n });\n\n if (assets.some(asset => !asset.dimensions)) warnings.push('Image dimensions are unavailable for one or more selected assets.');\n if (options.strict) {\n const strictErrors = [\n ...(selectedItems.length === 0 ? ['empty_selection'] : []),\n ...assets.filter(asset => asset.local.absolute_path && !asset.local.exists).map(asset => `missing_local_file:${asset.asset_id}`),\n ...errors,\n ];\n if (strictErrors.length > 0) {\n throw new LineageSelectionPacketError(`Lineage selection packet strict mode failed: ${strictErrors.join(', ')}`, warnings, strictErrors);\n }\n }\n\n const context = {\n campaign: options.campaign,\n channel: options.channel,\n labels: options.labels || [],\n notes: options.contextNotes,\n };\n const identity = {\n assets: assets.map(asset => ({\n asset_id: asset.asset_id,\n checksum_sha256: asset.checksum_sha256,\n local_path: asset.local.absolute_path,\n s3_key: asset.s3.key,\n storage_state: asset.storage_state,\n })),\n context,\n project,\n root_asset_id: workspace.root_asset_id,\n schema_version: 'lineage.selection_packet.v1',\n selection: selectedItems,\n workspace_id: workspace.id,\n };\n\n return {\n assets,\n context,\n created_at: new Date().toISOString(),\n errors,\n kind: 'lineage.selection_packet',\n packet_id: packetId(identity),\n product: catalogSummary.product,\n project,\n schema_version: 'lineage.selection_packet.v1',\n selection: {\n asset_ids: selectedItems.map(item => item.asset_id),\n count: selectedItems.length,\n items: selectedItems,\n root_asset_id: workspace.root_asset_id,\n },\n source: {\n app: 'lineage',\n command: options.command,\n db_path: options.dbPath || process.env.LINEAGE_DB || lineageDbPath(),\n package: options.packageVersion,\n },\n warnings: [...new Set(warnings)],\n workspace: {\n active_at: workspace.active_at,\n id: workspace.id,\n notes: workspace.notes,\n root_asset_id: workspace.root_asset_id,\n status: workspace.status,\n title: workspace.title,\n },\n };\n}\n\nfunction getLineageSelectionPacketV2(project: string, options: LineageSelectionPacketOptions): LineageSelectionPacketV2 {\n const workspace = resolveWorkspace(project, options);\n const snapshot = getLineageSnapshot(project, workspace.root_asset_id);\n const catalogSummary = validateProject(project);\n const catalogAssets = listAllAssets(project);\n const catalogById = new Map(catalogAssets.map(asset => [asset.asset_id, asset]));\n const warnings: string[] = [];\n const errors: string[] = [];\n const diagnostics: LineageSelectionPacketDiagnostic[] = [];\n const nodeById = new Map(snapshot.nodes.map(node => [node.asset_id, node]));\n const selectedItems = snapshot.selections.map(selection => ({\n asset_id: selection.asset_id,\n position: selection.position,\n selected_at: selection.selected_at,\n selection_note: selection.notes,\n }));\n\n if (selectedItems.length === 0) {\n warnings.push(`Lineage workspace ${workspace.id} has no selected assets.`);\n addDiagnostic(diagnostics, { code: 'empty_selection', severity: 'warning' });\n }\n\n const assets: LineageSelectionPacketV2Asset[] = [];\n for (const item of selectedItems) {\n const node = nodeById.get(item.asset_id);\n if (!node) {\n const message = `Selected asset ${item.asset_id} is not present in the resolved workspace snapshot.`;\n warnings.push(message);\n errors.push(message);\n const diagnostic = { asset_id: item.asset_id, code: 'selected_asset_outside_workspace', severity: 'error' } as const;\n addDiagnostic(diagnostics, diagnostic);\n throw new LineageSelectionPacketError(message, warnings, ['selected_asset_outside_workspace'], diagnostics);\n }\n assets.push(assetForNodeV2(node, catalogById.get(item.asset_id), catalogById, warnings, errors, diagnostics));\n }\n\n if (assets.some(asset => !asset.dimensions)) {\n warnings.push('Image dimensions are unavailable for one or more selected assets.');\n }\n\n if (options.strict) {\n const strictErrors = [\n ...(selectedItems.length === 0 ? ['empty_selection'] : []),\n ...assets.filter(asset => asset.local.absolute_path && !asset.local.exists).map(asset => `missing_local_file:${asset.asset_id}`),\n ...assets.filter(asset => asset.storage_state === 'unresolved').map(asset => `unresolved_current_attempt_media:${asset.asset_id}`),\n ...diagnostics\n .filter(diagnostic => diagnostic.severity === 'error')\n .map(diagnostic => `${diagnostic.code}${diagnostic.asset_id ? `:${diagnostic.asset_id}` : ''}`),\n ];\n if (strictErrors.length > 0) {\n throw new LineageSelectionPacketError(\n `Lineage selection packet strict mode failed: ${strictErrors.join(', ')}`,\n warnings,\n strictErrors,\n diagnostics,\n );\n }\n }\n\n const packet: LineageSelectionPacketV2 = {\n assets,\n context: {\n campaign: options.campaign,\n channel: options.channel,\n labels: options.labels || [],\n notes: options.contextNotes,\n },\n created_at: new Date().toISOString(),\n diagnostics,\n errors: [...new Set(errors)],\n identity_sha256: '',\n kind: 'lineage.selection_packet',\n packet_id: '',\n product: catalogSummary.product,\n project,\n schema_version: 'lineage.selection_packet.v2',\n selection: {\n asset_ids: selectedItems.map(item => item.asset_id),\n count: selectedItems.length,\n items: selectedItems,\n root_asset_id: workspace.root_asset_id,\n },\n source: {\n app: 'lineage',\n command: options.command,\n db_path: options.dbPath || process.env.LINEAGE_DB || lineageDbPath(),\n package: options.packageVersion,\n },\n warnings: [...new Set(warnings)],\n workspace: {\n active_at: workspace.active_at,\n id: workspace.id,\n notes: workspace.notes,\n root_asset_id: workspace.root_asset_id,\n status: workspace.status,\n title: workspace.title,\n },\n };\n packet.identity_sha256 = lineageSelectionPacketV2IdentitySha256(packet);\n packet.packet_id = `lineage_packet_${packet.identity_sha256.slice(0, 24)}`;\n return packet;\n}\n\nexport function getLineageSelectionPacket(project: string, options: LineageSelectionPacketOptions = {}): LineageSelectionPacket {\n return options.schema === 'v2'\n ? getLineageSelectionPacketV2(project, options)\n : getLineageSelectionPacketV1(project, options);\n}\n", "import { createHash } from 'node:crypto';\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } from 'node:fs';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { lineageDbPath, nowIso, type DatabaseSync } from './assetLineageDb';\nimport { repoRoot } from './assetCore';\nimport { runtimeProfileIdentity } from './lineageProfiles';\nimport { loadNodeSqlite } from './nodeSqlite';\nimport { lineageCliLauncher, lineageRuntimeSelector } from './lineageRuntimeCommand';\nimport {\n lineageRuntimeBuildSchemaVersion,\n lineageRuntimeInstallSchemaVersion,\n type LineageRuntimeBuildIdentity,\n type LineageRuntimeChannel,\n type LineageRuntimeCodeIdentity,\n type LineageRuntimeInfo,\n type LineageRuntimeInstallReceipt,\n} from '../shared/runtimeInfoTypes';\n\nconst processStartedAt = new Date().toISOString();\n\nfunction isLineagePackageRoot(root: string): boolean {\n try {\n const info = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string };\n return info.name === '@mean-weasel/lineage';\n } catch {\n return false;\n }\n}\n\nfunction executingCodeRoot(): string {\n const moduleDirectory = dirname(fileURLToPath(import.meta.url));\n const candidates = [resolve(moduleDirectory, '../..'), resolve(moduleDirectory, '..')];\n const root = candidates.find(isLineagePackageRoot);\n if (!root) throw new Error(`Unable to derive Lineage code root from executing module ${fileURLToPath(import.meta.url)}`);\n return canonicalRoot(root);\n}\n\nconst codeRoot = executingCodeRoot();\n\nfunction sha256(value: string | Buffer): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction canonicalRoot(root: string): string {\n try {\n return realpathSync(root);\n } catch {\n return resolve(root);\n }\n}\n\nfunction packageInfo(root = codeRoot): { name: string; version: string } {\n try {\n const info = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; version?: string };\n return { name: info.name || '@mean-weasel/lineage', version: info.version || '0.0.0' };\n } catch {\n return { name: '@mean-weasel/lineage', version: '0.0.0' };\n }\n}\n\nexport function normalizeRuntimeChannel(value?: string): LineageRuntimeChannel {\n if (value === 'stable' || value === 'preview' || value === 'dev') return value;\n if (value === 'production') return 'stable';\n if (value === 'next') return 'preview';\n if (value === 'development') return 'dev';\n return process.env.NODE_ENV === 'production' ? 'stable' : 'dev';\n}\n\nfunction git(root: string, args: string[]): string | undefined {\n const result = spawnSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });\n return result.status === 0 ? result.stdout : undefined;\n}\n\nfunction untrackedFingerprint(root: string, status: string): string {\n const hash = createHash('sha256');\n hash.update(status);\n const listed = git(root, ['ls-files', '--others', '--exclude-standard', '-z']);\n if (listed === undefined) return hash.digest('hex');\n for (const relativePath of listed.split('\\0').filter(Boolean).sort()) {\n hash.update('\\0');\n hash.update(relativePath);\n const path = join(root, relativePath);\n try {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) hash.update(readlinkSync(path));\n else if (stat.isFile()) hash.update(readFileSync(path));\n else hash.update(`[${stat.mode}:${stat.size}]`);\n } catch (error) {\n hash.update(`[unreadable:${error instanceof Error ? error.message : String(error)}]`);\n }\n }\n return hash.digest('hex');\n}\n\nfunction checkoutCodeIdentity(root: string, channel: LineageRuntimeChannel, version: string): LineageRuntimeCodeIdentity {\n const errors: string[] = [];\n const gitRootRaw = git(root, ['rev-parse', '--show-toplevel'])?.trim();\n const gitSha = git(root, ['rev-parse', 'HEAD'])?.trim();\n const status = git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);\n const diff = git(root, ['diff', '--binary', 'HEAD', '--']);\n const canonicalGitRoot = gitRootRaw ? canonicalRoot(gitRootRaw) : undefined;\n if (!canonicalGitRoot || canonicalGitRoot !== root) errors.push('Code root is not the canonical root of a Git checkout/worktree');\n if (!gitSha || !/^[a-f0-9]{40}$/i.test(gitSha)) errors.push('Checkout Git revision is unavailable');\n if (status === undefined || diff === undefined) errors.push('Checkout dirty state could not be inspected');\n if (channel !== 'dev') errors.push(`Checkout code may run only as dev, not ${channel}`);\n const dirty = Boolean(status);\n const sourceFingerprint = sha256(`${gitSha || 'unknown'}\\0${sha256(diff || '')}\\0${untrackedFingerprint(root, status || '')}`);\n return {\n channel,\n dirty,\n errors,\n fingerprint: sha256(JSON.stringify({ channel, dirty, git_sha: gitSha, origin: 'checkout', root, source_fingerprint: sourceFingerprint, version })),\n git_sha: gitSha,\n origin: 'checkout',\n package_version: version,\n root,\n source_fingerprint: sourceFingerprint,\n verified: errors.length === 0,\n };\n}\n\nfunction buildFingerprint(build: Omit<LineageRuntimeBuildIdentity, 'build_fingerprint'>): string {\n return sha256(JSON.stringify({\n package_name: build.package_name,\n package_version: build.package_version,\n schema_version: build.schema_version,\n source_dirty: build.source_dirty,\n source_fingerprint: build.source_fingerprint,\n source_git_sha: build.source_git_sha,\n }));\n}\n\nfunction readBuildIdentity(root: string, errors: string[]): LineageRuntimeBuildIdentity | undefined {\n const path = join(root, 'dist', 'runtime-build.json');\n let build: LineageRuntimeBuildIdentity;\n try {\n build = JSON.parse(readFileSync(path, 'utf8')) as LineageRuntimeBuildIdentity;\n } catch (error) {\n errors.push(`Embedded build identity is missing or unreadable at ${path}: ${error instanceof Error ? error.message : String(error)}`);\n return undefined;\n }\n if (build.schema_version !== lineageRuntimeBuildSchemaVersion) errors.push(`Unsupported build identity schema: ${String(build.schema_version)}`);\n if (!/^[a-f0-9]{40}$/i.test(build.source_git_sha || '')) errors.push('Embedded build Git revision is invalid');\n if (!/^[a-f0-9]{64}$/i.test(build.source_fingerprint || '')) errors.push('Embedded source fingerprint is invalid');\n const expected = buildFingerprint(build);\n if (build.build_fingerprint !== expected) errors.push('Embedded build fingerprint does not match its contents');\n return build;\n}\n\nfunction readInstallReceipt(path: string | undefined, errors: string[]): (LineageRuntimeInstallReceipt & { receipt_path: string }) | undefined {\n if (!path) {\n errors.push('Packaged runtime was not launched through a channel install receipt');\n return undefined;\n }\n let receipt: LineageRuntimeInstallReceipt;\n const receiptPath = resolve(path);\n try {\n receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) as LineageRuntimeInstallReceipt;\n } catch (error) {\n errors.push(`Runtime install receipt is missing or unreadable at ${receiptPath}: ${error instanceof Error ? error.message : String(error)}`);\n return undefined;\n }\n if (receipt.schema_version !== lineageRuntimeInstallSchemaVersion) errors.push(`Unsupported runtime install receipt schema: ${String(receipt.schema_version)}`);\n if (!isAbsolute(receipt.package_root || '')) errors.push('Runtime install receipt package_root must be absolute');\n if (!receipt.package_integrity?.startsWith('sha512-')) errors.push('Runtime install receipt package integrity is invalid');\n if (receipt.package_source !== 'registry' && receipt.package_source !== 'local') errors.push('Runtime install receipt package source is invalid');\n if (typeof receipt.package_spec !== 'string' || !receipt.package_spec) errors.push('Runtime install receipt package spec is invalid');\n if (!/^[a-f0-9]{64}$/i.test(receipt.package_tree_sha256 || '')) errors.push('Runtime install receipt package tree hash is invalid');\n if (Number.isNaN(Date.parse(receipt.installed_at))) errors.push('Runtime install receipt timestamp is invalid');\n return { ...receipt, receipt_path: receiptPath };\n}\n\nexport function lineagePackageTreeSha256(root: string): string {\n const hash = createHash('sha256');\n const visit = (directory: string, relativeDirectory = '') => {\n for (const entry of readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {\n const relativePath = relativeDirectory ? join(relativeDirectory, entry.name) : entry.name;\n const path = join(directory, entry.name);\n hash.update(relativePath.replaceAll('\\\\', '/'));\n hash.update('\\0');\n if (entry.isDirectory()) {\n hash.update('directory\\0');\n visit(path, relativePath);\n } else if (entry.isSymbolicLink()) {\n hash.update('symlink\\0');\n hash.update(readlinkSync(path));\n } else if (entry.isFile()) {\n hash.update('file\\0');\n hash.update(readFileSync(path));\n } else {\n hash.update('other\\0');\n }\n hash.update('\\0');\n }\n };\n visit(root);\n return hash.digest('hex');\n}\n\nfunction packageCodeIdentity(\n root: string,\n channel: LineageRuntimeChannel,\n info: { name: string; version: string },\n receiptPath?: string,\n): LineageRuntimeCodeIdentity {\n const errors: string[] = [];\n const build = readBuildIdentity(root, errors);\n const install = readInstallReceipt(receiptPath, errors);\n if (channel === 'dev') errors.push('Published package code cannot run as dev; use a Git checkout/worktree');\n if (build?.package_name !== info.name || build?.package_version !== info.version) {\n errors.push('Embedded build package identity does not match package.json');\n }\n if (build?.source_dirty) errors.push('Stable and preview package installs require a clean-source build');\n if (install) {\n if (install.channel !== channel) errors.push(`Install receipt channel ${install.channel} does not match requested ${channel}`);\n if (canonicalRoot(install.package_root) !== root) errors.push('Install receipt package root does not match the executing package root');\n if (install.package_name !== info.name || install.package_version !== info.version) errors.push('Install receipt package identity does not match package.json');\n if (build && install.build_fingerprint !== build.build_fingerprint) errors.push('Install receipt build fingerprint does not match the embedded build');\n try {\n if (lineagePackageTreeSha256(root) !== install.package_tree_sha256) errors.push('Installed package tree does not match the channel install receipt');\n } catch (error) {\n errors.push(`Installed package tree could not be verified: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n const gitSha = build?.source_git_sha;\n const sourceFingerprint = build?.source_fingerprint;\n return {\n build,\n channel,\n dirty: build?.source_dirty,\n errors,\n fingerprint: sha256(JSON.stringify({\n build_fingerprint: build?.build_fingerprint,\n channel,\n install_integrity: install?.package_integrity,\n origin: 'package',\n root,\n version: info.version,\n })),\n git_sha: gitSha,\n install,\n origin: 'package',\n package_version: info.version,\n root,\n source_fingerprint: sourceFingerprint,\n verified: errors.length === 0,\n };\n}\n\nexport function getLineageCodeIdentity(\n channel: LineageRuntimeChannel,\n options: { receiptPath?: string; root?: string } = {},\n): LineageRuntimeCodeIdentity {\n const root = canonicalRoot(options.root || codeRoot);\n const info = packageInfo(root);\n if (existsSync(join(root, '.git'))) return checkoutCodeIdentity(root, channel, info.version);\n if (existsSync(join(root, 'package.json'))) {\n return packageCodeIdentity(root, channel, info, options.receiptPath ?? process.env.LINEAGE_RUNTIME_RECEIPT);\n }\n const errors = [`Code root has neither checkout metadata nor package.json: ${root}`];\n return {\n channel,\n errors,\n fingerprint: sha256(JSON.stringify({ channel, origin: 'unknown', root, version: info.version })),\n origin: 'unknown',\n package_version: info.version,\n root,\n verified: false,\n };\n}\n\nexport function assertLineageCodeOrigin(channel: LineageRuntimeChannel): LineageRuntimeCodeIdentity {\n const identity = getLineageCodeIdentity(channel);\n if (!identity.verified) {\n const migration = channel === 'dev'\n ? 'Run dev from a Git checkout with npm run lineage:dev -- <command>.'\n : `Install and launch an isolated ${channel} runtime with lineage-channel install ${channel}.`;\n throw new Error(`Unverified ${channel} code origin: ${identity.errors.join('; ')}. ${migration}`);\n }\n return identity;\n}\n\nfunction tableExists(database: DatabaseSync, table: string): boolean {\n return Boolean(database.prepare(\"select name from sqlite_master where type = 'table' and name = ?\").get(table));\n}\n\nfunction tableCount(database: DatabaseSync, table: string): number | undefined {\n if (!tableExists(database, table)) return undefined;\n const row = database.prepare(`select count(*) count from ${table}`).get() as { count?: number } | undefined;\n return typeof row?.count === 'number' ? row.count : undefined;\n}\n\nfunction migrationKeys(database: DatabaseSync): string[] {\n if (!tableExists(database, 'lineage_schema_migrations')) return [];\n return (database.prepare('select key from lineage_schema_migrations order by key').all() as Array<{ key: string }>).map(row => row.key);\n}\n\nexport function getLineageRuntimeInfo(options: { channel?: string; code?: LineageRuntimeCodeIdentity; dbPath?: string } = {}): LineageRuntimeInfo {\n const info = packageInfo();\n const dbPath = options.dbPath || lineageDbPath();\n const channel = normalizeRuntimeChannel(options.channel || process.env.LINEAGE_CHANNEL || process.env.LINEAGE_RELEASE_CHANNEL);\n const code = options.code || getLineageCodeIdentity(channel);\n const databaseInfo: LineageRuntimeInfo['database'] = { exists: existsSync(dbPath), path: dbPath };\n const schema: LineageRuntimeInfo['schema'] = { migration_keys: [] };\n const serviceInstanceId = process.env.LINEAGE_SERVICE_INSTANCE_ID;\n const launcherPid = process.env.LINEAGE_LAUNCHER_PID ? Number(process.env.LINEAGE_LAUNCHER_PID) : undefined;\n const isServiceProcess = Boolean(serviceInstanceId && Number.isInteger(launcherPid) && launcherPid! > 0);\n\n if (databaseInfo.exists) {\n try {\n const stat = statSync(dbPath);\n databaseInfo.modified_at = stat.mtime.toISOString();\n databaseInfo.size_bytes = stat.size;\n const { DatabaseSync } = loadNodeSqlite();\n const database = new DatabaseSync(dbPath, { readOnly: true });\n try {\n databaseInfo.projects = tableCount(database, 'projects');\n databaseInfo.workspaces = tableCount(database, 'lineage_workspaces');\n schema.migration_keys = migrationKeys(database);\n if (tableExists(database, 'lineage_profile_identity')) {\n const columns = new Set((database.prepare('pragma table_info(lineage_profile_identity)').all() as Array<{ name: string }>).map(row => row.name));\n const fingerprintExpression = columns.has('profile_fingerprint') ? 'profile_fingerprint' : \"null as profile_fingerprint\";\n const rows = database.prepare(`select profile_id, environment, ${fingerprintExpression} from lineage_profile_identity`).all() as Array<{\n environment: LineageRuntimeInfo['profile']['environment'];\n profile_fingerprint?: string;\n profile_id: string;\n }>;\n if (rows.length === 1) {\n schema.profile_id = rows[0].profile_id;\n schema.profile_environment = rows[0].environment;\n if (rows[0].profile_fingerprint) schema.profile_fingerprint = rows[0].profile_fingerprint;\n }\n }\n } finally {\n database.close();\n }\n } catch (error) {\n databaseInfo.error = error instanceof Error ? error.message : String(error);\n }\n }\n\n return {\n asset_root: repoRoot,\n channel,\n cli: {\n launcher: lineageCliLauncher(channel),\n runtime_selector: lineageRuntimeSelector(dbPath),\n },\n code,\n database: databaseInfo,\n fetchedAt: nowIso(),\n git_sha: code.git_sha,\n node_env: process.env.NODE_ENV,\n package_name: info.name,\n process: {\n pid: process.pid,\n role: isServiceProcess ? 'service' : 'command',\n started_at: processStartedAt,\n },\n profile: runtimeProfileIdentity(channel),\n schema,\n ...(isServiceProcess ? {\n service: {\n instance_id: serviceInstanceId,\n launcher_pid: launcherPid,\n mode: process.env.LINEAGE_SERVICE_MODE === 'managed' ? 'managed' as const : 'foreground' as const,\n pid: process.pid,\n started_at: processStartedAt,\n },\n } : {}),\n version: info.version,\n };\n}\n", "export type LineageRuntimeChannel = 'stable' | 'preview' | 'dev';\n\nexport const lineageRuntimeBuildSchemaVersion = 'lineage.runtime_build.v1' as const;\nexport const lineageRuntimeInstallSchemaVersion = 'lineage.runtime_install.v1' as const;\n\ntype LineageRuntimeEnvironment = 'production' | 'preview' | 'development';\n\ninterface LineageRuntimeDatabaseInfo {\n error?: string;\n exists: boolean;\n modified_at?: string;\n path: string;\n projects?: number;\n size_bytes?: number;\n workspaces?: number;\n}\n\ninterface LineageRuntimeProfileInfo {\n bound: boolean;\n environment: LineageRuntimeEnvironment;\n fingerprint?: string;\n id: string;\n manifest_path?: string;\n service_origin?: string;\n warning?: string;\n}\n\ninterface LineageRuntimeSchemaInfo {\n migration_keys: string[];\n profile_environment?: LineageRuntimeEnvironment;\n profile_fingerprint?: string;\n profile_id?: string;\n}\n\nexport interface LineageRuntimeBuildIdentity {\n build_fingerprint: string;\n package_name: string;\n package_version: string;\n schema_version: typeof lineageRuntimeBuildSchemaVersion;\n source_dirty: boolean;\n source_fingerprint: string;\n source_git_sha: string;\n}\n\nexport interface LineageRuntimeInstallReceipt {\n build_fingerprint: string;\n channel: Exclude<LineageRuntimeChannel, 'dev'>;\n installed_at: string;\n package_integrity: string;\n package_name: string;\n package_root: string;\n package_source: 'local' | 'registry';\n package_spec: string;\n package_tree_sha256: string;\n package_version: string;\n schema_version: typeof lineageRuntimeInstallSchemaVersion;\n}\n\nexport interface LineageRuntimeCodeIdentity {\n build?: LineageRuntimeBuildIdentity;\n channel: LineageRuntimeChannel;\n dirty?: boolean;\n errors: string[];\n fingerprint: string;\n git_sha?: string;\n install?: LineageRuntimeInstallReceipt & { receipt_path: string };\n origin: 'checkout' | 'package' | 'unknown';\n package_version: string;\n root: string;\n source_fingerprint?: string;\n verified: boolean;\n}\n\nexport interface LineageRuntimeInfo {\n asset_root: string;\n channel: LineageRuntimeChannel;\n cli: {\n launcher: string;\n runtime_selector: string;\n };\n code?: LineageRuntimeCodeIdentity;\n database: LineageRuntimeDatabaseInfo;\n fetchedAt: string;\n git_sha?: string;\n node_env?: string;\n package_name: string;\n process?: {\n pid: number;\n role: 'command' | 'service';\n started_at: string;\n };\n profile: LineageRuntimeProfileInfo;\n schema: LineageRuntimeSchemaInfo;\n service?: {\n instance_id?: string;\n mode: 'foreground' | 'managed';\n launcher_pid?: number;\n pid: number;\n started_at: string;\n };\n version: string;\n}\n", "import type express from 'express';\nimport type { LineageRuntimeChannel } from '../shared/runtimeInfoTypes';\nimport type { ResolvedLineageProfile } from '../shared/lineageProfileTypes';\nimport { AgentClaimError, type AgentClaim } from './agentClaims';\nimport type { ProfileWriterLease } from './profileWriterLease';\nimport { getProfileWriterDelegation } from './profileWriterLease';\n\nexport const managedWriterRequestSchemaVersion = 'lineage.managed_writer_request.v1' as const;\nconst managedWriterResponseSchemaVersion = 'lineage.managed_writer_response.v1' as const;\nexport const managedWriterRoute = '/api/managed-writer/execute' as const;\nconst delegationHeader = 'X-Lineage-Writer-Delegation';\n\ninterface ManagedWriterIdentity {\n channel: LineageRuntimeChannel;\n environment: ResolvedLineageProfile['environment'];\n profile_id: string;\n service_origin: string;\n}\n\ninterface ManagedWriterRequest {\n args: string[];\n channel: LineageRuntimeChannel;\n command: string;\n environment: ResolvedLineageProfile['environment'];\n profile_id: string;\n schema_version: typeof managedWriterRequestSchemaVersion;\n service_origin: string;\n}\n\ninterface ManagedWriterResponse {\n ok: true;\n result: unknown;\n schema_version: typeof managedWriterResponseSchemaVersion;\n service: ManagedWriterIdentity;\n}\n\nexport class ManagedWriterRoutingError extends Error {\n constructor(message: string, public readonly status = 409, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ManagedWriterRoutingError';\n }\n}\n\nexport function isManagedWriterRoutingError(error: unknown): error is ManagedWriterRoutingError {\n return error instanceof ManagedWriterRoutingError;\n}\n\nexport function managedWriterTimeoutMs(command: string, args: string[]): number {\n const positions = args.filter(arg => !arg.startsWith('-'));\n const slowImport = (command === 'reroll' && positions[0] === 'import')\n || (command === 'generate' && positions[0] === 'image' && positions[1] === 'import');\n return slowImport ? 5 * 60_000 : 30_000;\n}\n\nfunction requestBody(value: unknown): ManagedWriterRequest {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ManagedWriterRoutingError('Managed writer request must be a JSON object', 400);\n }\n const body = value as Partial<ManagedWriterRequest>;\n if (body.schema_version !== managedWriterRequestSchemaVersion) {\n throw new ManagedWriterRoutingError(`Unsupported managed writer request schema: ${String(body.schema_version)}`, 400);\n }\n if (typeof body.command !== 'string' || !body.command || !Array.isArray(body.args) || body.args.some(arg => typeof arg !== 'string')) {\n throw new ManagedWriterRoutingError('Managed writer request requires a command and string args', 400);\n }\n if (\n typeof body.profile_id !== 'string'\n || typeof body.channel !== 'string'\n || typeof body.environment !== 'string'\n || typeof body.service_origin !== 'string'\n ) {\n throw new ManagedWriterRoutingError('Managed writer request requires profile identity', 400);\n }\n return body as ManagedWriterRequest;\n}\n\nfunction containsProtectedOverride(args: string[]): boolean {\n return args.some(arg => arg === '--db' || arg.startsWith('--db=')\n || arg === '--asset-root' || arg.startsWith('--asset-root=')\n || arg === '--profile' || arg.startsWith('--profile='));\n}\n\nexport function registerManagedWriterRoute(\n app: express.Express,\n fields: {\n channel: LineageRuntimeChannel;\n accepts: (command: string, args: string[]) => boolean;\n execute: (command: string, args: string[]) => unknown;\n profile?: ResolvedLineageProfile;\n writerLease?: ProfileWriterLease;\n },\n): void {\n app.post(managedWriterRoute, (req, res, next) => {\n try {\n if (!fields.profile || !fields.writerLease) {\n throw new ManagedWriterRoutingError('Managed writer delegation is unavailable for an unprofiled service', 404);\n }\n if (!fields.writerLease.authenticate(req.header(delegationHeader))) {\n throw new ManagedWriterRoutingError('Managed writer delegation was not authorized', 401);\n }\n const body = requestBody(req.body);\n if (\n body.profile_id !== fields.profile.profile_id\n || body.channel !== fields.channel\n || body.environment !== fields.profile.environment\n || body.service_origin !== fields.profile.service_origin\n ) {\n throw new ManagedWriterRoutingError('Managed writer request profile/service identity does not match this service', 409);\n }\n if (containsProtectedOverride(body.args)) {\n throw new ManagedWriterRoutingError('Managed writer requests cannot override profile, database, or asset root', 400);\n }\n if (!fields.accepts(body.command, body.args)) {\n throw new ManagedWriterRoutingError(`Unsupported managed writer command: ${body.command}`, 400);\n }\n const result = fields.execute(body.command, body.args);\n const response: ManagedWriterResponse = {\n ok: true,\n result,\n schema_version: managedWriterResponseSchemaVersion,\n service: {\n channel: fields.channel,\n environment: fields.profile.environment,\n profile_id: fields.profile.profile_id,\n service_origin: fields.profile.service_origin,\n },\n };\n res.json(response);\n } catch (error) {\n next(error);\n }\n });\n}\n\nfunction errorMessage(body: unknown, fallback: string): string {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return fallback;\n const record = body as Record<string, unknown>;\n if (typeof record.message === 'string') return record.message;\n if (typeof record.error === 'string') return record.error;\n return fallback;\n}\n\nfunction agentClaimError(body: unknown, status: number): AgentClaimError | undefined {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return undefined;\n const record = body as Record<string, unknown>;\n if (typeof record.message !== 'string' || typeof record.error !== 'string') return undefined;\n const conflicts = Array.isArray(record.conflicts) ? record.conflicts as AgentClaim[] : [];\n return new AgentClaimError(record.message, status, record.error, conflicts);\n}\n\nfunction assertResponseIdentity(\n body: unknown,\n profile: ResolvedLineageProfile,\n channel: LineageRuntimeChannel,\n): asserts body is ManagedWriterResponse {\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n throw new ManagedWriterRoutingError('Managed writer service returned a non-object response', 502);\n }\n const response = body as Partial<ManagedWriterResponse>;\n if (\n response.ok !== true\n || response.schema_version !== managedWriterResponseSchemaVersion\n || !response.service\n || response.service.profile_id !== profile.profile_id\n || response.service.environment !== profile.environment\n || response.service.service_origin !== profile.service_origin\n || response.service.channel !== channel\n ) {\n throw new ManagedWriterRoutingError('Managed writer response identity does not match the selected profile/service', 502);\n }\n}\n\nexport async function executeManagedWriterCommand(\n profile: ResolvedLineageProfile,\n channel: LineageRuntimeChannel,\n command: string,\n args: string[],\n): Promise<unknown> {\n const delegation = getProfileWriterDelegation(profile);\n let response: Response;\n try {\n response = await fetch(new URL(managedWriterRoute, delegation.service_origin), {\n body: JSON.stringify({\n args,\n channel,\n command,\n environment: profile.environment,\n profile_id: profile.profile_id,\n schema_version: managedWriterRequestSchemaVersion,\n service_origin: profile.service_origin,\n } satisfies ManagedWriterRequest),\n headers: {\n 'Content-Type': 'application/json',\n [delegationHeader]: delegation.token,\n },\n method: 'POST',\n redirect: 'error',\n signal: AbortSignal.timeout(managedWriterTimeoutMs(command, args)),\n });\n } catch (error) {\n throw new ManagedWriterRoutingError(\n `Managed service for Lineage profile ${profile.profile_id} is unavailable or did not respond at ${profile.service_origin}; no direct fallback was attempted and the mutation outcome is unknown`,\n 503,\n { cause: error },\n );\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new ManagedWriterRoutingError('Managed writer service returned invalid JSON; mutation result is unknown', 502, { cause: error });\n }\n if (!response.ok) {\n const claimError = agentClaimError(body, response.status);\n if (claimError) throw claimError;\n throw new ManagedWriterRoutingError(errorMessage(body, `Managed writer service returned HTTP ${response.status}`), response.status);\n }\n assertResponseIdentity(body, profile, channel);\n return body.result;\n}\n", "#!/usr/bin/env node\n\nimport { runLineageCli } from './lineageCli';\n\nawait runLineageCli({\n binName: 'lineage-preview',\n channel: 'preview',\n defaultHost: 'lineage-preview.localhost',\n defaultPort: 5199,\n displayName: 'Lineage Preview',\n});\n"],
|
|
5
|
+
"mappings": ";;;AAAA,SAAS,cAAAA,cAAY,aAAAC,YAAW,gBAAAC,eAAc,iBAAAC,sBAAqB;AACnE,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,WAAAC,UAAS,YAAAC,iBAAgB;AAClC,SAAS,WAAAC,UAAS,QAAAC,QAAM,WAAAC,gBAAe;AACvC,SAAS,aAAa;AACtB,SAAS,iBAAAC,sBAAqB;;;ACLvB,IAAM,uBAAuB;AAI7B,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YACkB,MAChB,SACA;AACA,UAAM,OAAO;AAHG;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;AAEO,SAAS,qBAAqB,OAAoC;AACvE,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,OAAM,IAAI,2BAA2B,YAAY,2BAA2B;AAC3G,QAAM,QAAQ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iB,cAAc,QAAQA,KAAI;AAAA,IAC7C,SAAS,OAAO;AACd,YAAMC,WAAU,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAC7F,UAAID,OAAM;AACR,cAAM,SAAS,kBAAkB,KAAK,IAClC,EAAE,IAAI,OAAO,SAAS,SAAS,YAAY,IAAI,OAAO,MAAM,MAAM,SAAAC,UAAS,WAAW,MAAM,UAAU,IACtG,EAAE,IAAI,OAAO,SAAS,SAAS,YAAY,IAAI,OAAOA,SAAQ;AAClE,gBAAQ,MAAM,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,MAC/C,OAAO;AACL,gBAAQ,MAAM,GAAG,OAAO,OAAO,KAAKA,QAAO,EAAE;AAAA,MAC/C;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,OAAO,KAAK,SAAS,QAAQ;AACnC,QAAM,UAAU,oBAAoB,OAAO;AAC3C,MAAI,KAAM,SAAQ,MAAM,KAAK,UAAU,EAAE,IAAI,OAAO,SAAS,OAAO,QAAQ,GAAG,MAAM,CAAC,CAAC;AAAA,MAClF,SAAQ,MAAM,GAAG,OAAO,OAAO,KAAK,OAAO,EAAE;AAClD,UAAQ,KAAK,CAAC;AAChB;;;AwB1zCA,MAAM,cAAc;AAAA,EAClB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AACf,CAAC;",
|
|
6
|
+
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "randomUUID", "homedir", "platform", "dirname", "join", "resolve", "fileURLToPath", "createHash", "timingSafeEqual", "existsSync", "mkdirSync", "join", "existsSync", "mkdirSync", "readdirSync", "readFileSync", "dirname", "join", "resolve", "existsSync", "statSync", "basename", "join", "repoRoot", "repoRoot", "existsSync", "join", "basename", "statSync", "join", "existsSync", "packageInfo", "readFileSync", "dirname", "resolve", "join", "existsSync", "existsSync", "readFileSync", "mkdirSync", "dirname", "start", "createHash", "randomUUID", "existsSync", "lstatSync", "mkdirSync", "readFileSync", "renameSync", "rmSync", "writeFileSync", "dirname", "join", "resolve", "createHash", "chmodSync", "copyFileSync", "existsSync", "mkdirSync", "readFileSync", "statSync", "writeFileSync", "dirname", "join", "relative", "resolve", "require", "resolve", "join", "record", "dirname", "existsSync", "readFileSync", "createHash", "mkdirSync", "writeFileSync", "statSync", "chmodSync", "existsSync", "resolve", "mkdirSync", "dirname", "join", "chmodSync", "writeFileSync", "relative", "fileSha256", "createHash", "readFileSync", "statSync", "copyFileSync", "join", "dirname", "lstatSync", "readFileSync", "mkdirSync", "writeFileSync", "rmSync", "createHash", "renameSync", "randomUUID", "resolve", "existsSync", "join", "existsSync", "mkdirSync", "createHash", "timingSafeEqual", "claim", "isAbsolute", "join", "resolve", "randomBytes", "randomId", "randomBytes", "metadataJson", "parseMetadata", "recordEvent", "timestamp", "ensureProject", "ensureProject", "channelOverlaps", "isAbsolute", "resolve", "join", "requireAsset", "canonicalRoot", "requireAsset", "requireAsset", "requireAsset", "existsSync", "createRequire", "join", "require", "createRequire", "join", "existsSync", "existsSync", "realpathSync", "statSync", "relative", "resolve", "randomUUID", "value", "randomUUID", "relative", "resolve", "existsSync", "realpathSync", "statSync", "createHash", "existsSync", "statSync", "isAbsolute", "resolve", "isAbsolute", "resolve", "existsSync", "statSync", "createHash", "createHash", "spawnSync", "existsSync", "lstatSync", "readFileSync", "readdirSync", "realpathSync", "statSync", "dirname", "isAbsolute", "join", "resolve", "fileURLToPath", "readFileSync", "join", "dirname", "fileURLToPath", "resolve", "sha256", "createHash", "realpathSync", "spawnSync", "lstatSync", "isAbsolute", "readdirSync", "existsSync", "tableExists", "statSync", "record", "packageRoot", "resolve", "dirname", "fileURLToPath", "packageInfo", "readFileSync", "join", "platform", "homedir", "mkdirSync", "writeFileSync", "jobId", "join", "packageRoot", "existsSync", "mkdirSync", "dirname", "randomUUID", "code", "json", "message"]
|
|
7
7
|
}
|