@evident-ai/runner-synchroniser 0.1.1-dev.7568241 → 0.1.1-dev.96bc2ed

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 (3) hide show
  1. package/README.md +84 -5
  2. package/dist/cli.js +396 -4
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -62,6 +62,7 @@ version at all.
62
62
  | `sync-once <claude\|opencode>` | — | `0` = ran; non-zero = tool broken |
63
63
  | `model-auth-ready` | — | `0` = ready, `10` = not ready; other = tool broken |
64
64
  | `self-stop` | — | `0` = stopped, `20` = keep the task; other = tool broken |
65
+ | `session-db-classify <litestream-restore-exit-code> <attempt> [--on-unusable-replica=<prune\|leave\|clear\|crash>]` | — | `0` = restored/no-replica/disabled, `32` = re-run and ask again, `31` = unusable (booted fresh, skip replicate), `30` = fatal; other = usage/tool broken |
65
66
 
66
67
  `self-stop` scales this agent's own ECS service to `desiredCount=0` on a clean idle exit
67
68
  (see Configuration for `CLUSTER`/`SERVICE`/`EVIDENT_SELFSTOP_ROLE_ARN`). It exits `0`
@@ -74,6 +75,66 @@ broader: `src/logger.ts` marks it verbatim because operator greps and CloudWatch
74
75
  match on that exact string, so widening what it labels is cheaper than breaking every
75
76
  saved query.
76
77
 
78
+ ### `session-db-classify`
79
+
80
+ Implementation-facing reference for the 7th command: it decides what a just-run `litestream restore` of `opencode.db` means and, on attempt 2 only, may run a recovery strategy against S3. `packages/runner-image/README.md`'s [Strategy/What/Cost table](../runner-image/README.md#when-the-replica-is-unusable-evident_on_unusable_replica) is the operator-facing view of the same command — this section doesn't restate it.
81
+
82
+ #### Positionals
83
+
84
+ | Positional | Meaning |
85
+ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
86
+ | `<litestream-restore-exit-code>` | Status of the `litestream restore` the shell just ran. `0` → stat the local DB; any non-zero → the recovery ladder below. The value itself is never inspected (a Go panic `2` is treated exactly like a `1`). |
87
+ | `<attempt>` | 1-based (`/^\d+$/`, `>= 1`) — the sole mutation gate. |
88
+
89
+ #### The attempt ladder
90
+
91
+ | Attempt | Behaviour |
92
+ | ------- | ---------------------------------------------------------------- |
93
+ | 1 | Plain retry — **zero S3 calls, not even the probe**. |
94
+ | 2 | The **only** attempt that may probe or mutate S3. |
95
+ | ≥ 3 | Gives up **before** the probe. |
96
+
97
+ `entrypoint.sh` caps its retry loop at a hard-coded `3` as a real second bound: the classifier is stateless per invocation, so nothing except that loop stops attempt 2 from being asked twice.
98
+
99
+ #### `--on-unusable-replica` flag syntax
100
+
101
+ - Only the `=`-joined form (`--on-unusable-replica=leave`); the space-separated form is rejected.
102
+ - Position-free.
103
+ - Repeating the flag is rejected, even with the same value both times.
104
+ - Any other `--` token is rejected.
105
+ - Every rejection exits `2` (`EXIT_USAGE`) with the usage message — **never** a silent fall-back to the destructive default.
106
+
107
+ #### Outcome → exit code
108
+
109
+ | Outcome | Code | When |
110
+ | ----------------------------------------------- | ---- | -------------------------------------------------------------------------------- |
111
+ | `disabled` | `0` | bucket or prefix unset — short-circuits **before** the exit code is examined |
112
+ | `restored` | `0` | restore exit `0` and the local DB is non-empty |
113
+ | `noReplica` | `0` | restore exit `0` but the DB is absent or zero-byte |
114
+ | `retryTransient` | `32` | restore failed, attempt 1 — no probe, no S3 call at all |
115
+ | `recovered` | `32` | attempt 2, a successful `prune` (1 key) or any `clear` (including a partial one) |
116
+ | `unusableReplica(strategy)` | `31` | attempt 2, `leave` |
117
+ | `unusableReplica(attemptsExhausted)` | `31` | attempt ≥ 3, before the probe |
118
+ | `unusableReplica(targetHealthy\|layoutMismatch)` | `31` | attempt 2, `prune` declined to delete anything |
119
+ | `unusableReplica(recoveryFailed)` | `31` | attempt 2, `prune`'s delete itself threw |
120
+ | `fatal(misconfig)` | `30` | no object store while persistence is enabled, or the probe failed on attempt 2 |
121
+ | `fatal(deliberate)` | `30` | attempt 2, `crash` |
122
+
123
+ `31` also guarantees local debris (`opencode.db`, `-wal`, `-shm`) is discarded, one `try` per path, at the classifier's single return point. Note `32` isn't purely "transient" — `recovered` shares it with `retryTransient` even though a `recovered` outcome already mutated S3.
124
+
125
+ The probe is a `list`, not a `get`: S3 answers a wrong bucket name with `NoSuchBucket`, also a 404, so a `get`-based probe would read a misconfigured bucket as healthy and unlock recovery against it.
126
+
127
+ #### The four `--on-unusable-replica` strategies
128
+
129
+ - **`prune` (default)** — ≤1 guarded delete iff the newest L0's own bytes fail the LTX header check (`length >= 100` and magic `"LTX1"`) → `recovered`/`32`; declined (`targetHealthy`/`layoutMismatch`) or a failed delete (`recoveryFailed`) → `31`. **Header-only** check: a valid header with deeper corruption is judged sound and left alone — the real trade-off, and **not** "can destroy a healthy L0 object when an older one is corrupt" (false of merged `main`: the delete is unreachable unless the object's own bytes fail the check). `targetHealthy` also covers an unreadable object (absent evidence must not unlock a delete). Never escalates to `clear`, never prunes twice.
130
+ - **`leave`** — zero S3 mutation → `31`. Cost is not just "prior history lost": `entrypoint.sh` also skips `litestream replicate` for the **whole boot**, so this boot's history is ephemeral too. Upside: replica left byte-intact for forensics, no crash loop.
131
+ - **`clear`** — deletes every key under `<prefix>/opencode.db/` passing `isDeletableReplicaKey`; that guard, not the `list()` prefix, is the boundary (IAM grants `s3:DeleteObject*` bucket-wide). One `try` per key. A **partial** clear still reports `recovered`/`32`. Cost: all saved history, unconditionally.
132
+ - **`crash`** — first in the switch, no S3 mutation even considered → `fatal(deliberate)`/`30` → `entrypoint.sh` `die`s → task replaced → **crash loop** until an operator intervenes.
133
+
134
+ `EVIDENT_ON_UNUSABLE_REPLICA` is a `packages/runner-image` (entrypoint) variable translated into the flag above at boot — this CLI never reads it, so it has no row in this README's Configuration table below; see [runner-image's README](../runner-image/README.md#when-the-replica-is-unusable-evident_on_unusable_replica). An unrecognised value (including wrong casing, e.g. `Prune`) exits `2`, outside `entrypoint.sh`'s `0|10|20|30|31|32` allow-list — a typo **crash-loops the task on attempt 1** rather than falling back to `prune`, and also logs the misleading "credential persistence is DEGRADED" ERROR.
135
+
136
+ See `specs/local-runner.feature:49-70` for the behavioural anchor (31 comes online, 30 does not).
137
+
77
138
  ### Why the contract is asymmetric
78
139
 
79
140
  `restore` and `sync-once` **never** report a domain outcome through the exit code. A
@@ -97,6 +158,8 @@ that it has no auth. `self-stop` decides whether a task may go away, so a broken
97
158
  must never kill one: `entrypoint.sh` reads any non-zero exactly like `20` and keeps the
98
159
  task, and only a `0` — returned solely on a confirmed `desiredCount` of 0 — lets it stop.
99
160
 
161
+ `session-db-classify` is neither a domain outcome nor a predicate — it's a **third category**: a typed classification with four actionable answers (`0` ran, `32` retry, `31` unusable, `30` fatal), numbered above the two predicates' codes so they can't collide with a future one (`cli.ts:42-47`; see `diagnostics.ts`'s `sessionDbExitCode` for the single outcome → code mapping). The fail-safe direction inverts here: the two predicates above treat an unexpected code as the *safe* answer, but `entrypoint.sh` treats an unexpected code from `session-db-classify` as **fatal** (it `die`s) — correctly, because a boot that can't classify its own replica must not guess about deleting S3 objects.
162
+
100
163
  `src/shell-contract.json` is the machine-checked source of truth for the command list, and
101
164
  `shell-contract.test.ts` holds **every** shell that speaks it to it — Fargate's
102
165
  `packages/runner-image/entrypoint.sh` and the MicroVM's
@@ -142,10 +205,23 @@ The paths and keys that follow from the bucket/prefix:
142
205
  | OpenCode DB | `$HOME/.local/share/opencode/opencode.db` | `<prefix>/opencode.db` (litestream) |
143
206
 
144
207
  The session database is replicated by litestream itself; this package only generates its
145
- config. `env` emits `CREDS_BUCKET`, `CLAUDE_CREDS`, `OPENCODE_DB_PATH` and
208
+ config. `env` emits `PERSISTENCE_BUCKET`, `CLAUDE_CREDS`, `OPENCODE_DB_PATH` and
146
209
  `CREDS_SYNC_INTERVAL`, each single-quoted so a value containing shell metacharacters is
147
210
  inert when `eval`'d.
148
211
 
212
+ `entrypoint.sh` asserts, right after it `eval`s this output, that each key is *defined*
213
+ (not merely non-empty) and splits the four into two groups: a key is **required** — the
214
+ shell dies naming it — if it has no safe degradation; it is **tolerated** — the shell logs
215
+ a WARNING naming it and carries on — if it does. `OPENCODE_DB_PATH` and
216
+ `CREDS_SYNC_INTERVAL` are required: both are dereferenced for real work (deleting/creating
217
+ the session DB, sizing the sync-loop sleep), so a guessed value would be actively wrong,
218
+ not merely absent. `PERSISTENCE_BUCKET` and `CLAUDE_CREDS` are tolerated: an empty
219
+ `PERSISTENCE_BUCKET` is already the designed "persistence disabled" state, and
220
+ `CLAUDE_CREDS` is dereferenced only in operator-facing message text. If you change
221
+ `renderEnv` to make a required key conditional, the entrypoint will brick every container
222
+ running that version — the runner installs this package from a floating npm tag (`dev` /
223
+ `latest`), so the shell and the CLI can genuinely be different versions (#779, #821).
224
+
149
225
  ## Behaviour worth knowing
150
226
 
151
227
  - **A non-empty local file that is not valid JSON is protected**, never overwritten and
@@ -170,11 +246,14 @@ inert when `eval`'d.
170
246
 
171
247
  ## The `ObjectStore` port
172
248
 
173
- `restore` and `sync` talk to a two-method interface `get(key)` returning `null` when
174
- the object is absent, and `put(key, body)`. S3 vocabulary (`@aws-sdk/client-s3`, the
175
- typed `NoSuchKey`/`NotFound` errors) is confined to the single adapter in
249
+ `restore`/`sync` and `session-db-classify` talk to a four-method interface: `get(key)`
250
+ returning `null` when the object is absent, `put(key, body)`, `list(prefix)` and
251
+ `delete(key)` for session-DB recovery. `list` throws on any error and never maps one to
252
+ `[]` (an empty array means "reached the store, nothing there"); the adapter owns
253
+ pagination, and `delete` is idempotent. S3 vocabulary (`@aws-sdk/client-s3`, the typed
254
+ `NoSuchKey`/`NotFound` errors) is confined to the single adapter in
176
255
  `src/s3-object-store.ts`, so the storage backend can be swapped without touching the
177
- restore/sync logic.
256
+ restore/sync/classify logic.
178
257
 
179
258
  The S3 adapter is the only one that exists. It uses no static credentials — auth is
180
259
  whatever the ambient AWS credential chain resolves (on the Evident runner, the ECS task
package/dist/cli.js CHANGED
@@ -39606,6 +39606,87 @@ function describeRestoreOutcome(label, path2, outcome) {
39606
39606
  return assertNever(outcome);
39607
39607
  }
39608
39608
  }
39609
+ function assertNeverSessionDb(value) {
39610
+ throw new Error(`Unhandled session-DB restore outcome: ${JSON.stringify(value)}`);
39611
+ }
39612
+ function assertNeverUnusableReplicaReason(value) {
39613
+ throw new Error(`Unhandled unusable-replica reason: ${JSON.stringify(value)}`);
39614
+ }
39615
+ function assertNeverFatalCause(value) {
39616
+ throw new Error(`Unhandled fatal cause: ${JSON.stringify(value)}`);
39617
+ }
39618
+ function sessionDbExitCode(outcome) {
39619
+ switch (outcome.kind) {
39620
+ case "disabled":
39621
+ case "restored":
39622
+ case "noReplica":
39623
+ return 0;
39624
+ case "retryTransient":
39625
+ case "recovered":
39626
+ return 32;
39627
+ // re-run `litestream restore` and ask again
39628
+ case "unusableReplica":
39629
+ return 31;
39630
+ // booted with a fresh DB; the shell must skip `litestream replicate`
39631
+ case "fatal":
39632
+ return 30;
39633
+ // shared by a genuine misconfig and a deliberate `crash` choice
39634
+ default:
39635
+ return assertNeverSessionDb(outcome);
39636
+ }
39637
+ }
39638
+ function describeUnusableReplica(reason) {
39639
+ const base = "SESSION-DB-REPLICA-UNUSABLE: booting with a FRESH opencode.db; prior session history is lost until the replica is fixed.";
39640
+ switch (reason) {
39641
+ case "strategy":
39642
+ return `${base} (--on-unusable-replica=leave was selected; nothing in S3 was touched.)`;
39643
+ case "attemptsExhausted":
39644
+ return `${base} (recovery did not make the replica usable after retrying; giving up.)`;
39645
+ case "layoutMismatch":
39646
+ return `${base} (no level-0 LTX object was found under the replica prefix, so --on-unusable-replica=prune had nothing matching its expected layout to delete.)`;
39647
+ case "recoveryFailed":
39648
+ return `${base} (the recovery delete itself failed; see the warning above for the S3 error.)`;
39649
+ case "targetHealthy":
39650
+ return `${base} (--on-unusable-replica=prune found a newest L0 object but could not confirm it is corrupt \u2014 it either passed the LTX structural check or could not be re-read \u2014 so it declined to delete it; nothing in S3 was touched.)`;
39651
+ default:
39652
+ return assertNeverUnusableReplicaReason(reason);
39653
+ }
39654
+ }
39655
+ function describeSessionDbFatal(outcome, config) {
39656
+ switch (outcome.cause) {
39657
+ // Names the bucket/region and the probe error — never the crash flag.
39658
+ case "misconfig":
39659
+ return `FATAL: could not verify the opencode.db replica in S3 is reachable/authorised (bucket=${config.bucket ?? "<unset>"}, region=${config.region ?? "<unset>"}): ${outcome.detail}`;
39660
+ // Names the flag and states nothing was touched — never bucket/region, so an
39661
+ // operator reading this is never sent chasing IAM over their own flag.
39662
+ case "deliberate":
39663
+ return `FATAL: ${outcome.detail}`;
39664
+ default:
39665
+ return assertNeverFatalCause(outcome.cause);
39666
+ }
39667
+ }
39668
+ function describeSessionDbClassification(outcome, config) {
39669
+ switch (outcome.kind) {
39670
+ case "disabled":
39671
+ return "No opencode.db restore attempted; credential persistence is disabled (LITESTREAM_BUCKET/LITESTREAM_PREFIX unset).";
39672
+ case "restored":
39673
+ return "opencode.db restored from the object store.";
39674
+ case "noReplica":
39675
+ return "No opencode.db replica found in the object store; opencode will create a fresh session DB.";
39676
+ case "retryTransient":
39677
+ return "opencode.db replica restore failed (transient); retrying.";
39678
+ case "recovered": {
39679
+ const objects = outcome.deleted.length === 0 ? "no objects (see the warnings above for what failed)" : `${outcome.deleted.length} object${outcome.deleted.length === 1 ? "" : "s"} (${outcome.deleted.join(", ")})`;
39680
+ return `Attempted opencode.db replica recovery via --on-unusable-replica=${outcome.strategy}, deleting ${objects}; retrying the restore.` + (outcome.strategy === "clear" ? " Prior session history is lost." : "");
39681
+ }
39682
+ case "unusableReplica":
39683
+ return describeUnusableReplica(outcome.reason);
39684
+ case "fatal":
39685
+ return describeSessionDbFatal(outcome, config);
39686
+ default:
39687
+ return assertNeverSessionDb(outcome);
39688
+ }
39689
+ }
39609
39690
 
39610
39691
  // src/file-ops.ts
39611
39692
  init_esm_shims();
@@ -39708,6 +39789,48 @@ async function modelAuthReady(config, fileOps) {
39708
39789
  return config.hasModelApiKey;
39709
39790
  }
39710
39791
 
39792
+ // src/replica-keys.ts
39793
+ init_esm_shims();
39794
+ var DEFAULT_UNUSABLE_REPLICA_STRATEGY = "prune";
39795
+ var STRATEGIES = ["prune", "leave", "clear", "crash"];
39796
+ function parseUnusableReplicaStrategy(value) {
39797
+ if (value === void 0) return DEFAULT_UNUSABLE_REPLICA_STRATEGY;
39798
+ return STRATEGIES.includes(value) ? value : null;
39799
+ }
39800
+ function replicaDbPrefix(prefix) {
39801
+ return `${prefix}/opencode.db/`;
39802
+ }
39803
+ var LTX_FILENAME = /^([0-9a-fA-F]+)-([0-9a-fA-F]+)\.ltx$/;
39804
+ function parseLtxKey(prefix, key) {
39805
+ if (key.split("/").includes("..")) return null;
39806
+ const root12 = `${replicaDbPrefix(prefix)}ltx/`;
39807
+ if (!key.startsWith(root12)) return null;
39808
+ const [levelPart, filename, ...rest] = key.slice(root12.length).split("/");
39809
+ if (rest.length > 0 || filename === void 0 || !/^\d+$/.test(levelPart)) return null;
39810
+ const match = LTX_FILENAME.exec(filename);
39811
+ if (!match) return null;
39812
+ return {
39813
+ level: Number.parseInt(levelPart, 10),
39814
+ minTxid: BigInt(`0x${match[1]}`),
39815
+ maxTxid: BigInt(`0x${match[2]}`)
39816
+ };
39817
+ }
39818
+ function newestL0Key(prefix, keys) {
39819
+ let newest = null;
39820
+ for (const key of keys) {
39821
+ const parsed = parseLtxKey(prefix, key);
39822
+ if (parsed === null || parsed.level !== 0) continue;
39823
+ if (newest === null || parsed.maxTxid > newest.maxTxid) {
39824
+ newest = { key, maxTxid: parsed.maxTxid };
39825
+ }
39826
+ }
39827
+ return newest?.key ?? null;
39828
+ }
39829
+ function isDeletableReplicaKey(prefix, key) {
39830
+ if (!key.startsWith(replicaDbPrefix(prefix))) return false;
39831
+ return !key.split("/").includes("..");
39832
+ }
39833
+
39711
39834
  // src/restore.ts
39712
39835
  init_esm_shims();
39713
39836
  import { dirname as dirname3 } from "path";
@@ -43273,6 +43396,10 @@ var _ep4 = {
43273
43396
  DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true },
43274
43397
  Bucket: { type: "contextParams", name: "Bucket" }
43275
43398
  };
43399
+ var _ep8 = {
43400
+ Bucket: { type: "contextParams", name: "Bucket" },
43401
+ Prefix: { type: "contextParams", name: "Prefix" }
43402
+ };
43276
43403
  var _mw011 = (Command3, cs, config, o7) => [
43277
43404
  getThrow200ExceptionsPlugin(config)
43278
43405
  ];
@@ -49549,11 +49676,21 @@ var S3Client = class extends Client {
49549
49676
  }
49550
49677
  };
49551
49678
 
49679
+ // ../../node_modules/.pnpm/@aws-sdk+client-s3@3.1095.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectCommand.js
49680
+ init_esm_shims();
49681
+ var DeleteObjectCommand = class extends command11(_ep011, _mw011, "DeleteObject", DeleteObject$) {
49682
+ };
49683
+
49552
49684
  // ../../node_modules/.pnpm/@aws-sdk+client-s3@3.1095.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectCommand.js
49553
49685
  init_esm_shims();
49554
49686
  var GetObjectCommand = class extends command11(_ep011, _mw7, "GetObject", GetObject$) {
49555
49687
  };
49556
49688
 
49689
+ // ../../node_modules/.pnpm/@aws-sdk+client-s3@3.1095.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectsV2Command.js
49690
+ init_esm_shims();
49691
+ var ListObjectsV2Command = class extends command11(_ep8, _mw011, "ListObjectsV2", ListObjectsV2$) {
49692
+ };
49693
+
49557
49694
  // ../../node_modules/.pnpm/@aws-sdk+client-s3@3.1095.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectCommand.js
49558
49695
  init_esm_shims();
49559
49696
  var PutObjectCommand = class extends command11(_ep011, _mw11, "PutObject", PutObject$) {
@@ -49588,8 +49725,190 @@ var S3ObjectStore = class {
49588
49725
  async put(key, body) {
49589
49726
  await this.client.send(new PutObjectCommand({ Bucket: this.bucket, Key: key, Body: body }));
49590
49727
  }
49728
+ async list(prefix) {
49729
+ const keys = [];
49730
+ let continuationToken;
49731
+ do {
49732
+ const response = await this.client.send(
49733
+ new ListObjectsV2Command({
49734
+ Bucket: this.bucket,
49735
+ Prefix: prefix,
49736
+ ContinuationToken: continuationToken
49737
+ })
49738
+ );
49739
+ for (const object of response.Contents ?? []) {
49740
+ if (object.Key) keys.push(object.Key);
49741
+ }
49742
+ continuationToken = response.NextContinuationToken;
49743
+ } while (continuationToken);
49744
+ return keys;
49745
+ }
49746
+ async delete(key) {
49747
+ try {
49748
+ await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }));
49749
+ } catch (error) {
49750
+ if (isNotFound(error)) return;
49751
+ throw error;
49752
+ }
49753
+ }
49591
49754
  };
49592
49755
 
49756
+ // src/session-db.ts
49757
+ init_esm_shims();
49758
+
49759
+ // src/replica-recovery.ts
49760
+ init_esm_shims();
49761
+
49762
+ // src/ltx-format.ts
49763
+ init_esm_shims();
49764
+ var LTX_HEADER_SIZE = 100;
49765
+ var LTX_MAGIC = "LTX1";
49766
+ function isStructurallySoundLtxObject(bytes) {
49767
+ if (bytes.length < LTX_HEADER_SIZE) return false;
49768
+ return bytes.subarray(0, LTX_MAGIC.length).toString("ascii") === LTX_MAGIC;
49769
+ }
49770
+
49771
+ // src/replica-recovery.ts
49772
+ async function probeReplica(store, prefix, log) {
49773
+ const root12 = replicaDbPrefix(prefix);
49774
+ try {
49775
+ const keys = await store.list(root12);
49776
+ return { ok: true, keys };
49777
+ } catch (error) {
49778
+ const detail = describeError(error);
49779
+ log(`WARNING: could not list the replica prefix ${root12}: ${detail}`);
49780
+ return { ok: false, detail };
49781
+ }
49782
+ }
49783
+ async function pruneNewestL0(store, prefix, keys, log) {
49784
+ const target = newestL0Key(prefix, keys);
49785
+ if (target === null || !isDeletableReplicaKey(prefix, target)) {
49786
+ if (target !== null) {
49787
+ log(`WARNING: refusing to prune ${target}: failed the replica-key guard.`);
49788
+ }
49789
+ return { deleted: null, reason: "layoutMismatch" };
49790
+ }
49791
+ let bytes;
49792
+ try {
49793
+ bytes = await store.get(target);
49794
+ } catch (error) {
49795
+ log(
49796
+ `WARNING: could not re-read ${target} to check whether it is actually corrupt before pruning it: ${describeError(error)}. Declining to prune without positive evidence.`
49797
+ );
49798
+ return { deleted: null, reason: "targetHealthy" };
49799
+ }
49800
+ if (bytes === null || isStructurallySoundLtxObject(bytes)) {
49801
+ log(
49802
+ `INFO: the newest L0 replica object ${target} ` + (bytes === null ? "is already gone" : "looks structurally sound") + "; declining to prune it without positive evidence it is the corrupt one."
49803
+ );
49804
+ return { deleted: null, reason: "targetHealthy" };
49805
+ }
49806
+ log(`INFO: pruning the newest L0 replica object ${target} (fails the LTX structural check).`);
49807
+ try {
49808
+ await store.delete(target);
49809
+ } catch (error) {
49810
+ log(`WARNING: failed to prune ${target}: ${describeError(error)}`);
49811
+ return { deleted: null, reason: "deleteFailed" };
49812
+ }
49813
+ return { deleted: target };
49814
+ }
49815
+ async function clearReplica(store, prefix, keys, log) {
49816
+ const deleted = [];
49817
+ const failed = [];
49818
+ for (const key of keys) {
49819
+ if (!isDeletableReplicaKey(prefix, key)) {
49820
+ log(`WARNING: refusing to delete ${key}: outside the replica prefix.`);
49821
+ continue;
49822
+ }
49823
+ try {
49824
+ await store.delete(key);
49825
+ deleted.push(key);
49826
+ } catch (error) {
49827
+ log(`WARNING: failed to delete ${key}: ${describeError(error)}`);
49828
+ failed.push(key);
49829
+ }
49830
+ }
49831
+ return { deleted, failed };
49832
+ }
49833
+
49834
+ // src/session-db.ts
49835
+ function assertNeverStrategy(value) {
49836
+ throw new Error(`Unhandled unusable-replica strategy: ${JSON.stringify(value)}`);
49837
+ }
49838
+ async function classifySessionDbRestore(params) {
49839
+ const outcome = await decideSessionDbRestore(params);
49840
+ if (outcome.kind === "unusableReplica") {
49841
+ await discardLocalDebris(params.fileOps, params.config.opencodeDbPath, params.log);
49842
+ }
49843
+ return outcome;
49844
+ }
49845
+ async function decideSessionDbRestore(params) {
49846
+ const { exitCode, attempt, strategy, config, fileOps, store, log } = params;
49847
+ if (config.bucket === null || config.prefix === null) {
49848
+ return { kind: "disabled" };
49849
+ }
49850
+ const prefix = config.prefix;
49851
+ if (exitCode === 0) {
49852
+ const stat2 = await fileOps.stat(config.opencodeDbPath);
49853
+ return stat2 !== null && stat2.size > 0 ? { kind: "restored" } : { kind: "noReplica" };
49854
+ }
49855
+ if (store === null) {
49856
+ return {
49857
+ kind: "fatal",
49858
+ cause: "misconfig",
49859
+ detail: "persistence is enabled (LITESTREAM_BUCKET/LITESTREAM_PREFIX are set) but no object store is available to verify the replica is reachable"
49860
+ };
49861
+ }
49862
+ if (attempt === 1) {
49863
+ return { kind: "retryTransient" };
49864
+ }
49865
+ if (attempt >= 3) {
49866
+ return { kind: "unusableReplica", reason: "attemptsExhausted" };
49867
+ }
49868
+ const probe = await probeReplica(store, prefix, log);
49869
+ if (!probe.ok) {
49870
+ return {
49871
+ kind: "fatal",
49872
+ cause: "misconfig",
49873
+ detail: `could not verify the session-DB replica is reachable: ${probe.detail}`
49874
+ };
49875
+ }
49876
+ const keys = probe.keys;
49877
+ switch (strategy) {
49878
+ case "crash":
49879
+ return {
49880
+ kind: "fatal",
49881
+ cause: "deliberate",
49882
+ detail: "the replica is unusable and --on-unusable-replica=crash was selected; no S3 object was touched"
49883
+ };
49884
+ case "leave":
49885
+ return { kind: "unusableReplica", reason: "strategy" };
49886
+ case "prune": {
49887
+ const result = await pruneNewestL0(store, prefix, keys, log);
49888
+ if (result.deleted === null) {
49889
+ const reason = result.reason === "deleteFailed" ? "recoveryFailed" : result.reason;
49890
+ return { kind: "unusableReplica", reason };
49891
+ }
49892
+ return { kind: "recovered", strategy: "prune", deleted: [result.deleted] };
49893
+ }
49894
+ case "clear": {
49895
+ const result = await clearReplica(store, prefix, keys, log);
49896
+ return { kind: "recovered", strategy: "clear", deleted: result.deleted };
49897
+ }
49898
+ default:
49899
+ return assertNeverStrategy(strategy);
49900
+ }
49901
+ }
49902
+ async function discardLocalDebris(fileOps, dbPath, log) {
49903
+ for (const path2 of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
49904
+ try {
49905
+ await fileOps.remove(path2);
49906
+ } catch (error) {
49907
+ log(`WARNING: could not remove local session-DB debris at ${path2}: ${describeError(error)}`);
49908
+ }
49909
+ }
49910
+ }
49911
+
49593
49912
  // src/self-stop.ts
49594
49913
  init_esm_shims();
49595
49914
  function isComplete(credentials) {
@@ -49666,7 +49985,15 @@ async function selfStop({
49666
49985
 
49667
49986
  // src/shell-contract.json
49668
49987
  var shell_contract_default = {
49669
- commands: ["env", "litestream-config", "restore", "sync-once", "model-auth-ready", "self-stop"]
49988
+ commands: [
49989
+ "env",
49990
+ "litestream-config",
49991
+ "restore",
49992
+ "sync-once",
49993
+ "model-auth-ready",
49994
+ "self-stop",
49995
+ "session-db-classify"
49996
+ ]
49670
49997
  };
49671
49998
 
49672
49999
  // src/sync.ts
@@ -49718,6 +50045,9 @@ var EXIT_NOT_READY = 10;
49718
50045
  var EXIT_KEEP_TASK = 20;
49719
50046
  var EXIT_USAGE = 2;
49720
50047
  var EXIT_BROKEN = 1;
50048
+ var EXIT_SESSION_DB_FATAL = 30;
50049
+ var EXIT_SESSION_DB_UNUSABLE = 31;
50050
+ var EXIT_SESSION_DB_RETRY = 32;
49721
50051
  var STATE_SUFFIX = ".synchash";
49722
50052
  var COMMANDS = shell_contract_default.commands;
49723
50053
  var USAGE = `Usage: runner-synchroniser <command> [args]
@@ -49729,6 +50059,12 @@ var USAGE = `Usage: runner-synchroniser <command> [args]
49729
50059
  model-auth-ready exit 0 when some model auth is configured, ${EXIT_NOT_READY} when not
49730
50060
  self-stop scale this agent's own ECS service to 0; exit 0 only
49731
50061
  when desiredCount is confirmed 0, ${EXIT_KEEP_TASK} to keep the task
50062
+ session-db-classify <litestream-restore-exit-code> <attempt>
50063
+ [--on-unusable-replica=<prune|leave|clear|crash>]
50064
+ classify a just-run \`litestream restore\` of opencode.db;
50065
+ exit 0 restored/no-replica/disabled, ${EXIT_SESSION_DB_RETRY} re-run
50066
+ and ask again, ${EXIT_SESSION_DB_UNUSABLE} unusable (booted fresh,
50067
+ skip replicate), ${EXIT_SESSION_DB_FATAL} fatal
49732
50068
  `;
49733
50069
  function shellQuote(value) {
49734
50070
  return `'${value.replaceAll("'", `'\\''`)}'`;
@@ -49742,11 +50078,39 @@ function awsSelfStopAccessFor(config) {
49742
50078
  function parseStoreName(value) {
49743
50079
  return value === "claude" || value === "opencode" ? value : null;
49744
50080
  }
50081
+ var ON_UNUSABLE_REPLICA_FLAG = "--on-unusable-replica=";
50082
+ function parseNonNegativeInt(value) {
50083
+ return /^\d+$/.test(value) ? Number.parseInt(value, 10) : null;
50084
+ }
50085
+ function parseSessionDbClassifyArgs(args) {
50086
+ let strategyRaw;
50087
+ const positional = [];
50088
+ for (const arg of args) {
50089
+ if (arg.startsWith(ON_UNUSABLE_REPLICA_FLAG)) {
50090
+ if (strategyRaw !== void 0) return null;
50091
+ strategyRaw = arg.slice(ON_UNUSABLE_REPLICA_FLAG.length);
50092
+ } else if (arg.startsWith("--")) {
50093
+ return null;
50094
+ } else {
50095
+ positional.push(arg);
50096
+ }
50097
+ }
50098
+ if (positional.length !== 2) return null;
50099
+ const exitCode = parseNonNegativeInt(positional[0]);
50100
+ const attempt = parseNonNegativeInt(positional[1]);
50101
+ const strategy = parseUnusableReplicaStrategy(strategyRaw);
50102
+ if (exitCode === null || attempt === null || attempt < 1 || strategy === null) return null;
50103
+ return { exitCode, attempt, strategy };
50104
+ }
49745
50105
  function renderEnv(config) {
49746
50106
  return [
49747
- // Empty when persistence is disabled entrypoint.sh gates the sync loop
49748
- // on this being non-empty, exactly as it did when it computed it itself.
49749
- `CREDS_BUCKET=${shellQuote(config.bucket ?? "")}`,
50107
+ // The bucket NAME, kept (not reduced to a boolean) so an operator can
50108
+ // read it; empty exactly when persistence is disabled (both
50109
+ // LITESTREAM_BUCKET and LITESTREAM_PREFIX must be set — see config.ts's
50110
+ // persistenceEnabled). entrypoint.sh gates BOTH the credential-sync
50111
+ // loop and whether it starts litestream replicate on this being
50112
+ // non-empty.
50113
+ `PERSISTENCE_BUCKET=${shellQuote(config.bucket ?? "")}`,
49750
50114
  `CLAUDE_CREDS=${shellQuote(config.claude.path)}`,
49751
50115
  `OPENCODE_DB_PATH=${shellQuote(config.opencodeDbPath)}`,
49752
50116
  `CREDS_SYNC_INTERVAL=${shellQuote(String(config.syncIntervalSeconds))}`
@@ -49812,6 +50176,20 @@ async function commandSyncOnce(name, config, deps) {
49812
50176
  await writeLastHash(fileOps, statePath, result.hash, log);
49813
50177
  }
49814
50178
  }
50179
+ async function commandSessionDbClassify(args, config, deps) {
50180
+ const { fileOps, log } = deps;
50181
+ const outcome = await classifySessionDbRestore({
50182
+ exitCode: args.exitCode,
50183
+ attempt: args.attempt,
50184
+ strategy: args.strategy,
50185
+ config: { bucket: config.bucket, prefix: config.prefix, opencodeDbPath: config.opencodeDbPath },
50186
+ fileOps,
50187
+ store: (deps.objectStoreFor ?? s3ObjectStoreFor)(config),
50188
+ log
50189
+ });
50190
+ log(describeSessionDbClassification(outcome, { bucket: config.bucket, region: config.region }));
50191
+ return sessionDbExitCode(outcome);
50192
+ }
49815
50193
  async function main(argv, deps) {
49816
50194
  const { env: env3, fileOps, log, out } = deps;
49817
50195
  const [command12, ...rest] = argv;
@@ -49847,6 +50225,17 @@ ${USAGE}`);
49847
50225
  });
49848
50226
  return stopped ? 0 : EXIT_KEEP_TASK;
49849
50227
  }
50228
+ if (command12 === "session-db-classify") {
50229
+ const args = parseSessionDbClassifyArgs(rest);
50230
+ if (args === null) {
50231
+ log(
50232
+ `'session-db-classify' needs <litestream-restore-exit-code> <attempt> and an optional --on-unusable-replica=<prune|leave|clear|crash>.
50233
+ ${USAGE}`
50234
+ );
50235
+ return EXIT_USAGE;
50236
+ }
50237
+ return commandSessionDbClassify(args, config, deps);
50238
+ }
49850
50239
  const name = parseStoreName(rest[0]);
49851
50240
  if (name === null) {
49852
50241
  log(`'${command12}' needs a store name: claude or opencode.
@@ -49886,6 +50275,9 @@ export {
49886
50275
  EXIT_BROKEN,
49887
50276
  EXIT_KEEP_TASK,
49888
50277
  EXIT_NOT_READY,
50278
+ EXIT_SESSION_DB_FATAL,
50279
+ EXIT_SESSION_DB_RETRY,
50280
+ EXIT_SESSION_DB_UNUSABLE,
49889
50281
  EXIT_USAGE,
49890
50282
  main
49891
50283
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evident-ai/runner-synchroniser",
3
- "version": "0.1.1-dev.7568241",
3
+ "version": "0.1.1-dev.96bc2ed",
4
4
  "description": "Restores and syncs the Evident runner's OpenCode credential stores (and litestream config) to an object store, so a runner survives task replacement with almost no state loss.",
5
5
  "type": "module",
6
6
  "main": "./dist/cli.js",