@1agh/maude 1.6.12 → 1.6.13

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.
@@ -38,7 +38,7 @@
38
38
  // retry-until-delivered machinery and no ordering guarantees: it is a doorbell,
39
39
  // not a delivery.
40
40
 
41
- import { parsePoke } from './poke.ts';
41
+ import { isKeepalive, parsePoke } from './poke.ts';
42
42
 
43
43
  /** The reserved control document. Must match the hub's `files-ctl.mjs`. */
44
44
  export const FILES_CTL_DOC = 'maude.files';
@@ -170,6 +170,10 @@ export function createCtlProvider(opts: CtlProviderOptions): CtlProvider {
170
170
  });
171
171
  p.on('stateless', (data: { payload: string }) => {
172
172
  if (stopped) return;
173
+ // The hub's keep-alive: its whole job was arriving (it keeps the
174
+ // provider's silence check quiet on a healthy socket). Not a poke, and
175
+ // not malformed either.
176
+ if (isKeepalive(data?.payload)) return;
173
177
  const poke = parsePoke(data?.payload);
174
178
  if (poke === null) {
175
179
  malformed += 1;
@@ -347,6 +347,8 @@ export function createFileLedger(opts: FileLedgerOptions): FileLedger {
347
347
  const data: LedgerFileShape = load();
348
348
  let timer: ReturnType<typeof setTimeout> | null = null;
349
349
  const outbox = new Set<string>();
350
+ /** The last state written, `updatedAt` excluded — see `persist`. */
351
+ let lastPersisted: string | null = null;
350
352
 
351
353
  function load(): LedgerFileShape {
352
354
  const fresh: LedgerFileShape = {
@@ -438,9 +440,20 @@ export function createFileLedger(opts: FileLedgerOptions): FileLedger {
438
440
 
439
441
  function persist(): void {
440
442
  try {
443
+ // A WRITE THAT CHANGES NOTHING IS NOT FREE. Every plane pass ends in
444
+ // `setPosition` + `flush`, and this file lives under the design root the
445
+ // watcher reports on — so restamping `updatedAt` on an unchanged ledger
446
+ // raised an `fs:any` that scheduled the next pass, which flushed again:
447
+ // a self-fed journal read every ~2 s on a project nobody was touching,
448
+ // and a cloud cell that never slept (2026-10-05, 10.55 instance-hours
449
+ // overnight). Compare the state WITHOUT the stamp; write only news.
450
+ const { updatedAt: _stamp, ...state } = data;
451
+ const body = JSON.stringify(state);
452
+ if (body === lastPersisted && existsSync(file)) return;
441
453
  mkdirSync(dir, { recursive: true });
442
454
  data.updatedAt = now();
443
455
  atomicWrite(file, `${JSON.stringify(data, null, 2)}\n`);
456
+ lastPersisted = body;
444
457
  } catch (err) {
445
458
  // Never throws into the sync hot path. A ledger we cannot persist costs
446
459
  // a re-anchor next boot, which is noise rather than loss.
@@ -78,6 +78,18 @@ import { isLoopbackHost } from './loopback.ts';
78
78
  import { migrateFlatFallback } from './migrate-flat-fallback.ts';
79
79
  import { migrateSeed } from './migrate-seed.ts';
80
80
  import { ORIGINS } from './origins.ts';
81
+ import {
82
+ initialParkState,
83
+ isLocalWorkRel,
84
+ PARK_TIMINGS,
85
+ type ParkEffect,
86
+ type ParkEvent,
87
+ type ParkState,
88
+ type ParkTimings,
89
+ parkReducer,
90
+ parseCellState,
91
+ } from './park.ts';
92
+ import { hasSelfRetryingWork } from './presentation.ts';
81
93
  import { createProjectConfigPusher } from './project-config-push.ts';
82
94
  import { createDocProjection, type DocProjection } from './projection.ts';
83
95
  import {
@@ -679,6 +691,16 @@ export interface CreateSyncRuntimeOptions {
679
691
  jitterMs?: number;
680
692
  now?: () => number;
681
693
  };
694
+ /**
695
+ * The desktop park (`sync/park.ts`) — test injection. Production uses the
696
+ * module timings, the real clock and global `fetch`.
697
+ */
698
+ park?: {
699
+ timings?: Partial<ParkTimings>;
700
+ tickMs?: number;
701
+ now?: () => number;
702
+ fetch?: typeof fetch;
703
+ };
682
704
  /**
683
705
  * Override the offline-mode connection monitor (Task 8 test injection —
684
706
  * lets tests pass injectable timers/clock). Defaults to a real monitor that
@@ -1365,6 +1387,26 @@ export function createSyncRuntime(
1365
1387
  * there), and whenever `linkedHub.fileEvents` is false.
1366
1388
  */
1367
1389
  let fileEventsCtl: import('./ctl-provider.ts').CtlProvider | null = null;
1390
+ /** Rebuilds the control channel with the options it was first built with —
1391
+ * the desktop park closes it and brings it back. */
1392
+ let makeFileEventsCtl: (() => import('./ctl-provider.ts').CtlProvider) | null = null;
1393
+ /**
1394
+ * THE DESKTOP PARK (`sync/park.ts`). An idle desktop closes its sockets and
1395
+ * its poll so the cloud cell sleeps through its own `sleepAfter`, and comes
1396
+ * back on the next local change, click, or a change somebody else made.
1397
+ * `parkedNow` is the one flag every lane checks; `parkDispatch` is armed by
1398
+ * `start()` only where parking is possible.
1399
+ */
1400
+ let parkedNow = false;
1401
+ let parkDispatch: ((event: ParkEvent) => void) | null = null;
1402
+ let parkTimer: ReturnType<typeof setInterval> | null = null;
1403
+ let parkProbe: AbortController | null = null;
1404
+ let parkUiUnsub: (() => void) | null = null;
1405
+ const parkClock = opts.park?.now ?? (() => Date.now());
1406
+ /** A local edit, a doc update, a click: news for the park machine. */
1407
+ const noteParkActivity = (type: 'localEdit' | 'uiActivity'): void => {
1408
+ parkDispatch?.({ type, now: parkClock() });
1409
+ };
1368
1410
  /**
1369
1411
  * Cancels the boot-time capability probe. A `stop()` that leaves a `/health`
1370
1412
  * fetch in flight is a timer keeping a dying process alive and a promise
@@ -1446,7 +1488,9 @@ export function createSyncRuntime(
1446
1488
  // Captured, not re-read: `stop()` clears `filePlane`, and a pass that has
1447
1489
  // already decided to run must not dereference the field it was cleared to.
1448
1490
  const lane = filePlane;
1449
- if (stopped || !lane) return;
1491
+ // Parked: no journal reads. A local change unparks first (`fs:any`), and
1492
+ // the unpark runs a full pass of its own.
1493
+ if (stopped || !lane || parkedNow) return;
1450
1494
  // A pass already running IS this pass: it reads the same disk and the same
1451
1495
  // cursor, so the caller waits for its answer rather than racing it. The
1452
1496
  // poll's `await` therefore still means "a pass has happened".
@@ -1518,7 +1562,7 @@ export function createSyncRuntime(
1518
1562
  * recently); false only for boot.
1519
1563
  */
1520
1564
  function pollRemoteSoon(opts: { cooled?: boolean } = {}): void {
1521
- if (stopped || remotePollSoonTimer !== null) return;
1565
+ if (stopped || parkedNow || remotePollSoonTimer !== null) return;
1522
1566
  // ACCEPTED REVISIONS: a poke means "a revision was accepted", and the
1523
1567
  // canvas it created, moved or deleted — or the folder — must reach this
1524
1568
  // peer now, not on the next 20 s tick. Still bounded (one pass per
@@ -2733,7 +2777,17 @@ export function createSyncRuntime(
2733
2777
  // first is the exact, cheap version of the mtime-granularity guard: the
2734
2778
  // watcher KNOWS this path moved, so the next scan must read it rather
2735
2779
  // than trust a timestamp that a same-length edit could have left alone.
2736
- if (fileLedger) {
2780
+ //
2781
+ // NOT FOR RUNTIME STATE. The plane's own ledger lives under
2782
+ // `_state/file-ledger/`, so a pass that flushed it raised the event that
2783
+ // scheduled the next pass — a journal read every ~2 s with nobody
2784
+ // editing, and a cloud cell that never slept (2026-10-05). Runtime state
2785
+ // is never plane work (`isRuntimeStateRel`), so it never triggers a
2786
+ // pass. `fs-watch.ts` still reports `_state/` to every OTHER subscriber.
2787
+ // Somebody's work, not the studio talking to itself: it keeps a desktop
2788
+ // awake, and unparks a parked one BEFORE the pass below is asked for.
2789
+ if (isLocalWorkRel(rel)) noteParkActivity('localEdit');
2790
+ if (fileLedger && isLocalWorkRel(rel)) {
2737
2791
  fileLedger.noteChanged(rel.split('\\').join('/'));
2738
2792
  schedulePlanePass();
2739
2793
  }
@@ -3578,6 +3632,12 @@ export function createSyncRuntime(
3578
3632
  document,
3579
3633
  });
3580
3634
  providers.set(canvas.slug, provider);
3635
+ // ANY change to a synced document is activity — a local edit unparks a
3636
+ // parked desktop, and a peer's edit arriving keeps a live collaboration
3637
+ // connected rather than parking under it.
3638
+ const onDocUpdate = (): void => noteParkActivity('localEdit');
3639
+ provider.document.on('update', onDocUpdate);
3640
+ noteDetach(statusDetaches, canvas.slug, () => provider.document.off('update', onDocUpdate));
3581
3641
  // Fix 5 (sync RCA 2026-08-10): stamp the canvas path BEFORE the
3582
3642
  // handshake, not only after reconcile. The path derives from this peer's
3583
3643
  // real local file, so it is known NOW — and the hub's FIRST
@@ -4602,6 +4662,7 @@ export function createSyncRuntime(
4602
4662
  const discovery = documentDiscovery;
4603
4663
  documentDiscoveryUnsub = ctx.bus.on('sync:documents-changed', () => discovery.schedule());
4604
4664
  const pollRemote = (): void => {
4665
+ if (parkedNow) return;
4605
4666
  void discovery
4606
4667
  .flush()
4607
4668
  .then(() => pullFilesOnce())
@@ -4664,7 +4725,9 @@ export function createSyncRuntime(
4664
4725
  ? (providerFactory as DisposableProviderFactory)
4665
4726
  : null);
4666
4727
  const stallCheck = (): void => {
4667
- if (stopped || !reconnectable) return;
4728
+ // Parked is a deliberate silence, not a stall (issue #118's watchdog
4729
+ // must never "recover" a link the desktop closed on purpose).
4730
+ if (stopped || parkedNow || !reconnectable) return;
4668
4731
  const snap = mon.snapshot();
4669
4732
  const docs = snap.docs;
4670
4733
  if (snap.state !== 'online' || !docs) return;
@@ -4691,6 +4754,159 @@ export function createSyncRuntime(
4691
4754
  stallTimer = setInterval(stallCheck, stallCheckMs);
4692
4755
  stallTimer.unref?.();
4693
4756
 
4757
+ // ── The desktop park (2026-10-05) ─────────────────────────────────────
4758
+ //
4759
+ // A connected desktop is permanent activity to a cloud cell: every socket
4760
+ // message and every 20 s poll renews its timer, and an open socket blocks
4761
+ // expiry outright. So an idle desktop parks: it closes its sockets, its
4762
+ // poll and its control channel, and the cell sleeps through its ordinary
4763
+ // `sleepAfter`. The cell is never stopped under an open socket — the hub
4764
+ // flushes before it closes sockets, and sleep has only ever been lossless
4765
+ // because it happened with none attached.
4766
+ //
4767
+ // NEVER PARK BLIND: the first park needs a contract answer from the cell's
4768
+ // own `/_cell/state` (`parseCellState`). A self-hosted hub or an old cell
4769
+ // answers anything else, and this runtime then never parks — today's
4770
+ // behaviour. Not in a cell (its studio IS the hub's neighbour), and only
4771
+ // with a socket layer that can close and reopen.
4772
+ const parkable =
4773
+ !cellPairing &&
4774
+ typeof (providerFactory as Partial<DisposableProviderFactory>).park === 'function' &&
4775
+ typeof (providerFactory as Partial<DisposableProviderFactory>).unpark === 'function'
4776
+ ? (providerFactory as DisposableProviderFactory)
4777
+ : null;
4778
+ if (parkable) {
4779
+ const timings: ParkTimings = { ...PARK_TIMINGS, ...(opts.park?.timings ?? {}) };
4780
+ const parkFetch = opts.park?.fetch ?? fetch;
4781
+ let parkState: ParkState = initialParkState({ now: parkClock(), eligible: true });
4782
+ /** Outbound work that must land before the sockets may close. */
4783
+ const hasPendingWork = (): boolean => {
4784
+ if (planePassInFlight || filePassTimer !== null || remotePollSoonTimer !== null) {
4785
+ return true;
4786
+ }
4787
+ for (const p of providers.values()) {
4788
+ if ((p as unknown as { hasUnsyncedChanges?: boolean }).hasUnsyncedChanges === true) {
4789
+ return true;
4790
+ }
4791
+ }
4792
+ // Saves, uploads and retries the other lanes report (attacker F1).
4793
+ return hasSelfRetryingWork(store.get());
4794
+ };
4795
+ const doPark = (): void => {
4796
+ parkedNow = true;
4797
+ // Flush what we know; the pending-work check already proved nothing is
4798
+ // in flight.
4799
+ fileLedger?.flush();
4800
+ if (remotePollTimer !== null) clearInterval(remotePollTimer);
4801
+ remotePollTimer = null;
4802
+ if (filePassTimer !== null) clearTimeout(filePassTimer);
4803
+ filePassTimer = null;
4804
+ if (remotePollSoonTimer !== null) clearTimeout(remotePollSoonTimer);
4805
+ remotePollSoonTimer = null;
4806
+ fileEventsCtl?.stop();
4807
+ fileEventsCtl = null;
4808
+ parkable.park?.();
4809
+ store.updateParked({ since: Date.now() });
4810
+ console.log(
4811
+ `[sync] idle for ${Math.round(timings.afterMs / 60_000)} min — parked so the cloud project can sleep; the next change or click reconnects.`
4812
+ );
4813
+ };
4814
+ const doUnpark = (): void => {
4815
+ parkProbe?.abort();
4816
+ parkProbe = null;
4817
+ parkedNow = false;
4818
+ store.updateParked(null);
4819
+ // The watchdog measures from the last promotion; a park of hours must
4820
+ // not read as hours of stall the moment the sockets reopen (#118).
4821
+ lastPromotionAt = stallNow();
4822
+ parkable.unpark?.();
4823
+ if (remotePollTimer === null && !stopped) {
4824
+ remotePollTimer = setInterval(pollRemote, REMOTE_POLL_MS);
4825
+ remotePollTimer.unref?.();
4826
+ }
4827
+ if (!fileEventsCtl && makeFileEventsCtl) fileEventsCtl = makeFileEventsCtl();
4828
+ // Each provider re-promotes itself on reconnect (`repromoteOnReconnect`
4829
+ // via its status listener); this is the project half — discovery plus
4830
+ // a full file-plane pass, which treats a moved journal epoch as a
4831
+ // resync exactly as after any reconnect.
4832
+ void remotePull?.().catch((err) => console.error('[sync] unpark resync failed:', err));
4833
+ console.log('[sync] unparked — reconnecting to the cloud project.');
4834
+ };
4835
+ const doProbe = (): void => {
4836
+ parkProbe?.abort();
4837
+ const ac = new AbortController();
4838
+ parkProbe = ac;
4839
+ const timer = setTimeout(() => ac.abort(), 10_000);
4840
+ timer.unref?.();
4841
+ void (async () => {
4842
+ let result: import('./park.ts').ProbeResult;
4843
+ try {
4844
+ const res = await parkFetch(`${linkedHub.url.replace(/\/+$/, '')}/_cell/state`, {
4845
+ headers: { authorization: `Bearer ${token}`, 'x-maude-sync-park': '1' },
4846
+ // The contract is a 200 JSON answer; a redirect is `unsupported`
4847
+ // anyway, and the bearer must never follow one anywhere.
4848
+ redirect: 'manual',
4849
+ signal: ac.signal,
4850
+ });
4851
+ result = parseCellState(
4852
+ res.status,
4853
+ res.headers.get('content-type'),
4854
+ (await res.text()).slice(0, 4_096)
4855
+ );
4856
+ } catch {
4857
+ result = { kind: 'network-error' };
4858
+ } finally {
4859
+ clearTimeout(timer);
4860
+ }
4861
+ if (stopped || parkProbe !== ac) return;
4862
+ parkProbe = null;
4863
+ if (result.kind === 'unsupported' && parkState.phase === 'active') {
4864
+ console.log(
4865
+ '[sync] this hub cannot report whether it is asleep — staying connected (no park this session).'
4866
+ );
4867
+ }
4868
+ dispatch({ type: 'probeResult', result, now: parkClock() });
4869
+ })();
4870
+ };
4871
+ const run = (effects: ParkEffect[]): void => {
4872
+ for (const effect of effects) {
4873
+ if (stopped) return;
4874
+ if (effect === 'park') {
4875
+ // RE-CHECK AT THE MOMENT OF CLOSING. Pending work was sampled on
4876
+ // the tick that sent the probe, up to 10 s ago; a poke or an edit
4877
+ // in between must not have its timer cleared under it (F3).
4878
+ if (hasPendingWork()) {
4879
+ parkState = {
4880
+ ...parkState,
4881
+ phase: 'active',
4882
+ pending: true,
4883
+ parkedAt: null,
4884
+ parkMark: null,
4885
+ nextProbeAt: null,
4886
+ };
4887
+ continue;
4888
+ }
4889
+ doPark();
4890
+ } else if (effect === 'unpark') doUnpark();
4891
+ else doProbe();
4892
+ }
4893
+ };
4894
+ const dispatch = (event: ParkEvent): void => {
4895
+ if (stopped) return;
4896
+ const step = parkReducer(parkState, event, timings);
4897
+ parkState = step.state;
4898
+ run(step.effects);
4899
+ };
4900
+ parkDispatch = dispatch;
4901
+ parkUiUnsub = ctx.bus.on('ui:active', () => noteParkActivity('uiActivity'));
4902
+ parkTimer = setInterval(() => {
4903
+ const now = parkClock();
4904
+ dispatch({ type: 'pendingChanged', pending: hasPendingWork(), now });
4905
+ dispatch({ type: 'tick', now });
4906
+ }, opts.park?.tickMs ?? 15_000);
4907
+ parkTimer.unref?.();
4908
+ }
4909
+
4694
4910
  // ── Sync v2 Increment 2 — the poke, desktop side (DDR-226 §4) ──────────
4695
4911
  //
4696
4912
  // CAPABILITY-GATED, and the gate is the compat matrix (§10, BINDING): a
@@ -4788,25 +5004,29 @@ export function createSyncRuntime(
4788
5004
  // A ledger hub with the plane ON owns pushes; with the file-plane
4789
5005
  // flag OFF the legacy client still carries the DDR-217 assets lane.
4790
5006
  decidePushLane(filePlane === null);
4791
- fileEventsCtl = createCtlProvider({
4792
- url: linkedHub.url,
4793
- token,
4794
- onDocuments: () => documentDiscovery?.schedule(),
4795
- onPoke: () => {
4796
- // Reuses `pollRemoteSoon` rather than calling the file lanes
4797
- // directly, for two reasons: it already coalesces a burst into
4798
- // one pass (a fresh link appends hundreds of rows), and it is
4799
- // the exact path a reconnect takes — one behaviour to reason
4800
- // about instead of two that can drift.
4801
- //
4802
- // The PULL itself is unchanged: missing-only, idempotent, and
4803
- // re-validating everything it accepts. So a poke can at worst
4804
- // cost one early pass, and the scheduled poll remains the
4805
- // reconciler underneath it.
4806
- pokesSeen += 1;
4807
- pollRemoteSoon({ cooled: true });
4808
- },
4809
- });
5007
+ makeFileEventsCtl = () =>
5008
+ createCtlProvider({
5009
+ url: linkedHub.url,
5010
+ token,
5011
+ onDocuments: () => documentDiscovery?.schedule(),
5012
+ onPoke: () => {
5013
+ // Reuses `pollRemoteSoon` rather than calling the file lanes
5014
+ // directly, for two reasons: it already coalesces a burst into
5015
+ // one pass (a fresh link appends hundreds of rows), and it is
5016
+ // the exact path a reconnect takes — one behaviour to reason
5017
+ // about instead of two that can drift.
5018
+ //
5019
+ // The PULL itself is unchanged: missing-only, idempotent, and
5020
+ // re-validating everything it accepts. So a poke can at worst
5021
+ // cost one early pass, and the scheduled poll remains the
5022
+ // reconciler underneath it.
5023
+ pokesSeen += 1;
5024
+ pollRemoteSoon({ cooled: true });
5025
+ },
5026
+ });
5027
+ // A desktop that parked before the capability probe answered keeps
5028
+ // the channel closed; the unpark builds it.
5029
+ if (!parkedNow) fileEventsCtl = makeFileEventsCtl();
4810
5030
  console.log(
4811
5031
  '[sync/ctl] file-event channel attached — cloud changes now arrive in seconds instead of on the 20 s tick.'
4812
5032
  );
@@ -4874,6 +5094,13 @@ export function createSyncRuntime(
4874
5094
  remotePollTimer = null;
4875
5095
  if (stallTimer !== null) clearInterval(stallTimer);
4876
5096
  stallTimer = null;
5097
+ if (parkTimer !== null) clearInterval(parkTimer);
5098
+ parkTimer = null;
5099
+ parkProbe?.abort();
5100
+ parkProbe = null;
5101
+ parkDispatch = null;
5102
+ parkUiUnsub?.();
5103
+ parkUiUnsub = null;
4877
5104
  if (remotePollSoonTimer !== null) clearTimeout(remotePollSoonTimer);
4878
5105
  remotePollSoonTimer = null;
4879
5106
  documentDiscoveryUnsub?.();
@@ -5729,6 +5956,16 @@ export interface DisposableProviderFactory extends ProviderFactory {
5729
5956
  * handshake and never a re-attach.
5730
5957
  */
5731
5958
  reconnect(): void;
5959
+ /**
5960
+ * Close every shared socket and keep it closed — the desktop park
5961
+ * (`sync/park.ts`). Providers stay attached and learn of the close through
5962
+ * the socket's own `close` event, exactly as after a drop; nothing is
5963
+ * destroyed, so `unpark()` costs a handshake and never a re-attach.
5964
+ * Optional: a factory without it never parks.
5965
+ */
5966
+ park?(): void;
5967
+ /** Bring parked sockets back through the ordinary reconnect path. */
5968
+ unpark?(): void;
5732
5969
  }
5733
5970
 
5734
5971
  /**
@@ -6080,6 +6317,37 @@ export function createDefaultProviderFactory(
6080
6317
  }
6081
6318
  }
6082
6319
  },
6320
+ park(): void {
6321
+ for (const socket of allSockets()) {
6322
+ try {
6323
+ // `disconnect()` IS right here, where it is wrong in `reconnect()`:
6324
+ // it sets `shouldConnect = false` so the close does NOT re-arm, which
6325
+ // is the whole point of parking. The raw close still emits `close`,
6326
+ // so every provider resets `isAuthenticated`/`synced` as after any
6327
+ // drop.
6328
+ socket.disconnect();
6329
+ } catch (err) {
6330
+ console.warn(`[sync] socket park failed: ${(err as Error).message}`);
6331
+ }
6332
+ }
6333
+ },
6334
+ unpark(): void {
6335
+ for (const socket of allSockets()) {
6336
+ try {
6337
+ // THE WEDGE (see `reconnect()`): `connect()` returns early while the
6338
+ // status still reads `connected`, ABOVE the line that restores
6339
+ // `shouldConnect`. A park's close normally landed long ago; if it has
6340
+ // not, restore the flag and let that close re-arm the socket itself.
6341
+ if (socket.status === 'connected') {
6342
+ socket.shouldConnect = true;
6343
+ continue;
6344
+ }
6345
+ void Promise.resolve(socket.connect()).catch(() => {});
6346
+ } catch (err) {
6347
+ console.warn(`[sync] socket unpark failed: ${(err as Error).message}`);
6348
+ }
6349
+ }
6350
+ },
6083
6351
  });
6084
6352
  }
6085
6353