@bastani/atomic 0.9.82 → 0.9.83
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 +20 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +2 -16
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +2 -16
- package/dist/builtin/workflows/src/index.js +2 -16
- package/dist/builtin/workflows/src/local-worker-entry.mjs +2 -16
- package/dist/cli/storage-command.d.ts +11 -1
- package/dist/cli/storage-command.d.ts.map +1 -1
- package/dist/cli/storage-command.js +102 -4
- package/dist/cli/storage-command.js.map +1 -1
- package/dist/core/storage/journal-adoption.d.ts +48 -0
- package/dist/core/storage/journal-adoption.d.ts.map +1 -1
- package/dist/core/storage/journal-adoption.js +41 -1
- package/dist/core/storage/journal-adoption.js.map +1 -1
- package/dist/core/storage/journal-transfer.d.ts +126 -0
- package/dist/core/storage/journal-transfer.d.ts.map +1 -0
- package/dist/core/storage/journal-transfer.js +690 -0
- package/dist/core/storage/journal-transfer.js.map +1 -0
- package/docs/reference/cli.md +4 -0
- package/docs/storage.md +54 -0
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.9.83] - 2026-11-13
|
|
6
|
+
|
|
7
|
+
Workflow runs that travel between machines.
|
|
8
|
+
|
|
9
|
+
- **Carry workflow runs as plain files.** `atomic storage export <dir>` writes runs from the local journal to versioned JSONL files, and `atomic storage import <dir>` loads them back, so hosts that persist only files keep their runs and an interrupted run resumes on the new machine ([#4716](https://github.com/bastani-inc/atomic/issues/4716), [#4717](https://github.com/bastani-inc/atomic/pull/4717)).
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Added `atomic storage export <dir>` and `atomic storage import <dir>`, which move workflow runs between the local workflow journal and versioned JSONL files (one `<runId>.jsonl` per run), so hosts that persist only files can keep runs between machines. Export selects runs with `--run`, `--unfinished` and `--limit`, reads a consistent snapshot, writes each file atomically, and gives byte-identical output for an unchanged run. Import checks every file before writing, is idempotent, accepts files whose string values were redacted, and leaves imported runs unowned so an interrupted run resumes on the new machine ([#4716](https://github.com/bastani-inc/atomic/issues/4716), [#4717](https://github.com/bastani-inc/atomic/pull/4717))
|
|
14
|
+
|
|
15
|
+
## [0.9.83-alpha.1] - 2026-11-13
|
|
16
|
+
|
|
17
|
+
Workflow runs that travel between machines.
|
|
18
|
+
|
|
19
|
+
- **Carry workflow runs as plain files.** `atomic storage export <dir>` writes runs from the local journal to versioned JSONL files, and `atomic storage import <dir>` loads them back, so hosts that persist only files keep their runs and an interrupted run resumes on the new machine ([#4716](https://github.com/bastani-inc/atomic/issues/4716), [#4717](https://github.com/bastani-inc/atomic/pull/4717)).
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- Added `atomic storage export <dir>` and `atomic storage import <dir>`, which move workflow runs between the local workflow journal and versioned JSONL files (one `<runId>.jsonl` per run), so hosts that persist only files can keep runs between machines. Export selects runs with `--run`, `--unfinished` and `--limit`, reads a consistent snapshot, writes each file atomically, and gives byte-identical output for an unchanged run. Import checks every file before writing, is idempotent, accepts files whose string values were redacted, and leaves imported runs unowned so an interrupted run resumes on the new machine ([#4716](https://github.com/bastani-inc/atomic/issues/4716))
|
|
24
|
+
|
|
5
25
|
## [0.9.82] - 2026-11-13
|
|
6
26
|
|
|
7
27
|
More predictable file search and a steadier RPC startup.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/intercom",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.83",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension providing a private coordination channel between parent and child agent sessions. Fork of: https://github.com/nicobailon/pi-intercom",
|
|
6
6
|
"contributors": [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/web-access",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.83",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension for web search, URL fetching, GitHub repo cloning, PDF/video extraction. Fork of: https://github.com/nicobailon/pi-web-access",
|
|
6
6
|
"contributors": [
|
|
@@ -11305,6 +11305,7 @@ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
|
11305
11305
|
import {
|
|
11306
11306
|
openNodeSqliteDatabase,
|
|
11307
11307
|
renderStorageIdentifiers as renderStorageIdentifiers2,
|
|
11308
|
+
runJournalTableDefinitions,
|
|
11308
11309
|
SqlSnapshotBlobStore,
|
|
11309
11310
|
StorageUnavailableError as StorageUnavailableError2
|
|
11310
11311
|
} from "@bastani/atomic/storage";
|
|
@@ -11412,22 +11413,7 @@ class SqlRunJournal {
|
|
|
11412
11413
|
await tx.run(`INSERT INTO ${t.meta} VALUES (?)`, JOURNAL_SCHEMA_VERSION);
|
|
11413
11414
|
} else
|
|
11414
11415
|
SqlRunJournal.assertSchemaVersion(versions[0][JOURNAL_COLUMNS.schemaVersion]);
|
|
11415
|
-
await tx.exec(
|
|
11416
|
-
CREATE TABLE IF NOT EXISTS ${t.runs}(
|
|
11417
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, ${JOURNAL_COLUMNS.name} TEXT NOT NULL, ${JOURNAL_COLUMNS.cwd} TEXT NOT NULL,
|
|
11418
|
-
${JOURNAL_COLUMNS.createdAt} INTEGER NOT NULL, ${JOURNAL_COLUMNS.status} TEXT NOT NULL, ${JOURNAL_COLUMNS.headerJson} TEXT NOT NULL
|
|
11419
|
-
);
|
|
11420
|
-
CREATE TABLE IF NOT EXISTS ${t.events}(
|
|
11421
|
-
${JOURNAL_COLUMNS.runId} TEXT NOT NULL,
|
|
11422
|
-
${JOURNAL_COLUMNS.seq} INTEGER NOT NULL, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.key} TEXT,
|
|
11423
|
-
${JOURNAL_COLUMNS.type} TEXT NOT NULL, ${JOURNAL_COLUMNS.payload} TEXT NOT NULL, ${JOURNAL_COLUMNS.at} INTEGER NOT NULL,
|
|
11424
|
-
PRIMARY KEY(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.seq}), UNIQUE(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.key})
|
|
11425
|
-
);
|
|
11426
|
-
CREATE TABLE IF NOT EXISTS ${t.leases}(
|
|
11427
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY,
|
|
11428
|
-
${JOURNAL_COLUMNS.holderId} TEXT, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.renewedAt} INTEGER NOT NULL
|
|
11429
|
-
);
|
|
11430
|
-
`);
|
|
11416
|
+
await tx.exec(runJournalTableDefinitions(prefix));
|
|
11431
11417
|
await SqlSnapshotBlobStore.initialize(tx, prefix);
|
|
11432
11418
|
}, JOURNAL_WRITE_TRANSACTION);
|
|
11433
11419
|
}
|
|
@@ -3744,6 +3744,7 @@ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
|
3744
3744
|
import {
|
|
3745
3745
|
openNodeSqliteDatabase,
|
|
3746
3746
|
renderStorageIdentifiers as renderStorageIdentifiers2,
|
|
3747
|
+
runJournalTableDefinitions,
|
|
3747
3748
|
SqlSnapshotBlobStore,
|
|
3748
3749
|
StorageUnavailableError as StorageUnavailableError2
|
|
3749
3750
|
} from "@bastani/atomic/storage";
|
|
@@ -3851,22 +3852,7 @@ class SqlRunJournal {
|
|
|
3851
3852
|
await tx.run(`INSERT INTO ${t.meta} VALUES (?)`, JOURNAL_SCHEMA_VERSION);
|
|
3852
3853
|
} else
|
|
3853
3854
|
SqlRunJournal.assertSchemaVersion(versions[0][JOURNAL_COLUMNS.schemaVersion]);
|
|
3854
|
-
await tx.exec(
|
|
3855
|
-
CREATE TABLE IF NOT EXISTS ${t.runs}(
|
|
3856
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, ${JOURNAL_COLUMNS.name} TEXT NOT NULL, ${JOURNAL_COLUMNS.cwd} TEXT NOT NULL,
|
|
3857
|
-
${JOURNAL_COLUMNS.createdAt} INTEGER NOT NULL, ${JOURNAL_COLUMNS.status} TEXT NOT NULL, ${JOURNAL_COLUMNS.headerJson} TEXT NOT NULL
|
|
3858
|
-
);
|
|
3859
|
-
CREATE TABLE IF NOT EXISTS ${t.events}(
|
|
3860
|
-
${JOURNAL_COLUMNS.runId} TEXT NOT NULL,
|
|
3861
|
-
${JOURNAL_COLUMNS.seq} INTEGER NOT NULL, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.key} TEXT,
|
|
3862
|
-
${JOURNAL_COLUMNS.type} TEXT NOT NULL, ${JOURNAL_COLUMNS.payload} TEXT NOT NULL, ${JOURNAL_COLUMNS.at} INTEGER NOT NULL,
|
|
3863
|
-
PRIMARY KEY(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.seq}), UNIQUE(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.key})
|
|
3864
|
-
);
|
|
3865
|
-
CREATE TABLE IF NOT EXISTS ${t.leases}(
|
|
3866
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY,
|
|
3867
|
-
${JOURNAL_COLUMNS.holderId} TEXT, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.renewedAt} INTEGER NOT NULL
|
|
3868
|
-
);
|
|
3869
|
-
`);
|
|
3855
|
+
await tx.exec(runJournalTableDefinitions(prefix));
|
|
3870
3856
|
await SqlSnapshotBlobStore.initialize(tx, prefix);
|
|
3871
3857
|
}, JOURNAL_WRITE_TRANSACTION);
|
|
3872
3858
|
}
|
|
@@ -2326,6 +2326,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
2326
2326
|
import {
|
|
2327
2327
|
openNodeSqliteDatabase,
|
|
2328
2328
|
renderStorageIdentifiers as renderStorageIdentifiers2,
|
|
2329
|
+
runJournalTableDefinitions,
|
|
2329
2330
|
SqlSnapshotBlobStore,
|
|
2330
2331
|
StorageUnavailableError as StorageUnavailableError2
|
|
2331
2332
|
} from "@bastani/atomic/storage";
|
|
@@ -2433,22 +2434,7 @@ class SqlRunJournal {
|
|
|
2433
2434
|
await tx.run(`INSERT INTO ${t.meta} VALUES (?)`, JOURNAL_SCHEMA_VERSION);
|
|
2434
2435
|
} else
|
|
2435
2436
|
SqlRunJournal.assertSchemaVersion(versions[0][JOURNAL_COLUMNS.schemaVersion]);
|
|
2436
|
-
await tx.exec(
|
|
2437
|
-
CREATE TABLE IF NOT EXISTS ${t.runs}(
|
|
2438
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, ${JOURNAL_COLUMNS.name} TEXT NOT NULL, ${JOURNAL_COLUMNS.cwd} TEXT NOT NULL,
|
|
2439
|
-
${JOURNAL_COLUMNS.createdAt} INTEGER NOT NULL, ${JOURNAL_COLUMNS.status} TEXT NOT NULL, ${JOURNAL_COLUMNS.headerJson} TEXT NOT NULL
|
|
2440
|
-
);
|
|
2441
|
-
CREATE TABLE IF NOT EXISTS ${t.events}(
|
|
2442
|
-
${JOURNAL_COLUMNS.runId} TEXT NOT NULL,
|
|
2443
|
-
${JOURNAL_COLUMNS.seq} INTEGER NOT NULL, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.key} TEXT,
|
|
2444
|
-
${JOURNAL_COLUMNS.type} TEXT NOT NULL, ${JOURNAL_COLUMNS.payload} TEXT NOT NULL, ${JOURNAL_COLUMNS.at} INTEGER NOT NULL,
|
|
2445
|
-
PRIMARY KEY(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.seq}), UNIQUE(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.key})
|
|
2446
|
-
);
|
|
2447
|
-
CREATE TABLE IF NOT EXISTS ${t.leases}(
|
|
2448
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY,
|
|
2449
|
-
${JOURNAL_COLUMNS.holderId} TEXT, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.renewedAt} INTEGER NOT NULL
|
|
2450
|
-
);
|
|
2451
|
-
`);
|
|
2437
|
+
await tx.exec(runJournalTableDefinitions(prefix));
|
|
2452
2438
|
await SqlSnapshotBlobStore.initialize(tx, prefix);
|
|
2453
2439
|
}, JOURNAL_WRITE_TRANSACTION);
|
|
2454
2440
|
}
|
|
@@ -3744,6 +3744,7 @@ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
|
3744
3744
|
import {
|
|
3745
3745
|
openNodeSqliteDatabase,
|
|
3746
3746
|
renderStorageIdentifiers as renderStorageIdentifiers2,
|
|
3747
|
+
runJournalTableDefinitions,
|
|
3747
3748
|
SqlSnapshotBlobStore,
|
|
3748
3749
|
StorageUnavailableError as StorageUnavailableError2
|
|
3749
3750
|
} from "@bastani/atomic/storage";
|
|
@@ -3851,22 +3852,7 @@ class SqlRunJournal {
|
|
|
3851
3852
|
await tx.run(`INSERT INTO ${t.meta} VALUES (?)`, JOURNAL_SCHEMA_VERSION);
|
|
3852
3853
|
} else
|
|
3853
3854
|
SqlRunJournal.assertSchemaVersion(versions[0][JOURNAL_COLUMNS.schemaVersion]);
|
|
3854
|
-
await tx.exec(
|
|
3855
|
-
CREATE TABLE IF NOT EXISTS ${t.runs}(
|
|
3856
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, ${JOURNAL_COLUMNS.name} TEXT NOT NULL, ${JOURNAL_COLUMNS.cwd} TEXT NOT NULL,
|
|
3857
|
-
${JOURNAL_COLUMNS.createdAt} INTEGER NOT NULL, ${JOURNAL_COLUMNS.status} TEXT NOT NULL, ${JOURNAL_COLUMNS.headerJson} TEXT NOT NULL
|
|
3858
|
-
);
|
|
3859
|
-
CREATE TABLE IF NOT EXISTS ${t.events}(
|
|
3860
|
-
${JOURNAL_COLUMNS.runId} TEXT NOT NULL,
|
|
3861
|
-
${JOURNAL_COLUMNS.seq} INTEGER NOT NULL, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.key} TEXT,
|
|
3862
|
-
${JOURNAL_COLUMNS.type} TEXT NOT NULL, ${JOURNAL_COLUMNS.payload} TEXT NOT NULL, ${JOURNAL_COLUMNS.at} INTEGER NOT NULL,
|
|
3863
|
-
PRIMARY KEY(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.seq}), UNIQUE(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.key})
|
|
3864
|
-
);
|
|
3865
|
-
CREATE TABLE IF NOT EXISTS ${t.leases}(
|
|
3866
|
-
${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY,
|
|
3867
|
-
${JOURNAL_COLUMNS.holderId} TEXT, ${JOURNAL_COLUMNS.epoch} INTEGER NOT NULL, ${JOURNAL_COLUMNS.renewedAt} INTEGER NOT NULL
|
|
3868
|
-
);
|
|
3869
|
-
`);
|
|
3855
|
+
await tx.exec(runJournalTableDefinitions(prefix));
|
|
3870
3856
|
await SqlSnapshotBlobStore.initialize(tx, prefix);
|
|
3871
3857
|
}, JOURNAL_WRITE_TRANSACTION);
|
|
3872
3858
|
}
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* selection comes from, whether its adapter loads and its database answers, and what the running Intercom broker
|
|
4
4
|
* uses. `atomic storage join` points this machine's global `storage` setting at a shared libSQL / Turso database.
|
|
5
5
|
* `atomic storage adopt` registers existing journal files in the journal store in place, and `atomic storage
|
|
6
|
-
* consolidate` moves their finished runs into the store's own shards.
|
|
6
|
+
* consolidate` moves their finished runs into the store's own shards. `atomic storage export` and `atomic storage
|
|
7
|
+
* import` move workflow runs between the local workflow journal and versioned JSONL files (#4716).
|
|
7
8
|
*/
|
|
8
9
|
import type { IntercomBrokerControl } from "../core/intercom-broker-control.js";
|
|
9
10
|
import { LIBSQL_ADAPTER_PACKAGE, STORAGE_TOKEN_FILE } from "../core/storage/selection.js";
|
|
@@ -25,6 +26,15 @@ export type StorageCommand = {
|
|
|
25
26
|
readonly discover: boolean;
|
|
26
27
|
} | {
|
|
27
28
|
readonly kind: "consolidate";
|
|
29
|
+
} | {
|
|
30
|
+
readonly kind: "export";
|
|
31
|
+
readonly directory: string;
|
|
32
|
+
readonly runs?: readonly string[];
|
|
33
|
+
readonly unfinished: boolean;
|
|
34
|
+
readonly limit?: number;
|
|
35
|
+
} | {
|
|
36
|
+
readonly kind: "import";
|
|
37
|
+
readonly directory: string;
|
|
28
38
|
};
|
|
29
39
|
export declare class StorageCommandError extends Error {
|
|
30
40
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-command.d.ts","sourceRoot":"","sources":["../../src/cli/storage-command.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"storage-command.d.ts","sourceRoot":"","sources":["../../src/cli/storage-command.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAchF,OAAO,EAGN,sBAAsB,EAEtB,kBAAkB,EAClB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAEN,KAAK,YAAY,EAIjB,KAAK,aAAa,EAClB,MAAM,mCAAmC,CAAC;AAG3C,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,CAAC;AAiDtD,MAAM,MAAM,cAAc,GACvB;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA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CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACxC,iEAAiE;IACjE,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,qBAAqB,CAAC,CAAC;CAC5D;AAID,+EAA+E;AAC/E,wBAAsB,iBAAiB,CAAC,OAAO,EAAE;IAChD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,qBAAqB,CAAC,CAAC;CAC5D,GAAG,OAAO,CAAC,qBAAqB,GAAG,KAAK,CAAC,CAQzC;AAED,wGAAwG;AACxG,wBAAgB,MAAM,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAOpD;AAQD,8DAA8D;AAC9D,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,EAAE,CAkEnE;AAwED,4DAA4D;AAC5D,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,CAiChH"}
|
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
* selection comes from, whether its adapter loads and its database answers, and what the running Intercom broker
|
|
4
4
|
* uses. `atomic storage join` points this machine's global `storage` setting at a shared libSQL / Turso database.
|
|
5
5
|
* `atomic storage adopt` registers existing journal files in the journal store in place, and `atomic storage
|
|
6
|
-
* consolidate` moves their finished runs into the store's own shards.
|
|
6
|
+
* consolidate` moves their finished runs into the store's own shards. `atomic storage export` and `atomic storage
|
|
7
|
+
* import` move workflow runs between the local workflow journal and versioned JSONL files (#4716).
|
|
7
8
|
*/
|
|
8
9
|
import { join, resolve } from "node:path";
|
|
9
10
|
import { APP_NAME } from "../config.js";
|
|
10
11
|
import { isJournalStoreError, isTeamProfileConfigError, isTeamProfileError } from "../core/storage/errors.js";
|
|
11
12
|
import { adoptJournals, consolidateJournalStore, defaultJournalStoreDirectory, } from "../core/storage/journal-adoption.js";
|
|
13
|
+
import { exportWorkflowRuns, importWorkflowRuns, isWorkflowRunTransferError, WORKFLOW_RUN_EXPORT_VERSION, } from "../core/storage/journal-transfer.js";
|
|
12
14
|
import { checkTeamUrl, isFileUrl, LIBSQL_ADAPTER_PACKAGE, missingTeamToken, STORAGE_TOKEN_FILE, } from "../core/storage/selection.js";
|
|
13
15
|
import { collectStorageStatus, describeStorageError, describeStorageSelection, effectiveJournalSelection, } from "../core/storage/storage-status.js";
|
|
14
16
|
import { joinSharedDatabase } from "../core/storage/team.js";
|
|
@@ -18,6 +20,8 @@ const HELP = `Usage:
|
|
|
18
20
|
${APP_NAME} storage join <url> [--token-file <path>] [--prefix <prefix>]
|
|
19
21
|
${APP_NAME} storage adopt <path>... [--no-discover]
|
|
20
22
|
${APP_NAME} storage consolidate
|
|
23
|
+
${APP_NAME} storage export <dir> [--run <id>]... [--unfinished] [--limit <n>]
|
|
24
|
+
${APP_NAME} storage import <dir>
|
|
21
25
|
|
|
22
26
|
Commands:
|
|
23
27
|
status Show, for sessions, workflow runs, and Intercom, the selected storage and where the
|
|
@@ -38,13 +42,23 @@ Commands:
|
|
|
38
42
|
Move finished runs (completed, failed or cancelled, not leased, without local workers)
|
|
39
43
|
from adopted journals into the journal store's own shards. Other runs stay where they
|
|
40
44
|
are. An interrupted consolidation leaves every run readable; run it again to finish.
|
|
45
|
+
export Write workflow runs to <dir>/<runId>.jsonl, one file per run (format version
|
|
46
|
+
${WORKFLOW_RUN_EXPORT_VERSION}): a header line, then one line per journal event. Every run by default;
|
|
47
|
+
a file is replaced whole, and one that already holds the same run is not rewritten.
|
|
48
|
+
import Restore every *.jsonl export in <dir> into this directory's workflow journal. All files
|
|
49
|
+
are checked first, so a malformed or unsupported file changes nothing. Importing again
|
|
50
|
+
adds nothing; a newer export of a run adds its later events. Imported runs are not
|
|
51
|
+
owned by any process: an interrupted one can be resumed here.
|
|
41
52
|
|
|
42
53
|
Options:
|
|
43
54
|
--json Print the status as JSON
|
|
44
55
|
--token-file <path> File holding the database token, for example from \`turso db tokens create\`;
|
|
45
56
|
surrounding whitespace is removed. Required except for file: URLs
|
|
46
57
|
--prefix <prefix> Table prefix, to share one database between projects or teams
|
|
47
|
-
--no-discover adopt: register only the given paths
|
|
58
|
+
--no-discover adopt: register only the given paths
|
|
59
|
+
--run <id> export: only this run; repeat for more
|
|
60
|
+
--unfinished export: only runs that are not completed, failed or cancelled
|
|
61
|
+
--limit <n> export: at most n runs, newest first`;
|
|
48
62
|
const HELP_HINT = `Use "${APP_NAME} storage --help" for usage.`;
|
|
49
63
|
export class StorageCommandError extends Error {
|
|
50
64
|
}
|
|
@@ -58,6 +72,8 @@ export function parseStorageCommand(args) {
|
|
|
58
72
|
const values = new Map();
|
|
59
73
|
let json = false;
|
|
60
74
|
let discover = true;
|
|
75
|
+
let unfinished = false;
|
|
76
|
+
const runs = [];
|
|
61
77
|
for (let index = 0; index < rest.length; index++) {
|
|
62
78
|
const arg = rest[index];
|
|
63
79
|
if (command === "status" && arg === "--json") {
|
|
@@ -68,7 +84,19 @@ export function parseStorageCommand(args) {
|
|
|
68
84
|
discover = false;
|
|
69
85
|
continue;
|
|
70
86
|
}
|
|
71
|
-
if (command === "
|
|
87
|
+
if (command === "export" && arg === "--unfinished") {
|
|
88
|
+
unfinished = true;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (command === "export" && arg === "--run") {
|
|
92
|
+
const value = rest[++index];
|
|
93
|
+
if (value === undefined || value === "")
|
|
94
|
+
throw new StorageCommandError("--run needs a run ID.");
|
|
95
|
+
runs.push(value);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if ((command === "join" && (arg === "--token-file" || arg === "--prefix")) ||
|
|
99
|
+
(command === "export" && arg === "--limit")) {
|
|
72
100
|
const value = rest[++index];
|
|
73
101
|
if (value === undefined)
|
|
74
102
|
throw new StorageCommandError(`${arg} needs a value.`);
|
|
@@ -111,6 +139,28 @@ export function parseStorageCommand(args) {
|
|
|
111
139
|
throw new StorageCommandError(`Usage: ${APP_NAME} storage consolidate`);
|
|
112
140
|
return { kind: "consolidate" };
|
|
113
141
|
}
|
|
142
|
+
if (command === "export") {
|
|
143
|
+
const [directory, ...extra] = positional;
|
|
144
|
+
if (directory === undefined || extra.length > 0)
|
|
145
|
+
throw new StorageCommandError(`Usage: ${APP_NAME} storage export <dir> [--run <id>]... [--unfinished] [--limit <n>]`);
|
|
146
|
+
const limitText = values.get("--limit");
|
|
147
|
+
const limit = limitText === undefined ? undefined : Number(limitText);
|
|
148
|
+
if (limit !== undefined && (!/^[0-9]+$/.test(limitText) || !Number.isSafeInteger(limit) || limit < 1))
|
|
149
|
+
throw new StorageCommandError(`--limit needs a positive whole number, not "${limitText}".`);
|
|
150
|
+
return {
|
|
151
|
+
kind: "export",
|
|
152
|
+
directory,
|
|
153
|
+
unfinished,
|
|
154
|
+
...(runs.length === 0 ? {} : { runs }),
|
|
155
|
+
...(limit === undefined ? {} : { limit }),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
if (command === "import") {
|
|
159
|
+
const [directory, ...extra] = positional;
|
|
160
|
+
if (directory === undefined || extra.length > 0)
|
|
161
|
+
throw new StorageCommandError(`Usage: ${APP_NAME} storage import <dir>`);
|
|
162
|
+
return { kind: "import", directory };
|
|
163
|
+
}
|
|
114
164
|
throw new StorageCommandError(`Unknown storage command "${command}".\n${HELP_HINT}`);
|
|
115
165
|
}
|
|
116
166
|
const errorText = describeStorageError;
|
|
@@ -278,6 +328,10 @@ export async function runStorageCommand(args, options) {
|
|
|
278
328
|
return await adopt(command, options, log);
|
|
279
329
|
if (command.kind === "consolidate")
|
|
280
330
|
return await consolidate(options, log);
|
|
331
|
+
if (command.kind === "export")
|
|
332
|
+
return await exportRuns(command, options, log, error);
|
|
333
|
+
if (command.kind === "import")
|
|
334
|
+
return await importRuns(command, options, log);
|
|
281
335
|
return await joinStorage(command, options, (...lines) => {
|
|
282
336
|
for (const line of lines)
|
|
283
337
|
log(line);
|
|
@@ -290,7 +344,10 @@ export async function runStorageCommand(args, options) {
|
|
|
290
344
|
error(caught.hint);
|
|
291
345
|
return 1;
|
|
292
346
|
}
|
|
293
|
-
error(caught instanceof StorageCommandError ||
|
|
347
|
+
error(caught instanceof StorageCommandError ||
|
|
348
|
+
isWorkflowRunTransferError(caught) ||
|
|
349
|
+
isTeamProfileError(caught) ||
|
|
350
|
+
isTeamProfileConfigError(caught)
|
|
294
351
|
? caught.message
|
|
295
352
|
: `Error: ${errorText(caught)}`);
|
|
296
353
|
return 1;
|
|
@@ -342,4 +399,45 @@ async function consolidate(options, log) {
|
|
|
342
399
|
log(note);
|
|
343
400
|
return failures.size === 0 ? 0 : 1;
|
|
344
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* The local workflow journal this directory's runs use, which `export` and `import` read and write. A shared database
|
|
404
|
+
* is refused: every machine joined to it already reads its runs, so there is nothing to carry between them.
|
|
405
|
+
*/
|
|
406
|
+
function transferStorage(options, command) {
|
|
407
|
+
const selection = effectiveJournalSelection(options.cwd, options.agentDir);
|
|
408
|
+
if (selection.kind === "sharded")
|
|
409
|
+
return { kind: "store", directory: selection.dir };
|
|
410
|
+
if (selection.kind === "sqlite" && selection.path !== ":memory:")
|
|
411
|
+
return {
|
|
412
|
+
kind: "sqlite",
|
|
413
|
+
path: resolve(options.cwd, selection.path),
|
|
414
|
+
...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),
|
|
415
|
+
};
|
|
416
|
+
throw new StorageCommandError(`${APP_NAME} storage ${command} works with a local workflow journal (the journal store or a SQLite file), but workflow runs here use ${describeStorageSelection(selection)}.` +
|
|
417
|
+
(selection.kind === "adapter"
|
|
418
|
+
? " 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."
|
|
419
|
+
: ""));
|
|
420
|
+
}
|
|
421
|
+
async function exportRuns(command, options, log, error) {
|
|
422
|
+
const storage = transferStorage(options, "export");
|
|
423
|
+
const directory = resolve(options.cwd, command.directory);
|
|
424
|
+
const report = await exportWorkflowRuns(storage, directory, {
|
|
425
|
+
unfinished: command.unfinished,
|
|
426
|
+
...(command.runs === undefined ? {} : { runs: command.runs }),
|
|
427
|
+
...(command.limit === undefined ? {} : { limit: command.limit }),
|
|
428
|
+
});
|
|
429
|
+
const total = report.written.length + report.unchanged.length;
|
|
430
|
+
log(`Exported ${total} workflow run${total === 1 ? "" : "s"} to ${directory} (${report.written.length} written, ${report.unchanged.length} unchanged).`);
|
|
431
|
+
for (const skipped of report.skipped)
|
|
432
|
+
error(`Skipped ${skipped.runId === undefined ? skipped.path : `run ${skipped.runId}`}: ${skipped.reason}.`);
|
|
433
|
+
return 0;
|
|
434
|
+
}
|
|
435
|
+
async function importRuns(command, options, log) {
|
|
436
|
+
const storage = transferStorage(options, "import");
|
|
437
|
+
const directory = resolve(options.cwd, command.directory);
|
|
438
|
+
const report = await importWorkflowRuns(storage, directory);
|
|
439
|
+
const total = report.added.length + report.updated.length + report.unchanged.length;
|
|
440
|
+
log(`Imported ${total} workflow run${total === 1 ? "" : "s"} from ${directory} (${report.added.length} added, ${report.updated.length} updated, ${report.unchanged.length} already up to date).`);
|
|
441
|
+
return 0;
|
|
442
|
+
}
|
|
345
443
|
//# sourceMappingURL=storage-command.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-command.js","sourceRoot":"","sources":["../../src/cli/storage-command.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;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,YAAY,EACZ,SAAS,EACT,sBAAsB,EACtB,gBAAgB,EAChB,kBAAkB,GAClB,MAAM,8BAA8B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/F,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI;QAC5B,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;YAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IACxG,KAAK,MAAM,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,IAAI,GAAG,kBAAkB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACpD,IAAI,IAAI,KAAK,SAAS;QAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,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.\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\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\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\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\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\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\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 === \"join\" && (arg === \"--token-file\" || arg === \"--prefix\")) {\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\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\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 || isTeamProfileError(caught) || isTeamProfileConfigError(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"]}
|
|
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;AA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AAC,MAAM,WAAW,MAAM,CAAC,OAAO,CAAC,MAAM,aAAa,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"]}
|