@bastani/atomic 0.9.83 → 0.9.84-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/package.json +1 -1
  7. package/dist/cli/storage-command.d.ts +12 -1
  8. package/dist/cli/storage-command.d.ts.map +1 -1
  9. package/dist/cli/storage-command.js +210 -47
  10. package/dist/cli/storage-command.js.map +1 -1
  11. package/dist/core/session-transfer.d.ts +84 -0
  12. package/dist/core/session-transfer.d.ts.map +1 -0
  13. package/dist/core/session-transfer.js +270 -0
  14. package/dist/core/session-transfer.js.map +1 -0
  15. package/dist/core/storage/journal-transfer.d.ts +74 -35
  16. package/dist/core/storage/journal-transfer.d.ts.map +1 -1
  17. package/dist/core/storage/journal-transfer.js +384 -278
  18. package/dist/core/storage/journal-transfer.js.map +1 -1
  19. package/dist/core/storage/transfer-files.d.ts +75 -0
  20. package/dist/core/storage/transfer-files.d.ts.map +1 -0
  21. package/dist/core/storage/transfer-files.js +170 -0
  22. package/dist/core/storage/transfer-files.js.map +1 -0
  23. package/dist/core/storage-transfer.d.ts +30 -0
  24. package/dist/core/storage-transfer.d.ts.map +1 -0
  25. package/dist/core/storage-transfer.js +49 -0
  26. package/dist/core/storage-transfer.js.map +1 -0
  27. package/dist/modes/interactive-engine/isolated-runtime.d.ts +7 -0
  28. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  29. package/dist/modes/interactive-engine/isolated-runtime.js +21 -1
  30. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  31. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  32. package/dist/modes/rpc/rpc-command-handler.js +1 -0
  33. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  34. package/docs/reference/cli.md +31 -3
  35. package/docs/storage.md +81 -17
  36. package/npm-shrinkwrap.json +38 -38
  37. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"storage-command.js","sourceRoot":"","sources":["../../src/cli/storage-command.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC9G,OAAO,EACN,aAAa,EACb,uBAAuB,EACvB,4BAA4B,GAC5B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACN,kBAAkB,EAClB,kBAAkB,EAClB,0BAA0B,EAC1B,2BAA2B,GAE3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACN,YAAY,EACZ,SAAS,EACT,sBAAsB,EACtB,gBAAgB,EAChB,kBAAkB,GAClB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,oBAAoB,EAEpB,oBAAoB,EACpB,wBAAwB,EACxB,yBAAyB,GAEzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,CAAC;AAEtD,MAAM,IAAI,GAAG;IACT,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;;;;;;;;;kBASM,sBAAsB;;;;;;;;;;;;;aAa3B,2BAA2B;;;;;;;;;;;;;;;6DAeqB,CAAC;AAE9D,MAAM,SAAS,GAAG,QAAQ,QAAQ,6BAA6B,CAAC;AAiBhE,MAAM,OAAO,mBAAoB,SAAQ,KAAK;CAAG;AAEjD,2CAA2C;AAC3C,MAAM,UAAU,mBAAmB,CAAC,IA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Aa,MAAM,CAAC,SAAS,CAAC,MAAM,uBAAuB,CAC5L,CAAC;IACF,OAAO,CAAC,CAAC;AACV,CAAC","sourcesContent":["/**\n * `atomic storage status` shows which storage each domain (sessions, workflow runs, Intercom) selects, where the\n * selection comes from, whether its adapter loads and its database answers, and what the running Intercom broker\n * uses. `atomic storage join` points this machine's global `storage` setting at a shared libSQL / Turso database.\n * `atomic storage adopt` registers existing journal files in the journal store in place, and `atomic storage\n * consolidate` moves their finished runs into the store's own shards. `atomic storage export` and `atomic storage\n * import` move workflow runs between the local workflow journal and versioned JSONL files (#4716).\n */\n\nimport { join, resolve } from \"node:path\";\nimport { APP_NAME } from \"../config.js\";\nimport type { IntercomBrokerControl } from \"../core/intercom-broker-control.js\";\nimport { isJournalStoreError, isTeamProfileConfigError, isTeamProfileError } from \"../core/storage/errors.js\";\nimport {\n\tadoptJournals,\n\tconsolidateJournalStore,\n\tdefaultJournalStoreDirectory,\n} from \"../core/storage/journal-adoption.js\";\nimport {\n\texportWorkflowRuns,\n\timportWorkflowRuns,\n\tisWorkflowRunTransferError,\n\tWORKFLOW_RUN_EXPORT_VERSION,\n\ttype WorkflowRunTransferStorage,\n} from \"../core/storage/journal-transfer.js\";\nimport {\n\tcheckTeamUrl,\n\tisFileUrl,\n\tLIBSQL_ADAPTER_PACKAGE,\n\tmissingTeamToken,\n\tSTORAGE_TOKEN_FILE,\n} from \"../core/storage/selection.js\";\nimport {\n\tcollectStorageStatus,\n\ttype DomainStatus,\n\tdescribeStorageError,\n\tdescribeStorageSelection,\n\teffectiveJournalSelection,\n\ttype StorageStatus,\n} from \"../core/storage/storage-status.js\";\nimport { joinSharedDatabase } from \"../core/storage/team.js\";\n\nexport { LIBSQL_ADAPTER_PACKAGE, STORAGE_TOKEN_FILE };\n\nconst HELP = `Usage:\n ${APP_NAME} storage status [--json]\n ${APP_NAME} storage join <url> [--token-file <path>] [--prefix <prefix>]\n ${APP_NAME} storage adopt <path>... [--no-discover]\n ${APP_NAME} storage consolidate\n ${APP_NAME} storage export <dir> [--run <id>]... [--unfinished] [--limit <n>]\n ${APP_NAME} storage import <dir>\n\nCommands:\n status Show, for sessions, workflow runs, and Intercom, the selected storage and where the\n selection comes from (environment variable, project or global settings, or default),\n whether its adapter loads, whether its database answers a SELECT 1, and what the running\n Intercom broker uses. Exits 1 when a selection is invalid, an adapter cannot load, or a\n database does not answer. Nothing is created or changed.\n join Use a shared libSQL / Turso database on this machine: check the token and the connection\n with ${LIBSQL_ADAPTER_PACKAGE}, store the token in the agent directory (mode 600), and\n write only the global \\`storage\\` setting. Reports environment variables and settings that\n override it. Creates no tables; Atomic creates them on first use.\n adopt Register existing workflow journal files in the journal store in place, without copying,\n so their runs resolve by ID for status, resume, attach, fork and history://. Each <path>\n is a journal .sqlite file or a directory holding journal.sqlite. Every path is checked\n before the first is registered. Journals the adopted runs were written to are adopted\n too unless --no-discover is given.\n consolidate\n Move finished runs (completed, failed or cancelled, not leased, without local workers)\n from adopted journals into the journal store's own shards. Other runs stay where they\n are. An interrupted consolidation leaves every run readable; run it again to finish.\n export Write workflow runs to <dir>/<runId>.jsonl, one file per run (format version\n ${WORKFLOW_RUN_EXPORT_VERSION}): a header line, then one line per journal event. Every run by default;\n a file is replaced whole, and one that already holds the same run is not rewritten.\n import Restore every *.jsonl export in <dir> into this directory's workflow journal. All files\n are checked first, so a malformed or unsupported file changes nothing. Importing again\n adds nothing; a newer export of a run adds its later events. Imported runs are not\n owned by any process: an interrupted one can be resumed here.\n\nOptions:\n --json Print the status as JSON\n --token-file <path> File holding the database token, for example from \\`turso db tokens create\\`;\n surrounding whitespace is removed. Required except for file: URLs\n --prefix <prefix> Table prefix, to share one database between projects or teams\n --no-discover adopt: register only the given paths\n --run <id> export: only this run; repeat for more\n --unfinished export: only runs that are not completed, failed or cancelled\n --limit <n> export: at most n runs, newest first`;\n\nconst HELP_HINT = `Use \"${APP_NAME} storage --help\" for usage.`;\n\nexport type StorageCommand =\n\t| { readonly kind: \"help\" }\n\t| { readonly kind: \"status\"; readonly json: boolean }\n\t| { readonly kind: \"join\"; readonly url: string; readonly tokenFile?: string; readonly prefix?: string }\n\t| { readonly kind: \"adopt\"; readonly paths: readonly string[]; readonly discover: boolean }\n\t| { readonly kind: \"consolidate\" }\n\t| {\n\t\t\treadonly kind: \"export\";\n\t\t\treadonly directory: string;\n\t\t\treadonly runs?: readonly string[];\n\t\t\treadonly unfinished: boolean;\n\t\t\treadonly limit?: number;\n\t }\n\t| { readonly kind: \"import\"; readonly directory: string };\n\nexport class StorageCommandError extends Error {}\n\n/** Parse the arguments after `storage`. */\nexport function parseStorageCommand(args: readonly string[]): StorageCommand {\n\tconst [command, ...rest] = args;\n\tif (command === undefined || command === \"help\" || args.includes(\"--help\") || args.includes(\"-h\")) {\n\t\treturn { kind: \"help\" };\n\t}\n\tconst positional: string[] = [];\n\tconst values = new Map<string, string>();\n\tlet json = false;\n\tlet discover = true;\n\tlet unfinished = false;\n\tconst runs: string[] = [];\n\tfor (let index = 0; index < rest.length; index++) {\n\t\tconst arg = rest[index]!;\n\t\tif (command === \"status\" && arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (command === \"adopt\" && arg === \"--no-discover\") {\n\t\t\tdiscover = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (command === \"export\" && arg === \"--unfinished\") {\n\t\t\tunfinished = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (command === \"export\" && arg === \"--run\") {\n\t\t\tconst value = rest[++index];\n\t\t\tif (value === undefined || value === \"\") throw new StorageCommandError(\"--run needs a run ID.\");\n\t\t\truns.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\t(command === \"join\" && (arg === \"--token-file\" || arg === \"--prefix\")) ||\n\t\t\t(command === \"export\" && arg === \"--limit\")\n\t\t) {\n\t\t\tconst value = rest[++index];\n\t\t\tif (value === undefined) throw new StorageCommandError(`${arg} needs a value.`);\n\t\t\tvalues.set(arg, value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg.startsWith(\"-\"))\n\t\t\tthrow new StorageCommandError(`Unknown option ${arg} for \"storage ${command}\".\\n${HELP_HINT}`);\n\t\tpositional.push(arg);\n\t}\n\tif (command === \"status\") {\n\t\tif (positional.length > 0) throw new StorageCommandError(`Usage: ${APP_NAME} storage status [--json]`);\n\t\treturn { kind: \"status\", json };\n\t}\n\tif (command === \"join\") {\n\t\tconst [url, ...extra] = positional;\n\t\tif (url === undefined || extra.length > 0) {\n\t\t\tthrow new StorageCommandError(\n\t\t\t\t`Usage: ${APP_NAME} storage join <url> [--token-file <path>] [--prefix <prefix>]`,\n\t\t\t);\n\t\t}\n\t\tcheckTeamUrl(url, \"cli\");\n\t\tconst tokenFile = values.get(\"--token-file\");\n\t\tif (tokenFile === undefined && !isFileUrl(url)) throw missingTeamToken(url, \"cli\");\n\t\tconst prefix = values.get(\"--prefix\");\n\t\treturn {\n\t\t\tkind: \"join\",\n\t\t\turl,\n\t\t\t...(tokenFile === undefined ? {} : { tokenFile }),\n\t\t\t...(prefix === undefined ? {} : { prefix }),\n\t\t};\n\t}\n\tif (command === \"adopt\") {\n\t\tif (positional.length === 0)\n\t\t\tthrow new StorageCommandError(`Usage: ${APP_NAME} storage adopt <path>... [--no-discover]`);\n\t\treturn { kind: \"adopt\", paths: positional, discover };\n\t}\n\tif (command === \"consolidate\") {\n\t\tif (positional.length > 0) throw new StorageCommandError(`Usage: ${APP_NAME} storage consolidate`);\n\t\treturn { kind: \"consolidate\" };\n\t}\n\tif (command === \"export\") {\n\t\tconst [directory, ...extra] = positional;\n\t\tif (directory === undefined || extra.length > 0)\n\t\t\tthrow new StorageCommandError(\n\t\t\t\t`Usage: ${APP_NAME} storage export <dir> [--run <id>]... [--unfinished] [--limit <n>]`,\n\t\t\t);\n\t\tconst limitText = values.get(\"--limit\");\n\t\tconst limit = limitText === undefined ? undefined : Number(limitText);\n\t\tif (limit !== undefined && (!/^[0-9]+$/.test(limitText!) || !Number.isSafeInteger(limit) || limit < 1))\n\t\t\tthrow new StorageCommandError(`--limit needs a positive whole number, not \"${limitText}\".`);\n\t\treturn {\n\t\t\tkind: \"export\",\n\t\t\tdirectory,\n\t\t\tunfinished,\n\t\t\t...(runs.length === 0 ? {} : { runs }),\n\t\t\t...(limit === undefined ? {} : { limit }),\n\t\t};\n\t}\n\tif (command === \"import\") {\n\t\tconst [directory, ...extra] = positional;\n\t\tif (directory === undefined || extra.length > 0)\n\t\t\tthrow new StorageCommandError(`Usage: ${APP_NAME} storage import <dir>`);\n\t\treturn { kind: \"import\", directory };\n\t}\n\tthrow new StorageCommandError(`Unknown storage command \"${command}\".\\n${HELP_HINT}`);\n}\n\nexport interface StorageCommandOptions {\n\treadonly cwd: string;\n\treadonly agentDir: string;\n\treadonly log?: (line: string) => void;\n\treadonly error?: (line: string) => void;\n\t/** Defaults to the bundled Intercom package's broker control. */\n\treadonly loadControl?: () => Promise<IntercomBrokerControl>;\n}\n\nconst errorText = describeStorageError;\n\n/** The bundled Intercom package's broker control, or why it could not load. */\nexport async function loadBrokerControl(options: {\n\treadonly loadControl?: () => Promise<IntercomBrokerControl>;\n}): Promise<IntercomBrokerControl | Error> {\n\ttry {\n\t\tif (options.loadControl) return await options.loadControl();\n\t\tconst { loadIntercomBrokerControl } = await import(\"../core/intercom-broker-control.js\");\n\t\treturn await loadIntercomBrokerControl();\n\t} catch (error) {\n\t\treturn error instanceof Error ? error : new Error(String(error));\n\t}\n}\n\n/** Whether a domain's selection is invalid, its adapter cannot load, or its database did not answer. */\nexport function failed(domain: DomainStatus): boolean {\n\treturn (\n\t\tdomain.error !== undefined ||\n\t\tdomain.probe?.adapter?.loaded === false ||\n\t\tdomain.probe?.connection.status === \"failed\" ||\n\t\t(domain.journalStore?.unavailable.length ?? 0) > 0\n\t);\n}\n\nconst DOMAIN_LABELS: Record<DomainStatus[\"domain\"], string> = {\n\tsessions: \"Sessions\",\n\tjournal: \"Workflow runs\",\n\tintercom: \"Intercom\",\n};\n\n/** The status as the lines `atomic storage status` prints. */\nexport function formatStorageStatus(status: StorageStatus): string[] {\n\tconst lines = [\n\t\t`Agent directory: ${status.agentDir}`,\n\t\t`Project: ${status.cwd}${status.projectTrusted ? \"\" : \" (not trusted)\"}`,\n\t];\n\tfor (const domain of status.domains) {\n\t\tlines.push(\"\", `${DOMAIN_LABELS[domain.domain]}: ${domain.selection}`);\n\t\tlines.push(` source: ${domain.source}`);\n\t\tif (domain.overridden.length > 0) lines.push(` overrides: ${domain.overridden.join(\", \")}`);\n\t\tif (domain.error !== undefined) lines.push(` error: ${domain.error}`);\n\t\tconst probe = domain.probe;\n\t\tif (probe?.sameAs !== undefined) {\n\t\t\tlines.push(` connection: same as ${DOMAIN_LABELS[probe.sameAs].toLowerCase()}`);\n\t\t} else if (probe !== undefined) {\n\t\t\tif (probe.adapter !== undefined) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` adapter: ${probe.adapter.loaded ? \"loaded\" : \"failed to load\"}${probe.adapter.detail === undefined ? \"\" : ` (${probe.adapter.detail})`}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlines.push(` connection: ${probe.connection.status} (${probe.connection.detail})`);\n\t\t}\n\t\tif (domain.multiNode !== undefined) lines.push(` multi-node: ${domain.multiNode}`);\n\t\tif (domain.liveBrokers !== undefined) {\n\t\t\tlines.push(\n\t\t\t\t` brokers: ${domain.liveBrokers.length} live in the database${domain.liveBrokers.length === 0 ? \"\" : ` (${[...new Set(domain.liveBrokers)].join(\", \")})`}`,\n\t\t\t);\n\t\t}\n\t\tconst store = domain.journalStore;\n\t\tif (store !== undefined) {\n\t\t\tlines.push(\n\t\t\t\t` journals: ${store.shards} shard${store.shards === 1 ? \"\" : \"s\"}, ${store.adopted} adopted journal${store.adopted === 1 ? \"\" : \"s\"}, ${store.runs} run${store.runs === 1 ? \"\" : \"s\"}`,\n\t\t\t);\n\t\t\tfor (const shard of store.unavailable)\n\t\t\t\tlines.push(\n\t\t\t\t\t` unavailable: ${shard.path} (${shard.kind}, ${shard.code === \"shard-missing\" ? \"no longer exists\" : \"cannot be opened\"}: ${shard.code}${shard.detail === undefined ? \"\" : `, ${shard.detail}`})`,\n\t\t\t\t);\n\t\t\tfor (const skipped of store.skipped) lines.push(` skipped: ${skipped.path} (${skipped.reason})`);\n\t\t}\n\t}\n\tconst broker = status.broker;\n\tif (broker !== undefined) {\n\t\tlines.push(\"\");\n\t\tif (broker.state === \"stopped\") {\n\t\t\tlines.push(\n\t\t\t\t\"Intercom broker: not running (the next session that uses Intercom starts one with the selection above)\",\n\t\t\t);\n\t\t} else if (broker.state === \"unknown\") {\n\t\t\tlines.push(`Intercom broker: unknown (${broker.error ?? \"no answer\"})`);\n\t\t} else if (broker.state === \"legacy\") {\n\t\t\tlines.push(\n\t\t\t\t`Intercom broker: running${broker.pid === undefined ? \"\" : ` (pid ${broker.pid})`}, started by an older Atomic that does not report its storage; run \\`${APP_NAME} intercom restart\\``,\n\t\t\t);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t`Intercom broker: running (pid ${broker.pid}, ${broker.sessions} session${broker.sessions === 1 ? \"\" : \"s\"} connected)`,\n\t\t\t);\n\t\t\tlines.push(\n\t\t\t\tbroker.matchesCurrent\n\t\t\t\t\t? \" storage: matches the selection above\"\n\t\t\t\t\t: ` storage: differs from the selection above${broker.source === \"env\" ? \" (a session started it with ATOMIC_STORAGE, ATOMIC_PROFILE=ci or --storage)\" : \"\"}; run \\`${APP_NAME} intercom restart\\` to use the current one`,\n\t\t\t);\n\t\t\tif (broker.multiNodeLine !== undefined) lines.push(` multi-node: ${broker.multiNodeLine}`);\n\t\t}\n\t}\n\tif (status.notes.length > 0) lines.push(\"\", \"Notes:\", ...status.notes.map((note) => ` - ${note}`));\n\treturn lines;\n}\n\nasync function status(json: boolean, options: StorageCommandOptions, log: (line: string) => void): Promise<number> {\n\tconst control = await loadBrokerControl(options);\n\tconst collected = await collectStorageStatus({\n\t\tcwd: options.cwd,\n\t\tagentDir: options.agentDir,\n\t\tprobe: true,\n\t\t...(control instanceof Error ? {} : { control }),\n\t});\n\tconst result: StorageStatus =\n\t\tcontrol instanceof Error ? { ...collected, broker: { state: \"unknown\", error: errorText(control) } } : collected;\n\tif (json) log(JSON.stringify(result, null, 2));\n\telse for (const line of formatStorageStatus(result)) log(line);\n\treturn result.domains.some(failed) ? 1 : 0;\n}\n\nasync function joinStorage(\n\tcommand: Extract<StorageCommand, { kind: \"join\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (...lines: string[]) => void,\n): Promise<number> {\n\tconst { agentDir, cwd } = options;\n\tconst joined = await joinSharedDatabase({ ...command, agentDir, cwd, pinLocalSessions: false }, \"cli\");\n\tlog(`Connected to ${command.url}.`);\n\tif (joined.tokenPath !== undefined) {\n\t\tlog(\n\t\t\tjoined.token === \"reused\"\n\t\t\t\t? `Kept the token in ${joined.tokenPath}; it already holds this token.`\n\t\t\t\t: `Stored the token in ${joined.tokenPath} (mode 600).`,\n\t\t);\n\t}\n\tlog(`Set \\`storage\\` in ${join(agentDir, \"settings.json\")}; other settings are unchanged.`);\n\tif (joined.replaced !== undefined) log(`It replaces the previous selection: ${joined.replaced}.`);\n\n\tconst control = await loadBrokerControl(options);\n\tlet collected: StorageStatus;\n\ttry {\n\t\tcollected = await collectStorageStatus({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tprobe: false,\n\t\t\t...(control instanceof Error ? {} : { control }),\n\t\t});\n\t} catch (error) {\n\t\t// Settings and the token are already committed; optional diagnostics cannot undo that success.\n\t\tlog(`Storage was saved, but could not report overrides: ${errorText(error as Error)}.`);\n\t\tlog(`Run \\`${APP_NAME} storage status\\` after fixing the reported settings error.`);\n\t\treturn 0;\n\t}\n\tconst overridden = collected.domains.filter(\n\t\t(domain) => domain.source !== \"global settings: storage\" && domain.source !== \"default\",\n\t);\n\tif (overridden.length > 0) {\n\t\tlog(\"\", \"These take precedence over the new selection here:\");\n\t\tfor (const domain of overridden) log(` - ${DOMAIN_LABELS[domain.domain]}: ${domain.source}`);\n\t}\n\tfor (const note of collected.notes) log(`Note: ${note}`);\n\tconst broker = collected.broker;\n\tif (broker?.state === \"running\" && !broker.matchesCurrent) {\n\t\tlog(\n\t\t\t`The running Intercom broker (pid ${broker.pid}) still uses its previous selection. Run \\`${APP_NAME} intercom restart\\` so it uses the new one.`,\n\t\t);\n\t} else if (broker?.state === \"legacy\") {\n\t\tlog(\n\t\t\t`An Intercom broker from an older ${APP_NAME} is running. Run \\`${APP_NAME} intercom restart\\` to replace it.`,\n\t\t);\n\t}\n\tlog(`Run \\`${APP_NAME} storage status\\` to check each domain.`);\n\treturn 0;\n}\n\n/** Run `atomic storage <args>` and return the exit code. */\nexport async function runStorageCommand(args: readonly string[], options: StorageCommandOptions): Promise<number> {\n\tconst log = options.log ?? ((line: string) => console.log(line));\n\tconst error = options.error ?? ((line: string) => console.error(line));\n\ttry {\n\t\tconst command = parseStorageCommand(args);\n\t\tif (command.kind === \"help\") {\n\t\t\tlog(HELP);\n\t\t\treturn 0;\n\t\t}\n\t\tif (command.kind === \"status\") return await status(command.json, options, log);\n\t\tif (command.kind === \"adopt\") return await adopt(command, options, log);\n\t\tif (command.kind === \"consolidate\") return await consolidate(options, log);\n\t\tif (command.kind === \"export\") return await exportRuns(command, options, log, error);\n\t\tif (command.kind === \"import\") return await importRuns(command, options, log);\n\t\treturn await joinStorage(command, options, (...lines) => {\n\t\t\tfor (const line of lines) log(line);\n\t\t});\n\t} catch (caught) {\n\t\tif (isJournalStoreError(caught)) {\n\t\t\terror(caught.message);\n\t\t\tif (caught.hint !== undefined) error(caught.hint);\n\t\t\treturn 1;\n\t\t}\n\t\terror(\n\t\t\tcaught instanceof StorageCommandError ||\n\t\t\t\tisWorkflowRunTransferError(caught) ||\n\t\t\t\tisTeamProfileError(caught) ||\n\t\t\t\tisTeamProfileConfigError(caught)\n\t\t\t\t? caught.message\n\t\t\t\t: `Error: ${errorText(caught as Error)}`,\n\t\t);\n\t\treturn 1;\n\t}\n}\n\n/** A note when this directory's workflow runs use another journal than the journal store `adopt` writes to. */\nfunction storeSelectionNote(options: StorageCommandOptions, directory: string): string | undefined {\n\tconst selection = effectiveJournalSelection(options.cwd, options.agentDir);\n\tif (selection.kind === \"sharded\") return undefined;\n\treturn `Note: workflow runs here use ${describeStorageSelection(selection)}, so they see the journal store ${directory} only once that selection is removed.`;\n}\n\nasync function adopt(\n\tcommand: Extract<StorageCommand, { kind: \"adopt\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (line: string) => void,\n): Promise<number> {\n\tconst directory = defaultJournalStoreDirectory(options.agentDir);\n\tconst report = await adoptJournals(\n\t\tdirectory,\n\t\tcommand.paths.map((path) => resolve(options.cwd, path)),\n\t\t{ discover: command.discover },\n\t);\n\tfor (const outcome of report.adopted) {\n\t\tlog(\n\t\t\toutcome.status === \"adopted\"\n\t\t\t\t? `Adopted ${outcome.path} in place (shard ${outcome.shardId}, ${outcome.runs} run${outcome.runs === 1 ? \"\" : \"s\"}).`\n\t\t\t\t: `Already registered: ${outcome.path} (shard ${outcome.shardId}).`,\n\t\t);\n\t}\n\tfor (const record of report.discovered) {\n\t\tlog(\n\t\t\trecord.outcome === \"skipped\"\n\t\t\t\t? `Skipped ${record.path}, referenced by runs in ${record.referencedBy} (${record.reason}).`\n\t\t\t\t: `Adopted ${record.path}, referenced by runs in ${record.referencedBy}.`,\n\t\t);\n\t}\n\tconst note = storeSelectionNote(options, directory);\n\tif (note !== undefined) log(note);\n\treturn 0;\n}\n\nasync function consolidate(options: StorageCommandOptions, log: (line: string) => void): Promise<number> {\n\tconst directory = defaultJournalStoreDirectory(options.agentDir);\n\tconst report = await consolidateJournalStore(directory);\n\tlog(`Moved ${report.moved} finished run${report.moved === 1 ? \"\" : \"s\"} into the journal store's shards.`);\n\tconst reasons = new Map<string, number>();\n\tfor (const run of report.runs)\n\t\tif (run.outcome === \"skipped\") reasons.set(run.reason, (reasons.get(run.reason) ?? 0) + 1);\n\tfor (const [reason, count] of reasons)\n\t\tlog(`Skipped completing consolidation for ${count} run${count === 1 ? \"\" : \"s\"}: ${reason}.`);\n\tconst failures = new Map<string, string>();\n\tfor (const run of report.runs)\n\t\tif (run.error !== undefined) failures.set(run.error.message, `${run.error.message} ${run.error.hint}`);\n\tfor (const failure of failures.values()) log(failure);\n\tconst note = storeSelectionNote(options, directory);\n\tif (note !== undefined) log(note);\n\treturn failures.size === 0 ? 0 : 1;\n}\n\n/**\n * The local workflow journal this directory's runs use, which `export` and `import` read and write. A shared database\n * is refused: every machine joined to it already reads its runs, so there is nothing to carry between them.\n */\nfunction transferStorage(options: StorageCommandOptions, command: \"export\" | \"import\"): WorkflowRunTransferStorage {\n\tconst selection = effectiveJournalSelection(options.cwd, options.agentDir);\n\tif (selection.kind === \"sharded\") return { kind: \"store\", directory: selection.dir };\n\tif (selection.kind === \"sqlite\" && selection.path !== \":memory:\")\n\t\treturn {\n\t\t\tkind: \"sqlite\",\n\t\t\tpath: resolve(options.cwd, selection.path),\n\t\t\t...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),\n\t\t};\n\tthrow new StorageCommandError(\n\t\t`${APP_NAME} storage ${command} works with a local workflow journal (the journal store or a SQLite file), but workflow runs here use ${describeStorageSelection(selection)}.` +\n\t\t\t(selection.kind === \"adapter\"\n\t\t\t\t? \" A shared database already holds the runs of every machine joined to it, so there is nothing to export or import; use its own backups instead.\"\n\t\t\t\t: \"\"),\n\t);\n}\n\nasync function exportRuns(\n\tcommand: Extract<StorageCommand, { kind: \"export\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): Promise<number> {\n\tconst storage = transferStorage(options, \"export\");\n\tconst directory = resolve(options.cwd, command.directory);\n\tconst report = await exportWorkflowRuns(storage, directory, {\n\t\tunfinished: command.unfinished,\n\t\t...(command.runs === undefined ? {} : { runs: command.runs }),\n\t\t...(command.limit === undefined ? {} : { limit: command.limit }),\n\t});\n\tconst total = report.written.length + report.unchanged.length;\n\tlog(\n\t\t`Exported ${total} workflow run${total === 1 ? \"\" : \"s\"} to ${directory} (${report.written.length} written, ${report.unchanged.length} unchanged).`,\n\t);\n\tfor (const skipped of report.skipped)\n\t\terror(`Skipped ${skipped.runId === undefined ? skipped.path : `run ${skipped.runId}`}: ${skipped.reason}.`);\n\treturn 0;\n}\n\nasync function importRuns(\n\tcommand: Extract<StorageCommand, { kind: \"import\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (line: string) => void,\n): Promise<number> {\n\tconst storage = transferStorage(options, \"import\");\n\tconst directory = resolve(options.cwd, command.directory);\n\tconst report = await importWorkflowRuns(storage, directory);\n\tconst total = report.added.length + report.updated.length + report.unchanged.length;\n\tlog(\n\t\t`Imported ${total} workflow run${total === 1 ? \"\" : \"s\"} from ${directory} (${report.added.length} added, ${report.updated.length} updated, ${report.unchanged.length} already up to date).`,\n\t);\n\treturn 0;\n}\n"]}
1
+ {"version":3,"file":"storage-command.js","sourceRoot":"","sources":["../../src/cli/storage-command.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AACvF,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC9G,OAAO,EACN,aAAa,EACb,uBAAuB,EACvB,4BAA4B,GAC5B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACN,kBAAkB,EAClB,2BAA2B,GAE3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACN,YAAY,EACZ,SAAS,EACT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MAAM,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACnC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC;YACtD,GAAG,CACF,YAAY,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,SAAS,yBAAyB,CAAC,SAAS,CAAC,KAAK,KAAK,CAAC,MAAM,WAAW,OAAO,CAAC,MAAM,aAAa,SAAS,CAAC,MAAM,uBAAuB,CAC1N,CAAC;QACH,CAAC;QACD,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YACpC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC;YACvD,GAAG,CACF,YAAY,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,SAAS,0BAA0B,CAAC,SAAS,CAAC,KAAK,KAAK,CAAC,MAAM,WAAW,OAAO,CAAC,MAAM,aAAa,SAAS,CAAC,MAAM,uBAAuB,CAChO,CAAC;QACH,CAAC;QACD,OAAO,CAAC,CAAC;IACV,CAAC;YAAS,CAAC;QACV,MAAM,YAAY,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC;IACvC,CAAC;AACF,CAAC;AAED,SAAS,YAAY,CAAC,QAAwD;IAC7E,OAAO,QAAQ,KAAK,SAAS,IAAI,QAAQ,IAAI,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AACrF,CAAC","sourcesContent":["/**\n * `atomic storage status` shows which storage each domain (sessions, workflow runs, Intercom) selects, where the\n * selection comes from, whether its adapter loads and its database answers, and what the running Intercom broker\n * uses. `atomic storage join` points this machine's global `storage` setting at a shared libSQL / Turso database.\n * `atomic storage adopt` registers existing journal files in the journal store in place, and `atomic storage\n * consolidate` moves their finished runs into the store's own shards. `atomic storage export` and `atomic storage\n * import` move sessions and workflow runs between their storage and JSONL files (#4716, #4720).\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { APP_NAME } from \"../config.js\";\nimport type { IntercomBrokerControl } from \"../core/intercom-broker-control.js\";\nimport { resolveSessionStore, selectSessionStorage } from \"../core/session-storage.js\";\nimport { exportSessions } from \"../core/session-transfer.ts\";\nimport { SettingsManager } from \"../core/settings-manager.ts\";\nimport { isJournalStoreError, isTeamProfileConfigError, isTeamProfileError } from \"../core/storage/errors.js\";\nimport {\n\tadoptJournals,\n\tconsolidateJournalStore,\n\tdefaultJournalStoreDirectory,\n} from \"../core/storage/journal-adoption.js\";\nimport {\n\texportWorkflowRuns,\n\tWORKFLOW_RUN_EXPORT_VERSION,\n\ttype WorkflowRunTransferStorage,\n} from \"../core/storage/journal-transfer.js\";\nimport {\n\tcheckTeamUrl,\n\tisFileUrl,\n\tLIBSQL_ADAPTER_PACKAGE,\n\tmissingTeamToken,\n\tSTORAGE_TOKEN_FILE,\n} from \"../core/storage/selection.js\";\nimport type { SessionStore } from \"../core/storage/session/types.js\";\nimport { SESSION_FORMAT_VERSION } from \"../core/storage/session/types.js\";\nimport {\n\tcollectStorageStatus,\n\ttype DomainStatus,\n\tdescribeStorageError,\n\tdescribeStorageSelection,\n\teffectiveJournalSelection,\n\tprojectTrust,\n\ttype StorageStatus,\n} from \"../core/storage/storage-status.js\";\nimport { joinSharedDatabase } from \"../core/storage/team.js\";\nimport {\n\tisStorageImportIncompleteError,\n\tisStorageTransferError,\n\ttype TransferredIds,\n} from \"../core/storage/transfer-files.js\";\nimport { importStorage, sessionsTransferDirectory, workflowsTransferDirectory } from \"../core/storage-transfer.ts\";\n\nexport { LIBSQL_ADAPTER_PACKAGE, STORAGE_TOKEN_FILE };\n\nconst HELP = `Usage:\n ${APP_NAME} storage status [--json]\n ${APP_NAME} storage join <url> [--token-file <path>] [--prefix <prefix>]\n ${APP_NAME} storage adopt <path>... [--no-discover]\n ${APP_NAME} storage consolidate\n ${APP_NAME} storage export <dir> [--sessions] [--workflows] [--run <id>]... [--unfinished]\n [--limit <n>] [--since <time>]\n ${APP_NAME} storage import <dir> [--sessions] [--workflows]\n\nCommands:\n status Show, for sessions, workflow runs, and Intercom, the selected storage and where the\n selection comes from (environment variable, project or global settings, or default),\n whether its adapter loads, whether its database answers a SELECT 1, and what the running\n Intercom broker uses. Exits 1 when a selection is invalid, an adapter cannot load, or a\n database does not answer. Nothing is created or changed.\n join Use a shared libSQL / Turso database on this machine: check the token and the connection\n with ${LIBSQL_ADAPTER_PACKAGE}, store the token in the agent directory (mode 600), and\n write only the global \\`storage\\` setting. Reports environment variables and settings that\n override it. Creates no tables; Atomic creates them on first use.\n adopt Register existing workflow journal files in the journal store in place, without copying,\n so their runs resolve by ID for status, resume, attach, fork and history://. Each <path>\n is a journal .sqlite file or a directory holding journal.sqlite. Every path is checked\n before the first is registered. Journals the adopted runs were written to are adopted\n too unless --no-discover is given.\n consolidate\n Move finished runs (completed, failed or cancelled, not leased, without local workers)\n from adopted journals into the journal store's own shards. Other runs stay where they\n are. An interrupted consolidation leaves every run readable; run it again to finish.\n export Write sessions to <dir>/sessions/<sessionId>.jsonl (session format version\n ${SESSION_FORMAT_VERSION}, the format \\`${APP_NAME} --import\\` reads) and workflow runs to\n <dir>/workflows/<runId>.jsonl (workflow run export version ${WORKFLOW_RUN_EXPORT_VERSION}), one file per\n session or run. Both kinds by default; --sessions or --workflows limits it to one. Each\n file is replaced whole, one that already holds the same bytes is not rewritten, and no\n file is deleted. A kind kept in a shared libSQL / Turso database is skipped (an error\n when --sessions or --workflows asks for it): every machine joined to it reads it already.\n import Restore the sessions in <dir>/sessions and the workflow runs in <dir>/workflows into\n this directory's storage; other files are ignored. Every file of both kinds is checked\n first, so a malformed or unsupported file changes nothing. Importing again adds\n nothing; a newer export of a session or run adds its later entries. Imported runs are\n not owned by any process: an interrupted one can be resumed here. If the import fails\n after writing part of it, it names what was and was not written; run it again to finish.\n\nOptions:\n --json Print the status as JSON\n --token-file <path> File holding the database token, for example from \\`turso db tokens create\\`;\n surrounding whitespace is removed. Required except for file: URLs\n --prefix <prefix> Table prefix, to share one database between projects or teams\n --no-discover adopt: register only the given paths\n --sessions export, import: sessions only (with --workflows too: both)\n --workflows export, import: workflow runs only (with --sessions too: both)\n --run <id> export: only this workflow run; repeat for more\n --unfinished export: only workflow runs that are not completed, failed or cancelled\n --limit <n> export: at most n workflow runs, newest first, and at most n sessions,\n most recently modified first\n --since <time> export: only sessions modified at or after <time>, a date such as\n 2026-11-01 or a date and time such as 2026-11-01T09:30:00Z`;\n\nconst HELP_HINT = `Use \"${APP_NAME} storage --help\" for usage.`;\n\nexport type StorageCommand =\n\t| { readonly kind: \"help\" }\n\t| { readonly kind: \"status\"; readonly json: boolean }\n\t| { readonly kind: \"join\"; readonly url: string; readonly tokenFile?: string; readonly prefix?: string }\n\t| { readonly kind: \"adopt\"; readonly paths: readonly string[]; readonly discover: boolean }\n\t| { readonly kind: \"consolidate\" }\n\t| {\n\t\t\treadonly kind: \"export\";\n\t\t\treadonly directory: string;\n\t\t\t/** The kinds to export; both when neither `--sessions` nor `--workflows` is given. */\n\t\t\treadonly kinds: TransferKinds;\n\t\t\treadonly runs?: readonly string[];\n\t\t\treadonly unfinished: boolean;\n\t\t\treadonly limit?: number;\n\t\t\t/** `--since`, in milliseconds since the epoch. */\n\t\t\treadonly since?: number;\n\t }\n\t| { readonly kind: \"import\"; readonly directory: string; readonly kinds: TransferKinds };\n\n/** Which kinds an export or import covers, and whether `--sessions` or `--workflows` named them. */\nexport interface TransferKinds {\n\treadonly sessions: boolean;\n\treadonly workflows: boolean;\n\treadonly explicit: boolean;\n}\n\nexport class StorageCommandError extends Error {}\n\n/** Parse the arguments after `storage`. */\nexport function parseStorageCommand(args: readonly string[]): StorageCommand {\n\tconst [command, ...rest] = args;\n\tif (command === undefined || command === \"help\" || args.includes(\"--help\") || args.includes(\"-h\")) {\n\t\treturn { kind: \"help\" };\n\t}\n\tconst positional: string[] = [];\n\tconst values = new Map<string, string>();\n\tlet json = false;\n\tlet discover = true;\n\tlet unfinished = false;\n\tlet sessions = false;\n\tlet workflows = false;\n\tconst runs: string[] = [];\n\tfor (let index = 0; index < rest.length; index++) {\n\t\tconst arg = rest[index]!;\n\t\tif (command === \"status\" && arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (command === \"adopt\" && arg === \"--no-discover\") {\n\t\t\tdiscover = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif ((command === \"export\" || command === \"import\") && (arg === \"--sessions\" || arg === \"--workflows\")) {\n\t\t\tif (arg === \"--sessions\") sessions = true;\n\t\t\telse workflows = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (command === \"export\" && arg === \"--unfinished\") {\n\t\t\tunfinished = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (command === \"export\" && arg === \"--run\") {\n\t\t\tconst value = rest[++index];\n\t\t\tif (value === undefined || value === \"\") throw new StorageCommandError(\"--run needs a run ID.\");\n\t\t\truns.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\t(command === \"join\" && (arg === \"--token-file\" || arg === \"--prefix\")) ||\n\t\t\t(command === \"export\" && (arg === \"--limit\" || arg === \"--since\"))\n\t\t) {\n\t\t\tconst value = rest[++index];\n\t\t\tif (value === undefined) throw new StorageCommandError(`${arg} needs a value.`);\n\t\t\tvalues.set(arg, value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg.startsWith(\"-\"))\n\t\t\tthrow new StorageCommandError(`Unknown option ${arg} for \"storage ${command}\".\\n${HELP_HINT}`);\n\t\tpositional.push(arg);\n\t}\n\tif (command === \"status\") {\n\t\tif (positional.length > 0) throw new StorageCommandError(`Usage: ${APP_NAME} storage status [--json]`);\n\t\treturn { kind: \"status\", json };\n\t}\n\tif (command === \"join\") {\n\t\tconst [url, ...extra] = positional;\n\t\tif (url === undefined || extra.length > 0) {\n\t\t\tthrow new StorageCommandError(\n\t\t\t\t`Usage: ${APP_NAME} storage join <url> [--token-file <path>] [--prefix <prefix>]`,\n\t\t\t);\n\t\t}\n\t\tcheckTeamUrl(url, \"cli\");\n\t\tconst tokenFile = values.get(\"--token-file\");\n\t\tif (tokenFile === undefined && !isFileUrl(url)) throw missingTeamToken(url, \"cli\");\n\t\tconst prefix = values.get(\"--prefix\");\n\t\treturn {\n\t\t\tkind: \"join\",\n\t\t\turl,\n\t\t\t...(tokenFile === undefined ? {} : { tokenFile }),\n\t\t\t...(prefix === undefined ? {} : { prefix }),\n\t\t};\n\t}\n\tif (command === \"adopt\") {\n\t\tif (positional.length === 0)\n\t\t\tthrow new StorageCommandError(`Usage: ${APP_NAME} storage adopt <path>... [--no-discover]`);\n\t\treturn { kind: \"adopt\", paths: positional, discover };\n\t}\n\tif (command === \"consolidate\") {\n\t\tif (positional.length > 0) throw new StorageCommandError(`Usage: ${APP_NAME} storage consolidate`);\n\t\treturn { kind: \"consolidate\" };\n\t}\n\tconst kinds: TransferKinds =\n\t\tsessions || workflows\n\t\t\t? { sessions, workflows, explicit: true }\n\t\t\t: { sessions: true, workflows: true, explicit: false };\n\tif (command === \"export\") {\n\t\tconst [directory, ...extra] = positional;\n\t\tif (directory === undefined || extra.length > 0)\n\t\t\tthrow new StorageCommandError(\n\t\t\t\t`Usage: ${APP_NAME} storage export <dir> [--sessions] [--workflows] [--run <id>]... [--unfinished] [--limit <n>] [--since <time>]`,\n\t\t\t);\n\t\tconst limitText = values.get(\"--limit\");\n\t\tconst limit = limitText === undefined ? undefined : Number(limitText);\n\t\tif (limit !== undefined && (!/^[0-9]+$/.test(limitText!) || !Number.isSafeInteger(limit) || limit < 1))\n\t\t\tthrow new StorageCommandError(`--limit needs a positive whole number, not \"${limitText}\".`);\n\t\tconst sinceText = values.get(\"--since\");\n\t\tconst since = sinceText === undefined ? undefined : Date.parse(sinceText);\n\t\tif (since !== undefined && Number.isNaN(since))\n\t\t\tthrow new StorageCommandError(\n\t\t\t\t`--since needs a date such as 2026-11-01 or a date and time such as 2026-11-01T09:30:00Z, not \"${sinceText}\".`,\n\t\t\t);\n\t\tif (!kinds.workflows && (runs.length > 0 || unfinished))\n\t\t\tthrow new StorageCommandError(\n\t\t\t\t`${runs.length > 0 ? \"--run\" : \"--unfinished\"} selects workflow runs, which --sessions alone does not export.`,\n\t\t\t);\n\t\tif (!kinds.sessions && since !== undefined)\n\t\t\tthrow new StorageCommandError(\"--since selects sessions, which --workflows alone does not export.\");\n\t\treturn {\n\t\t\tkind: \"export\",\n\t\t\tdirectory,\n\t\t\tkinds,\n\t\t\tunfinished,\n\t\t\t...(runs.length === 0 ? {} : { runs }),\n\t\t\t...(limit === undefined ? {} : { limit }),\n\t\t\t...(since === undefined ? {} : { since }),\n\t\t};\n\t}\n\tif (command === \"import\") {\n\t\tconst [directory, ...extra] = positional;\n\t\tif (directory === undefined || extra.length > 0)\n\t\t\tthrow new StorageCommandError(`Usage: ${APP_NAME} storage import <dir> [--sessions] [--workflows]`);\n\t\treturn { kind: \"import\", directory, kinds };\n\t}\n\tthrow new StorageCommandError(`Unknown storage command \"${command}\".\\n${HELP_HINT}`);\n}\n\nexport interface StorageCommandOptions {\n\treadonly cwd: string;\n\treadonly agentDir: string;\n\treadonly log?: (line: string) => void;\n\treadonly error?: (line: string) => void;\n\t/** Defaults to the bundled Intercom package's broker control. */\n\treadonly loadControl?: () => Promise<IntercomBrokerControl>;\n}\n\nconst errorText = describeStorageError;\n\n/** The bundled Intercom package's broker control, or why it could not load. */\nexport async function loadBrokerControl(options: {\n\treadonly loadControl?: () => Promise<IntercomBrokerControl>;\n}): Promise<IntercomBrokerControl | Error> {\n\ttry {\n\t\tif (options.loadControl) return await options.loadControl();\n\t\tconst { loadIntercomBrokerControl } = await import(\"../core/intercom-broker-control.js\");\n\t\treturn await loadIntercomBrokerControl();\n\t} catch (error) {\n\t\treturn error instanceof Error ? error : new Error(String(error));\n\t}\n}\n\n/** Whether a domain's selection is invalid, its adapter cannot load, or its database did not answer. */\nexport function failed(domain: DomainStatus): boolean {\n\treturn (\n\t\tdomain.error !== undefined ||\n\t\tdomain.probe?.adapter?.loaded === false ||\n\t\tdomain.probe?.connection.status === \"failed\" ||\n\t\t(domain.journalStore?.unavailable.length ?? 0) > 0\n\t);\n}\n\nconst DOMAIN_LABELS: Record<DomainStatus[\"domain\"], string> = {\n\tsessions: \"Sessions\",\n\tjournal: \"Workflow runs\",\n\tintercom: \"Intercom\",\n};\n\n/** The status as the lines `atomic storage status` prints. */\nexport function formatStorageStatus(status: StorageStatus): string[] {\n\tconst lines = [\n\t\t`Agent directory: ${status.agentDir}`,\n\t\t`Project: ${status.cwd}${status.projectTrusted ? \"\" : \" (not trusted)\"}`,\n\t];\n\tfor (const domain of status.domains) {\n\t\tlines.push(\"\", `${DOMAIN_LABELS[domain.domain]}: ${domain.selection}`);\n\t\tlines.push(` source: ${domain.source}`);\n\t\tif (domain.overridden.length > 0) lines.push(` overrides: ${domain.overridden.join(\", \")}`);\n\t\tif (domain.error !== undefined) lines.push(` error: ${domain.error}`);\n\t\tconst probe = domain.probe;\n\t\tif (probe?.sameAs !== undefined) {\n\t\t\tlines.push(` connection: same as ${DOMAIN_LABELS[probe.sameAs].toLowerCase()}`);\n\t\t} else if (probe !== undefined) {\n\t\t\tif (probe.adapter !== undefined) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` adapter: ${probe.adapter.loaded ? \"loaded\" : \"failed to load\"}${probe.adapter.detail === undefined ? \"\" : ` (${probe.adapter.detail})`}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlines.push(` connection: ${probe.connection.status} (${probe.connection.detail})`);\n\t\t}\n\t\tif (domain.multiNode !== undefined) lines.push(` multi-node: ${domain.multiNode}`);\n\t\tif (domain.liveBrokers !== undefined) {\n\t\t\tlines.push(\n\t\t\t\t` brokers: ${domain.liveBrokers.length} live in the database${domain.liveBrokers.length === 0 ? \"\" : ` (${[...new Set(domain.liveBrokers)].join(\", \")})`}`,\n\t\t\t);\n\t\t}\n\t\tconst store = domain.journalStore;\n\t\tif (store !== undefined) {\n\t\t\tlines.push(\n\t\t\t\t` journals: ${store.shards} shard${store.shards === 1 ? \"\" : \"s\"}, ${store.adopted} adopted journal${store.adopted === 1 ? \"\" : \"s\"}, ${store.runs} run${store.runs === 1 ? \"\" : \"s\"}`,\n\t\t\t);\n\t\t\tfor (const shard of store.unavailable)\n\t\t\t\tlines.push(\n\t\t\t\t\t` unavailable: ${shard.path} (${shard.kind}, ${shard.code === \"shard-missing\" ? \"no longer exists\" : \"cannot be opened\"}: ${shard.code}${shard.detail === undefined ? \"\" : `, ${shard.detail}`})`,\n\t\t\t\t);\n\t\t\tfor (const skipped of store.skipped) lines.push(` skipped: ${skipped.path} (${skipped.reason})`);\n\t\t}\n\t}\n\tconst broker = status.broker;\n\tif (broker !== undefined) {\n\t\tlines.push(\"\");\n\t\tif (broker.state === \"stopped\") {\n\t\t\tlines.push(\n\t\t\t\t\"Intercom broker: not running (the next session that uses Intercom starts one with the selection above)\",\n\t\t\t);\n\t\t} else if (broker.state === \"unknown\") {\n\t\t\tlines.push(`Intercom broker: unknown (${broker.error ?? \"no answer\"})`);\n\t\t} else if (broker.state === \"legacy\") {\n\t\t\tlines.push(\n\t\t\t\t`Intercom broker: running${broker.pid === undefined ? \"\" : ` (pid ${broker.pid})`}, started by an older Atomic that does not report its storage; run \\`${APP_NAME} intercom restart\\``,\n\t\t\t);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t`Intercom broker: running (pid ${broker.pid}, ${broker.sessions} session${broker.sessions === 1 ? \"\" : \"s\"} connected)`,\n\t\t\t);\n\t\t\tlines.push(\n\t\t\t\tbroker.matchesCurrent\n\t\t\t\t\t? \" storage: matches the selection above\"\n\t\t\t\t\t: ` storage: differs from the selection above${broker.source === \"env\" ? \" (a session started it with ATOMIC_STORAGE, ATOMIC_PROFILE=ci or --storage)\" : \"\"}; run \\`${APP_NAME} intercom restart\\` to use the current one`,\n\t\t\t);\n\t\t\tif (broker.multiNodeLine !== undefined) lines.push(` multi-node: ${broker.multiNodeLine}`);\n\t\t}\n\t}\n\tif (status.notes.length > 0) lines.push(\"\", \"Notes:\", ...status.notes.map((note) => ` - ${note}`));\n\treturn lines;\n}\n\nasync function status(json: boolean, options: StorageCommandOptions, log: (line: string) => void): Promise<number> {\n\tconst control = await loadBrokerControl(options);\n\tconst collected = await collectStorageStatus({\n\t\tcwd: options.cwd,\n\t\tagentDir: options.agentDir,\n\t\tprobe: true,\n\t\t...(control instanceof Error ? {} : { control }),\n\t});\n\tconst result: StorageStatus =\n\t\tcontrol instanceof Error ? { ...collected, broker: { state: \"unknown\", error: errorText(control) } } : collected;\n\tif (json) log(JSON.stringify(result, null, 2));\n\telse for (const line of formatStorageStatus(result)) log(line);\n\treturn result.domains.some(failed) ? 1 : 0;\n}\n\nasync function joinStorage(\n\tcommand: Extract<StorageCommand, { kind: \"join\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (...lines: string[]) => void,\n): Promise<number> {\n\tconst { agentDir, cwd } = options;\n\tconst joined = await joinSharedDatabase({ ...command, agentDir, cwd, pinLocalSessions: false }, \"cli\");\n\tlog(`Connected to ${command.url}.`);\n\tif (joined.tokenPath !== undefined) {\n\t\tlog(\n\t\t\tjoined.token === \"reused\"\n\t\t\t\t? `Kept the token in ${joined.tokenPath}; it already holds this token.`\n\t\t\t\t: `Stored the token in ${joined.tokenPath} (mode 600).`,\n\t\t);\n\t}\n\tlog(`Set \\`storage\\` in ${join(agentDir, \"settings.json\")}; other settings are unchanged.`);\n\tif (joined.replaced !== undefined) log(`It replaces the previous selection: ${joined.replaced}.`);\n\n\tconst control = await loadBrokerControl(options);\n\tlet collected: StorageStatus;\n\ttry {\n\t\tcollected = await collectStorageStatus({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tprobe: false,\n\t\t\t...(control instanceof Error ? {} : { control }),\n\t\t});\n\t} catch (error) {\n\t\t// Settings and the token are already committed; optional diagnostics cannot undo that success.\n\t\tlog(`Storage was saved, but could not report overrides: ${errorText(error as Error)}.`);\n\t\tlog(`Run \\`${APP_NAME} storage status\\` after fixing the reported settings error.`);\n\t\treturn 0;\n\t}\n\tconst overridden = collected.domains.filter(\n\t\t(domain) => domain.source !== \"global settings: storage\" && domain.source !== \"default\",\n\t);\n\tif (overridden.length > 0) {\n\t\tlog(\"\", \"These take precedence over the new selection here:\");\n\t\tfor (const domain of overridden) log(` - ${DOMAIN_LABELS[domain.domain]}: ${domain.source}`);\n\t}\n\tfor (const note of collected.notes) log(`Note: ${note}`);\n\tconst broker = collected.broker;\n\tif (broker?.state === \"running\" && !broker.matchesCurrent) {\n\t\tlog(\n\t\t\t`The running Intercom broker (pid ${broker.pid}) still uses its previous selection. Run \\`${APP_NAME} intercom restart\\` so it uses the new one.`,\n\t\t);\n\t} else if (broker?.state === \"legacy\") {\n\t\tlog(\n\t\t\t`An Intercom broker from an older ${APP_NAME} is running. Run \\`${APP_NAME} intercom restart\\` to replace it.`,\n\t\t);\n\t}\n\tlog(`Run \\`${APP_NAME} storage status\\` to check each domain.`);\n\treturn 0;\n}\n\n/** Run `atomic storage <args>` and return the exit code. */\nexport async function runStorageCommand(args: readonly string[], options: StorageCommandOptions): Promise<number> {\n\tconst log = options.log ?? ((line: string) => console.log(line));\n\tconst error = options.error ?? ((line: string) => console.error(line));\n\ttry {\n\t\tconst command = parseStorageCommand(args);\n\t\tif (command.kind === \"help\") {\n\t\t\tlog(HELP);\n\t\t\treturn 0;\n\t\t}\n\t\tif (command.kind === \"status\") return await status(command.json, options, log);\n\t\tif (command.kind === \"adopt\") return await adopt(command, options, log);\n\t\tif (command.kind === \"consolidate\") return await consolidate(options, log);\n\t\tif (command.kind === \"export\") return await exportRuns(command, options, log, error);\n\t\tif (command.kind === \"import\") return await importRuns(command, options, log, error);\n\t\treturn await joinStorage(command, options, (...lines) => {\n\t\t\tfor (const line of lines) log(line);\n\t\t});\n\t} catch (caught) {\n\t\tif (isJournalStoreError(caught)) {\n\t\t\terror(caught.message);\n\t\t\tif (caught.hint !== undefined) error(caught.hint);\n\t\t\treturn 1;\n\t\t}\n\t\terror(\n\t\t\tcaught instanceof StorageCommandError ||\n\t\t\t\tisStorageTransferError(caught) ||\n\t\t\t\tisTeamProfileError(caught) ||\n\t\t\t\tisTeamProfileConfigError(caught)\n\t\t\t\t? caught.message\n\t\t\t\t: `Error: ${errorText(caught as Error)}`,\n\t\t);\n\t\treturn 1;\n\t}\n}\n\n/** A note when this directory's workflow runs use another journal than the journal store `adopt` writes to. */\nfunction storeSelectionNote(options: StorageCommandOptions, directory: string): string | undefined {\n\tconst selection = effectiveJournalSelection(options.cwd, options.agentDir);\n\tif (selection.kind === \"sharded\") return undefined;\n\treturn `Note: workflow runs here use ${describeStorageSelection(selection)}, so they see the journal store ${directory} only once that selection is removed.`;\n}\n\nasync function adopt(\n\tcommand: Extract<StorageCommand, { kind: \"adopt\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (line: string) => void,\n): Promise<number> {\n\tconst directory = defaultJournalStoreDirectory(options.agentDir);\n\tconst report = await adoptJournals(\n\t\tdirectory,\n\t\tcommand.paths.map((path) => resolve(options.cwd, path)),\n\t\t{ discover: command.discover },\n\t);\n\tfor (const outcome of report.adopted) {\n\t\tlog(\n\t\t\toutcome.status === \"adopted\"\n\t\t\t\t? `Adopted ${outcome.path} in place (shard ${outcome.shardId}, ${outcome.runs} run${outcome.runs === 1 ? \"\" : \"s\"}).`\n\t\t\t\t: `Already registered: ${outcome.path} (shard ${outcome.shardId}).`,\n\t\t);\n\t}\n\tfor (const record of report.discovered) {\n\t\tlog(\n\t\t\trecord.outcome === \"skipped\"\n\t\t\t\t? `Skipped ${record.path}, referenced by runs in ${record.referencedBy} (${record.reason}).`\n\t\t\t\t: `Adopted ${record.path}, referenced by runs in ${record.referencedBy}.`,\n\t\t);\n\t}\n\tconst note = storeSelectionNote(options, directory);\n\tif (note !== undefined) log(note);\n\treturn 0;\n}\n\nasync function consolidate(options: StorageCommandOptions, log: (line: string) => void): Promise<number> {\n\tconst directory = defaultJournalStoreDirectory(options.agentDir);\n\tconst report = await consolidateJournalStore(directory);\n\tlog(`Moved ${report.moved} finished run${report.moved === 1 ? \"\" : \"s\"} into the journal store's shards.`);\n\tconst reasons = new Map<string, number>();\n\tfor (const run of report.runs)\n\t\tif (run.outcome === \"skipped\") reasons.set(run.reason, (reasons.get(run.reason) ?? 0) + 1);\n\tfor (const [reason, count] of reasons)\n\t\tlog(`Skipped completing consolidation for ${count} run${count === 1 ? \"\" : \"s\"}: ${reason}.`);\n\tconst failures = new Map<string, string>();\n\tfor (const run of report.runs)\n\t\tif (run.error !== undefined) failures.set(run.error.message, `${run.error.message} ${run.error.hint}`);\n\tfor (const failure of failures.values()) log(failure);\n\tconst note = storeSelectionNote(options, directory);\n\tif (note !== undefined) log(note);\n\treturn failures.size === 0 ? 0 : 1;\n}\n\n/** What an export or import of one kind reads or writes, or why that kind is refused here. */\ntype Transfer<T> = { readonly target: T } | { readonly refused: string };\n\n/**\n * The local workflow journal this directory's runs use, which `export` and `import` read and write. A shared database\n * is refused: every machine joined to it already reads its runs, so there is nothing to carry between them.\n */\nfunction workflowTransfer(\n\toptions: StorageCommandOptions,\n\tcommand: \"export\" | \"import\",\n): Transfer<WorkflowRunTransferStorage> {\n\tconst selection = effectiveJournalSelection(options.cwd, options.agentDir);\n\tif (selection.kind === \"sharded\") return { target: { kind: \"store\", directory: selection.dir } };\n\tif (selection.kind === \"sqlite\" && selection.path !== \":memory:\")\n\t\treturn {\n\t\t\ttarget: {\n\t\t\t\tkind: \"sqlite\",\n\t\t\t\tpath: resolve(options.cwd, selection.path),\n\t\t\t\t...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),\n\t\t\t},\n\t\t};\n\treturn {\n\t\trefused:\n\t\t\t`${APP_NAME} storage ${command} works with a local workflow journal (the journal store or a SQLite file), but workflow runs here use ${describeStorageSelection(selection)}.` +\n\t\t\t(selection.kind === \"adapter\"\n\t\t\t\t? \" A shared database already holds the runs of every machine joined to it, so there is nothing to export or import; use its own backups instead.\"\n\t\t\t\t: \"\"),\n\t};\n}\n\n/**\n * The session storage this directory selects, as a session started here would open it: the default database, a JSONL\n * directory, a SQLite file or an adapter. A shared libSQL / Turso database is refused as it is for workflow runs, and so\n * is in-memory storage, which keeps nothing. Undefined target for an export when nothing has been stored yet, so an\n * export creates no database.\n */\nasync function sessionTransfer(\n\toptions: StorageCommandOptions,\n\tcommand: \"export\" | \"import\",\n): Promise<Transfer<SessionStore | undefined>> {\n\tconst settings = SettingsManager.create(options.cwd, options.agentDir, {\n\t\tprojectTrusted: projectTrust(options.cwd, options.agentDir),\n\t}).getSettings();\n\tconst storageOptions = { agentDir: options.agentDir, settings };\n\tconst selection = selectSessionStorage(options.cwd, storageOptions);\n\tif (!(\"load\" in selection)) {\n\t\tif (selection.kind === \"memory\" || (selection.kind === \"sqlite\" && selection.path === \":memory:\"))\n\t\t\treturn {\n\t\t\t\trefused: `${APP_NAME} storage ${command} needs stored sessions, but sessions here use ${describeStorageSelection(selection)}, which keeps nothing.`,\n\t\t\t};\n\t\tif (selection.kind === \"adapter\" && selection.module === LIBSQL_ADAPTER_PACKAGE)\n\t\t\treturn {\n\t\t\t\trefused: `${APP_NAME} storage ${command} works with local session storage, but sessions here use ${describeStorageSelection(selection)}. A shared database already holds the sessions of every machine joined to it, so there is nothing to export or import; use its own backups instead.`,\n\t\t\t};\n\t\tif (command === \"export\") {\n\t\t\tconst stored =\n\t\t\t\tselection.kind === \"jsonl\"\n\t\t\t\t\t? existsSync(selection.dir)\n\t\t\t\t\t: selection.kind !== \"sqlite\" ||\n\t\t\t\t\t\texistsSync(resolve(options.cwd, selection.path)) ||\n\t\t\t\t\t\texistsSync(join(options.agentDir, \"sessions\"));\n\t\t\tif (!stored) return { target: undefined };\n\t\t}\n\t}\n\treturn { target: await resolveSessionStore(options.cwd, storageOptions) };\n}\n\nconst plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? \"\" : \"s\"}`;\n\nasync function exportRuns(\n\tcommand: Extract<StorageCommand, { kind: \"export\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): Promise<number> {\n\tconst directory = resolve(options.cwd, command.directory);\n\tconst workflows = command.kinds.workflows ? workflowTransfer(options, \"export\") : undefined;\n\tconst sessions = command.kinds.sessions ? await sessionTransfer(options, \"export\") : undefined;\n\ttry {\n\t\tconst refusals = [workflows, sessions].flatMap((transfer) =>\n\t\t\ttransfer !== undefined && \"refused\" in transfer ? [transfer.refused] : [],\n\t\t);\n\t\tconst kinds = Number(command.kinds.sessions) + Number(command.kinds.workflows);\n\t\tif (refusals.length > 0 && (command.kinds.explicit || refusals.length === kinds))\n\t\t\tthrow new StorageCommandError(refusals.join(\"\\n\"));\n\t\tfor (const refused of refusals) error(`Skipped: ${refused}`);\n\t\t// Workflow runs first: an unknown --run fails the export before any file of either kind is written.\n\t\tif (workflows !== undefined && \"target\" in workflows) {\n\t\t\tconst target = workflowsTransferDirectory(directory);\n\t\t\tconst report = await exportWorkflowRuns(workflows.target, target, {\n\t\t\t\tunfinished: command.unfinished,\n\t\t\t\t...(command.runs === undefined ? {} : { runs: command.runs }),\n\t\t\t\t...(command.limit === undefined ? {} : { limit: command.limit }),\n\t\t\t});\n\t\t\tconst total = report.written.length + report.unchanged.length;\n\t\t\tlog(\n\t\t\t\t`Exported ${plural(total, \"workflow run\")} to ${target} (${report.written.length} written, ${report.unchanged.length} unchanged).`,\n\t\t\t);\n\t\t\tfor (const skipped of report.skipped)\n\t\t\t\terror(\n\t\t\t\t\t`Skipped ${skipped.runId === undefined ? skipped.path : `run ${skipped.runId} (${skipped.path})`}: ${skipped.reason}.`,\n\t\t\t\t);\n\t\t}\n\t\tif (sessions !== undefined && \"target\" in sessions) {\n\t\t\tconst target = sessionsTransferDirectory(directory);\n\t\t\tconst report =\n\t\t\t\tsessions.target === undefined\n\t\t\t\t\t? { written: [], unchanged: [] }\n\t\t\t\t\t: await exportSessions(sessions.target, target, {\n\t\t\t\t\t\t\t...(command.limit === undefined ? {} : { limit: command.limit }),\n\t\t\t\t\t\t\t...(command.since === undefined ? {} : { since: command.since }),\n\t\t\t\t\t\t});\n\t\t\tconst total = report.written.length + report.unchanged.length;\n\t\t\tlog(\n\t\t\t\t`Exported ${plural(total, \"session\")} to ${target} (${report.written.length} written, ${report.unchanged.length} unchanged).`,\n\t\t\t);\n\t\t}\n\t\treturn 0;\n\t} finally {\n\t\tawait sessionStore(sessions)?.close();\n\t}\n}\n\nfunction describeIds(ids: TransferredIds): string {\n\tconst parts = [\n\t\tids.sessions.length === 0\n\t\t\t? undefined\n\t\t\t: `${ids.sessions.length === 1 ? \"session\" : \"sessions\"} ${ids.sessions.join(\", \")}`,\n\t\tids.workflows.length === 0\n\t\t\t? undefined\n\t\t\t: `${ids.workflows.length === 1 ? \"workflow run\" : \"workflow runs\"} ${ids.workflows.join(\", \")}`,\n\t].filter((part) => part !== undefined);\n\treturn parts.length === 0 ? \"nothing\" : parts.join(\"; \");\n}\n\nasync function importRuns(\n\tcommand: Extract<StorageCommand, { kind: \"import\" }>,\n\toptions: StorageCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): Promise<number> {\n\tconst directory = resolve(options.cwd, command.directory);\n\tif (!existsSync(directory)) throw new StorageCommandError(`${directory}: no such directory.`);\n\tconst workflows = command.kinds.workflows ? workflowTransfer(options, \"import\") : undefined;\n\tconst sessions = command.kinds.sessions ? await sessionTransfer(options, \"import\") : undefined;\n\ttry {\n\t\tconst refusals = [workflows, sessions].flatMap((transfer) =>\n\t\t\ttransfer !== undefined && \"refused\" in transfer ? [transfer.refused] : [],\n\t\t);\n\t\tconst kinds = Number(command.kinds.sessions) + Number(command.kinds.workflows);\n\t\tif (refusals.length > 0 && (command.kinds.explicit || refusals.length === kinds))\n\t\t\tthrow new StorageCommandError(refusals.join(\"\\n\"));\n\t\tfor (const refused of refusals) error(`Skipped: ${refused}`);\n\t\tconst sessionTarget = sessionStore(sessions);\n\t\tconst workflowStorage = workflows !== undefined && \"target\" in workflows ? workflows.target : undefined;\n\t\tlet report: Awaited<ReturnType<typeof importStorage>>;\n\t\ttry {\n\t\t\treport = await importStorage(directory, {\n\t\t\t\t...(sessionTarget === undefined ? {} : { sessions: sessionTarget }),\n\t\t\t\t...(workflowStorage === undefined ? {} : { workflows: workflowStorage }),\n\t\t\t});\n\t\t} catch (caught) {\n\t\t\tif (isStorageImportIncompleteError(caught)) {\n\t\t\t\terror(caught.message);\n\t\t\t\terror(`Imported before the failure: ${describeIds(caught.written)}.`);\n\t\t\t\terror(`Not imported: ${describeIds(caught.notWritten)}.`);\n\t\t\t\terror(\"Run the same import again to finish: it imports only what is missing.\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (isStorageTransferError(caught)) {\n\t\t\t\terror(caught.message);\n\t\t\t\terror(\"Nothing was imported.\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tthrow caught;\n\t\t}\n\t\tif (report.sessions !== undefined) {\n\t\t\tconst { added, updated, unchanged } = report.sessions;\n\t\t\tlog(\n\t\t\t\t`Imported ${plural(added.length + updated.length + unchanged.length, \"session\")} from ${sessionsTransferDirectory(directory)} (${added.length} added, ${updated.length} updated, ${unchanged.length} already up to date).`,\n\t\t\t);\n\t\t}\n\t\tif (report.workflows !== undefined) {\n\t\t\tconst { added, updated, unchanged } = report.workflows;\n\t\t\tlog(\n\t\t\t\t`Imported ${plural(added.length + updated.length + unchanged.length, \"workflow run\")} from ${workflowsTransferDirectory(directory)} (${added.length} added, ${updated.length} updated, ${unchanged.length} already up to date).`,\n\t\t\t);\n\t\t}\n\t\treturn 0;\n\t} finally {\n\t\tawait sessionStore(sessions)?.close();\n\t}\n}\n\nfunction sessionStore(transfer: Transfer<SessionStore | undefined> | undefined): SessionStore | undefined {\n\treturn transfer !== undefined && \"target\" in transfer ? transfer.target : undefined;\n}\n"]}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Sessions as format-4 JSONL files for `atomic storage export` and `import` (#4720): each session is written to
3
+ * `<dir>/<sessionId>.jsonl` in the format JSONL session storage keeps and `atomic --import` reads, with the tool outputs
4
+ * and worktree snapshot content it references carried inline as `/export <file>.jsonl` carries them, and read back with
5
+ * the same parser.
6
+ */
7
+ import type { SessionEntry } from "./session-manager-types.ts";
8
+ import { type SessionBlobCopy } from "./session-tool-output.ts";
9
+ import { type SessionRecordHeader, type SessionStore } from "./storage/session/types.js";
10
+ export interface SessionExportOptions {
11
+ /** At most this many sessions, most recently modified first. */
12
+ readonly limit?: number;
13
+ /** Only sessions modified at or after this time, in milliseconds since the epoch. */
14
+ readonly since?: number;
15
+ }
16
+ export interface SessionExportReport {
17
+ /** Sessions whose file was written. */
18
+ readonly written: readonly string[];
19
+ /** Sessions whose file already held exactly this export, left untouched. */
20
+ readonly unchanged: readonly string[];
21
+ }
22
+ export interface SessionImportReport {
23
+ /** Sessions the storage did not hold. */
24
+ readonly added: readonly string[];
25
+ /** Sessions the storage held an earlier part of, which now have the file's later entries. */
26
+ readonly updated: readonly string[];
27
+ /** Sessions the storage already held every entry of. */
28
+ readonly unchanged: readonly string[];
29
+ }
30
+ /**
31
+ * Exports the sessions of `store`, every project's and workflow stage sessions included, to
32
+ * `<directory>/<sessionId>.jsonl`, one file per session. Each file is written whole or not at all; the same session
33
+ * gives the same bytes, and a file that already holds them is not rewritten.
34
+ */
35
+ export declare function exportSessions(store: SessionStore, directory: string, options?: SessionExportOptions): Promise<SessionExportReport>;
36
+ /** A session read from an export file and checked: everything an import writes for it. */
37
+ export interface ParsedSession {
38
+ readonly file: string;
39
+ readonly header: SessionRecordHeader;
40
+ /** The entries without the tool outputs they carried inline, which are in `blobs`. */
41
+ readonly entries: readonly SessionEntry[];
42
+ readonly blobs: readonly SessionBlobCopy[];
43
+ }
44
+ /**
45
+ * Reads and checks every `*.jsonl` session export file in `directory`; nothing is written. A directory that does not
46
+ * exist holds no sessions. Throws `StorageTransferError` with the file, and the line where there is one, for the first
47
+ * file that is not a valid format-4 session.
48
+ */
49
+ export declare function readSessionExports(directory: string): Promise<ParsedSession[]>;
50
+ /** What an import does to one session. */
51
+ export type SessionImportAction = "add" | "update" | "unchanged";
52
+ interface PlannedSession {
53
+ readonly session: ParsedSession;
54
+ readonly action: SessionImportAction;
55
+ /** How many entries the storage holds, and the sequence number a write must expect. */
56
+ readonly storedEntries: number;
57
+ readonly storedSeq: number;
58
+ }
59
+ /** What importing a set of session export files does to a session store, decided before anything is written. */
60
+ export interface SessionImportPlan {
61
+ readonly store: SessionStore;
62
+ readonly sessions: readonly PlannedSession[];
63
+ }
64
+ /** The sessions of a plan an import writes. */
65
+ export declare function pendingSessions(plan: SessionImportPlan): string[];
66
+ /**
67
+ * Compares every session of `sessions` with the store's copy, writing nothing. A session is identified by its header
68
+ * ID, as `atomic --import` identifies it: one the store lacks is added; one whose entries the store holds the first
69
+ * part of gets the rest; one the store holds every entry of is left alone. A session created at another time, or one
70
+ * whose entries continued differently in the store, fails with the file and line.
71
+ */
72
+ export declare function planSessionImport(store: SessionStore, sessions: readonly ParsedSession[]): Promise<SessionImportPlan>;
73
+ /**
74
+ * Writes what `plan` decided, one session at a time. Each write expects the store to hold exactly what the plan
75
+ * compared: a session another process created or added entries to since fails with the file, and nothing of it is
76
+ * written. Session storage has no lock an import can hold across sessions, so when a write fails after earlier writes
77
+ * (or after `workflowsWritten`, the runs the same import already wrote), `StorageImportIncompleteError` names what was
78
+ * written and what was not; importing again writes only what is missing. A session the store already holds in full
79
+ * gets the tool outputs of the file it lacks, so a rerun also finishes a session whose outputs an interrupted import
80
+ * did not store.
81
+ */
82
+ export declare function applySessionImport(plan: SessionImportPlan, workflowsWritten?: readonly string[]): Promise<SessionImportReport>;
83
+ export {};
84
+ //# sourceMappingURL=session-transfer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-transfer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AAe,EAAE,CAAC;CAC3C;AA8CD;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAwBpF;AAED,0CAA0C;AAC1C,MAAM,MAAM,mBAAmB,GAAG,KAAK,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEjE,UAAU,cAAc;IACvB,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,mBAAmB,CAAC;IACrC,uFAAuF;IACvF,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC3B;AAED,gHAAgH;AAChH,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,SAAS,cAAc,EAAE,CAAC;CAC7C;AAMD,+CAA+C;AAC/C,wBAAgB,eAAe,CAAC,IAAI,EAAE,iBAAiB,GAAG,MAAM,EAAE,CAEjE;AAWD;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACtC,KAAK,EAAE,YAAY,EACnB,QAAQ,EAAE,SAAS,aAAa,EAAE,GAChC,OAAO,CAAC,iBAAiB,CAAC,CA+B5B;AAeD;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CACvC,IAAI,EAAE,iBAAiB,EACvB,gBAAgB,GAAE,SAAS,MAAM,EAAO,GACtC,OAAO,CAAC,mBAAmB,CAAC,CAsD9B"}
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Sessions as format-4 JSONL files for `atomic storage export` and `import` (#4720): each session is written to
3
+ * `<dir>/<sessionId>.jsonl` in the format JSONL session storage keeps and `atomic --import` reads, with the tool outputs
4
+ * and worktree snapshot content it references carried inline as `/export <file>.jsonl` carries them, and read back with
5
+ * the same parser.
6
+ */
7
+ import { mkdir } from "node:fs/promises";
8
+ import { assertSessionBlobStore, inlineToolOutput, storeSessionBlobs, takeInlineToolOutput, } from "./session-tool-output.js";
9
+ import { adoptInlineSnapshotBlobs, inlineSnapshotBlobs, sessionSnapshotBlobs } from "./session-worktree-snapshots.js";
10
+ import { SessionConflictError, SessionExistsError } from "./storage/session/errors.js";
11
+ import { JsonlSessionStore } from "./storage/session/jsonl-session-store.js";
12
+ import { isCurrentSessionHeader } from "./storage/session/legacy-format.js";
13
+ import { SESSION_FORMAT_VERSION, } from "./storage/session/types.js";
14
+ import { readTransferDirectory, StorageImportIncompleteError, StorageTransferError, transferFile, writeLinesAtomically, } from "./storage/transfer-files.js";
15
+ function storeLocation(store) {
16
+ return store.descriptor.location;
17
+ }
18
+ function newestFirst(left, right) {
19
+ const modified = Date.parse(right.modifiedAt) - Date.parse(left.modifiedAt);
20
+ if (modified !== 0)
21
+ return modified;
22
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
23
+ }
24
+ /**
25
+ * A session's export file, line by line: the header, then every entry in append order, with the snapshot records,
26
+ * snapshot content and tool outputs the store holds carried inline, each once. Tool outputs are read one at a time.
27
+ */
28
+ async function* sessionExportLines(store, snapshot) {
29
+ yield JSON.stringify({ type: "session", ...snapshot.header });
30
+ const records = new Map();
31
+ for (const entry of snapshot.entries)
32
+ if (entry.type === "worktree_snapshot" && entry.snapshot !== undefined && !records.has(entry.snapshotId))
33
+ records.set(entry.snapshotId, entry.snapshot);
34
+ const entries = await inlineSnapshotBlobs(snapshot.entries, records, sessionSnapshotBlobs(store.snapshotBlobs, snapshot.entries));
35
+ for await (const entry of inlineToolOutput(entries, store, snapshot.header.id))
36
+ yield JSON.stringify(entry);
37
+ }
38
+ /**
39
+ * Exports the sessions of `store`, every project's and workflow stage sessions included, to
40
+ * `<directory>/<sessionId>.jsonl`, one file per session. Each file is written whole or not at all; the same session
41
+ * gives the same bytes, and a file that already holds them is not rewritten.
42
+ */
43
+ export async function exportSessions(store, directory, options = {}) {
44
+ let summaries = [];
45
+ for await (const summary of store.list({ includeInternal: true }))
46
+ summaries.push(summary);
47
+ if (options.since !== undefined) {
48
+ const since = options.since;
49
+ summaries = summaries.filter((summary) => Date.parse(summary.modifiedAt) >= since);
50
+ }
51
+ summaries.sort(newestFirst);
52
+ if (options.limit !== undefined)
53
+ summaries = summaries.slice(0, options.limit);
54
+ await mkdir(directory, { recursive: true });
55
+ const written = [];
56
+ const unchanged = [];
57
+ for (const summary of summaries) {
58
+ const snapshot = await store.load(summary.id);
59
+ const outcome = await writeLinesAtomically(transferFile(directory, summary.id), sessionExportLines(store, snapshot));
60
+ (outcome === "written" ? written : unchanged).push(summary.id);
61
+ }
62
+ return { written, unchanged };
63
+ }
64
+ /** Checks one export file with the parser JSONL session storage and `atomic --import` use. */
65
+ async function parseSessionFile(source, { file, lines }) {
66
+ const fail = (line, reason, cause) => {
67
+ throw new StorageTransferError({ path: file, ...(line === undefined ? {} : { line }), reason, cause });
68
+ };
69
+ if (lines.length === 0)
70
+ return fail(1, "is empty; expected a session header");
71
+ const parsed = [];
72
+ for (const { line, text } of lines) {
73
+ if (text.trim() === "")
74
+ fail(line, "is empty");
75
+ let value;
76
+ try {
77
+ value = JSON.parse(text);
78
+ }
79
+ catch (error) {
80
+ return fail(line, `is not valid JSON (${error.message})`);
81
+ }
82
+ if (typeof value !== "object" || value === null || Array.isArray(value))
83
+ fail(line, "is not a JSON object");
84
+ parsed.push(value);
85
+ }
86
+ const first = parsed[0];
87
+ if (first.type !== "session")
88
+ fail(1, `is not an Atomic session export: its type is ${JSON.stringify(first.type ?? null)}, not "session"`);
89
+ if (!isCurrentSessionHeader(first))
90
+ fail(1, `has unsupported session format version ${JSON.stringify(first.version ?? null)}; this Atomic reads version ${SESSION_FORMAT_VERSION}`);
91
+ let loaded;
92
+ try {
93
+ loaded = await source.loadFile(file);
94
+ }
95
+ catch (error) {
96
+ return fail(undefined, `is not a valid session: ${error.message}`, error);
97
+ }
98
+ try {
99
+ const { entries, blobs } = takeInlineToolOutput(loaded.entries, loaded.header.id);
100
+ // Checks the snapshot content carried inline against its hashes, writing nothing.
101
+ await adoptInlineSnapshotBlobs(entries, undefined);
102
+ return { file, header: loaded.header, entries, blobs };
103
+ }
104
+ catch (error) {
105
+ return fail(undefined, `carries content that does not match its hash: ${error.message}`);
106
+ }
107
+ }
108
+ /**
109
+ * Reads and checks every `*.jsonl` session export file in `directory`; nothing is written. A directory that does not
110
+ * exist holds no sessions. Throws `StorageTransferError` with the file, and the line where there is one, for the first
111
+ * file that is not a valid format-4 session.
112
+ */
113
+ export async function readSessionExports(directory) {
114
+ const files = await readTransferDirectory(directory);
115
+ if (files.length === 0)
116
+ return [];
117
+ const source = await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
118
+ try {
119
+ const parsed = [];
120
+ const seen = new Map();
121
+ for (const lines of files) {
122
+ const session = await parseSessionFile(source, lines);
123
+ const earlier = seen.get(session.header.id);
124
+ if (earlier !== undefined)
125
+ throw new StorageTransferError({
126
+ path: session.file,
127
+ line: 1,
128
+ id: session.header.id,
129
+ reason: `session ${session.header.id} is also in ${earlier}; keep one file per session`,
130
+ });
131
+ seen.set(session.header.id, session.file);
132
+ parsed.push(session);
133
+ }
134
+ return parsed;
135
+ }
136
+ finally {
137
+ await source.close();
138
+ }
139
+ }
140
+ function pendingIds(sessions) {
141
+ return sessions.map((planned) => planned.session.header.id);
142
+ }
143
+ /** The sessions of a plan an import writes. */
144
+ export function pendingSessions(plan) {
145
+ return plan.sessions.filter((session) => session.action !== "unchanged").map((session) => session.session.header.id);
146
+ }
147
+ /**
148
+ * The fields import compares between an entry of a file and the stored entry at the same position: its ID, its
149
+ * parent and its type, as `--import` and session storage identify entries. Everything else may differ, so a file a
150
+ * tool redacted strings in imports as the session it came from.
151
+ */
152
+ function sameEntry(stored, exported) {
153
+ return stored.id === exported.id && stored.parentId === exported.parentId && stored.type === exported.type;
154
+ }
155
+ /**
156
+ * Compares every session of `sessions` with the store's copy, writing nothing. A session is identified by its header
157
+ * ID, as `atomic --import` identifies it: one the store lacks is added; one whose entries the store holds the first
158
+ * part of gets the rest; one the store holds every entry of is left alone. A session created at another time, or one
159
+ * whose entries continued differently in the store, fails with the file and line.
160
+ */
161
+ export async function planSessionImport(store, sessions) {
162
+ const planned = [];
163
+ const location = storeLocation(store);
164
+ for (const session of sessions) {
165
+ const { header, entries, file } = session;
166
+ const fail = (line, reason) => {
167
+ throw new StorageTransferError({ path: file, line, id: header.id, reason });
168
+ };
169
+ if ((await store.readHeader(header.id)) === undefined) {
170
+ assertBlobs(store, session);
171
+ planned.push({ session, action: "add", storedEntries: 0, storedSeq: 0 });
172
+ continue;
173
+ }
174
+ const stored = await store.load(header.id);
175
+ if (stored.header.createdAt !== header.createdAt)
176
+ fail(1, `session ${header.id} in ${location} was created at another time; it is a different session with the same ID`);
177
+ const shared = Math.min(stored.entries.length, entries.length);
178
+ for (let index = 0; index < shared; index++)
179
+ if (!sameEntry(stored.entries[index], entries[index]))
180
+ fail(index + 2, `entry ${index + 1} differs from entry ${index + 1} of session ${header.id} in ${location}: the session continued differently there`);
181
+ const action = entries.length > stored.entries.length ? "update" : "unchanged";
182
+ if (action === "update")
183
+ assertBlobs(store, session);
184
+ planned.push({ session, action, storedEntries: stored.entries.length, storedSeq: stored.lastSeq });
185
+ }
186
+ return { store, sessions: planned };
187
+ }
188
+ function assertBlobs(store, session) {
189
+ try {
190
+ assertSessionBlobStore(store, session.header.id, session.blobs.length);
191
+ }
192
+ catch (error) {
193
+ throw new StorageTransferError({
194
+ path: session.file,
195
+ id: session.header.id,
196
+ reason: error.message,
197
+ cause: error,
198
+ });
199
+ }
200
+ }
201
+ /**
202
+ * Writes what `plan` decided, one session at a time. Each write expects the store to hold exactly what the plan
203
+ * compared: a session another process created or added entries to since fails with the file, and nothing of it is
204
+ * written. Session storage has no lock an import can hold across sessions, so when a write fails after earlier writes
205
+ * (or after `workflowsWritten`, the runs the same import already wrote), `StorageImportIncompleteError` names what was
206
+ * written and what was not; importing again writes only what is missing. A session the store already holds in full
207
+ * gets the tool outputs of the file it lacks, so a rerun also finishes a session whose outputs an interrupted import
208
+ * did not store.
209
+ */
210
+ export async function applySessionImport(plan, workflowsWritten = []) {
211
+ const { store } = plan;
212
+ const report = { added: [], updated: [], unchanged: [] };
213
+ const pending = plan.sessions.filter((planned) => planned.action !== "unchanged");
214
+ /** `error`, naming what this import wrote before it when it wrote anything, and the sessions it did not write. */
215
+ const failure = (error, notWritten) => {
216
+ const sessionsWritten = [...report.added, ...report.updated];
217
+ if (sessionsWritten.length === 0 && workflowsWritten.length === 0)
218
+ return error;
219
+ return new StorageImportIncompleteError(error, {
220
+ written: { sessions: sessionsWritten, workflows: workflowsWritten },
221
+ notWritten: { sessions: notWritten, workflows: [] },
222
+ });
223
+ };
224
+ for (const planned of plan.sessions) {
225
+ if (planned.action !== "unchanged")
226
+ continue;
227
+ // An import stopped between writing a new session's entries and its tool outputs left the session complete but
228
+ // its outputs missing: the rerun stores the ones the store lacks.
229
+ const { header, blobs } = planned.session;
230
+ try {
231
+ for (const blob of blobs)
232
+ if ((await store.getBlob?.(header.id, blob.hash)) === undefined)
233
+ await store.putBlob?.(header.id, blob.read());
234
+ }
235
+ catch (caught) {
236
+ throw failure(caught, [header.id, ...pendingIds(pending)]);
237
+ }
238
+ report.unchanged.push(header.id);
239
+ }
240
+ for (const [index, planned] of pending.entries()) {
241
+ const { header, file, blobs } = planned.session;
242
+ try {
243
+ const entries = await adoptInlineSnapshotBlobs(planned.session.entries, store.snapshotBlobs);
244
+ if (planned.action === "add") {
245
+ await store.create(header, entries);
246
+ await storeSessionBlobs(store, header.id, blobs);
247
+ }
248
+ else {
249
+ for (const blob of blobs)
250
+ await store.putBlob(header.id, blob.read());
251
+ await store.append(header.id, entries.slice(planned.storedEntries), { expectSeq: planned.storedSeq });
252
+ }
253
+ }
254
+ catch (caught) {
255
+ const error = caught instanceof SessionConflictError || caught instanceof SessionExistsError
256
+ ? new StorageTransferError({
257
+ path: file,
258
+ line: 1,
259
+ id: header.id,
260
+ reason: `session ${header.id} changed in ${storeLocation(store)} after the import compared it (another process wrote to it); it was not imported`,
261
+ cause: caught,
262
+ })
263
+ : caught;
264
+ throw failure(error, pendingIds(pending.slice(index)));
265
+ }
266
+ (planned.action === "add" ? report.added : report.updated).push(header.id);
267
+ }
268
+ return report;
269
+ }
270
+ //# sourceMappingURL=session-transfer.js.map