@tnunamak/dalan 0.5.2 → 0.6.0

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 (62) hide show
  1. package/CHANGELOG.md +29 -25
  2. package/PROTOCOL.md +16 -4
  3. package/README.md +127 -260
  4. package/SECURITY.md +1 -1
  5. package/bin/dalan.mjs +5 -0
  6. package/bin/dot-worker.mjs +35 -26
  7. package/docs/chatgpt-worker-onboarding.md +5 -5
  8. package/docs/claude-worker-onboarding.md +5 -5
  9. package/docs/codex-to-muse.md +175 -0
  10. package/docs/connect-chatgpt.md +9 -4
  11. package/docs/connection-longevity.md +7 -1
  12. package/docs/dalan-upgrade.md +17 -13
  13. package/docs/deadman.md +5 -3
  14. package/docs/local-agent-mcp.md +8 -6
  15. package/docs/manual-setup.md +8 -8
  16. package/docs/mirror-fetch.md +1 -2
  17. package/docs/operations.md +90 -42
  18. package/docs/operator-duties.md +1 -1
  19. package/docs/owner-integrator.md +2 -2
  20. package/docs/portable-auth-profile.md +12 -14
  21. package/docs/pr-head-reviewer.md +21 -5
  22. package/docs/pr-preflight.md +2 -0
  23. package/docs/pull-queue.md +131 -0
  24. package/docs/pull-workers.md +7 -10
  25. package/docs/redaction.md +1 -1
  26. package/docs/service-setup.md +56 -3
  27. package/docs/setup-reference.md +1 -1
  28. package/docs/t3-integration.md +2 -0
  29. package/docs/t3-result-retry-delivery.md +2 -2
  30. package/docs/t3-reverse-control.md +7 -7
  31. package/docs/usage.md +19 -15
  32. package/docs/worker-clients.md +18 -13
  33. package/package.json +3 -1
  34. package/scripts/dalan-try-selfcheck.mjs +29 -0
  35. package/scripts/worker-bridge-setup.mjs +1 -1
  36. package/src/acp-bridge.mjs +18 -12
  37. package/src/as.mjs +41 -0
  38. package/src/child-exit.mjs +18 -0
  39. package/src/child-registry.mjs +94 -0
  40. package/src/cli-help.mjs +25 -11
  41. package/src/demo-worker.mjs +2 -2
  42. package/src/drained-owner.mjs +26 -0
  43. package/src/drained-slot.mjs +20 -3
  44. package/src/mcp-outcome.mjs +10 -1
  45. package/src/mcp-sse.mjs +62 -0
  46. package/src/pr-head-reviewer.mjs +3 -3
  47. package/src/process-inspection.mjs +36 -0
  48. package/src/pull-queue.mjs +159 -0
  49. package/src/route-setting.mjs +24 -0
  50. package/src/server.mjs +157 -29
  51. package/src/service-migrate-workers.mjs +113 -0
  52. package/src/service.mjs +388 -0
  53. package/src/setup.mjs +63 -0
  54. package/src/store.mjs +21 -9
  55. package/src/tool-registry.mjs +3 -1
  56. package/src/try-exposure.mjs +908 -0
  57. package/src/try-hosted-clients.mjs +46 -0
  58. package/src/try-hosted.mjs +444 -0
  59. package/src/try-selfcheck.mjs +168 -0
  60. package/src/try.mjs +63 -17
  61. package/src/workers.mjs +33 -23
  62. package/src/workspace.mjs +10 -3
@@ -1,13 +1,21 @@
1
1
  # Dalan operations
2
2
 
3
+ Use this reference to operate an existing bridge. For installation, start with the [README](../README.md).
4
+
5
+ - [Recover a stalled job or delivery](#recovery-and-operation)
6
+ - [Back up, restore or upgrade](#upgrade-and-rollback)
7
+ - [Restart or remove a service](#restart-a-service-and-check-its-state)
8
+ - [Review repository access](#repository-access-per-worker)
9
+ - [Configure host checks](#execution-capability-and-check-evidence)
10
+
3
11
  The admin socket is mode `0600`, but every process that runs as the bridge's own user can connect to it, so run executors and worker processes as a different user. The current check sandbox does not enforce this separation: it confines the check process but does not change its Unix user.
4
12
 
5
13
  Fresh homes use Dalan directories; existing installations retain their populated legacy roots. Use `dalan paths --json` with the service HOME and environment for the effective config, data, state and workspace roots. See [the upgrade guide](dalan-upgrade.md) for settings, catalog retention, local HTTP and explicit path migration.
6
14
 
7
15
  ## Versions and upgrades
8
16
 
9
- **Versions (0.5.2).** Package releases and SQLite schema numbers are
10
- separate: this package is 0.5.2 and `Store` supports schema 65. The recorded
17
+ **Versions (0.6.0).** Package releases and SQLite schema numbers are
18
+ separate: this package is 0.6.0 and `Store` supports schema 66. The recorded
11
19
  0.2.0/0.3.0 release history is manual version bumps, changelog sections and tags;
12
20
  it does not establish a general compatibility promise. The 0.3.0 changelog puts
13
21
  operator actions first.
@@ -29,7 +37,7 @@ Even additive catalog changes need deliberate catalog review and coordinated
29
37
  connector Refresh + worker reboot when the advertised profile changes; see
30
38
  `scripts/catalog-golden-test.mjs` and the profile-specific protocol guidance.
31
39
 
32
- **Current schema behavior.** Startup refuses `user_version > 65` before schema bootstrap, making no schema or row change; SQLite may create, recover or clean up the `-wal` and `-shm` files. `Store.migrate()` advances supported historical layouts to schema 65; version 65 needs no version upgrade. Versions 35 and later must carry `s1v2-worker-facts-20261022` in `schema_migrations`; abandoned worker-isolation layouts are refused. Valid layout, keys and private permissions are also required: a version number alone is not compatibility proof. Migrations never run down; never edit `user_version` to force an old build to open newer state.
40
+ **Current schema behavior.** Startup refuses `user_version > 66` before schema bootstrap, making no schema or row change; SQLite may create, recover or clean up the `-wal` and `-shm` files. `Store.migrate()` advances supported historical layouts to schema 66; version 66 needs no version upgrade. Versions 35 and later must carry `s1v2-worker-facts-20261022` in `schema_migrations`; abandoned worker-isolation layouts are refused. Valid layout, keys and private permissions are also required: a version number alone is not compatibility proof. Migrations never run down; never edit `user_version` to force an old build to open newer state.
33
41
 
34
42
  **Release checklist (followed for 0.3.0).** Update `package.json` and the lockfile to the
35
43
  same version; add a CHANGELOG section with operator actions first (backup,
@@ -37,11 +45,7 @@ schema/config/CLI migration and catalog refresh requirements). Review and test
37
45
  the release, merge it, create an annotated `vX.Y.Z` tag on that merge commit,
38
46
  then publish GitHub release notes with those actions and compatibility limits.
39
47
 
40
- **Rollback.** Stop the service and restore a full, compatible pre-upgrade backup
41
- with the older code, not just an older executable against the migrated database.
42
- Follow [Upgrade and rollback](#upgrade-and-rollback) for the complete state set,
43
- lock-file exclusions and compatible newer delivery-ACK preservation. Snapshot
44
- restore loses later work; losing newer ACK proof can duplicate accepted notices.
48
+ **Rollback.** Stop every writer and first verify whether the target code supports the current database, keys and configuration. If it does, preserve current state and newer delivery-ACK proof. If it does not, use compatible code or a separately reviewed restore of the complete pre-upgrade backup. A snapshot restore discards later work, and losing newer ACK proof can duplicate accepted notices. Follow [Upgrade and rollback](#upgrade-and-rollback) before starting older code.
45
49
 
46
50
  ## Opt-in legacy-v46 catalog
47
51
 
@@ -59,9 +63,7 @@ tools are unavailable in this profile even for a capable worker.
59
63
  This is a catalog compatibility option, not evidence of live deployment or a
60
64
  completed migration. Existing `questions-v1` and `protocol-v0` behavior is unchanged.
61
65
 
62
- Paths: `<home>` is your home directory and `<config>` is `<home>/.config`.
63
-
64
- This page holds the operating detail for the bridge: service configuration, delivery and recovery, claims and leases, lifecycle metrics, usage breaks, workspaces and checks. It was moved out of the README, which now gives a short overview. Start with the [README](../README.md) if you have not seen the bridge before.
66
+ Paths: `<home>` means the bridge service's `HOME`, which may differ from your login home; `<config>` means `<home>/.config`. Use `dalan paths` with the service's environment to resolve an existing installation's active roots.
65
67
 
66
68
  A Node 24 service stores immutable assignments, exposes worker MCP tools and MCP Events, and sends report or stored legacy watch notices to the exact bound T3 thread. The assignment path does not launch models, decide fallback, merge patches, or stop remote worker compute. The public endpoint is `https://dalan.example.com/<secret>/mcp`; OAuth authenticates worker requests, and `<config>/dalan/env` holds the additional path secret. The service listens on port 8787 by default.
67
69
 
@@ -141,7 +143,7 @@ Local proof recovery starts at service startup and runs at most once per minute,
141
143
 
142
144
  Event retries reuse one event ID, and a stored legacy watch is a one-shot attention notice and never launches fallback. Pause prevents new claims and outbound notices; resume drains eligible work. Cancel withdraws bridge authority, but `compute_stopped` remains false. Cancel is refused with `uncertain_delivery: reconcile first` while an owner delivery for the job is `uncertain`, `sending`, `uncertain_terminal` or `waiting`; run `dalan reconcile ID --json` first. A paused bridge is not a frozen database: do not copy `bridge.db` while the service runs, even when paused. Stop the service, then take the copy with SQLite's `.backup` command, as the [backup procedure](#upgrade-and-rollback) describes. Do not copy the database file by hand. With a still-valid claim, a new finish after cancellation retains bounded audit-only `late_evidence` and returns `assignment_cancelled`; it creates no report or successful late receipt and does not wake the owner. A `late:true` success can only repeat a matching already-stored legacy report.
143
145
 
144
- **Delivery guarantee.** The current T3 `sendArgs` always uses `--if-busy steer` for CLI-delivered notices. Results sent through the result transport instead use orchestration `message.dispatch`: by default, `steer_active` targets the latest active run; if no active run exists, `queue_after_active` is selected when a queued run exists, and `start_immediately` otherwise. See [result retry and delivery](t3-result-retry-delivery.md) for the separate transport and lifecycle contract. "Never dropped" means every result, blocker and watch message is stored durably and its state stays visible in `dalan get` and `status`. It does not mean exactly-once. A send that fails with `invalid session credential` is a known pre-accept rejection from T3: the message stays `pending` and is retried with backoff under the same event ID, up to 8 attempts (`DALAN_T3_AUTH_RETRY_MAX` overrides this for tests), then becomes `uncertain` with a reason. Any other failure after a send starts stays `uncertain` without automatic resend. The transcript-marker lookup is available only through explicit manual reconciliation. The automatic age-release policy above never resends an unknown notice; a late accepted message remains possible.
146
+ **Delivery guarantee.** The current T3 `sendArgs` always uses `--if-busy steer` for CLI-delivered notices. Results sent through the result transport instead use orchestration `message.dispatch`: by default, `steer_active` targets the latest active run; if no active run exists, `queue_after_active` is selected when a queued run exists, and `start_immediately` otherwise. See [result retry and delivery](t3-result-retry-delivery.md) for the separate transport and lifecycle contract. "Never dropped" means every result, blocker and watch message is stored durably and its state stays visible in `dalan get` and `status`. It does not mean exactly-once. A send that fails with `invalid session credential` is a known pre-accept rejection from T3: the message stays `pending` and is retried with backoff under the same event ID, up to 8 attempts (`DALAN_T3_AUTH_RETRY_MAX` overrides this for tests), then becomes `uncertain` with a reason. Any other failure after a send starts stays `uncertain` without automatic resend. The transcript-marker lookup is available only through explicit manual reconciliation. Aging an unknown notice to `uncertain_terminal` stops automatic retry; it does not release the claim fence or prove delivery. A late accepted message remains possible.
145
147
 
146
148
  **Claim refused with `claim_effects_unverified`.** The bridge will not give a job to a new worker until it has proof that the host checks of the earlier claim have stopped. The error `claim_effects_unverified: prior host work has not verifiably stopped` means that proof is missing. The usual causes: the stop recorder saw a process still alive in the check's control group (for example a task stuck in uninterruptible I/O), or the bridge or host stopped before the recorder wrote its result. The first verdict is kept as written and is not changed later.
147
149
 
@@ -156,7 +158,7 @@ A process that is still alive, a read error, an unreadable boot id, or a check f
156
158
 
157
159
  Back up the application state consistently: `bridge.db`, its `bridge.db.secrets/storage.key`, the independent positive-ACK ledger, owner receipts, the artifact index and artifact bytes, and the relevant auth/config files including `as-storage.key`. Never copy the `bridge.db.secrets/owner.sqlite` lock file; it is recreated locally. Preserve their private permissions and binding identity. Exclude `as-owner.sqlite` as required by [authorization-server ownership](#built-in-authorization-server-ownership); it is not application backup data. A database-only backup is not a complete recovery set.
158
160
 
159
- For an operational code rollback, preserve newer jobs, reports, receipts, artifact-index entries, artifacts and positive ACK proof; do not overwrite them with an older full-state snapshot merely to run older code. A schema-incompatible build needs a separately reviewed recovery plan, not a blind database downgrade. The legacy snapshot-restore recipe below is a destructive rollback boundary, not this state-preserving procedure. Restoring missing ACK evidence from backup may recover some proof but cannot establish exactly-once delivery for the lost interval. No restart, restore, deadline extension, redispatch or operator waiver is required for automatic age release.
161
+ For an operational code rollback, preserve newer jobs, reports, receipts, artifact-index entries, artifacts and positive ACK proof; do not overwrite them with an older full-state snapshot merely to run older code. A schema-incompatible build needs a separately reviewed recovery plan, not a blind database downgrade. The legacy snapshot-restore recipe below is a destructive rollback boundary, not this state-preserving procedure. Restoring missing ACK evidence from backup may recover some proof but cannot establish exactly-once delivery for the lost interval. The transition to `uncertain_terminal` happens automatically. Regrant remains blocked until matching positive acknowledgment evidence or explicit reconciliation resolves the delivery.
160
162
 
161
163
  ### Legacy question ties
162
164
 
@@ -200,7 +202,7 @@ Optional self-check timers are deployment-specific, so review their endpoint, is
200
202
 
201
203
  ## Upgrade and rollback
202
204
 
203
- The package version is `0.5.2`; the bridge database schema is version 65. Stop the service and every other writer before making a backup or replacing files; keep them stopped until the complete backup set is captured. Keep each backup set consistent: include `<home>/.local/share/dalan/bridge.db`, `delivery-acks.db`, `notify-sent.db`, `<config>/dalan/as.sqlite` when built-in authorization is used, the private `<config>/dalan` files, owner receipts in `<home>/.local/share/dalan/receipts`, and artifact ownership entries in `<home>/.local/share/dalan/artifact-index`. Preserve file permissions. Do not copy either `bridge.db.secrets/owner.sqlite` or `as-owner.sqlite` lock database; recreate them locally after restoring with the service stopped, as described above. If external OAuth is used, its issuer database is managed separately and is not part of this bridge backup.
205
+ The package version is `0.6.0`; the bridge database schema is version 66. Stop the service and every other writer before making a backup or replacing files; keep them stopped until the complete backup set is captured. Keep each backup set consistent: include `<home>/.local/share/dalan/bridge.db`, `delivery-acks.db`, `notify-sent.db`, `<config>/dalan/as.sqlite` when built-in authorization is used, the private `<config>/dalan` files, owner receipts in `<home>/.local/share/dalan/receipts`, and artifact ownership entries in `<home>/.local/share/dalan/artifact-index`. Preserve file permissions. Do not copy either `bridge.db.secrets/owner.sqlite` or `as-owner.sqlite` lock database; recreate them locally after restoring with the service stopped, as described above. If external OAuth is used, its issuer database is managed separately and is not part of this bridge backup.
204
206
 
205
207
  Take each existing application database (`bridge.db`, `delivery-acks.db`, `notify-sent.db`, and `as.sqlite` when built-in authorization is used) with SQLite's `.backup` command into a fresh destination in a new backup directory. Run `umask 077` and create the directory with mode 0700 first, so every copy is private. For each existing source file, set `source` and `destination` to its full source and fresh backup paths, then run `[ ! -e "$destination" ] && sqlite3 -bail "$source" ".backup '$destination'" || exit 1` (use destination paths without single quotes). This refuses an existing destination, so it cannot overwrite an earlier backup such as the rollback set. Stop immediately on any error and discard the incomplete set; do not accept a partial set. Copy the matching keys and other non-database state listed here with their private permissions. Use `.backup` for every application database. If it fails, stop and fix the error; do not fall back to copying only the database file, because a stopped writer can leave committed rows in a `-wal` file or a hot `-journal` that SQLite needs for recovery. Use the installation's resolved roots, including legacy roots and configured paths. Never delete a `-wal` or `-journal` file from a live database just because the service stopped. When you restore a `.backup` snapshot, first move the current database and its `-wal`, `-shm` and `-journal` files aside together, with every process stopped; the snapshot is restored without the old database's sidecar files. The rollback recipe below does this for `bridge.db` (it removes `-wal` and `-shm`); when you restore `delivery-acks.db`, `notify-sent.db` or `as.sqlite` by hand, move aside that database's `-wal`, `-shm` and `-journal` files first.
206
208
 
@@ -257,6 +259,7 @@ The loop skips `bridge.db.secrets/owner.sqlite` and `as-owner.sqlite` on purpose
257
259
  **Check a restore.** The check copies the backup into a new, empty home and then reads it with `restore-check.mjs`. That script opens the databases read-only and decrypts what the bridge would decrypt. It starts no bridge, no delivery loop and no network socket, so a webhook subscription or pending notice in the restored copy is not sent. Set `backup` to the backup directory and, if you want to read one request back, `request_id` to a known recent request ID. Then run:
258
260
 
259
261
  ```sh
262
+ (
260
263
  umask 077
261
264
  export DALAN_HOME="$HOME/dalan-restore-check"
262
265
  [ ! -e "$DALAN_HOME" ] || { echo "$DALAN_HOME exists; choose a new path" >&2; exit 1; }
@@ -264,11 +267,51 @@ mkdir -m 0700 "$DALAN_HOME" || exit 1
264
267
  data_root="$(dalan paths --data-root)" || exit 1
265
268
  config_root="$(dalan paths --config-root)" || exit 1
266
269
  workspace_root="$(dalan paths --workspace-root)" || exit 1
270
+ node --input-type=module - "$data_root" "$config_root" "$workspace_root" <<'JS' || exit 1
271
+ import fs from 'node:fs';
272
+ import path from 'node:path';
273
+ try {
274
+ const home = fs.realpathSync(process.env.DALAN_HOME);
275
+ if (!fs.statSync(home).isDirectory()) throw new Error('restore home is not a directory');
276
+ for (const root of process.argv.slice(2)) {
277
+ const normalized = path.resolve(root);
278
+ if (!path.isAbsolute(root) || root !== normalized) {
279
+ throw new Error(`restore root is not a normalized absolute path: ${root}`);
280
+ }
281
+ let ancestor = normalized;
282
+ const missing = [];
283
+ for (;;) {
284
+ try {
285
+ fs.lstatSync(ancestor);
286
+ break;
287
+ } catch (error) {
288
+ if (error.code !== 'ENOENT') throw error;
289
+ const parent = path.dirname(ancestor);
290
+ if (parent === ancestor) throw error;
291
+ missing.unshift(path.basename(ancestor));
292
+ ancestor = parent;
293
+ }
294
+ }
295
+ // A dangling symlink or unreadable existing ancestor fails here.
296
+ const realAncestor = fs.realpathSync(ancestor);
297
+ if (!fs.statSync(realAncestor).isDirectory()) throw new Error(`not a directory: ${ancestor}`);
298
+ const canonical = path.resolve(realAncestor, ...missing);
299
+ const relative = path.relative(home, canonical);
300
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
301
+ throw new Error(`restore root is outside the disposable home: ${root}`);
302
+ }
303
+ }
304
+ } catch (error) {
305
+ console.error(`Restore stopped before copying: ${error.message}`);
306
+ process.exit(1);
307
+ }
308
+ JS
267
309
  mkdir -p "$data_root" "$config_root" "$workspace_root" || exit 1
268
310
  cp -Rp "$backup/data/." "$data_root/" || exit 1
269
311
  find "$backup/config" -maxdepth 1 -type f -exec sh -c 'cp -p "$@" "$0"' "$config_root" {} + || exit 1
270
312
  if [ -d "$backup/artifacts" ]; then cp -Rp "$backup/artifacts" "$workspace_root/artifacts" || exit 1; fi
271
313
  node "$(npm root -g)/@tnunamak/dalan/src/restore-check.mjs" "$data_root" "$config_root" "$request_id" || exit 1
314
+ )
272
315
  ```
273
316
 
274
317
  From a checkout, run `node src/restore-check.mjs` in the checkout instead of the `npm root -g` path. With `request_id` empty, the script counts the assignments instead. The script prints one JSON line and exits 0 only when `bridge.db` passes `integrity_check`, its status reads back and every stored subscription secret decrypts with the restored key. For an encrypted database a missing key stops it with `subscription storage key is missing`, and a wrong key with `subscription storage cannot be decrypted with the restored key`. It also checks `as.sqlite` and `workers-audit-checkpoint.sqlite` when they are present. For `as.sqlite` it authenticates the storage verifier and decrypts every sealed row with `as-storage.key`, so a wrong key of the right size fails with `authorization storage cannot be decrypted with the restored key`. It does not prove that the whole service starts. To prove that, start the restored home as a service in an environment you have cut off from the network: nothing in these commands cuts it off, and a full start runs the delivery loops. A backup that fails this check is incomplete: take a new one. Delete the restore home when you are done.
@@ -284,19 +327,19 @@ Install the new code while the service is stopped (for a source install, follow
284
327
 
285
328
  If the current ACK ledger is missing, restore its compatible backup. If the newer ledger cannot be read by the target code, prefer code that supports it. Restoring an older compatible ledger instead loses later acknowledgments and can repeat already-accepted notices. A consistent backup does not recover ACKs recorded after that backup. Missing receipts or artifact bytes can also make prior results unavailable.
286
329
 
287
- This build refuses startup when `bridge.db` has a SQLite `user_version` above 65. The refusal occurs before schema bootstrap, claim recovery, or listener startup; it reports both versions and makes no schema or row change. SQLite may create, recover or clean up the `-wal` and `-shm` files. Use code that supports the database version, or restore a consistent backup compatible with the code. Never lower `user_version` by hand. Some older builds do not check for a future schema and can modify a database they do not understand. Keep the service stopped during downgrade and restore the full compatible backup before running old code.
330
+ This build refuses startup when `bridge.db` has a SQLite `user_version` above 66. The refusal occurs before schema bootstrap, claim recovery, or listener startup; it reports both versions and makes no schema or row change. SQLite may create, recover or clean up the `-wal` and `-shm` files. Use code that supports the database version, or restore a consistent backup compatible with the code. Never lower `user_version` by hand. Some older builds do not check for a future schema and can modify a database they do not understand. Keep the service stopped during downgrade and restore the full compatible backup before running old code.
288
331
 
289
332
  ### Restart a service and check its state
290
333
 
291
- Linux (systemd user manager):
334
+ Linux (systemd user manager). For `dalan service install`, replace `UNIT.service` with the exact unit printed by install, such as `dalan-<10 hex>.service`. The legacy `scripts/worker-bridge-setup.mjs` uses `dot-bridge-NAME.service`:
292
335
 
293
336
  ```sh
294
- systemctl --user restart dot-bridge-NAME.service
295
- systemctl --user is-active dot-bridge-NAME.service
296
- journalctl --user -u dot-bridge-NAME.service -n 20
337
+ systemctl --user restart UNIT.service
338
+ systemctl --user is-active UNIT.service
339
+ journalctl --user -u UNIT.service -n 20
297
340
  ```
298
341
 
299
- macOS (launchd). `LABEL` is `org.dalan.dot-bridge-NAME`, or the label of the older release when it generated the service (find the file with `ls ~/Library/LaunchAgents | grep dot-bridge`):
342
+ macOS (launchd; the Linux-only `dalan service install` does not apply). These commands are for the legacy `scripts/worker-bridge-setup.mjs`. `LABEL` is `org.dalan.dot-bridge-NAME`, or the label of the older release when it generated the service (find the file with `ls ~/Library/LaunchAgents | grep dot-bridge`):
300
343
 
301
344
  ```sh
302
345
  launchctl kickstart -k user/$(id -u)/LABEL
@@ -321,7 +364,7 @@ Setup loads the agent into the `user/UID` launchd domain. Earlier releases loade
321
364
  `dalan doctor` is a local check; it does not prove that a worker can finish a job. After setup, a restart or an upgrade, run these with `DALAN_HOME` set to the service's home:
322
365
 
323
366
  1. `dalan status --json` exits 0 and shows the queue and worker state.
324
- 2. Confirm that the log shows `MCP listening on 127.0.0.1:PORT`.
367
+ 2. Confirm that the log shows `MCP listening` on the bind address and port configured for this service. Generated built-in-auth services use `127.0.0.1:PORT`; an external-OAuth service behind an HTTPS reverse proxy may use its explicitly configured non-loopback address.
325
368
  3. Connect the worker's client as in [worker pairing](manual-setup.md#worker-setup), using the service's HTTPS URL from `$DALAN_HOME/resource-url`. The `try` command does not run against an existing service, and a plain loopback URL is not accepted outside loopback mode.
326
369
  4. Submit the repository-free job from [the manual setup](manual-setup.md#submit-finish-and-read-the-result) with `dalan submit --worker NAME --execution none --deliver none --file first-job.json --json`, prompt the worker, then run `dalan wait REQUEST_ID` and `dalan decide REQUEST_ID accepted`. The job must reach `finished`.
327
370
 
@@ -347,7 +390,7 @@ Check that nothing is left: `systemctl --user list-units 'dot-bridge-*'` on Linu
347
390
 
348
391
  ### From 0.2.0
349
392
 
350
- 0.2.0 uses schema 49; this release supports schema 65. Stop the service and take the consistent backup above **before first startup**. Include the subscription key at `bridge.db.secrets/storage.key` and built-in-AS `as-storage.key` when present; do not copy either `bridge.db.secrets/owner.sqlite` or `as-owner.sqlite` lock file. Preserve the private permissions and the artifact bytes, receipts and positive ACK proof.
393
+ 0.2.0 uses schema 49; this release supports schema 66. Stop the service and take the consistent backup above **before first startup**. Include the subscription key at `bridge.db.secrets/storage.key` and built-in-AS `as-storage.key` when present; do not copy either `bridge.db.secrets/owner.sqlite` or `as-owner.sqlite` lock file. Preserve the private permissions and the artifact bytes, receipts and positive ACK proof.
351
394
 
352
395
  The table comes from a source review of `Store.migrate()` and the helper migrations it calls. The migration batch runs in one `BEGIN IMMEDIATE` transaction. “Additive” describes the SQL, not backward compatibility:
353
396
 
@@ -367,6 +410,7 @@ The table comes from a source review of `Store.migrate()` and the helper migrati
367
410
  | 61 | Add nullable `claims.connection_id` without inferring or backfilling a connection from the live set. Older grants keep NULL; built-in claim mutations require the recorded live granting connection. |
368
411
  | 62 | Add nullable lease boot and monotonic deadline fields on `claims`. Additive. |
369
412
  | 65 | Rename `dot_breaks` to `worker_breaks` (with its index) and `assignments.skipped_by_dot_at` to `skipped_at`; the `break_notices` foreign key follows the table. Data is unchanged, but older code looks for the old names, so **roll back only from the backup taken before this upgrade**. Schemas 63 and 64 belong to migrations merged before this one. A database that reached schema 35 under the earlier step keeps `DEFAULT 'dot'` on `assignments.target_worker` and `messages.target_worker` in its stored schema text (SQLite cannot change a default without rebuilding the table); a new database has an empty default, and every insert names the worker. |
413
+ | 66 | Add `policy_work_orders`, its backlog index and immutable-intent trigger for read-only worker pools. Additive; existing assignments are not rewritten. |
370
414
 
371
415
  **Live claims:** the `v0.2.0 live claim survives upgrade to schema 57` fixture is historical evidence for that upgrade, not a current built-in claim-continuity guarantee. Migration 61 retains older claim records but leaves their connection binding NULL. In built-in mode, those grants cannot mutate or retry as the holding connection (`connection_not_live`); wait for the prior lease deadline and verified host stop before acquiring a successor. The historical fixture does not bypass current connection, destination or lease guards. Two additional lease limits apply:
372
416
 
@@ -385,7 +429,7 @@ Upgrade steps:
385
429
 
386
430
  Short downtime does not keep a built-in claim valid across migration 61. A claim left in flight cannot act after the upgrade; wait for its lease deadline and verified host stop before acquiring a successor.
387
431
 
388
- **Rollback limit:** 0.2.0 refuses a database newer than schema 49 (see the 0.2.0 changelog); this build refuses versions above 65 before schema bootstrap. Do not lower `user_version` or undo encryption by hand. Use compatible code, or a separately reviewed restore of the complete pre-upgrade state. Restoring that snapshot discards later work; preserve compatible newer ACK proof and account for possible duplicate notices if proof is lost.
432
+ **Rollback limit:** 0.2.0 refuses a database newer than schema 49 (see the 0.2.0 changelog); this build refuses versions above 66 before schema bootstrap. Do not lower `user_version` or undo encryption by hand. Use compatible code, or a separately reviewed restore of the complete pre-upgrade state. Restoring that snapshot discards later work; preserve compatible newer ACK proof and account for possible duplicate notices if proof is lost.
389
433
 
390
434
  The request log rotates before the next append after it exceeds 32 MiB, retaining four older files (`requests.jsonl.1` through `.4`, newest to oldest). Set `DALAN_LOG_MAX_BYTES` and `DALAN_LOG_KEEP` to positive integers to override these defaults. Each line stays whole, so a file can exceed the threshold by one line. Fresh logs use mode 0600, and break-usage backfills read all retained generations, oldest first; older history is discarded when retention fills.
391
435
 
@@ -479,7 +523,7 @@ Limits: CPU and output are observed by a supervisor, so stopping can overshoot b
479
523
 
480
524
  The supervisor requires libseccomp and installs an inherited filter before any phase starts; failure to install it refuses the check. It denies inotify and fanotify creation, POSIX message queue creation, and keyring operations because their quotas can affect the host user. Watch-mode checks are unsupported: `inotify_init` and `inotify_init1` return `EPERM`. A failed phase includes a restriction notice when output space permits; the notice does not establish why the phase failed. POSIX message queues and keyring-dependent checks are also unsupported. The filter has been qualified only for the native architecture; 32-bit compatibility binaries are unsupported and their behavior has not been verified. Bubblewrap disables creation of further user namespaces, and the private IPC namespace isolates System V IPC objects. Other shared per-user or system-wide kernel resources, including queued signals and open files, are not exhaustively isolated or audited by these budgets.
481
525
 
482
- Run the Linux qualification with an outer timeout and reduced priority: `timeout --kill-after=5s 150s nice -n 10 node --test scripts/host-budgets-test.mjs`. It exercises fork exhaustion, memory growth, disk filling, wall/CPU exhaustion, output flooding, killed/frozen supervisors, bridge death, concurrent admission, cumulative phases, receipt protection and a persisted host-check result. On other platforms those kernel journeys explicitly skip. The older host journeys have no budget declarations and still test default-off refusal before skipping execution.
526
+ From a source checkout installed with `npm ci`, run the Linux qualification with an outer timeout and reduced priority: `timeout --kill-after=5s 150s nice -n 10 node --test scripts/host-budgets-test.mjs`. This test script is not included in the npm package. It exercises fork exhaustion, memory growth, disk filling, wall/CPU exhaustion, output flooding, killed/frozen supervisors, bridge death, concurrent admission, cumulative phases, receipt protection and a persisted host-check result. On other platforms those kernel journeys explicitly skip. The older host journeys have no budget declarations and still test default-off refusal before skipping execution.
483
527
 
484
528
  ### Worker identity and rollback
485
529
 
@@ -489,7 +533,7 @@ Run the Linux qualification with an outer timeout and reduced priority: `timeout
489
533
  {"workers":{"acme":{"connections":[{"issuer":"https://issuer.example/realm","subject":"owner","client_id":"acme-client"}],"capabilities":["t3"],"repos":[]},"example-worker":{"connections":[{"issuer":"https://issuer.example/realm","subject":"owner","client_id":"example-client"}],"repos":[]}},"default_execution":"none"}
490
534
  ```
491
535
 
492
- Submit with `dalan submit --worker NAME`. In profile mode, omitting it is refused with the configured worker names, except that a profile with exactly one worker defaults to it; only a legacy install (a database but no `workers.json`) defaults to `dot`. A new host starts with `dalan init --public-url URL --worker NAME`, which writes `workers.json` with `repos: []` for the worker (mode 0600, no `t3` capability, no host execution, and no repository access) and refuses to overwrite one that exists. `dalan init --legacy` writes none and keeps the legacy profile, for existing worker hosts only. `as-init` creates the AS files alone. `tell --worker NAME` targets a lightweight message. `pool` is unsupported as a target, name or configuration key. Assignments, claims and subscriptions retain their recorded identity when the profile changes. Removed workers see nothing; their subscriptions are revoked on startup and refused at delivery. Migration 35 has the durable identity `s1v2-worker-facts-20261022`. An abandoned worker-isolation database without that identity is refused: restore its pre-isolation backup. The supported upgrade starts from schema version 34, including live claims and unsealed uploads. The base supported exactly one worker. Subject-bearing facts outside the deployment's allowed subjects become `unknown`, never worker.
536
+ Submit with `dalan submit --worker NAME`. In profile mode, omitting it is refused with the configured worker names, except that a profile with exactly one worker defaults to it; only a legacy install (a database but no `workers.json`) defaults to `dot`. A new host starts with `dalan init --public-url URL --worker NAME`, which writes `workers.json` with `repos: []` for the worker (mode 0600, no `t3` capability, no host execution, and no repository access) and refuses to overwrite one that exists. `dalan init --legacy` is an explicit legacy-profile compatibility option, not the normal setup path. Prefer `dalan init --worker NAME` for new installations; legacy mode does not itself grant repository access. `as-init` creates the AS files alone. `tell --worker NAME` targets a lightweight message. `pool` is unsupported as a target, name or configuration key. Assignments, claims and subscriptions retain their recorded identity when the profile changes. Removed workers see nothing; their subscriptions are revoked on startup and refused at delivery. Migration 35 has the durable identity `s1v2-worker-facts-20261022`. An abandoned worker-isolation database without that identity is refused: restore its pre-isolation backup. The supported upgrade starts from schema version 34, including live claims and unsealed uploads. The base supported exactly one worker. Subject-bearing facts outside the deployment's allowed subjects become `unknown`, never worker.
493
537
 
494
538
  ### Repository access per worker
495
539
 
@@ -510,7 +554,7 @@ dalan worker deny alpha example-org/example-project
510
554
 
511
555
  `repos` contains exact, case-insensitive `OWNER/REPO` entries only. A future repository under an allowed owner stays denied. `owner/*`, `repo_access: "any"`, `denied_repos`, and `--any` are rejected. An explicit empty list denies all repository jobs. Fresh omitted policies also deny all. Existing installations receive a one-time exact list from each worker's retained claims and jobs still queued and live under the service's expiry rules; the profile-less legacy worker stores it without creating a connection profile. Expired queued jobs do not add repositories. The migration journal and its audit commit together, and restarts never reseed. See [the upgrade migration](dalan-upgrade.md#preserve-historical-repositories-on-upgrade). Fresh profiles start with `repos: []`; use `dalan worker allow NAME OWNER/REPO` to grant each exact repository. `deny` on an already-denied repository is a no-op. List and doctor report exact lists; a missing profile reports whether a persisted exact policy exists or repository work is denied. Admission checks policy before fetch, and claims check the current policy again after resolution. Tightening blocks new admission and claims at once. Queued rows remain durable; already-valid grants may finish under unchanged lease, check, epoch and cancellation guards. No running work is forcibly cancelled or mutated.
512
556
 
513
- `dalan worker list --json` includes the latest 20 retained changes from `workers-audit.jsonl`: event ID, timestamp, host operator UID, worker, and exact before/after lists. It reads at most the last 1 MiB of the append-only audit, plus the private one-time migration journal. If history is bounded, incomplete or unreadable, `change_count` is null and `changes_truncated` is true; current policy stays visible. Invalid history produces a diagnostic without echoing its contents. The UID is the host operator identity, separate from the OAuth worker identity. CLI edits write audit entries. A direct edit of `workers.json` is picked up at the next admission or claim check, and no grant applies without an audit record: when the bridge loads the file and finds a repository that its latest audit event does not list, it first appends an event marked `source: config-reconcile` and applies the grant only if that write succeeds (if the audit trail is unwritable or corrupt, the grant stays denied). Lists that predate the audit are recorded the same way once, so upgrades need no config edit. `dalan doctor` and `dalan worker list` report grants that have no audit record yet, and doctor also reports grants the bridge had to record itself, so you can confirm you meant them. Every writer of the audit (the bridge when it loads the file, and `worker allow` and `deny`) holds one lock, `workers-audit-checkpoint.sqlite` in the config directory, across its read, compare and append, so parallel loads write one event and a loader cannot record a list that a concurrent `deny` has since removed. That file also keeps a checkpoint of the audit log (byte length, SHA-256 and last event id), updated with each append. If `workers-audit.jsonl` is missing, shorter than the checkpoint, or its recorded prefix changed, the bridge fails closed: every grant without a matching event is denied, nothing is written, and `dalan doctor` and `dalan worker list` report that the audit log failed its checkpoint. To recover, review `workers.json`, then run `dalan worker allow NAME OWNER/REPO` for each grant you want; the first `allow` or `deny` drops from `workers.json` every grant the surviving audit does not list (it never adds one) and records the log as the new baseline. Only an install with no checkpoint at all (never audited) has its existing lists recorded once. The checkpoint stops accidental loss and one-sided tampering. A same-user actor who deletes both the checkpoint file and the log looks like a never-audited install; that actor can also rewrite `workers.json` and the queue, so the files are not tamper-proof against a compromised account. Known limit: the checkpoint does not stop a same-user actor from appending a forged event to the log together with a matching `workers.json` edit; such an event looks audited. Only a compromised operator account can do this, and that account can run `dalan worker allow` anyway. `worker allow` and `deny` first record any repository you added by hand as its own `config-reconcile` event, so the event for the command records only the repository you named. A repository grant is recorded in the audit before it takes effect; if the audit write fails, the grant is not applied. A removal takes effect first and reports a missing audit event with nonzero status; repeating a no-op edit does not create an event.
557
+ `dalan worker list --json` includes the latest 20 retained changes from `workers-audit.jsonl`: event ID, timestamp, host operator UID, worker, and exact before/after lists. It reads at most the last 1 MiB of the append-only audit, plus the private one-time migration journal. If history is bounded, incomplete or unreadable, `change_count` is null and `changes_truncated` is true; current policy stays visible. Invalid history produces a diagnostic without echoing its contents. The UID is the host operator identity, separate from the OAuth worker identity. CLI edits write audit entries. A direct edit of `workers.json` is picked up at the next admission or claim check, and no grant applies without an audit record: when the bridge loads the file and finds a repository that its latest audit event does not list, it first appends an event marked `source: config-reconcile` and applies the grant only if that write succeeds (if the audit trail is unwritable or corrupt, the grant stays denied). Lists that predate the audit are recorded the same way once, so upgrades need no config edit. `dalan doctor` and `dalan worker list` report grants that have no audit record yet, and doctor also reports grants the bridge had to record itself, so you can confirm you meant them. Every writer of the audit (the bridge when it loads the file, and `worker allow` and `deny`) holds one lock, `workers-audit-checkpoint.sqlite` in the config directory, across its read, compare and append, so parallel loads write one event and a loader cannot record a list that a concurrent `deny` has since removed. That file also keeps a checkpoint of the audit log (byte length, SHA-256 and last event id), updated with each append. If a checkpoint exists but `workers-audit.jsonl` is missing, shorter than the checkpoint, or its recorded prefix changed, the bridge fails closed: no event from that history is trusted, so every current grant is denied even if its raw list matches an event in the failed history. No grant event is written, and `dalan doctor` and `dalan worker list` report that the audit log failed its checkpoint. To recover, review the current policy. The first `allow` or `deny` drops every current repository grant before applying that explicit change and resetting the checkpoint. Run `dalan worker allow NAME OWNER/REPO` for every other grant you want restored; no event from the failed checkpoint history preserves a grant. Only an install with no checkpoint at all (never audited) has its existing lists recorded once. The checkpoint stops accidental loss and one-sided tampering. A same-user actor who deletes both the checkpoint file and the log looks like a never-audited install; that actor can also rewrite `workers.json` and the queue, so the files are not tamper-proof against a compromised account. Known limit: the checkpoint does not stop a same-user actor from appending a forged event to the log together with a matching `workers.json` edit; such an event looks audited. Only a compromised operator account can do this, and that account can run `dalan worker allow` anyway. `worker allow` and `deny` first record any repository you added by hand as its own `config-reconcile` event, so the event for the command records only the repository you named. A repository grant is recorded in the audit before it takes effect; if the audit write fails, the grant is not applied. A removal takes effect first and reports a missing audit event with nonzero status; repeating a no-op edit does not create an event.
514
558
 
515
559
  #### Legacy repository-policy migration
516
560
 
@@ -521,25 +565,31 @@ Repository work uses the bridge host's full GitHub credential through Git askpas
521
565
 
522
566
  Switching a host from legacy mode to a `workers.json` profile retires every legacy subscription that has no verified persisted connection, including an old OAuth callback. The bridge suppresses that subscription's unsent wakes. The default worker must send a new authenticated `events/subscribe` request before it receives wake-ups again; a successful subscription replays still-queued work and records the approved connection. Check `dalan status --json`: after retirement, `subscriptions_active` is `0` and `subscription.state` is `revoked` (or `absent` if no row remains). The bridge does not create a replacement subscription. ChatGPT's MCP Events client is documented to refresh before a finite `refreshBefore`, but this early-retirement path has not been observed and that refresh may be days away. For immediate wake-ups, reconnect or refresh the default worker connector on the approved OAuth client to prompt `events/subscribe`, then confirm `subscriptions_active` is nonzero and `subscription.state` is `active`.
523
567
 
524
- **PRE-UPGRADE backup.** Before installing this build, stop the pre-isolation service and take a consistent backup of its DB and artifact directory. Save `workers.json` only if it exists. Keep this backup: the refusal of an abandoned worker-isolation schema requires restoring a pre-isolation DB, not a rollback DB. Use the service's workspace-root environment and fresh backup destinations.
568
+ **Pre-isolation recovery backup.** Before upgrading a pre-isolation installation, stop every writer and follow the complete [worked backup and restore-check procedure](#upgrade-and-rollback). Keep that verified recovery set separately and label it with the installed version and date. Include the matching keys, configuration, receipts, artifact index and artifact bytes. Exclude both ownership-lock databases. Do not use a shorter directory-copy recipe: recovery from an abandoned worker-isolation schema requires a complete, compatible pre-upgrade set.
525
569
 
526
570
  <!-- pre-upgrade-backup -->
527
571
  ```sh
572
+ umask 077
528
573
  bridge_data_root="$(dalan paths --data-root)" || exit 1
529
574
  bridge_config_root="$(dalan paths --config-root)" || exit 1
530
- sqlite3 -bail "${bridge_data_root}/bridge.db" ".backup '${bridge_data_root}/bridge.db.pre-isolation'"
575
+ bridge_workspace_root="$(dalan paths --workspace-root)" || exit 1
576
+ sqlite3 -bail "${bridge_data_root}/bridge.db" ".backup '${bridge_data_root}/bridge.db.pre-isolation'" || exit 1
531
577
  if [ -f "${bridge_data_root}/delivery-acks.db" ]; then
532
- sqlite3 -bail "${bridge_data_root}/delivery-acks.db" ".backup '${bridge_data_root}/delivery-acks.db.pre-isolation'"
578
+ sqlite3 -bail "${bridge_data_root}/delivery-acks.db" ".backup '${bridge_data_root}/delivery-acks.db.pre-isolation'" || exit 1
533
579
  chmod 600 "${bridge_data_root}/delivery-acks.db.pre-isolation"
534
580
  fi
535
- if [ -f "${bridge_config_root}/workers.json" ]; then
536
- cp -p "${bridge_config_root}/workers.json" "${bridge_config_root}/workers.json.pre-isolation"
537
- fi
538
- if [ -f "${bridge_config_root}/workers-repos.json" ]; then
539
- cp -p "${bridge_config_root}/workers-repos.json" "${bridge_config_root}/workers-repos.json.pre-isolation"
581
+ for name in bridge.db.secrets receipts artifact-index; do
582
+ if [ -e "${bridge_data_root}/${name}" ]; then cp -Rp "${bridge_data_root}/${name}" "${bridge_data_root}/${name}.pre-isolation" || exit 1; fi
583
+ done
584
+ for name in workers.json workers-repos.json oauth.env as-storage.key operator.key alerts.env limits.json workers-audit.jsonl; do
585
+ if [ -f "${bridge_config_root}/${name}" ]; then cp -p "${bridge_config_root}/${name}" "${bridge_config_root}/${name}.pre-isolation" || exit 1; fi
586
+ done
587
+ for name in as.sqlite workers-audit-checkpoint.sqlite; do
588
+ if [ -f "${bridge_config_root}/${name}" ]; then sqlite3 -bail "${bridge_config_root}/${name}" ".backup '${bridge_config_root}/${name}.pre-isolation'" || exit 1; fi
589
+ done
590
+ if [ -d "${bridge_workspace_root}/artifacts" ]; then
591
+ cp -a "${bridge_workspace_root}/artifacts" "${bridge_workspace_root}/artifacts.pre-isolation" || exit 1
540
592
  fi
541
- bridge_workspace_root="$(dalan paths --workspace-root)" || exit 1
542
- cp -a "${bridge_workspace_root}/artifacts" "${bridge_workspace_root}/artifacts.pre-isolation"
543
593
  ```
544
594
 
545
595
  Upload IDs chosen by workers are request-scoped aliases. The server gives each upload a globally unique `id`; owner get, `/artifact` and the CLI artifact cache use only that ID. Existing worker IDs remain valid. Assignment error parity uses an absent-ID gate before validation and effects; it makes no timing-equivalence claim. Limitation: usage breaks are tracked only for the default worker. Break inference, ledgers and probe budgets are not per worker.
@@ -548,11 +598,9 @@ Upload IDs chosen by workers are request-scoped aliases. The server gives each u
548
598
 
549
599
  The retired pre-worker rollback procedure is retained in the [historical appendix](#historical-appendix-pre-worker-rollback). Current recovery uses compatible code or a reviewed complete backup restore as described under [Upgrade and rollback](#upgrade-and-rollback).
550
600
 
551
- ## Test
601
+ ## Test a source checkout
552
602
 
553
- ```sh
554
- npm test
555
- ```
603
+ From a source checkout installed with `npm ci`, run `npm test`. The npm package does not include this test suite. To verify an installed service, use [Smoke check an installed service](#smoke-check-an-installed-service).
556
604
 
557
605
  The fake-worker, durability, workspace, and OAuth tests use isolated temporary HOME directories and non-production ports. They do not send real T3 messages or use model API keys. Tests cover duplicate submit/claim/finish, owner receipt, watches, pause, cancellation, expiry and refresh, interrupted events, report persistence, ambiguous sends, transcript reconciliation, stopped threads, alert dedup, confined checks, patch/artifact transfer, OAuth rejection, and claim capacity. `DALAN_ALLOW_PRIVATE_WEBHOOKS=1` and `DALAN_T3_DRY_RUN=1` are test-only flags.
558
606
 
@@ -579,7 +627,7 @@ SERVICE_HOME="${DALAN_HOME:?Export DALAN_HOME as the trial home that try printed
579
627
  SERVICE_PATH="$PATH"
580
628
  ```
581
629
 
582
- For a manual foreground server, use its `DALAN_HOME` and launching `PATH` in the same two assignments. For a generated service, use instead the `HOME` and `PATH` from `dot-bridge-NAME.service` (systemd) or the `EnvironmentVariables` in `<home>/Library/LaunchAgents/org.dalan.dot-bridge-NAME.plist` (launchd; `<home>` is the home of the user who ran setup, not the private bridge home):
630
+ For a manual foreground server, use its `DALAN_HOME` and launching `PATH` in the same two assignments. For a service generated by the legacy `worker-bridge-setup.mjs`, use instead the `HOME` and `PATH` from `dot-bridge-NAME.service` (systemd) or the `EnvironmentVariables` in `<home>/Library/LaunchAgents/org.dalan.dot-bridge-NAME.plist` (launchd; `<home>` is the home of the user who ran setup, not the private bridge home):
583
631
 
584
632
  ```sh
585
633
  SERVICE_HOME='/absolute/bridge/home'
@@ -626,7 +674,7 @@ Importing `src/server.mjs` defines `main()` without starting the service or crea
626
674
 
627
675
  ## Historical appendix: pre-worker rollback
628
676
 
629
- **Do not run this historical recipe against schema 65 or other current layouts.** It omits newer retained relationships, including `submit_supersedes`. For a current downgrade, stop the service and use matching code or a separately reviewed restore of a complete compatible pre-upgrade backup, preserving compatible newer positive-ACK evidence. Do not alter `user_version` or delete relationship data to force compatibility. The following is retained only as a historical reference for the pre-worker build.
677
+ **Do not run this historical recipe against schema 66 or other current layouts.** It omits newer retained relationships, including `submit_supersedes`. For a current downgrade, stop the service and use matching code or a separately reviewed restore of a complete compatible pre-upgrade backup, preserving compatible newer positive-ACK evidence. Do not alter `user_version` or delete relationship data to force compatibility. The following is retained only as a historical reference for the pre-worker build.
630
678
 
631
679
  Rollback discards non-default-worker rows from the serving database to prevent even known-ID reads by the old worker. The backup retains them. Run these steps in order; do not expose the old route before the issuer gate passes.
632
680
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  This is a checklist of operator responsibilities, not another operating manual. Follow [operations](operations.md) for procedures and [the Dalan upgrade guide](dalan-upgrade.md) for command, setting and path compatibility. Use the service's HOME and environment when checking an installation.
4
4
 
5
- Each duty names a command or registered test, its source, and the limits of that evidence. A test name is an entry point, not a claim that it passed on this host. Run `node scripts/operator-duties-test.mjs` for this document's structural check: it reads repository files only, validates cited files, links, CLI forms and suite registrations, and executes none of the cited commands. It does not prove operational readiness or the semantic completeness of a regression test.
5
+ Each duty names a command or registered test, its source, and the limits of that evidence. A test name is an entry point, not a claim that it passed on this host. From a source checkout installed with `npm ci`, run `node scripts/operator-duties-test.mjs` for this document's structural check; the npm package does not include that script. The check reads repository files only, validates cited files, links, CLI forms and suite registrations, and executes none of the cited commands. It does not prove operational readiness or the semantic completeness of a regression test.
6
6
 
7
7
  ## Backup and restore
8
8
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  The owner-side verifier takes a sealed report patch and a local target ref. It creates a detached scratch worktree, applies the stored patch with the recorded digest and base SHA, and runs each evidence check through the `Workspace.runConfined` runner. Each check gets its own copy of the patched tree, so one check cannot alter the input to the next.
4
4
 
5
- The API is in `src/integrator.mjs`. To verify a patch:
5
+ This is a reference for maintainers embedding the JavaScript API in `src/integrator.mjs`, not a standalone CLI walkthrough. For owner-facing patch review and application, start with the [requester reference](usage.md). To use the internal verifier:
6
6
 
7
7
  1. Call `loadSealedResult(store, requestId)` to read the sealed patch artifact and its recorded base SHA from the stored report. `Workspace.artifact()` checks the artifact byte length and SHA-256 before it returns the bytes.
8
8
  2. Call `verifySealedResult({store, sealedResult, repoDir, targetBaseRef})` with a local checkout that already contains the target ref. It accepts only a nonempty patch from an implementation-scope assignment that is not a review result; a read-only `output_paths` patch is rejected.
@@ -20,7 +20,7 @@ If the target SHA differs from the patch base SHA, the verifier creates a new ca
20
20
 
21
21
  Scratch worktrees, per-check copies, and runner state stay under the integrator scratch root. They are left in place for inspection. The candidate's verified patch remains the sealed patch bytes plus the target SHA; the test runner's copies are evidence only.
22
22
 
23
- Run the focused segment with:
23
+ From a source checkout installed with `npm ci`, run the focused segment below; its script is not included in the npm package:
24
24
 
25
25
  ```sh
26
26
  node scripts/integrator-verifier-test.mjs
@@ -4,7 +4,7 @@ This guide describes the built-in authorization server and its connection flow.
4
4
 
5
5
  Path examples use fresh-home defaults. For an existing installation, resolve the actual roots with `dalan paths --json`: populated legacy roots remain active, as the [upgrade guide](dalan-upgrade.md) describes.
6
6
 
7
- Paths: `<home>` is your home directory and `<config>` is `<home>/.config`. (Docs avoid the tilde form so the bridge's own diff checks accept them.)
7
+ In this guide, `<home>` means the bridge service's private home and `<config>` means `<home>/.config`. Resolve an existing installation's active roots with `dalan paths --json` rather than assuming these defaults.
8
8
 
9
9
  ## Components
10
10
 
@@ -14,10 +14,10 @@ Paths: `<home>` is your home directory and `<config>` is `<home>/.config`. (Docs
14
14
 
15
15
  ## Connect a worker
16
16
 
17
- 1. On a fresh host, `dalan init --public-url https://<stable tunnel host> --worker NAME`. It runs `as-init`, which configures the public origin, and writes the worker profile; on a host that already has a profile, run `dalan as-init --public-url https://<stable tunnel host>` alone. Start the bridge with `DALAN_AUTH_MODE=builtin`; `dalan connect` fails until it runs. At server start, issuer = `<public origin>/<secret>/oauth` and resource = `<public origin>/<secret>/mcp` (the existing secret path segment stays).
17
+ 1. For a fresh installation, follow [service setup](service-setup.md#owner-setup), which creates the worker profile and built-in authorization state. For an existing built-in installation, keep its home, profile and public URL; do not rerun `init` or `as-init` merely to connect another client. An intentional issuer or endpoint change needs the [upgrade and recovery procedure](dalan-upgrade.md). The issuer is `<public origin>/<secret>/oauth` and the resource is `<public origin>/<secret>/mcp`.
18
18
  2. The owner starts a tunnel or reverse proxy that serves public HTTPS and supports the OAuth browser flow, and forwards only the public listener, never the owner socket. Preserve the public `Host` (including a non-default port); a mismatch returns 421, and forwarded headers do not override it. See [the exposure Host rule](../README.md#expose-your-bridge) and [service setup](service-setup.md) for network configuration. Issuer and resource come from config, never from forwarded headers.
19
- 3. Run `dalan connect start --worker NAME` before adding the connector in the vendor UI. The default pairing window lasts 10 minutes. The vendor reads the path-suffixed protected-resource metadata and AS metadata, then registers by DCR. DCR needs the secret namespace and an open window; registration creates no authority. A vendor that cannot register itself can use a static public client that the owner creates (see [Owner client commands](#owner-client-commands)).
20
- 4. The vendor opens the browser at `/<secret>/oauth/auth`, with PKCE S256, `resource`, scopes and redirect. The browser must run on the machine that runs the client callback listener. The interaction page shows a short pairing code (for example `KTBX-4QPM`) and an instruction to run `dalan connect approve KTBX-4QPM --worker example-worker` on the bridge computer. The page waits.
19
+ 3. Run `dalan connect start --worker NAME` before adding the connector in the vendor UI. The default pairing window lasts 10 minutes. The vendor reads the path-suffixed protected-resource metadata and AS metadata, then uses Dynamic Client Registration (DCR) to register the client. DCR needs the secret namespace and an open window; registration creates no authority. A vendor that cannot register itself can use a static public client that the owner creates (see [Owner client commands](#owner-client-commands)).
20
+ 4. The vendor opens the browser at `/<secret>/oauth/auth`, with PKCE S256, `resource`, scopes and redirect. For a native client with a loopback callback, open the sign-in page on the computer running that client's callback listener. For a hosted client, use the provider's browser sign-in flow. The interaction page shows a short pairing code (for example `KTBX-4QPM`) and an instruction to run `dalan connect approve KTBX-4QPM --worker example-worker` on the bridge computer. The page waits.
21
21
  5. The owner runs `dalan connect pending`. It shows each pending transaction: full pairing code, client_id, untrusted client name, exact redirect URI, worker, scopes and age. For native clients it warns that identity is not verified: host and name prove nothing. The teammate must read the pairing code from the browser page on their own machine and tell the owner over a trusted channel. `--confirm-redirect` checks for a redirect typo only; it is not identity proof. Approval of a native callback also requires the exact host, port and path: `dalan connect approve CODE --worker NAME --confirm-redirect URI`. Native entries are approved one code at a time: a native entry is never superseded, a newer native attempt never blocks or replaces an older one, and approving one code approves no other. `dalan connect pending` prints the approve command, with the redirect, for each native entry, so match the code and the redirect to the teammate. A web entry follows a different rule: only the newest web pending entry of a worker can be approved, and older web entries are shown as superseded because an app that registers again abandons its older attempts. A native entry never supersedes a web entry. If the code matches no pending entry, run `dalan connect pending` and compare the codes before retrying. The approval:
22
22
  - is bound to the interaction UID, which already binds the client, redirect, PKCE challenge and resource;
23
23
  - is single use and expires after 10 minutes;
@@ -43,7 +43,7 @@ A client still needs an open pairing window and owner approval before it can rec
43
43
 
44
44
  ## Secret namespace and discovery
45
45
 
46
- The explicit connector setup exposes the private resource URL to the chosen application. Treat the URL as a secret; ordinary pending and connection lists omit it. The AS encrypts OAuth state with `as-storage.key` in its private state directory. Back up the AS database and key, bridge database and its `.secrets/storage.key` together: losing the key prevents recovery of existing sessions. After migration, older bridge versions refuse to start against the upgraded bridge database (schema 52); restore a consistent pre-migration backup to roll back. Migration scrubs the managed SQLite database and its WAL, but does not erase older backups, snapshots, or copies.
46
+ The explicit connector setup exposes the private resource URL to the chosen application. Treat the URL as a secret; ordinary pending and connection lists omit it. The AS encrypts OAuth state with `as-storage.key` in its private state directory. Back up the AS database and key, bridge database and its `.secrets/storage.key` together: losing the key prevents recovery of existing sessions. Schema 52 introduced encrypted subscription storage; this release uses schema 66. Older code may refuse or be incompatible with migrated state. Follow [upgrade and rollback](operations.md#upgrade-and-rollback) and restore the matching pre-upgrade recovery set rather than lowering the schema number. Migration scrubs the managed SQLite database and its WAL, but does not erase older backups, snapshots, or copies.
47
47
 
48
48
  For resource `https://bridge.example/<secret>/mcp`:
49
49
 
@@ -68,9 +68,11 @@ Registration outside a window returns 403; an exhausted DCR budget returns 429;
68
68
 
69
69
  The loopback public listener sets `headersTimeout = 10,000 ms`, `requestTimeout = 30,000 ms`, `keepAliveTimeout = 5,000 ms`, `maxConnections = 128`, and socket inactivity timeout `180,000 ms`. Node checks incomplete requests every 1,000 ms, so deadline enforcement can lag by that interval. The header and body deadlines are absolute: sending a byte every few hundred milliseconds does not extend them. Ten seconds permits normal tunnel headers; thirty seconds permits bounded MCP uploads while limiting stalled bodies. Five seconds recycles idle keepalive connections; 128 sockets leaves room for normal parallel MCP calls with bounded exposure.
70
70
 
71
- `requestTimeout` limits receipt of the request, not tool execution or the response lifetime. The three-minute inactivity timeout covers stalled sockets and leaves a minute of headroom around the MCP T3 wait limit of 120 seconds. Responses with `Content-Type: text/event-stream` disable socket inactivity expiry when headers are sent, so a legitimate SSE response can stay open without a total response deadline. The current MCP endpoint returns JSON; SSE connections still count toward the connection cap. Legacy and external-OAuth listeners retain their prior settings.
71
+ `requestTimeout` limits receipt of the request, not tool execution or the response lifetime. The three-minute inactivity timeout covers stalled sockets and leaves headroom around `t3_thread_wait`: non-legacy catalogs advertise and enforce a 90-second default and maximum. The frozen `legacy-v46` catalog does not advertise T3 tools. On the hosted trial, a POST that accepts `text/event-stream` negotiates SSE only after bearer authentication, JSON-RPC validation and confirmation that the request has an ID. The response starts with a comment and sends comment keepalives every 20 seconds, followed by one final `event: message` JSON-RPC response. When SSE is not negotiated, normal MCP request/response calls keep JSON responses. SSE disables socket inactivity expiry when headers are sent, so the response has no total deadline; open streams still count toward the connection cap. Legacy and external-OAuth listeners retain their prior settings.
72
72
 
73
- ## Negative conformance tests (required before any live connection)
73
+ ## Maintainer conformance checklist
74
+
75
+ This checklist is for maintainers changing the authorization implementation. To connect a worker to an unmodified release, follow the setup and first-job checks in the [worker guide](worker-clients.md).
74
76
 
75
77
  1. Authorization without PKCE, or with `plain`: refused.
76
78
  2. A code reused, a code with the wrong verifier, a code for a different redirect or client: refused.
@@ -93,16 +95,12 @@ A worker's MCP client may be one-shot, with no push. Its fastest wake can be a t
93
95
  - The token is a separate 256-bit random value (64 hex characters) per worker in `~/.config/dalan/signal-token.<worker>`, mode 0600. It is not the MCP path secret. With no token file, the route answers 404. Migration: a host with one worker and an older single `signal-token` file keeps that URL working for its one worker; that worker's `--rotate` writes `signal-token.<worker>` and deletes the old file. With more than one worker the old file matches nothing.
94
96
  - A good token answers `200` with exactly `{"work":true}` or `{"work":false}`, plus `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`. `true` means at least one queued, live, uncancelled assignment targets the worker that owns the token, or the worker holds its own active claim whose lease has expired and that has had no claim activity for `DALAN_RESUME_IDLE_MS` (default 120000; `0` turns this second case off; see "Resume wake" in `docs/pull-workers.md`); other workers' queues and claims do not show. The answer has no ids, titles or counts. The bridge computes it at most once every 10 seconds per worker and caches the boolean.
95
97
  - A wrong or missing token answers `404` with an empty body, the same as any unknown path. The token compare is constant-time. A method other than GET with a good token answers `405`. The strict canonical Host check of the other routes applies first (`421`).
96
- - Rate limit, in memory: about one request per 5 seconds per source address with a burst of 3, and 30 requests per minute for the whole bridge. Excess requests get `429` with `Retry-After`. Only requests with a good token count, so a scanner with wrong tokens cannot use up the allowance. The bridge has no trusted-proxy setting, so the source address is the socket peer. Behind a tunnel on this computer that is the loopback address for every caller, and the limit becomes one shared bucket.
98
+ - Rate limit, in memory: about one request per 5 seconds per source address with a burst of 3, and 30 requests per minute for the whole bridge. Excess requests get `429` with `Retry-After`. Only requests with a good token count, so a scanner with wrong tokens cannot use up the allowance. The signal rate limiter uses the socket peer's address rather than a forwarded client address. `DALAN_TRUST_PROXY` acknowledges the HTTPS reverse-proxy deployment requirement on a non-loopback bind; it does not give this limiter a forwarded client IP. Behind a tunnel on this computer that is the loopback address for every caller, and the limit becomes one shared bucket.
97
99
  - The request log gets one line per request: `{kind:'signal', status, work}`. It never holds the token or the path.
98
100
 
99
- Hook example (bash, run every N seconds by the worker's host):
100
-
101
- ```sh
102
- curl -fsS "$SIGNAL_URL" | grep -q '"work":true' && wake
103
- ```
101
+ For a complete hook example, including transfer of the private signal file and replacement of the `wake` placeholder, see [The wake signal](pull-workers.md#the-wake-signal). Generate the signal file on the bridge host; the worker hook needs only that file.
104
102
 
105
- Treat the URL as a bearer secret: anyone who has it can learn whether work is queued. If it leaks, run `dalan connect signal-token --rotate`. Test: `node scripts/signal-endpoint-test.mjs` (about one minute, because it keeps the real 10 s cache and 5 s rate).
103
+ Treat the URL as a bearer secret: anyone who has it can learn whether work is queued. If it leaks, run `dalan connect signal-token --rotate`. Maintainer check: from a source checkout installed with `npm ci`, run `node scripts/signal-endpoint-test.mjs`. The npm package does not include it; it takes about one minute because it uses the real cache and rate-limit intervals.
106
104
 
107
105
  ## Not in scope
108
106
 
@@ -6,7 +6,7 @@
6
6
 
7
7
  0. Before the capacity gate (skipped with `--only`): for each PR that a queued or claimed assignment targets (objective key `pr:<owner>/<repo>#<n>`, or `inputs[0].github_repo` plus `pr_number`), at most `max_closed_checks` (40) per run, one REST `pulls/<n>` call (ETag-conditional, so an unchanged PR is a 304). A PR with `state` `closed` (merged or not) gets every such request cancelled with `dalan cancel ID --reason pr_closed`; the bridge stores it as `cancelled_reason`. Open PRs are untouched. A failure is logged as `error` with stage `pr-closed-check` and does not stop the run; a rate limit sets the usual backoff.
8
8
  1. `dalan status --json`. Stop when the pool is paused, when an owner-confirmed `worker_break` is active (`active` and `source === "owner"`), or when `claim_denied.capacity_hold_until` is in the future.
9
- 2. Free slots = `max_claimed_outer_assignments + headroom - (claimed + live queued)`, at most 0 or more. Submit at most `min(slots, max_submits_per_run)`. Defaults: headroom 6, 10 per run. With no free slot the run lists nothing.
9
+ 2. Free slots = `max(0, max_claimed_outer_assignments + headroom - claimed - live queued)`. Submit at most `min(slots, max_submits_per_run)`. Defaults are 6 headroom slots and 10 submissions per run. With no free slot, skip discovery.
10
10
  3. Discover open PRs with one REST-backed `gh search prs` per distinct configured owner and one per extra repo not covered by those owners. Apply case-insensitive exact `exclude_owners` and `exclude_repos`, and skip archived/fork repositories when the search or PR detail response identifies them. Bot PRs are skipped. A draft counts only if updated in the last 7 days; any other PR only if updated in the last 30 days. Ready PRs go first, newest first.
11
11
  4. Dedupe against `bridge.db` (read-only): any non-cancelled assignment for the same repository whose `inputs[0].head_sha` (or lone `base_sha`) is this head, or whose `objective_key` + `revision` is this PR at this head. This includes reviews that other owners submitted themselves. Cancelled assignments do not cover.
12
12
  5. Build the assignment so that `validateSubmission` accepts it: `scope_paths` are the PR's changed files still present at the head (deleted files are omitted), collapsed to directories only when over `max_scope_paths` (150) paths or `max_scope_bytes` (8000) bytes; `inputs` pin `{github_repo, base_sha: head}` in head-only mode (REST pull details provide a base tip, not a merge base); `execution_scope` is `read-only`; the brief names no path. A changed file the lint calls sensitive leaves the scope and the PR is then reviewed at its head without the diff (`inputs: [{github_repo, base_sha: head}]`). A PR whose files are all sensitive, a deletion-only PR, and a PR with more than `max_changed_files` (200) changed files, counting deletions, are skipped.
@@ -33,19 +33,35 @@ Every run logs `gh-calls` with invocation counts by `search`, `pull`, and `files
33
33
 
34
34
  ## Use
35
35
 
36
+ Before any run, configure the repository coverage and `bridge_db` and `t3_db` paths. Both databases must exist, and `t3_db` must contain `orchestration_v2_projection_threads`, even with delivery `none`. Install Node.js 24+, authenticate `gh`, and put `dalan` on `PATH`. See [Install on Linux](#install-on-linux) before enabling the timer.
37
+
36
38
  ```
37
- dalan-pr-reviewer --dry-run [--ignore-capacity] # print candidates; submit and write nothing
39
+ dalan-pr-reviewer --dry-run # inspect candidates without submitting
40
+ dalan-pr-reviewer --dry-run --ignore-capacity # also inspect candidates when capacity is full
38
41
  dalan-pr-reviewer --only OWNER/REPO#N # one PR, if in the repo's first 200 open search results (still gated and deduped)
39
42
  dalan-pr-reviewer --max N
40
43
  ```
41
44
 
42
45
  State and log: `~/.local/state/dot-pr-reviewer/{state.json,log.jsonl}` (one JSON line per decision).
43
46
 
44
- ## Install
47
+ ## Install on Linux
45
48
 
46
- ```
49
+ Run from the Dalan checkout or installed package directory, where `docs/` and `systemd/` exist. Install Node.js 24+, authenticate `gh`, and make `dalan` available on the unit's `PATH`. Disable any previous PR feeder before enabling this timer.
50
+
51
+ Create the directories and copy the example only if you have no configuration yet:
52
+
53
+ ```sh
47
54
  mkdir -p ~/.config/dot-pr-reviewer ~/.config/systemd/user
48
- cp docs/dot-pr-reviewer.config.example.json ~/.config/dot-pr-reviewer/config.json # then edit report_thread_id
55
+ if [ ! -e ~/.config/dot-pr-reviewer/config.json ]; then
56
+ cp docs/dot-pr-reviewer.config.example.json ~/.config/dot-pr-reviewer/config.json
57
+ fi
58
+ ```
59
+
60
+ Edit `config.json` before continuing: replace the example repository coverage, set `bridge_db` and `t3_db` to the intended existing databases, and replace `report_thread_id` with a verified destination or remove that key for quiet delivery. The T3 database must contain `orchestration_v2_projection_threads`, even with quiet delivery. Check the unit's checkout path and `PATH` as well.
61
+
62
+ Run `dalan-pr-reviewer --dry-run`. Confirm that it succeeds and shows only the intended repositories and destinations. Only then install and enable the timer:
63
+
64
+ ```sh
49
65
  ln -sf "$PWD"/systemd/dot-pr-reviewer.{service,timer} ~/.config/systemd/user/
50
66
  systemctl --user daemon-reload
51
67
  systemctl --user enable --now dot-pr-reviewer.timer
@@ -23,4 +23,6 @@ For example, add these fields to the normal assignment:
23
23
 
24
24
  A direct observation proves the head at its recorded instant. GitHub can change immediately afterward; the result remains tied to its declared SHA and must be verified against the current head before use. This preflight does not prove the broader objective is still useful. When the objective, revision or validity changes, the producer must prepare a new immutable identity; changing the old assignment conflicts.
25
25
 
26
+ The following checks require a source checkout installed with `npm ci`; their scripts are not included in the npm package.
27
+
26
28
  Run `node scripts/pr-preflight-test.mjs` and `node scripts/pr-preflight-commit-test.mjs` and `node scripts/pr-preflight-e2e.mjs`. The HTTP journey uses a local Git fixture and an inert gh executable, verifies zero assignments/claims on refusal, and proves claim retries keep their ID through a simulated observation outage. It does not contact GitHub or a live worker.