@moxuli/moremote 0.1.1 → 0.1.4

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 (45) hide show
  1. package/README.md +85 -7
  2. package/bin/moremote-cli.js +11 -4
  3. package/dist/activity.d.ts +79 -0
  4. package/dist/activity.js +193 -0
  5. package/dist/cli.js +36 -41
  6. package/dist/cloud-client.d.ts +13 -4
  7. package/dist/cloud-client.js +60 -15
  8. package/dist/config.d.ts +7 -0
  9. package/dist/config.js +23 -4
  10. package/dist/control.d.ts +1 -0
  11. package/dist/control.js +9 -0
  12. package/dist/crypto.d.ts +1 -1
  13. package/dist/crypto.js +2 -2
  14. package/dist/enrollment-files.d.ts +37 -0
  15. package/dist/enrollment-files.js +225 -0
  16. package/dist/enrollment-protocol.d.ts +50 -0
  17. package/dist/enrollment-protocol.js +44 -0
  18. package/dist/journal.js +2 -1
  19. package/dist/local-enrollment.d.ts +25 -0
  20. package/dist/local-enrollment.js +160 -0
  21. package/dist/official-client.d.ts +87 -6
  22. package/dist/official-client.js +135 -32
  23. package/dist/operations.d.ts +1 -0
  24. package/dist/operations.js +24 -4
  25. package/dist/projection.d.ts +7 -2
  26. package/dist/resources.d.ts +2 -1
  27. package/dist/resources.js +69 -32
  28. package/dist/runtime.d.ts +10 -1
  29. package/dist/runtime.js +111 -10
  30. package/dist/service.js +43 -8
  31. package/dist/setup-upgrade.d.ts +2 -0
  32. package/dist/setup-upgrade.js +65 -0
  33. package/dist/setup.d.ts +12 -0
  34. package/dist/setup.js +38 -0
  35. package/dist/supervisor.d.ts +1 -0
  36. package/dist/supervisor.js +44 -1
  37. package/docs/README.md +4 -3
  38. package/docs/STATE.md +327 -10
  39. package/docs/configuration.md +119 -5
  40. package/docs/plans/2026-11-11-native-service-acceptance.md +168 -0
  41. package/docs/specs/03-api-contract.md +122 -2
  42. package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
  43. package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
  44. package/docs/specs/06-managed-updates.md +34 -1
  45. package/package.json +2 -2
@@ -0,0 +1,168 @@
1
+ # Native service acceptance — 2026-11-11
2
+
3
+ ## Status and boundary
4
+
5
+ The current compiled source controller has exercised real macOS launchd installation,
6
+ start, status, stop and uninstall against the published0.1.1 managed runtime.
7
+ This is not a new npm release, a published-version upgrade, or Linux/Windows native
8
+ service-manager acceptance. Existing released0.1.1 bytes remain unchanged.
9
+
10
+ The acceptance used an unused per-user service label, an isolated HOME and a short,
11
+ owned state directory. Cloud was disabled, pairings were empty and the official
12
+ endpoint was an unreachable loopback address. No official daemon, real-work session,
13
+ model, enrollment or APNs request was used. Installation was refused unless the
14
+ service label and real-home registration file were initially absent.
15
+
16
+ ## Discovered shutdown race
17
+
18
+ The real service initially installed and started successfully. Stopping it could
19
+ fail with `CONTROL_CONNECTION_CLOSED`: native bootout had already begun graceful
20
+ supervisor/runtime shutdown while the CLI independently requested control shutdown.
21
+ The socket could close before its ownership records had finished retiring.
22
+
23
+ The correction preserves strict generic control transport errors. Only a managed
24
+ shutdown can cross this specific closure window; it must still wait for supervisor
25
+ retirement and confirm that no runtime remains. An empty response alone is never
26
+ success, malformed responses still fail, and an uncertain stop is not replayed
27
+ against a replacement generation. The workflow now lives with supervisor lifecycle
28
+ ownership instead of being duplicated in CLI command wiring.
29
+
30
+ Independent review exposed a second boundary: a final status probe can return null
31
+ for a departed generation while a replacement owner remains alive. Its regression
32
+ also failed before correction. Shutdown now revalidates the current supervisor and
33
+ runtime lock/PID synchronously after the awaited probe, including lock-only startup.
34
+ The replacement must remain intact and shutdown must fail rather than authorizing
35
+ uninstall. The independent follow-up found no remaining blocker in this scope.
36
+ These checks are snapshots; they cannot prevent an independent start afterward.
37
+
38
+ ## Exercised proof
39
+
40
+ - The new owned-socket/supervisor-retirement regression failed before the behavior
41
+ correction. It checks that closure cannot complete shutdown before retirement.
42
+ - 22 focused behavioral checks passed across `managed-shutdown.test.ts`,
43
+ `frontend-lifecycle.test.ts`, `control-response.test.ts` and `cli.test.ts`.
44
+ - `npm run typecheck` and `npm run build` passed.
45
+ - The corrected compiled source controller installed the real launchd registration,
46
+ reached the published runtime's authenticated status endpoint, stopped it and
47
+ removed the registration, plist and isolated state. Final launchd lookup returned
48
+ the platform's explicit missing-service result; no test login service remained.
49
+ - Earlier fixture setup failures were not product acceptance: one used an invalid
50
+ synthetic client identity; another exceeded the Unix-domain socket path limit.
51
+ The final native run used valid configuration and a short isolated path.
52
+
53
+ ## Remaining gates at the preceding checkpoint
54
+
55
+ 1. A separately authorized, immutable next-version release including current source;
56
+ the published0.1.1 package must not be represented as containing this correction.
57
+ 2. Real published-version activation/rollback through an installed native service.
58
+ 3. Equivalent native service-manager acceptance on Linux and Windows.
59
+
60
+ Do not install a test registration over an everyday service. A fake HOME isolates
61
+ registration files, not launchd's per-user label namespace. When that label is in
62
+ use, use a separately owned OS environment rather than stopping another instance.
63
+
64
+ ## Installed upgrade and rollback continuation — 2026-11-12
65
+
66
+ - A fresh anonymous npm download of immutable0.1.1 matches registry SHA512 and
67
+ published SHA256`358574ca750d27c8a116743cd729d7ab830c41fc17045ddfa46ff808ff3bba3b`.
68
+ The retained native service starts those actual published bootstrap bytes.
69
+ - The actual launchd namespace and real-home registration file are required to
70
+ be absent before installation. The service uses an owned temporary HOME/state,
71
+ no pairs, cloud disabled and an unreachable loopback official endpoint.
72
+ - Initial startup did not reach readiness because the fixture omitted the required
73
+ client-identity prefix. A private direct bootstrap diagnostic reports
74
+ `INVALID_CONFIG`; this is not a product startup defect.
75
+ - Failed-run cleanup exposed a real ownership defect: launchd canonicalizes
76
+ `/tmp` to `/private/tmp`, while the controller compared raw strings and rejected
77
+ its own registration. The exact first service was safely removed through the
78
+ normal controller using its independently established canonical definition.
79
+ - The product correction accepts a parent-path alias only when both leaves are
80
+ ordinary non-symlink files, device/inode match and real paths match. Exact
81
+ unchanged paths retain their fast path. Leaf symlinks, different files and
82
+ foreign registration/marker protections remain rejected. The same rule applies
83
+ to systemd's file path; Windows task matching is unchanged.
84
+ - All10focused service-lifecycle consumers, typecheck and build pass. Independent
85
+ OpenCode review reports no blocker. Distinct hard links/bind mounts remain a
86
+ conservative refusal; no general authority over user-writable services is added.
87
+ - The corrected real launchd run passes in181.29seconds: published0.1.1 bootstrap
88
+ → current synthetic9000.0.2 candidate → failed compatible9000.0.3 startup →
89
+ recovered9000.0.2. Authenticated status and durable selection agree; bootstrap/
90
+ previous remain0.1.1. Normal stop/uninstall leaves no registration, plist or
91
+ owned successful-run files.
92
+
93
+ This accepts macOS native activation/rollback with real installed package bytes
94
+ and a deliberately failing unpublished fixture. It is not a new immutable public
95
+ release, public-to-public next-version delivery, Linux/Windows native acceptance,
96
+ cloud activation or any real-work-session operation.
97
+
98
+ ## Linux user-service and Windows encoding continuation — 2026-11-12
99
+
100
+ Actual Linux acceptance uses the existing Ubuntu26.04 user manager, systemd259
101
+ and pinned Node24.13.0. The real unit reaches active/running/enabled and the
102
+ authenticated control reports the installed version. QA0.1.1 activates synthetic
103
+ 9000.0.2, then rejects compatible9000.0.3 before readiness and recovers9000.0.2
104
+ with unchanged bootstrap/previous0.1.1. Normal stop/uninstall leaves
105
+ LoadState=not-found, an empty FragmentPath, absent definition/control and no live
106
+ supervisor/runtime. This is actual user-systemd, not every Linux distribution.
107
+
108
+ The preceding Windows QA implementation identified missing BOM in a UTF-16LE
109
+ task import file. Native COM syntax-only validation of a decoded string did not
110
+ test the file bytes consumed by schtasks. That QA writer emitted FF FE; its
111
+ current reader was corrected to consume one leading U+FEFF while retaining
112
+ ownership/XML checks. This was current/current QA evidence, not retained-version
113
+ compatibility; the later correction below supersedes the persistent-BOM design.
114
+
115
+ That18consumer run covered writer/current-reader consumption, legacy unmarked
116
+ UTF-16 ownership inspection, repeated-BOM, wrong-encoding and foreign-marker
117
+ rejection. Typecheck and build also passed.
118
+
119
+ The final unwrapped native Windows Task Scheduler run passes in168.23seconds.
120
+ It installs/starts QA0.1.1, authenticates status, activates synthetic9000.0.2,
121
+ rejects9000.0.3 before readiness and recovers9000.0.2, then normally stops and
122
+ uninstalls. Independent task/definition/control checks are absent and no live
123
+ supervisor/runtime remains. The exercised QA archive SHA256 is
124
+ `8b5c55ac04edfaf5c93eb7b1708ad07be9eec5b0d288b04ec0b5dbbd81b4df82`.
125
+
126
+ No console-token impersonation, account/policy change, real daemon/cloud
127
+ operation or public release is used. A private fixture's elevated-owner ACL
128
+ mismatch was recorded separately rather than misrepresented as a product login
129
+ requirement. Failed and diagnostic task registrations were normally removed.
130
+ An independent provider review could not run because its read tools were
131
+ refused; no review approval is claimed.
132
+
133
+
134
+ ## Retained public reader correction — 2026-11-12
135
+
136
+ Fresh-context specification review found that unchanged public0.1.1 starts its
137
+ resource reader before runtime readiness and cannot consume persistent BOM-prefixed
138
+ ownership XML. A matching compatibility tuple and synthetic current/current
139
+ native pass did not establish retained-reader compatibility.
140
+
141
+ Persistent `moremote-cli-task.xml` is now BOM-free UTF-16LE. Native `/Create`
142
+ receives a separate BOM-prefixed XML file in an owned private temporary directory
143
+ outside shared state. `finally` removes that copy before `/Run`; registration or
144
+ cleanup failure cannot start the runtime. No schema bump or migration is needed.
145
+
146
+ Two new deterministic regressions first fail, then the20focused lifecycle/resource
147
+ consumers, typecheck and build pass. The frozen public reader is unmodified,
148
+ SHA256`1ee80f6bdab819e15da817038cecf46133b07d1a157663893a64112a2fdca13b`;
149
+ an independent anonymous npm download confirms those module bytes. Fresh-context
150
+ Stage A and Stage B re-review close the blocker, explicitly using the weaker
151
+ same-provider fallback after the unavailable cross-provider attempt.
152
+
153
+ The actual Windows journey starts unchanged npm0.1.1 bootstrap bytes, activates
154
+ the current synthetic9000.0.2, fails9000.0.3 before readiness, recovers9000.0.2
155
+ and normally stops/uninstalls. The native interval is183.86seconds; the enclosing
156
+ fleet job takes202.70seconds. Independent final observations show no task,
157
+ definition, control endpoint or live supervisor/runtime; successful-run runtime
158
+ files are removed. The intentionally unused loopback official target yields
159
+ degraded connection status while authenticated runtime/version checks succeed.
160
+
161
+ Public0.1.1 archive SHA256 is
162
+ `358574ca750d27c8a116743cd729d7ab830c41fc17045ddfa46ff808ff3bba3b`;
163
+ unpublished exercised candidate SHA256 is
164
+ `6dca555348e87dd395aa0564d97aa1499581fbeadc98b78dbb1c9c3c179ff861`.
165
+ No real daemon/cloud/model operation, account/security-policy change, npm
166
+ publication or everyday installed service occurs. Synthetic candidates are
167
+ still not a new immutable public release or public-to-public delivery.
168
+
@@ -1,6 +1,6 @@
1
1
  # 03 — Relay HTTP API, version 1
2
2
 
3
- **Status:** implementation detail of the owner-approved first notification/scoped-delivery iteration; review against the accepted architecture before coding
3
+ **Status:** living relay-v1 contract. Activity/widget additions below describe unreleased local integration, not published CLI0.1.1 or native/live-cloud acceptance.
4
4
 
5
5
  ## Common rules
6
6
 
@@ -103,7 +103,9 @@ without contacting cloud.
103
103
 
104
104
  ### PUT /pairs/{pairId}/state; GET /pairs/{pairId}/state
105
105
 
106
- Host writes, phone reads. Body/response contains `{envelope}` with `state` channel.
106
+ Host writes, phone reads. PUT accepts strict `{envelope}` or additive
107
+ `{envelope,widgetFingerprint}`; GET returns the envelope only, as specified below.
108
+ Envelope channel is `state`.
107
109
  Only the latest nonexpired snapshot keeps ciphertext, monotonic by issuedAt then
108
110
  immutable ID. Each state ID/digest remains a conflict guard through its own
109
111
  original envelope expiry, including after supersession; no additional24hour
@@ -395,3 +397,121 @@ may contain both original128KiB-bounded payload and a separate8KiB receipt; a
395
397
  host pairing response may contain two bounded proofs. A128KiB response reader
396
398
  would permanently reject valid work and is nonconforming. This larger response
397
399
  budget never raises the128KiB request or64KiB decrypted command-content limits.
400
+
401
+ ## Opt-in task activities and widget reloads
402
+
403
+ These additive routes do not change command, receipt, alert, pairing, service,
404
+ or managed-update identities. Cloud remains disabled by default. Every route
405
+ uses the existing pair bearer; subscription IDs and registration IDs are
406
+ lowercase canonical UUIDs. No pair-level activity-device registration exists.
407
+
408
+ | Route (under `/v1/pairs/{pairId}`) | Role | Exact JSON body | Admission |
409
+ | --- | --- | --- | --- |
410
+ | `PUT /activities/{subscriptionId}` | phone | `{registrationId,token,environment,topic,interest}` | normal |
411
+ | `DELETE /activities/{subscriptionId}` | phone | none | recovery |
412
+ | `GET /activities` | host | none | normal |
413
+ | `PUT /activities/{subscriptionId}/state` | host | `{registrationId,topic,event:"update",envelope}` | normal |
414
+ | `PUT /activities/{subscriptionId}/end` | host | `{registrationId,topic,event:"end",envelope}` | recovery |
415
+ | `PUT /widget-device` | phone | `{registrationId,token,environment}` | normal |
416
+ | `DELETE /widget-device/{registrationId}` | phone | none | recovery |
417
+
418
+ Tokens are even-length hex,1–256 bytes, normalized lowercase. Environment is
419
+ `sandbox|production`; provider configuration must match. The activity `topic`
420
+ is the existing pair-key HMAC `presenceTopic(rootKey,pairId,agentId)` (32 bytes,
421
+ base64url), not an APNs topic or plaintext agent identity. At most8 live
422
+ subscriptions are admitted per pair. GET returns
423
+ `{ok:true,subscriptions:[{id,registrationId,topic,interest,expiresAt}]}`.
424
+ PUT registration returns the same single row as `{ok:true,subscription:...}`.
425
+ Registration replacement uses a fresh registrationId; different bytes under
426
+ the same registrationId conflict. Native renewal must preserve the ActivityKit
427
+ activity's original8-hour ceiling. DELETE removes queued state immediately.
428
+ Retired subscription/registration IDs share a bounded1000-entry token-free guard
429
+ pool with widget registrations. Delayed registration PUTs cannot resurrect or
430
+ roll back retired identities. Widget DELETE is registration-exact; activity DELETE targets the subscription.
431
+ Activity guards retain the original8h ceiling and widget guards the original24h
432
+ expiry, without retry extension. Unknown DELETEs also reserve bounded guards;
433
+ capacity exhaustion fails closed, never evicts live protection.
434
+
435
+ The encrypted `interest` uses additive channel `activityInterest`, envelope.id
436
+ equal to subscriptionId, lifetime at most8h. Exact plaintext:
437
+ `{version:1,subscriptionId,daemonServerId,agentId}`. The companion authenticates
438
+ the envelope, pinned daemon, exact subscription and derived topic before any
439
+ read-only task lookup. This plaintext cannot authorize commands. No timeline
440
+ or chat download is required. Existing snapshot cadence (at least30s) admits
441
+ one bounded interest pass, at most8 exact fallback reads outside the recent list.
442
+ The owned optional lane has a2s deadline,250ms SDK reads and request cancellation.
443
+ Commands/control never await it; drain aborts/joins before SDK/journal close. Missing tasks never imply finish.
444
+
445
+ Activity state uses additive channel `activityState`, fresh envelope UUID and
446
+ at most600s lifetime, capped by subscription expiry. Exact plaintext:
447
+ `{version:1,subscriptionId,daemonServerId,agentId,title,hostName,phase,startedAt,measuredAt,expiresAt,requiresAttention,isTerminal}`.
448
+ Title/hostName are limited to160/80 characters. Phase is
449
+ `running|waiting|finished|error|idle`; permission attention maps to waiting;
450
+ official closed/error or current terminal attention maps to end. A running
451
+ turn supersedes an old terminal attention flag. startedAt is nullable, from
452
+ official activeTurn.startedAt or lastUserMessageAt, never a measurement
453
+ substitute. measuredAt/expiresAt exactly match envelope headers in milliseconds.
454
+ Existing encrypted snapshots also include optional lastUserMessageAt,
455
+ activeTurnStartedAt and bounded cwd per task. Encrypted usage adds genuine
456
+ provider displayName and window/balance label (at most128 characters each),
457
+ preserving absent values as unavailable. No full chats, invented labels or
458
+ synthetic percentages are added.
459
+
460
+ HKDF salt, AES-GCM nonce/tag framing, metadata AAD and existing channels remain
461
+ byte-compatible. Only the new channel name changes HKDF info. Activity state
462
+ serialized envelope is at most3000 UTF-8 bytes. Native ContentState has default
463
+ Codable field `payload`, a canonical JSON string of that envelope (key order
464
+ version,pairId,id,channel,issuedAt,expiresAt,nonce,ciphertext).
465
+ Updates derive directly from real semantic task transitions, independently of
466
+ alert admission/presence suppression. Unchanged measurements normally do not push.
467
+ Acknowledged nonterminal state renews from fresh samples every8minutes (120s before600s expiry).
468
+ Unknown admissions retain identical ciphertext until expiry; semantic changes can supersede progress. Disconnected state expires.
469
+
470
+ Live authenticated interests are cached against the current pair key/daemon. Terminal work precedes optional normal discovery, once per fresh
471
+ snapshot, without GET/state admission; authenticated404/409 invalidates its cache.
472
+ Only exact429 `daily_work_limit`, `x-moremote-budget:normal` and consistent future
473
+ `x-moremote-reset`/Retry-After pauses normal work alone. Missing/malformed hints,
474
+ outages, disable or recovery exhaustion preserve origin-wide pause/cycle fences.
475
+ Recovery still requires server admission; hints never grant operation authority.
476
+
477
+ APNs uses `apns-push-type:liveactivity`, configured main topic plus
478
+ `.push-type.liveactivity`, priority5 update/10 end, collapse-id subscriptionId,
479
+ apns-id envelope.id, expiration floor(expiresAt/1000). Body is
480
+ `{aps:{timestamp,event,"content-state":{payload},"stale-date"}}`; all APNs dates
481
+ are epoch seconds. End additionally sets dismissal-date. There is no apns-event
482
+ header. A512-byte static-attributes reserve and the complete4096-byte provider
483
+ payload limit both apply. End and invalid-token retirement compare the exact
484
+ current registration identity; stale provider failures never remove replacement
485
+ tokens. Provider admission is not proof of rendering.
486
+
487
+ Existing `PUT /state` accepts strict legacy `{envelope}` or additive
488
+ `{envelope,widgetFingerprint}`. GET state remains unchanged. The new fingerprint
489
+ is a pair-keyed HMAC using the presence domain over JSON
490
+ `["widgetSnapshot",meaningfulProjection]`. Projection includes bounded sorted
491
+ task identity/title/status/attention/latest turn/project plus usage values;
492
+ measurement and usage fetchedAt clocks are excluded. Only a changed opaque
493
+ fingerprint for the current widget registration queues a coalesced push.
494
+ Legacy envelope-only publications do not cause widget pushes.
495
+
496
+ Widget registration expires after24h and requires foreground/token renewal
497
+ (native renewal around12h uses a fresh registration ID).
498
+ Native uses the WidgetKit token, not an alert or activity token. Explicit
499
+ `APNS_WIDGET_TOPIC` is the widget extension bundle ID plus `.push-type.widgets`;
500
+ it is never derived from the main app topic. APNs uses push-type widgets,
501
+ priority5 and `{aps:{"content-changed":true}}`, no private identifiers.
502
+ WidgetKit automatically reloads timelines opportunistically on receipt;
503
+ WidgetPushHandler observes token/configuration updates. Timeline providers use
504
+ the existing sealed snapshot and its expiry; reload is not realtime delivery.
505
+ See Apple's [WidgetKit push documentation](https://developer.apple.com/documentation/widgetkit/updating-widgets-with-widgetkit-push-notifications).
506
+
507
+ Activity/widget work shares bounded provider attempts and background batches
508
+ with alerts; no recursive requests, unbounded retries, recovery-budget borrowing
509
+ for progress or changes to endpoint retirement/receipt/updater lifecycle.
510
+
511
+ Every APNs sender requires a synchronous `BeforeSend = () => boolean` fence
512
+ after asynchronous JWT signing and immediately before transport. The durable
513
+ caller rechecks service enabled, active pair, exact current registration and
514
+ publication, and expiry. Signing shares the original10s attempt deadline;
515
+ late signing cannot start transport. Global budgets and kill deadline are unchanged.
516
+ Physical Live Activity/widget behavior and live APNs/cloud delivery for this
517
+ delta remain pending; provider200 never establishes device delivery.
@@ -69,6 +69,18 @@ read-only but cannot approve a replacement. Before dispatch, refresh the actual
69
69
  pending request, match its binding/source and validate the selected actual action.
70
70
  Do not depend on requestId never being reused.
71
71
 
72
+ Request notifications use the exact current occurrence's first-observed clock,
73
+ independent of a task's older completion or global attention timestamp. Keep that
74
+ clock stable across repeated observations. A request/resolution event or a newer
75
+ accepted observation fences older in-flight reads of that agent before journal
76
+ synchronization or notification; delayed responses cannot recreate a retired
77
+ occurrence, replace newer authority or supply a fresh notification clock.
78
+ The official adapter owns synchronization into its exact journal; binding callers
79
+ do not observe the returned request array again. They match its generation/source
80
+ fingerprint and recheck currentness after binding. Queued internal request events
81
+ capture their occurrence when observed, so delayed draining cannot attach an old
82
+ event's clock to a replacement occurrence or consume its notification identity.
83
+
72
84
  Reject response fields outside the real upstream response shape. Any remembered
73
85
  permissions must be an actual offered suggestion explicitly selected by the user;
74
86
  never accept an arbitrary new grant or silently set remember. Edited input is
@@ -1,11 +1,135 @@
1
1
  # 05 — Endpoint and lifecycle behavior
2
2
 
3
- ## Enrollment QR v1
3
+ ## Single-pairing local enrollment v1 — unreleased
4
+
5
+ Normal users pair only official Paseo. Explicit `setup --yes` authenticates the
6
+ existing official daemon, enables automatic enrollment/cloud and installs/starts
7
+ only the existing owned CLI per-user service. Stop/reload only owned CLI state;
8
+ preserve custom origin/target, active/revoked pairs and update preference. An
9
+ absent API origin selects the built-in production HTTPS endpoint. Source checkout
10
+ without managed state binds its current frontend and manual-update policy;
11
+ installed packages/retained managed state use capability-aware exact-current
12
+ setup migration before enabling enrollment, retaining prior packages and update
13
+ opt-out while selecting an enrollment-capable active/bootstrap. Unavailable or
14
+ incapable current packages fail explicitly without cloud opt-in. Manifest
15
+ `localEnrollment:1` and `configBytes:524288` declare that capability.
16
+ `check`, `status` and config reads remain passive. Manual `pair` is expert-only.
17
+ No official modifications, new listener, hidden terminal/workspace, model prompt,
18
+ new relay, global upgrade or package publication is part of this protocol.
19
+
20
+ Discovery tree:
21
+
22
+ ```text
23
+ <home>/.moremote-cli-connect/<sha256(UTF8 daemonServerId)>/
24
+ descriptor.json
25
+ requests/<request UUID>.json
26
+ responses/<request UUID>.json
27
+ ```
28
+
29
+ Parent, daemon and request/response directories carry owned markers and are
30
+ ordinary owned POSIX0700 directories. Descriptor/responses are0600. Requests
31
+ created by the official file API may be0644 inside their private parent.
32
+ Windows relies on the user profile ACL. Reject symlinks, hardlinks, foreign
33
+ markers/users/types, response collisions and competing runtime ownership.
34
+ One marked daemon directory binds to the exact CLI state directory. Its own
35
+ exclusive PID/instance lock can be reclaimed only after the recorded process
36
+ is dead; this lock never authorizes signalling another process. No new socket
37
+ is created. Existing runtime ownership serializes config/cycle work.
38
+
39
+ The app obtains the actual home through official `directory_suggestions_request`
40
+ with query `~/././.`, preserving Windows path joining. A <=4096-byte descriptor is
41
+ exactly:
42
+
43
+ ```text
44
+ {version:1,daemonServerId,instanceId,apiOrigin,enabled,measuredAt,expiresAt}
45
+ ```
46
+
47
+ `instanceId` is a lowercase UUID. Times are safe integer Unix milliseconds.
48
+ `apiOrigin` is the configured/default validated canonical HTTPS origin, pinned
49
+ over the already authenticated official file channel. Descriptor lifetime is90s,
50
+ renewed no faster than30s; disablement can remove resources or publish disabled
51
+ without granting a new enabled lease. This is not a cloud heartbeat.
52
+
53
+ After validating the original authenticated host/session/generation and fresh
54
+ descriptor, the app durably retains one exact immutable UTF-8 request before
55
+ official create/read-revision/write. Empty files are unfinished creates, not
56
+ admissions. Unknown outcomes read the same exact path and never mint another
57
+ request identity. Request <=4096bytes:
58
+
59
+ ```text
60
+ {version:1,id,clientId,daemonServerId,issuedAt,expiresAt}
61
+ ```
62
+
63
+ IDs/client IDs are lowercase UUIDs; lifetime is at most600000ms, with no future
64
+ issuance or expiry grace. At most16 files are consumed per cycle with a rotating
65
+ cursor, and the existing16-pair ceiling remains. A durable record saves exact
66
+ bytes/fingerprint, original pair/canonical offer and exact cloud-create JSON
67
+ before I/O. Lost creation acknowledgements retry those identical bytes through
68
+ the unchanged relay's exact-offer-digest idempotency. A confirmed creation is
69
+ saved before any secret response. Changed bytes/client/daemon/expiry cannot
70
+ replace authority. A client with a current live endpoint cannot manufacture
71
+ another by changing its request ID. Old exact revoked/retired requests remain
72
+ disabled; an explicit fresh app Enable request can create a new independent
73
+ endpoint after retirement. Existing pairs are never reused or revived.
74
+
75
+ At most one cloud-create attempt runs per serialized cycle, independently aborted
76
+ after3s; no optional admission may accumulate sixteen20s cloud waits ahead of an
77
+ existing phone's commands. Requests retain original authority across that abort.
78
+
79
+ Response <=8192bytes:
80
+
81
+ ```text
82
+ {version:1,id,clientId,daemonServerId,expiresAt,status,offer?,code?}
83
+ ```
84
+
85
+ Status vocabulary is `pending|offer|active|disabled|error`. Only `offer` carries
86
+ the original canonical version1 offer defined below. Its origin must exactly
87
+ match the authenticated descriptor pin. Response expiry never exceeds either
88
+ original request or offer expiry. Pending/unknown cloud creation has no secret
89
+ response. Invalid/conflicting/foreign files fail closed without overwriting
90
+ them; the normal runtime reports only a redacted cycle failure. Disabled/retired
91
+ admitted requests can receive a nonsecret disabled response. The app stages and
92
+ claims automatically, without an offer-review screen, using the unchanged
93
+ phoneHello/companionHello proof and independently verified daemon identity.
94
+
95
+ Activation removes the owned request/private response. Expiry removes them and
96
+ their durable enrollment record; existing pair/audit retirement is unchanged.
97
+ Stop removes only owned responses/descriptor/lock, retaining exact request/pair
98
+ authority for restart until original expiry. Explicit cloud-off removes secret
99
+ responses and never creates another pair. Automatic observation is bounded by
100
+ the app to10 response reads over at most30s; a later foreground refresh retains
101
+ the same exact request. No forever polling, recursive requests or cloud pairing
102
+ on each launch.
103
+
104
+ Implementation APIs are `LocalEnrollment.cleanup/cycle/close`,
105
+ `EnrollmentFiles`/`discoveryDirectory`, `setupEnrollment`, and the explicit
106
+ `EnrollmentRequest`, `EnrollmentOffer`, `EnrollmentRecord`,
107
+ `EnrollmentDescriptor`, `EnrollmentResponse` types. All test homes/storage and
108
+ service lifecycle I/O are injectable; tests never create discovery in real HOME
109
+ or implicitly register a real service. Focused isolated consumers live in
110
+ `tests/local-enrollment.test.ts` and `tests/setup-command.test.ts`; they are
111
+ verification instructions, not a claim of execution.
112
+
113
+ Config/resource readers and atomic writers use the same524288-byte serialized
114
+ bound, preserving full original request bytes. Oversize writes reject before
115
+ replacement. Only acquired runtime ownership initializes fresh config; duplicate
116
+ `run` never writes an old loaded config over live enrollment.
117
+
118
+ ## Expert-only manual enrollment offer v1
4
119
 
5
120
  Canonical offer is compact UTF-8 JSON with exactly {version:1,apiOrigin,pairId,enrollmentToken,rootKey,expiresAt}. pairId is a lowercase UUID; token/rootKey are independently random canonical unpadded-base64url32-byte values. The ten-minute original expiry bounds claim, both proofs and activation; a claim just before the deadline does not extend it. Default QR/link is moremote://enhance# plus unpadded-base64url of those exact JSON bytes. --json emits raw JSON. The fragment never reaches an HTTP origin. Consumers reject extras, unsupported versions, expired/noncanonical offers and origin changes; HTTPS except explicit loopback development. The secret QR is explicit output, never diagnostics.
6
121
 
7
122
  The companion persists its root/host/enrollment capabilities before POST pairs, sending only identity, expiry and SHA256 hashes of the canonical bearer UTF-8 text (not decoded bytes). It verifies the pending phoneHello claim/token hash exactly, saves the accepted phone and immutable companionHello proof before activation, and enables actions only after confirmation within the original deadline. The phone independently verifies proof and exact saved daemon identity. Every phone is a separate pairing/key. Cloud credentials cannot satisfy this endpoint proof.
8
123
 
124
+ Unreleased source onboarding: invoking `pair` is explicit cloud consent. If
125
+ `apiOrigin` is absent, select the built-in
126
+ `https://moremote-cloud-ingress.pages.dev`; otherwise preserve and validate the
127
+ configured origin. Existing target, local official discovery and daemon pin
128
+ remain authoritative. Persist cloud-enabled configuration and the new offer
129
+ only after the official connection succeeds, before relay creation. Retained
130
+ pair keys, origins and revocation are never changed by a new enrollment.
131
+ Passive config loads/check/status do not opt in, and pairing installs no service.
132
+
9
133
  ## Official compatibility and observation
10
134
 
11
135
  Pin client/protocol0.15.3. createHostClient from client/node and exported internal/daemon-client types are the inspected API. Use clientType cli and a distinct companion clientId. Missing explicitEventSubscriptions fails closed. Subscribe only agent_attention_required, agent_permission_request, agent_permission_resolved, status.server_info with official remote notifications disabled. Never call client_heartbeat, clear_agent_attention, workspace read acknowledgement or register_push_token. Inspected SDK automatic liveness uses bare protocol ping (10s), not visible-user presence. Actual synthetic WebSocket consumers exercise the real adapter/SDK, await that liveness interval, verify wire traffic, then lose send/permission acknowledgements and reconnect without a second mutation.
@@ -16,7 +140,7 @@ Only selected paseo.pid and local-credential files are read, with bounded I/O an
16
140
 
17
141
  ## Bounded encrypted state and attention
18
142
 
19
- State plaintext is exactly {version:1,daemonServerId,hostName,measuredAt,tasks:[{agentId,title,status,updatedAt,requiresAttention,attentionReason,pendingRequests:[{requestId,requestBinding,request:<complete original official request JSON>}]}],usage,tasksTruncated}. At most100 recent noninternal/nonarchived tasks,10 requests/task,16 provider summaries and8 windows/balances/provider. A raw request over8KiB is omitted from enhanced actions, not silently truncated into another authority. Whole trailing tasks are omitted to keep serialized state under60000bytes; tasksTruncated is explicit. Unavailable usage is null/unavailable, never zero. No full conversation or files are projected. Measurement time survives immutable state retries.
143
+ State plaintext is exactly {version:1,daemonServerId,hostName,measuredAt,tasks:[{agentId,provider,title,status,createdAt,updatedAt,lastUserMessageAt,activeTurnStartedAt,cwd,requiresAttention,attentionReason,pendingRequests:[{requestId,requestBinding,request:<complete original official request JSON>}]}],usage,tasksTruncated}. Provider and creation time are additive unreleased source fields; older snapshots may omit them. Preserve genuine official provider and ISO-8601 createdAt/lastUserMessageAt facts; a missing last-user time stays null, never replaced by assistant-driven updatedAt. Consumers order recents by lastUserMessageAt, then creation time only when absent, then stable identity for ties. At most100 recent noninternal/nonarchived tasks,10 requests/task,16 provider summaries and8 windows/balances/provider. A raw request over8KiB is omitted from enhanced actions, not silently truncated into another authority. Whole trailing tasks are omitted to keep serialized state under60000bytes; tasksTruncated is explicit. Unavailable usage is null/unavailable, never zero. No full conversation or files are projected. Measurement time survives immutable state retries.
20
144
 
21
145
  Attention plaintext is exactly {agentId,requestId?,requestBinding?,kind,timestamp}. No form or prompt is in the push route. For question/approval actions the app must find the exact matching authenticated raw request and binding in state or open the original form; it cannot paste the same reply into unsupported/multiple questions. Own notification policy uses genuine short viewing leases, never official shouldNotify. Stable semantic attention identity is independent of reconnect-generated authority tokens: reconnect may retire an old action binding without replaying historical attention as a new push. Source change/resolution/current no-longer-requires-attention facts persist exact event invalidation and POST its resolve endpoint, stopping future relay retries without changing official read state. An already in-flight/displayed push cannot be retracted.
22
146
 
@@ -32,6 +32,31 @@ Automatic discovery requests bounded latest metadata once per six hours, persist
32
32
 
33
33
  `auto-update --disable` writes a separate durable marked private opt-out even while another writer is staging/draining. Readers immediately report disabled. No queued candidate activates while disabled, including an explicit manual candidate; `auto-update --enable` resumes eligible queued work. An automatic pending candidate is cancelled when the writer is available; a concurrent installation may finish staging but cannot activate. Enabling never resets discovery deadlines or failed-version suppression. `status` distinguishes package bootstrap required, source-checkout manual mode, and the managed active/pending/previous/error/check facts.
34
34
 
35
+ ## Explicit setup capability migration — CLI0.1.4 and later
36
+
37
+ `setup --yes` authorizes a specific owned CLI migration, not a global package,
38
+ Node or official daemon upgrade and not a change to automatic-update policy.
39
+ The current frontend recognizes its `localEnrollment:1` capability and routes
40
+ setup to selected code only when that selected package supports the same
41
+ enrollment/config-bound capability. A retained public0.1.2 handler cannot swallow
42
+ the command as unknown before the new handler runs.
43
+
44
+ After stopping only the owned runtime/service and authenticating official
45
+ identity, setup stages/verifies its exact current version when necessary.
46
+ Unavailable current packages or missing capability fail before feature/cloud
47
+ enablement; no old npm fallback is accepted. Then active/bootstrap move to the
48
+ capable package, previous/immutable packages and pair/custom-origin state remain,
49
+ and the independent update opt-out still wins for future automatic updates.
50
+ Source checkout without managed state instead binds its current own frontend.
51
+ Actual publication and installation receipts are recorded in docs/STATE.md.
52
+
53
+ All current config readers/resource validators/writers share524288bytes and
54
+ reject an oversized serialized replacement before publication. Original request
55
+ bytes are retained even when JSON control-character escaping expands them.
56
+ This explicit capability migration does not assert that a directly invoked old
57
+ 128KiB config reader can consume larger state. Retained public frontends route
58
+ subsequent commands to selected capable code rather than invoking old handlers.
59
+
35
60
  ## Compatibility and activation
36
61
 
37
62
  Every publish declares `moremote: {updateProtocol:1,journalSchema:1,wireProtocol:1}`. Both staging selection and the retained supervisor independently check this exact compatibility tuple. Missing/different compatibility remains pending with manualRequired and `UPDATE_MANUAL_COMPATIBILITY_REQUIRED`; it never drains or executes. Automatic-release validation also rejects another tuple. A compatible release MUST preserve all older retained versions' ability to read/write the same config/journal, mutation tombstones and wire lifecycle. A mere startup survival window cannot prove this property. Breaking storage/wire changes require a separately designed, owner-approved migration/release process; do not relabel an incompatible schema as1 or promise arbitrary downgrade safety. The existing FULL-sync journal, occurrence, revoke and no-replay contracts are unchanged.
@@ -42,9 +67,17 @@ After old exit, candidate readiness requires journal creation and acquired runti
42
67
 
43
68
  Opt-out during drain allows the old cycle to settle, then resumes old active without starting candidate. Opt-out during candidate startup drains it before resuming old active. Explicit stop signals only the owned service/runtime, writes a separate supervisor stop request, and waits for supervisor exit before managed deletion. Stop does not cause an internal respawn. A hung in-flight operation cannot be safely force-killed by an update: activation waits, status retains activating, and explicit operator stop remains separate. A staged package alone is never reported as active.
44
69
 
70
+ On Windows, the persistent ownership XML remains BOM-free UTF-16LE so unchanged
71
+ retained0.1.1 readers can validate shared state during startup and rollback.
72
+ Task Scheduler's file import instead receives an owned private transient copy
73
+ with the required UTF-16LE BOM, outside shared state. Remove that copy on every
74
+ normal success/failure path and before `/Run`; failed cleanup must not start the
75
+ runtime. Native registration acceptance must include unchanged public bootstrap
76
+ bytes, not only current code relabeled as an older QA version.
77
+
45
78
  ## Evidence entrypoints
46
79
 
47
- `npm run check` exercises ordinary regression tests and compiles; `npm run smoke:upgrade` then packs two synthetic versions of the actual compiled package, installs both through real npm into isolated private prefixes, starts the production retained service entry (without registering any OS service), confirms runtime.version advances from9000.0.1 to9000.0.2, retains the old/bootstrap executable and performs a clean stop. It contacts only npm plus an intentionally unavailable localhost official endpoint, never everyday official data or cloud. It is explicit acceptance, not an install hook. CI includes the same smoke on macOS/Linux/Windows. Neither this specification nor test source claims those checks have been exercised.
80
+ `npm run check` exercises ordinary regression tests and compiles; `npm run smoke:upgrade` then packs three synthetic versions of the actual compiled package and installs them through real npm into isolated private prefixes. It starts the production retained service entry without registering an OS service, confirms9000.0.1→9000.0.2, exercises the retained frontend through a path alias, then queues compatible9000.0.3 whose disposable runtime exits before readiness. The supervisor must return to9000.0.2, retain bootstrap/previous, record the failed candidate and clear pending/activating before a clean stop. Only the disposable failed package bytes change. It contacts npm plus an intentionally unavailable localhost endpoint, never everyday official data or cloud. This is explicit acceptance, not an install hook. CI includes this smoke on macOS/Linux/Windows; observed results belong in STATE, not this specification.
48
81
 
49
82
  The packaged smoke explicitly invokes the old frontend through a parent-directory symlink/junction and requires one selected-version response. Every network/subprocess/control/wait stage has a bounded deadline and a named checkpoint. Teardown retains handles to its own spawned processes, signals only their dedicated POSIX process groups or Windows PID subtrees, and awaits exit. Failure keeps the temporary root plus the last stage/selection; it never deletes an unexplained failed fixture or signals a PID discovered from an arbitrary state record.
50
83
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moxuli/moremote",
3
- "version": "0.1.1",
3
+ "version": "0.1.4",
4
4
  "description": "Optional encrypted notification and scoped-action companion for Paseo",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -8,7 +8,7 @@
8
8
  "homepage": "https://github.com/moxuli/moremote-cli#readme",
9
9
  "bugs": {"url": "https://github.com/moxuli/moremote-cli/issues"},
10
10
  "publishConfig": {"access": "public", "registry": "https://registry.npmjs.org"},
11
- "moremote": {"updateProtocol": 1, "journalSchema": 1, "wireProtocol": 1},
11
+ "moremote": {"updateProtocol": 1, "journalSchema": 1, "wireProtocol": 1, "localEnrollment": 1, "configBytes": 524288},
12
12
  "files": ["bin", "dist", "docs", "vectors", "licenses", "LICENSE", "NOTICE", "README.md"],
13
13
  "engines": {
14
14
  "node": ">=24.13.0 <25"