mnemonad-cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -118,6 +118,7 @@ Every command prints the installed CLI version as its first line of output.
118
118
  | `--pinata-jwt <jwt>` | Pinata JWT for IPFS offload of large files (or `PINATA_JWT` env var) |
119
119
  | `--manifest` | Write/use `.mnemonad` manifest for faster change detection. With no stream-id given, every command recovers it from an existing `.mnemonad` in the folder instead of requiring it explicitly |
120
120
  | `--force-snapshot` | Push a full snapshot regardless of prior history (repairs a corrupt stream) |
121
+ | `--detach` | `push`: build the next version here, send it from a background process, and return right away. Existing streams only. See "Push in the background" below |
121
122
  | `--index` | `push`/`watch`: update the folder's search index before every push (takes `--db`/`--model`/`--chunk-size`/`--chunk-overlap`); if indexing fails, nothing is pushed |
122
123
  | `--poll-interval <s>` | `watch`: seconds between remote version checks (default: `2`) |
123
124
  | `--debounce <ms>` | `watch`: quiet period in ms before pushing after a local change (default: `1000`) |
@@ -349,6 +350,48 @@ mnemonad burn 123
349
350
  mnemonad burn 123 --yes
350
351
  ```
351
352
 
353
+ ### Push in the background
354
+
355
+ A push spends most of its time waiting for the chain. `--detach` does everything that can
356
+ fail for your own reasons first, here and now: the owner check, unlocking, `--index`, "no
357
+ changes", and the balance against the estimated cost. Then it hands only the sending to a
358
+ background process and returns:
359
+
360
+ ```bash
361
+ mnemonad push ~/my-data --manifest --detach
362
+ # version 8 prepared (diff, gzip compressed, 2.1 KB)
363
+ # estimated cost: 0.0041 MON
364
+ # stream: 0x68d9…
365
+ # sending in the background: job 8f3c1a2b (pid 41210)
366
+ # log: ~/.cache/mnemonad/jobs/8f3c1a2b/push.log
367
+ # check: mnemonad info ~/my-data --manifest
368
+ ```
369
+
370
+ - **The version is frozen when the command runs.** Edits made after it returns go into the
371
+ next push, not this one.
372
+ - **Existing streams only.** It needs a stream id, or `--manifest` on a folder that has a
373
+ `.mnemonad`. Create a stream with a normal push first. `--passkey` can't be used: the browser
374
+ tab that signs for it closes when the command exits.
375
+ - **The next command waits for it.** A `push`, `pull`, `compact` or `watch` of the same stream
376
+ waits until the background push has finished, so nothing builds on, or restores, the version
377
+ before it. A push from the same wallet to another stream waits too, so the two don't race for
378
+ one nonce. `diff` only notes that a push is still sending.
379
+ - **Results:** `mnemonad info <path>` shows the last background push for the stream, and when
380
+ it failed, why. If one fails, the next command on that stream also prints a warning, once.
381
+ - **Nothing half-lands.** The background process refuses to send a version whose base is gone
382
+ (the stream changed after it was prepared), and the contract rejects any write that doesn't
383
+ land at the index it names. A failed background push leaves the stream as it was. Push again.
384
+ - **Secrets stay in memory.** The key, the password and a Pinata JWT are handed to the
385
+ background process over a pipe. They are never written to the job folder, the log, or the
386
+ process list.
387
+ - If the background process is killed mid-send, the job is reported as failed the next time a
388
+ command looks at it. A large push that was staged over several transactions, or paid for an
389
+ IPFS upload, can't be resumed. A paid but unused upload can be refunded after the gateway's
390
+ time limit, with the SDK's `MnemonadUploadGateway.refund()` (the CLI has no command for it).
391
+
392
+ Jobs live in `~/.cache/mnemonad/jobs/` (set `MNEMONAD_JOBS_DIR` to move them). Finished ones are
393
+ removed after 14 days.
394
+
352
395
  ### Repair a corrupt stream with a force snapshot
353
396
 
354
397
  If a diff patch was pushed against a stale base (e.g. a race condition in `watch`),
package/bin/mnemonad.js CHANGED
@@ -20,6 +20,7 @@ import { dirname, join } from 'node:path';
20
20
  import { push, pull, info, diff, watch, compact, burn, buildIndex, search } from '../lib/commands/index.js';
21
21
  import { parseQualifiedStreamId } from '../lib/commands/shared.js';
22
22
  import { closePasskeyBridge } from '../lib/passkeyBridge.js';
23
+ import { runPushJob } from '../lib/jobs.js';
23
24
  import defaultConfig from '../mnemonad.config.js';
24
25
 
25
26
  const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -104,6 +105,10 @@ Options:
104
105
  With no stream-id given, every command recovers it from an
105
106
  existing .mnemonad in <path> instead of requiring it explicitly
106
107
  --force-snapshot Push a full snapshot regardless of prior history (repairs corrupt streams)
108
+ --detach push: build the next version here, send it from a background process,
109
+ and return right away. Existing streams only (an id, or --manifest).
110
+ Later pushes and pulls of that stream wait for it; \`mnemonad info\`
111
+ shows how it went
107
112
  --index push/watch: update the folder's search index (search_index.db)
108
113
  before every push, so the stream is searchable right after a pull.
109
114
  Takes --db/--model/--chunk-size/--chunk-overlap like \`index\`
@@ -162,6 +167,7 @@ function parseArgs(argv) {
162
167
  index: false,
163
168
  rebuild: false,
164
169
  forceSnapshot: false,
170
+ detach: false,
165
171
  pollInterval: 2,
166
172
  debounce: 1000,
167
173
  pushOnly: false,
@@ -281,6 +287,8 @@ function parseArgs(argv) {
281
287
  args.rebuild = true;
282
288
  } else if (flag === '--force-snapshot') {
283
289
  args.forceSnapshot = true;
290
+ } else if (flag === '--detach') {
291
+ args.detach = true;
284
292
  } else if (flag === '--poll-interval' && i + 1 < raw.length) {
285
293
  args.pollInterval = Number(raw[++i]);
286
294
  } else if (flag === '--debounce' && i + 1 < raw.length) {
@@ -363,6 +371,9 @@ try {
363
371
  await buildIndex(args);
364
372
  } else if (args.command === 'search') {
365
373
  await search(args);
374
+ } else if (args.command === '__push-job') {
375
+ // The detached half of `push --detach` (lib/jobs.js) — never typed by a person.
376
+ await runPushJob(args.path);
366
377
  } else {
367
378
  console.error('Unknown command:', args.command);
368
379
  console.log(USAGE);
@@ -12,6 +12,7 @@ import {
12
12
  resolveOffloadParams,
13
13
  discoverStreamId,
14
14
  } from './shared.js';
15
+ import { settleStreamJobs } from '../jobs.js';
15
16
 
16
17
  /**
17
18
  * Monad has no rebate/refund concept — truncating a stream's history here gives back no
@@ -28,6 +29,7 @@ export async function compact(args) {
28
29
  if (!args.streamId) {
29
30
  throw new Error('stream-id is required for compact');
30
31
  }
32
+ await settleStreamJobs(args, { reason: 'before replacing the history with a fresh snapshot' });
31
33
 
32
34
  const fsFolder = new FSFolder(destPath, makeExcludes(args));
33
35
 
@@ -12,6 +12,7 @@ import {
12
12
  folderExists,
13
13
  discoverStreamId,
14
14
  } from './shared.js';
15
+ import { settleStreamJobs } from '../jobs.js';
15
16
 
16
17
  export function compareFileMaps(localFiles, remoteFiles) {
17
18
  const added = [];
@@ -55,6 +56,7 @@ export async function diff(args) {
55
56
  if (!args.streamId) {
56
57
  throw new Error('stream-id is required for diff');
57
58
  }
59
+ await settleStreamJobs(args, { wait: false });
58
60
 
59
61
  const client = await makeChainClient(args);
60
62
 
@@ -12,6 +12,7 @@ import {
12
12
  readManifest,
13
13
  streamIdsEqual,
14
14
  } from './shared.js';
15
+ import { streamKey, latestJob, describeJob } from '../jobs.js';
15
16
 
16
17
  export async function info(args) {
17
18
  const client = await makeChainClient(args);
@@ -45,6 +46,14 @@ export async function info(args) {
45
46
  }
46
47
  }
47
48
 
49
+ // The last background push (`push --detach`) for this stream, whichever way its id is
50
+ // known — even with no --manifest, the folder's own manifest names the stream.
51
+ const jobStreamId = args.streamId || manifest?.streamId;
52
+ if (jobStreamId) {
53
+ const job = latestJob(streamKey({ chain: args.chain, contractAddress: args.contractAddress, streamId: jobStreamId }));
54
+ if (job) console.log(' background push:', describeJob(job));
55
+ }
56
+
48
57
  if (!args.streamId) {
49
58
  return;
50
59
  }
@@ -11,6 +11,7 @@ import {
11
11
  formatStreamId,
12
12
  discoverStreamId,
13
13
  } from './shared.js';
14
+ import { settleStreamJobs } from '../jobs.js';
14
15
 
15
16
  export async function pull(args) {
16
17
  // Resolved up front (throws if missing) so a missing path fails fast, before any chain
@@ -24,6 +25,10 @@ export async function pull(args) {
24
25
  throw new Error('stream-id is required for pull');
25
26
  }
26
27
 
28
+ // Pulling while a background push of this folder is still sending would restore the
29
+ // version before it — and delete the very files that push is uploading.
30
+ await settleStreamJobs(args, { reason: 'so the pull includes it' });
31
+
27
32
  const client = await makeChainClient(args);
28
33
 
29
34
  const mn = new Mnemonad({
@@ -19,8 +19,12 @@ import {
19
19
  streamIdsEqual,
20
20
  discoverStreamId,
21
21
  userError,
22
+ formatBytes,
23
+ formatPath,
22
24
  } from './shared.js';
23
25
  import { updateIndex, checkIndex, indexDbName } from './buildIndex.js';
26
+ import { streamKey, waitForJobs, settleStreamJobs, startPushJob } from '../jobs.js';
27
+ import { formatEther } from 'viem';
24
28
 
25
29
  export async function push(args) {
26
30
  const destPath = resolvePath(args.path, { mustExist: true });
@@ -31,6 +35,25 @@ export async function push(args) {
31
35
  await discoverStreamId(args, destPath);
32
36
  let streamId = args.streamId;
33
37
 
38
+ if (args.detach) {
39
+ // Creating a stream prints the id the user has to keep, and needs signatures that have
40
+ // to be seen to succeed — nothing worth handing off. --passkey's signer is a browser
41
+ // tab that closes when this process exits.
42
+ if (!streamId) {
43
+ throw userError(
44
+ '--detach only pushes to an existing stream. Pass its id, or --manifest on a folder\n' +
45
+ ' that has a .mnemonad, or push once without --detach to create the stream first.'
46
+ );
47
+ }
48
+ if (args.passkey) {
49
+ throw userError('--detach can\'t be combined with --passkey: the browser tab signing for it closes when this command exits.');
50
+ }
51
+ }
52
+
53
+ // A background push still sending to this stream means its next version isn't on chain
54
+ // yet — building on top of the current tip now would only lose the race to it.
55
+ await settleStreamJobs(args, { reason: 'before building the next version on top of it' });
56
+
34
57
  // Before anything is scanned or signed: the push below then picks the updated index up
35
58
  // like any other file. A failure stops the push outright — a push that silently went out
36
59
  // without the index asked for would leave the stream unsearchable with no sign of why.
@@ -67,6 +90,12 @@ export async function push(args) {
67
90
  const client = await makeChainClient(args);
68
91
  requireWalletClient(client);
69
92
 
93
+ // Same wallet, different stream: two processes sending at once would race for one nonce.
94
+ await waitForJobs(
95
+ { signer: client.account.address, chain: args.chain },
96
+ { reason: 'so the two pushes don\'t race for the same wallet nonce' },
97
+ );
98
+
70
99
  const baseParams = {
71
100
  publicClient: client.publicClient,
72
101
  walletClient: client.walletClient,
@@ -139,6 +168,11 @@ export async function push(args) {
139
168
  }
140
169
  }
141
170
 
171
+ if (args.detach) {
172
+ await detachPush({ args, mn, monadSync, fsFolder, client, streamId, destPath, existingVersions });
173
+ return;
174
+ }
175
+
142
176
  console.log(' building patch + pushing to chain...');
143
177
  const result = await monadSync.push(fsFolder);
144
178
 
@@ -156,6 +190,80 @@ export async function push(args) {
156
190
  }
157
191
  }
158
192
 
193
+ /**
194
+ * `push --detach`: everything up to a finished patch runs here, so every error a user can act
195
+ * on still surfaces before this command exits. Only the sending — transactions, receipts, an
196
+ * IPFS upload — goes to a detached child (see lib/jobs.js), and this process exits as soon
197
+ * as it has started.
198
+ *
199
+ * The patch is frozen now: files edited after this command returns go into the next push,
200
+ * not this one. The manifest's file hashes are taken at the same moment for the same reason.
201
+ */
202
+ async function detachPush({ args, mn, monadSync, fsFolder, client, streamId, destPath, existingVersions }) {
203
+ console.log(' building patch...');
204
+ const prepared = await monadSync.preparePush(fsFolder);
205
+
206
+ // A single-item patch is the common case and the only one estimatePushCost models; a
207
+ // segmented one (over 8 MB) just goes without an estimate rather than a wrong one.
208
+ let cost = null;
209
+ if (prepared.itemCount === 1) {
210
+ try {
211
+ cost = await mn.estimatePushCost(prepared.patchBytes);
212
+ } catch {
213
+ // No estimate is not a reason to stop — the child surfaces any real send error.
214
+ }
215
+ }
216
+ if (cost) {
217
+ const balance = await client.publicClient.getBalance({ address: client.account.address });
218
+ if (balance < cost.total) {
219
+ throw userError(
220
+ `not enough MON to push: about ${formatEther(cost.total)} needed, ` +
221
+ `${formatEther(balance)} in ${client.account.address}. Nothing was sent.`
222
+ );
223
+ }
224
+ }
225
+
226
+ const files = args.manifest ? await hashLocalTree(fsFolder) : null;
227
+ const job = await startPushJob(
228
+ {
229
+ streamId: formatStreamId(streamId),
230
+ streamKey: streamKey({ chain: args.chain, contractAddress: args.contractAddress, streamId }),
231
+ chain: args.chain,
232
+ signer: client.account.address,
233
+ folder: destPath,
234
+ baseLength: prepared.baseLength,
235
+ version: prepared.version,
236
+ kind: prepared.kind,
237
+ bytes: prepared.patchBytes.length,
238
+ manifest: files ? { files } : null,
239
+ // Everything the child needs to rebuild the same chain client — never a secret.
240
+ args: {
241
+ chain: args.chain,
242
+ rpcUrl: args.rpcUrl,
243
+ contractAddress: args.contractAddress,
244
+ gatewayUrl: args.gatewayUrl,
245
+ presignUrl: args.presignUrl,
246
+ },
247
+ },
248
+ prepared.patchBytes,
249
+ {
250
+ key: args.key || process.env.MNEMONAD_KEY || null,
251
+ phrase: args.phrase,
252
+ password: args.password,
253
+ pinataJwt: args.pinataJwt,
254
+ },
255
+ );
256
+
257
+ const patchType = existingVersions === 0 || prepared.kind === 'patch' ? 'full snapshot' : 'diff';
258
+ const compressedNote = args.compress !== false ? ', gzip compressed' : '';
259
+ console.log(' version', prepared.version, 'prepared (' + patchType + compressedNote + ', ' + formatBytes(prepared.patchBytes.length) + ')');
260
+ if (cost) console.log(' estimated cost:', formatEther(cost.total), 'MON');
261
+ console.log(' stream:', formatStreamId(streamId));
262
+ console.log(' sending in the background: job', job.id, '(pid ' + job.pid + ')');
263
+ console.log(' log: ', formatPath(job.dir + '/push.log'));
264
+ console.log(' check: mnemonad info', formatPath(destPath) + (args.manifest ? ' --manifest' : ''));
265
+ }
266
+
159
267
  /**
160
268
  * A folder that already carries an index, pushed without `--index` after its files changed,
161
269
  * would publish an index that no longer matches them — searches keep returning the old text's
@@ -18,6 +18,7 @@ import {
18
18
  discoverStreamId,
19
19
  userError,
20
20
  } from './shared.js';
21
+ import { settleStreamJobs } from '../jobs.js';
21
22
  import { makeIndexer, updateIndex } from './buildIndex.js';
22
23
 
23
24
  function timestamp() {
@@ -37,6 +38,7 @@ export async function watch(args) {
37
38
  // no need to require it again.
38
39
  await discoverStreamId(args, cwd);
39
40
  if (!args.streamId) throw new Error('stream-id is required for watch');
41
+ await settleStreamJobs(args, { reason: 'before watching' });
40
42
  const debounceMs = args.debounce ?? 5000;
41
43
  const pollIntervalMs = (args.pollInterval ?? 2) * 1000;
42
44
  const pushEnabled = !args.pullOnly;
package/lib/jobs.js ADDED
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Background push jobs — what `mnemonad push --detach` leaves behind.
3
+ *
4
+ * A detached push builds its patch in the foreground (every check that can fail for the
5
+ * user's own reasons runs there: ownership, unlocking, indexing, "nothing to push", the
6
+ * balance), then hands only the sending to a detached child process and exits. Each job is a
7
+ * folder under `~/.cache/mnemonad/jobs/<id>/`:
8
+ *
9
+ * job.json — what to send where, and the job's status (see JOB_STATUS)
10
+ * patch.bin — the prepared patch, frozen when the command ran; deleted once sent
11
+ * push.log — the child's own output
12
+ *
13
+ * Secrets (a key, a phrase, a password, a Pinata JWT) never touch this folder or the child's
14
+ * argv: the parent writes them to the child's stdin and closes it.
15
+ *
16
+ * Correctness never depends on the locking below. The child refuses to send a patch whose
17
+ * base version is gone (`MonadSync.commitPush`), and the contract rejects any write that
18
+ * doesn't land at the index it names. The waiting here only keeps the next command from
19
+ * racing a job it would lose to anyway — or, for a pull, from overwriting the folder with the
20
+ * version before the one still being sent.
21
+ */
22
+ import { spawn } from 'node:child_process';
23
+ import { openSync, closeSync, readdirSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
24
+ import { mkdir, readFile, writeFile, rm } from 'node:fs/promises';
25
+ import { randomBytes } from 'node:crypto';
26
+ import { homedir } from 'node:os';
27
+ import { dirname, join } from 'node:path';
28
+ import { fileURLToPath } from 'node:url';
29
+ import Mnemonad from 'mnemonad';
30
+ import { MonadSync } from 'monadsync';
31
+ import { makeChainClient, requireWalletClient } from './chainClient.js';
32
+ import {
33
+ formatStreamId,
34
+ formatPath,
35
+ unlockStream,
36
+ resolveOffloadParams,
37
+ writeManifest,
38
+ userError,
39
+ } from './commands/shared.js';
40
+
41
+ const BIN_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'mnemonad.js');
42
+
43
+ /** pending: written, child not started yet · waiting: queued behind an earlier job from the
44
+ * same signer · sending: transactions in flight · done / failed: finished. */
45
+ export const JOB_STATUS = { PENDING: 'pending', WAITING: 'waiting', SENDING: 'sending', DONE: 'done', FAILED: 'failed' };
46
+
47
+ const ACTIVE = new Set([JOB_STATUS.PENDING, JOB_STATUS.WAITING, JOB_STATUS.SENDING]);
48
+
49
+ /** A job still `pending` with no pid after this long never got its child started. */
50
+ const SPAWN_GRACE_MS = 60_000;
51
+
52
+ /** Finished jobs older than this are removed the next time a job is created. */
53
+ const KEEP_FINISHED_MS = 14 * 24 * 60 * 60 * 1000;
54
+
55
+ const POLL_MS = 1000;
56
+
57
+ /** `MNEMONAD_JOBS_DIR` overrides the location (the tests use a temp dir). */
58
+ export function jobsRoot() {
59
+ return process.env.MNEMONAD_JOBS_DIR || join(homedir(), '.cache', 'mnemonad', 'jobs');
60
+ }
61
+
62
+ /**
63
+ * Identifies a stream across commands: the same token id is a different stream on another
64
+ * chain or registry.
65
+ *
66
+ * @param {{chain: string, contractAddress: ?string, streamId: bigint|string}} where
67
+ */
68
+ export function streamKey({ chain, contractAddress, streamId }) {
69
+ return `${chain}|${String(contractAddress || '').toLowerCase()}|${formatStreamId(streamId)}`;
70
+ }
71
+
72
+ function signerKey({ chain, signer }) {
73
+ return `${chain}|${String(signer || '').toLowerCase()}`;
74
+ }
75
+
76
+ function isPidAlive(pid) {
77
+ if (!pid) return false;
78
+ try {
79
+ process.kill(pid, 0);
80
+ return true;
81
+ } catch (err) {
82
+ // EPERM: the process exists, it's just not ours to signal.
83
+ return err.code === 'EPERM';
84
+ }
85
+ }
86
+
87
+ function writeJobSync(dir, job) {
88
+ // Synchronous on purpose: callers read-modify-write job.json from two processes, and a
89
+ // torn async write would leave a half-written file for the other side to parse.
90
+ const tmp = join(dir, `job.json.${process.pid}.tmp`);
91
+ writeFileSync(tmp, JSON.stringify(job, null, 2));
92
+ renameSync(tmp, join(dir, 'job.json'));
93
+ }
94
+
95
+ function readJobSync(dir) {
96
+ try {
97
+ return JSON.parse(readFileSync(join(dir, 'job.json'), 'utf8'));
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Re-reads a job and settles it as failed when it claims to be running but nothing is: the
105
+ * child was killed, the machine slept through a crash, or the spawn never happened.
106
+ */
107
+ function refreshJob(dir) {
108
+ const job = readJobSync(dir);
109
+ if (!job || !ACTIVE.has(job.status)) return job;
110
+
111
+ const neverStarted = !job.pid && Date.now() - Date.parse(job.createdAt) > SPAWN_GRACE_MS;
112
+ if (neverStarted || (job.pid && !isPidAlive(job.pid))) {
113
+ const settled = {
114
+ ...job,
115
+ status: JOB_STATUS.FAILED,
116
+ error: neverStarted
117
+ ? 'the background process never started'
118
+ : 'the background process exited before finishing',
119
+ finishedAt: new Date().toISOString(),
120
+ reported: false,
121
+ };
122
+ writeJobSync(dir, settled);
123
+ return settled;
124
+ }
125
+ return job;
126
+ }
127
+
128
+ /** Every job on disk, oldest first, with dead ones settled as failed. */
129
+ export function listJobs() {
130
+ let names;
131
+ try {
132
+ names = readdirSync(jobsRoot());
133
+ } catch {
134
+ return [];
135
+ }
136
+ const jobs = [];
137
+ for (const name of names) {
138
+ const dir = join(jobsRoot(), name);
139
+ const job = refreshJob(dir);
140
+ if (job) jobs.push({ ...job, dir });
141
+ }
142
+ return jobs.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
143
+ }
144
+
145
+ export function isActive(job) {
146
+ return ACTIVE.has(job.status);
147
+ }
148
+
149
+ /** Jobs still running for a stream (`{streamKey}`) or a signer (`{signer, chain}`). */
150
+ export function activeJobs(selector) {
151
+ return listJobs().filter((job) => isActive(job) && matches(job, selector));
152
+ }
153
+
154
+ function matches(job, selector) {
155
+ if (selector.streamKey) return job.streamKey === selector.streamKey;
156
+ return signerKey(job) === signerKey(selector);
157
+ }
158
+
159
+ /** The most recent job for a stream, active or not. */
160
+ export function latestJob(key) {
161
+ const jobs = listJobs().filter((job) => job.streamKey === key);
162
+ return jobs.length ? jobs[jobs.length - 1] : null;
163
+ }
164
+
165
+ /**
166
+ * Blocks until no job matching `selector` is still running, printing one line while it
167
+ * waits. Returns how many it waited for.
168
+ *
169
+ * @param {{streamKey: string}|{signer: string, chain: string}} selector
170
+ * @param {Object} [opts]
171
+ * @param {string} [opts.reason] - why this command has to wait, for the printed line
172
+ */
173
+ export async function waitForJobs(selector, { reason = 'before continuing' } = {}) {
174
+ let first = activeJobs(selector);
175
+ if (!first.length) return 0;
176
+
177
+ const job = first[first.length - 1];
178
+ console.log(
179
+ ` waiting for background push ${job.id} (version ${job.version}) to finish ${reason}...\n` +
180
+ ` log: ${formatPath(join(job.dir, 'push.log'))}`
181
+ );
182
+ while (first.length) {
183
+ await new Promise((r) => setTimeout(r, POLL_MS));
184
+ first = activeJobs(selector);
185
+ }
186
+ return 1;
187
+ }
188
+
189
+ /**
190
+ * Prints a failed job's error once — the next command on that stream after the failure —
191
+ * then marks it reported, so a failure is never silent past one run but doesn't nag forever.
192
+ * `mnemonad info` keeps showing it regardless (see describeJob).
193
+ */
194
+ export function reportFailedJob(key) {
195
+ const job = latestJob(key);
196
+ if (!job || job.status !== JOB_STATUS.FAILED || job.reported) return;
197
+ console.log(
198
+ ` warning: background push ${job.id} (version ${job.version}) failed: ${job.error}\n` +
199
+ ` nothing from it reached the stream. Log: ${formatPath(join(job.dir, 'push.log'))}`
200
+ );
201
+ writeJobSync(job.dir, { ...readJobSync(job.dir), reported: true });
202
+ }
203
+
204
+ /**
205
+ * What every command that touches a stream calls once its id is known: reports a failed
206
+ * background push (once), then either waits for a running one (`wait: true` — push, pull,
207
+ * compact, watch: anything that would build on, or overwrite with, the version before it) or
208
+ * just says one is running (diff, which only reads).
209
+ *
210
+ * @param {Object} args - parsed CLI args; needs `chain`, `contractAddress`, `streamId`
211
+ * @param {Object} [opts]
212
+ * @param {boolean} [opts.wait=true]
213
+ * @param {string} [opts.reason] - see waitForJobs
214
+ */
215
+ export async function settleStreamJobs(args, { wait = true, reason } = {}) {
216
+ if (!args.streamId) return;
217
+ const key = streamKey({ chain: args.chain, contractAddress: args.contractAddress, streamId: args.streamId });
218
+ reportFailedJob(key);
219
+ if (wait) {
220
+ await waitForJobs({ streamKey: key }, { reason });
221
+ return;
222
+ }
223
+ const running = activeJobs({ streamKey: key });
224
+ if (running.length) {
225
+ const job = running[running.length - 1];
226
+ console.log(
227
+ ` note: background push ${job.id} (version ${job.version}) is still sending —\n` +
228
+ ' this compares against the chain as it is before that version lands'
229
+ );
230
+ }
231
+ }
232
+
233
+ /** One line for `mnemonad info`. */
234
+ export function describeJob(job) {
235
+ const log = formatPath(join(job.dir, 'push.log'));
236
+ switch (job.status) {
237
+ case JOB_STATUS.DONE:
238
+ return `version ${job.version} sent ${job.finishedAt} (job ${job.id})`;
239
+ case JOB_STATUS.FAILED:
240
+ return `version ${job.version} FAILED: ${job.error} (job ${job.id}, log: ${log})`;
241
+ case JOB_STATUS.WAITING:
242
+ return `version ${job.version} queued behind another push from the same wallet (job ${job.id}, log: ${log})`;
243
+ default:
244
+ return `version ${job.version} still sending (job ${job.id}, pid ${job.pid ?? '?'}, log: ${log})`;
245
+ }
246
+ }
247
+
248
+ function pruneFinishedJobs() {
249
+ for (const job of listJobs()) {
250
+ if (isActive(job) || !job.finishedAt) continue;
251
+ if (Date.now() - Date.parse(job.finishedAt) > KEEP_FINISHED_MS) {
252
+ rmSync(job.dir, { recursive: true, force: true });
253
+ }
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Writes a job and starts its detached child.
259
+ *
260
+ * @param {Object} job - everything the child needs except secrets; see push.js's detachPush
261
+ * @param {Uint8Array} patchBytes
262
+ * @param {{key?: ?string, phrase?: ?string, password?: ?string, pinataJwt?: ?string}} secrets
263
+ * @returns {Promise<{id: string, dir: string, pid: number}>}
264
+ */
265
+ export async function startPushJob(job, patchBytes, secrets) {
266
+ pruneFinishedJobs();
267
+
268
+ const id = randomBytes(4).toString('hex');
269
+ const dir = join(jobsRoot(), id);
270
+ await mkdir(dir, { recursive: true });
271
+ await writeFile(join(dir, 'patch.bin'), patchBytes);
272
+ writeJobSync(dir, { ...job, id, status: JOB_STATUS.PENDING, pid: null, createdAt: new Date().toISOString() });
273
+
274
+ const logFd = openSync(join(dir, 'push.log'), 'a');
275
+ let child;
276
+ try {
277
+ child = spawn(process.execPath, [BIN_PATH, '__push-job', dir], {
278
+ detached: true,
279
+ stdio: ['pipe', logFd, logFd],
280
+ windowsHide: true,
281
+ });
282
+ } finally {
283
+ closeSync(logFd);
284
+ }
285
+
286
+ writeJobSync(dir, { ...readJobSync(dir), pid: child.pid });
287
+ child.stdin.end(JSON.stringify(secrets));
288
+ child.unref();
289
+ return { id, dir, pid: child.pid };
290
+ }
291
+
292
+ async function readStdin() {
293
+ const parts = [];
294
+ for await (const part of process.stdin) parts.push(part);
295
+ const raw = Buffer.concat(parts).toString('utf8');
296
+ return raw ? JSON.parse(raw) : {};
297
+ }
298
+
299
+ function log(...parts) {
300
+ console.log(new Date().toISOString(), ...parts);
301
+ }
302
+
303
+ /**
304
+ * The detached child: `mnemonad __push-job <dir>`. Never typed by a person — not in --help.
305
+ *
306
+ * Waits its turn behind earlier jobs from the same signer (two processes sending with one key
307
+ * would race for the same nonce), then sends the prepared patch from a fresh, never-replayed
308
+ * Mnemonad instance, and on success writes the folder's .mnemonad exactly like a foreground
309
+ * `push --manifest` would have.
310
+ *
311
+ * @param {string} dir - the job folder
312
+ */
313
+ export async function runPushJob(dir) {
314
+ if (!dir) throw userError('__push-job needs a job folder');
315
+ const secrets = await readStdin();
316
+
317
+ let job = readJobSync(dir);
318
+ if (!job) throw userError(`no job at ${dir}`);
319
+ const update = (fields) => {
320
+ job = { ...readJobSync(dir), ...fields };
321
+ writeJobSync(dir, job);
322
+ };
323
+ update({ pid: process.pid });
324
+
325
+ try {
326
+ const earlier = () => activeJobs({ signer: job.signer, chain: job.chain })
327
+ .filter((other) => other.createdAt < job.createdAt || (other.createdAt === job.createdAt && other.id < job.id));
328
+ if (earlier().length) {
329
+ update({ status: JOB_STATUS.WAITING });
330
+ log(`waiting for earlier background push(es) from ${job.signer}...`);
331
+ while (earlier().length) await new Promise((r) => setTimeout(r, POLL_MS));
332
+ }
333
+
334
+ update({ status: JOB_STATUS.SENDING, startedAt: new Date().toISOString() });
335
+ log(`sending version ${job.version} of ${job.streamId} on ${job.chain}...`);
336
+
337
+ const args = { ...job.args, key: secrets.key ?? null, phrase: secrets.phrase ?? null, password: secrets.password ?? null, pinataJwt: secrets.pinataJwt ?? null, passkey: false };
338
+ const client = await makeChainClient(args);
339
+ requireWalletClient(client);
340
+
341
+ const mn = new Mnemonad({
342
+ publicClient: client.publicClient,
343
+ walletClient: client.walletClient,
344
+ contractAddress: client.contractAddress,
345
+ id: job.streamId,
346
+ ...resolveOffloadParams(args, client.account),
347
+ });
348
+ await unlockStream(mn, { password: args.password, signer: client.walletClient });
349
+
350
+ const patchBytes = new Uint8Array(await readFile(join(dir, 'patch.bin')));
351
+ const result = await new MonadSync({ mnemonad: mn }).commitPush({ patchBytes, baseLength: job.baseLength });
352
+
353
+ if (job.manifest) {
354
+ await writeManifest(job.folder, { streamId: job.streamId, version: result.version, files: job.manifest.files });
355
+ }
356
+ update({ status: JOB_STATUS.DONE, version: result.version, finishedAt: new Date().toISOString() });
357
+ log(`version ${result.version} pushed`);
358
+ } catch (err) {
359
+ const error = err.code === 'STREAM_MOVED'
360
+ ? `the stream changed after this push was prepared (it was built on version ${job.baseLength}) — push again`
361
+ : err.message;
362
+ update({ status: JOB_STATUS.FAILED, error, finishedAt: new Date().toISOString(), reported: false });
363
+ log('failed:', err.stack || err.message);
364
+ process.exitCode = 1;
365
+ } finally {
366
+ await rm(join(dir, 'patch.bin'), { force: true });
367
+ }
368
+ }
369
+
370
+ /** For tests: blocks until a job has finished, and returns it. */
371
+ export async function waitForJob(dir, { timeoutMs = 60_000 } = {}) {
372
+ const deadline = Date.now() + timeoutMs;
373
+ for (;;) {
374
+ const job = refreshJob(dir);
375
+ if (job && !isActive(job)) return job;
376
+ if (Date.now() > deadline) throw new Error(`job ${dir} still ${job?.status} after ${timeoutMs} ms`);
377
+ await new Promise((r) => setTimeout(r, 200));
378
+ }
379
+ }
380
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnemonad-cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "CLI to sync local folders to versioned, diffed on-chain streams on Monad, backed by Mnemonad + monadsync.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,7 +26,7 @@
26
26
  "@sqliteai/sqlite-vector": "^1.1.2",
27
27
  "better-sqlite3": "^13.0.3",
28
28
  "mnemonad": "^0.0.1",
29
- "monadsync": "^0.0.1",
29
+ "monadsync": "^0.0.2",
30
30
  "open": "^11.0.4",
31
31
  "viem": "^2.56.3",
32
32
  "ws": "^8.22.0"