@tnunamak/dalan 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +8 -0
  4. package/README.md +68 -28
  5. package/bin/dalan.mjs +1 -1
  6. package/bin/dot-worker.mjs +115 -16
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +1 -1
  9. package/docs/local-agent-requester.md +46 -0
  10. package/docs/manual-setup.md +1 -1
  11. package/docs/operations.md +4 -3
  12. package/docs/pull-workers.md +1 -0
  13. package/docs/relationships.md +13 -0
  14. package/docs/service-setup.md +40 -17
  15. package/docs/setup-reference.md +1 -1
  16. package/docs/t3-integration.md +2 -0
  17. package/docs/t3-question-relationship.md +43 -0
  18. package/docs/t3-reverse-control.md +12 -8
  19. package/docs/t3-wake-fence-r4.md +42 -0
  20. package/docs/test-suite-isolation.md +205 -0
  21. package/docs/usage.md +14 -2
  22. package/docs/worker-clients.md +3 -1
  23. package/package.json +6 -3
  24. package/qualification/README.md +13 -0
  25. package/qualification/mcp.json +121 -0
  26. package/qualification/protocol-v0.json +127 -0
  27. package/src/admin-socket.mjs +2 -1
  28. package/src/answer-journal.mjs +200 -0
  29. package/src/auth-check.mjs +8 -2
  30. package/src/claim-command-ledger.mjs +3 -2
  31. package/src/cli-help.mjs +19 -10
  32. package/src/destinations/index.mjs +6 -0
  33. package/src/destinations/none.mjs +3 -0
  34. package/src/destinations/t3.mjs +63 -6
  35. package/src/execution.mjs +20 -2
  36. package/src/follow-current.mjs +4 -2
  37. package/src/gozar-routes.mjs +4 -3
  38. package/src/host-budget.mjs +17 -11
  39. package/src/host-execution-policy.mjs +2 -2
  40. package/src/host-stop-reverify.mjs +6 -4
  41. package/src/inbox.mjs +13 -3
  42. package/src/integrator.mjs +3 -1
  43. package/src/lifecycle.mjs +60 -2
  44. package/src/patch-apply.mjs +74 -13
  45. package/src/server.mjs +210 -34
  46. package/src/service-launchd.mjs +28 -8
  47. package/src/service-migrate-workers.mjs +12 -2
  48. package/src/service.mjs +52 -16
  49. package/src/status-summary.mjs +3 -0
  50. package/src/store.mjs +300 -34
  51. package/src/submission-policy.mjs +8 -4
  52. package/src/t3.mjs +21 -2
  53. package/src/tool-registry.mjs +54 -8
  54. package/src/workers.mjs +22 -3
  55. package/src/workspace.mjs +94 -15
package/CHANGELOG.md CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  This file lists user-visible changes, newest first. Check the section for your target release before you upgrade.
4
4
 
5
+ ## Unreleased
6
+
7
+ - **`finish` can hand a worker its next job (opt in per worker).** A worker whose session ends after each `finish` leaves work queued. Set `"finish_handoff": true` (or `{"wait_ms": N}`, 0 to 45000, default 20000) for the worker in `workers.json`. After the report is stored, the `finish` reply carries `next_job`: the oldest queued job, claimed through the normal `claim` path with a 10-minute lease. If nothing is queued, `finish` waits up to `wait_ms` for work, then returns `queue_empty`. A paused bridge, a closed client connection or a claim error ends the wait with the old `next_queued` hint, and the stored report is never affected. A repeated `finish` returns the same `next_job`. Off by default.
8
+
9
+ ## 0.8.1
10
+
11
+ - Cap claim leases per worker (`worker_claim_lease_ms` in limits.json) without changing the MCP catalog, so a worker whose sessions end early (Muse) frees its slot sooner (#44).
12
+ - Typed control events and held-wake display (#40); a revises link and stale guard for corrected jobs (#41); separate relationship, work and authority lifetimes (#33).
13
+
14
+ - **Relationships, work and authority have separate lifetimes.** Ending a worker relationship refuses new jobs while existing jobs, questions and results remain available under their own permissions and expiry.
15
+ - **Inspect relationships and permissions from the CLI.** `dalan relationships list` shows active and ended relationships, and `dalan relationships end ID` ends one. `dalan grants` lists permissions with each permission's enforcing component and expiry.
16
+
17
+ ## 0.8.0
18
+
19
+ **After you update, refresh every hosted connector you use (for example ChatGPT).** The `ask_question` tool now takes an optional `purpose` input, so the tool list the connector cached is out of date. Remove and re-add the connector, or use the connector's refresh action, so it reads the new list.
20
+
21
+ - **A worker can mark a question as a human-only decision.** `ask_question` takes an optional `purpose`: `clarification` (the default), `human_decision`, `authentication` or `tool_permission`. For any other value, the wake message tells the parent that a human must decide and gives it no answer command. Answering such a question also needs the operator key, not only the job's owner capability. Clarification questions behave as before. This is routing policy, not confinement: a process that can read the operator key file can use it.
22
+ - **`dalan answer` now survives a crash or a lost reply.** It saves the exact answer before it sends it, and sends the same answer again if the reply never arrives, so the worker gets it once. It now also works on protocol jobs, which refused it before. A different text for a question you already answered is refused on your machine, and an answer over 4096 bytes is refused with its byte count instead of cut short.
23
+ - **A stopped or interrupted parent is no longer woken by a worker's question or result.** Dalan holds the wake, keeps it in `dalan inbox`, and sends it once when the parent thread runs again. A repeated question wake now arrives once. Because T3 reports a stop and an interrupt the same way, a parent you only interrupted also stays held until it runs again. Question text in a wake is now shown as untrusted data.
24
+ - **Workers can accept jobs that require protocol features.** A worker's configuration can now name an adapter, and jobs that require a capability such as `identified_questions` are accepted only when that adapter is on the repository's list of verified adapters. An absent or unverified adapter refuses the job at submission and stores nothing. The qualification records ship in the package.
25
+ - **A worker with T3 access reaches only its own job's conversations.** Listing, reading, waiting, sending and setting now cover only the T3 threads that a claimed, unexpired job names; other conversations are hidden and refused, and a revoked grant stops later calls. Creating arbitrary threads is refused.
26
+ - **A job whose sensitive files were withheld shows its host checks again.** When a host job was admitted with some sensitive files withheld, `claim` and `get` reported that no host check could run (`scope_paths_read_isolation_unavailable`), although admission had accepted the job. They now show whether a check can still run, and refuse only when another sensitive file in the tree is not withheld, the tree or policy cannot be read, or the scope was narrowed.
27
+ - **Install and update are safer on macOS and with migrated workers.** A migrated worker policy with a capacity setting now installs. On macOS, install and update stop the existing LaunchAgent before replacing its plist and stop on an unknown launchd state before allocating a route. A fixture check that failed under restrictive umasks now passes.
28
+ - **Database migrations 67 to 69 run on first start.** They add the question purpose, the wake-hold records and the worker T3 scope, and keep existing rows. Back up the database before you update: a build older than 0.8.0 does not support the migrated database, so do not point 0.7.0 at it.
29
+ - Test-only: parallel test suites no longer share ports, systemd unit names, setup locks or scratch directories, and a new acceptance test covers question relationships across the CLI and T3 requesters.
30
+
31
+ - **Install checks setup before requesting a public route.** `dalan service install` now runs every check that only reads (the worker profile, the home, the service package link, service and automatic-update unit collisions, Gozar's state path and, on Linux, the user systemd manager) before it asks Gozar for a route. This includes macOS LaunchAgent plists. `--write-units-only` no longer asks Gozar for a route. A later file-write or startup failure can still leave a route. Install never closes a route on failure because it may have reused one; once the service receipt is written, `dalan service uninstall` can use its recorded handle to remove it.
32
+ - **Install names two common setup problems.** A `--home` whose admin socket path is too long for the system (107 bytes on Linux, 103 on macOS) is refused first, with the length, the limit and the fix: a shorter `--home`. A user systemd manager that cannot be reached is named, with `systemctl --user status` to see why and the note that a login session or `loginctl enable-linger` may be needed.
33
+ - **`dalan doctor --auth` explains your own pairing window.** When a pairing window for the same worker is already open, the check still fails and leaves the window alone, and now says it is your own window: finish pairing the client, or run `dalan connect stop`, then run doctor again.
34
+ - **A command with `--home` no longer runs the default home's version.** `dalan` hands each command to the version that the default home's service runs. With `--home DIR` (or `--home=DIR`) you name another home, so the installed `dalan` now runs the command itself. `DALAN_HOME` works as before.
35
+ - The [local-agent requester guide](docs/local-agent-requester.md) now passes the brief in single quotes, so the shell cannot run `$(...)` or backticks from it, and shows how to write a single quote inside the brief. It also no longer says that `report.summary` is always one line.
36
+
37
+ - Gozar's next step is now shown even when its error code is new to Dalan. The step is shown as sanitized text; Dalan does not act on it.
38
+
39
+ - Dalan now depends on Gozar `^0.3.0`, the route manager used to publish the bridge's HTTPS address.
40
+ - `dalan service migrate-workers` carries the claim-capacity setting from the source `limits.json` into the new home; conflicting source capacities are refused.
41
+ - Status now warns after 15 minutes without claim progress or tool activity, even while the lease remains live. Set `claim_idle_warning_ms` in `limits.json` to change the warning threshold. This observation does not cancel jobs or change leases.
42
+ - macOS service teardown now distinguishes a loaded agent, an explicitly absent agent and an unknown launchctl result. An unknown result stops teardown before either agent's plist is removed.
43
+ - The repository-job walkthrough now shows when to prompt the hosted worker, inspect its report and record acceptance. It also explains workspace setup limits for an existing service.
44
+ - The service guide now states macOS's loopback-only target restriction and that an update check missed during shutdown or logout does not catch up at login.
45
+ - Automatic-update failures roll back to the previous package on Linux and macOS. Tailscale session routes use port 8443, or 10000 when busy; service routes choose the first free port of 443, 8443 and 10000.
46
+
5
47
  ## 0.7.0
6
48
 
7
49
  Install, run and update Dalan with three commands on Linux and macOS:
package/CONTRIBUTING.md CHANGED
@@ -15,6 +15,10 @@ DALAN_HOST_CHECKS=0 npm test
15
15
 
16
16
  `DALAN_HOST_CHECKS=0` turns host checks off by default; tests that exercise host checks may still turn them on.
17
17
 
18
+ For concurrent runs, use a separate Git worktree and a separate short `TMPDIR` for each run (for example `/tmp/s-a-$$` and `/tmp/s-b-$$`). The temporary directory must exist before the run starts. Unix socket paths must fit within 107 bytes. Each test owns its temporary homes, databases, listeners, and host-check systemd units; installed dependencies and the toolchain may be shared read-only. Host-check resource ceilings apply per check, so concurrent runs add their resource use together.
19
+
20
+ New HTTP fixtures should bind port `0` and read the listening port. A fixture that must write its URL before starting a child should use `reservedPort({ start })` from `src/test-support/port.mjs` and report an actual bind failure with `error.code = 'EADDRINUSE'`; the helper then retries setup on another port. Calling `reservedPort()` without a startup callback only supplies a candidate, which can be taken before the listener binds. Tests that deliberately exercise a named or occupied port must retain that behavior rather than silently changing ports.
21
+
18
22
  Some upgrade tests also run against the source of releases from before Dalan was public. Maintainers keep those archives outside the repository and set `DALAN_PREPUBLIC_FIXTURES` to their directory; without it, those tests skip with the reason "pre-public release fixtures not present".
19
23
 
20
24
  ## Changes
package/PROTOCOL.md CHANGED
@@ -99,6 +99,8 @@ This section records the historical questions-v1 contract. The conformance adapt
99
99
 
100
100
  The owner lists questions with `dalan questions REQUEST_ID --json` and answers one with `dalan answer REQUEST_ID QUESTION_ID "answer text" --json`. These commands use the saved per-request owner capability. The corresponding Unix-socket routes are `GET /questions?id=REQUEST_ID` and `POST /answer {id,question_id,text}`. An answer requires an existing question from the current live grant. Missing, terminal, stale and already answered questions are refused; a second answer cannot replace the first. An answer remains awaiting consumption across restart. It queues an ordinary `assignment.available` event with the existing request/title payload; private notification metadata binds the wake to the question and epoch.
101
101
 
102
+ `ask_question` also takes an optional `purpose`: `clarification` (the default), `human_decision`, `authentication` or `tool_permission` (schema 67). Any value but `clarification` marks a question that only a human may answer: a choice, a sign-in or a permission grant. The wake that reaches the parent names what the human must do, says a human must decide, and carries no answer command. `POST /answer` for such a question needs the operator key (`x-operator-key`) in addition to the owner capability. The owner capability alone is refused with `FORBIDDEN` and nothing is stored. `get` and `GET /questions` show `purpose` only when it is not `clarification`; a clarification keeps its earlier shape. The same question ID asked again under another purpose is a `KEY_CONFLICT`. On one host this is routing and credential policy, not confinement: a process that can read the operator key file can use it. `dalan answer` sends only the owner capability today, so a person answers such a question with the operator key through the admin socket until the CLI sends it.
103
+
102
104
  `consume_answer {request_id,claim_id,question_id}` returns the saved answer and records its first consumption atomically. It requires the original current grant and refuses an unanswered question. An exact repeat under a live nonterminal job returns the same answer with `duplicate:true`. Cancelled and finished jobs refuse consumption, including a duplicate read; this does not change committed finish-receipt retries. Worker `get` includes question records without claim credentials or OAuth subject. A `completed` finish refuses `QUESTION_OPEN` while that grant has any unconsumed question, including an answered question. A `blocked` or `failed` finish may terminate without an answer; unanswered questions remain visible through owner `questions` as open audit facts, with no fabricated consumption or further authority. Questions from a prior epoch cannot block the new grant, and the new grant cannot answer or consume them. It must ask a fresh question and receive its own answer. Cancellation still permits audit-only late evidence under the existing rules.
103
105
 
104
106
  Schema 55 stores questions and their answer-wake associations. Ask, answer and first consumption append native lifecycle events with explicit `question:ask:ID`, `question:answer:ID` and `question:consume:ID` reasons. State and events commit together, and the conformance adapter projects these native facts; it does not infer answers from timestamps or keep a separate answer store. This revision adds no general command keys, revision compare-and-swap, or full profile-conformance claim. The historical v1 section below describes its pinned older source; v2 remains the authority and lease contract.
@@ -115,6 +117,12 @@ The local owner API also accepts `supersedes: {target_id, target_token}` on `POS
115
117
 
116
118
  Schema 58 commits the source, one immutable reference, cancellation through the existing cancellation core, notification/watch suppression, and any submit-command receipt in one transaction. `get` exposes `supersedes` on the source and `superseded_by` on the target as `{request_id, created_at}` (otherwise `null`), never capabilities. Exact retries preserve the reference, cancellation timestamp and receipt without cancelling twice; changing or omitting replacement intent conflicts. Only a first committed replacement wakes the target's attached owner waiter. Cancellation revokes bridge authority, not proof of physical compute stop. This adds no general lineage endpoint or post-submit relation mutation; `Store.submit` keeps `commandKey` as argument 16 and adds the narrow option after it.
117
119
 
120
+ The local owner API also accepts `revises: {prior_id, prior_token}` on `POST /submit`, to mark the new job as a corrected revision of an earlier one. `prior_token` is the owner capability of the earlier job, and `owner_token` still establishes or authenticates the new request. Unlike `supersedes`, `revises` never cancels the earlier job and works whatever its state. When both jobs carry `meta.revision`, the values must differ (`revises_same_revision`). `revises` cannot be combined with `supersedes` (`revises_and_supersedes`), cannot point at the job itself (`revises_cycle`), and is refused on the policy-routing submit path. A missing prior returns `revises_prior_not_found`; a wrong `prior_token` returns the usual owner-capability error. Exact retries replay the link; omitting or changing it conflicts. The request intent digest is unchanged, so existing receipts stay valid.
121
+
122
+ Schema 71 stores the link in `job_revisions(request_id, prior_id, input_revision, at)`; `input_revision` copies `meta.revision` and may be `null`. `get` exposes `revises` on the correction and `revised_by` on the earlier job, each as `{request_id, input_revision, at}` (otherwise `null`), never capabilities. A cancelled correction does not count: `revised_by` names the first correction that is not cancelled. While the earlier job is `queued` or `claimed`, the commit that stores the link also adds one owner note telling the worker that the job is superseded and to finish with a short report of where it stopped; the note is skipped, and the link kept, if the note budget is full. A finished job gets no note, so its rows do not change.
123
+
124
+ `POST /decide` with `accepted` or `applied` for a job that has a non-cancelled correction is refused with `stale_revision` and HTTP 400, and the body carries `stale: {request_id, revised_by, at, recorded}`. If the result had no earlier decision, the same transaction records a `stale` decision (actor `system`, via `revises`, note `revised by <id>`), so the refusal is durable and appears once. The report and artifacts stay as evidence. Rejecting the result (`not_useful`) and repeating an already recorded decision still work. An open question on the earlier job survives the correction. If the earlier job finishes first, its rows stay byte-identical when the correction arrives; the correction is new work.
125
+
118
126
  Before regrant, host check work must finish stopping with a verified process-group stop receipt. The HTTP claim handler waits outside the database transaction; the Store rechecks expiry, stop evidence and current authority in its transaction. Missing or unverified stop evidence refuses regrant, including interrupted checks after restart; automatic recovery of an unverified stop is not established here. A check whose authority expires is cancelled, and its output is discarded rather than published as a check result or artifact. Assignment-bound tools continue to require the active grant, so an old holder cannot mutate the new epoch's workspace.
119
127
 
120
128
  Owner-granted `t3` reverse-control tools and `notify_owner` have job-independent authority, no assignment epoch and no job-claim requirement. They are outside this contract's job-effect fencing. Worker profiles opt in with the `t3` capability; the legacy single-worker profile retains its existing grant. Their capability, scope and audit checks remain in force.
package/README.md CHANGED
@@ -1,45 +1,47 @@
1
1
  # Dalan
2
2
 
3
- Give your AI agent a coding job from your Mac or Linux computer, even when the agent can only connect through MCP. Dalan queues the job and brings its report back for you to review. It does not run a model or start your agent for you.
3
+ Put your MCP-only agent to work on coding jobs from your Mac or Linux computer. The hosted agent is the worker: it connects to your local Dalan bridge over MCP and claims jobs you queue. With explicit repository grants and workspace setup, it can return findings or a patch for you to review. You decide whether to apply changes. Dalan does not run a model or start the agent.
4
4
 
5
- Before you begin, install Node.js 24 or newer and Tailscale with Funnel enabled. Your agent's account must allow custom MCP connectors.
5
+ Before you begin, install [Node.js](https://nodejs.org) 24 or newer and [Tailscale](https://tailscale.com/download) with Funnel enabled. Your agent's account must allow custom MCP connectors.
6
6
 
7
7
  **Tailscale prerequisite.** `--route tailscale` publishes through Tailscale Funnel, which your tailnet administrator must allow (a `funnel` entry in the tailnet access controls; HTTPS and MagicDNS must be on too). If Funnel is not allowed, Dalan stops before it publishes anything and tells you which setup step is missing, or prints Tailscale's own refusal. Enable Funnel once at <https://tailscale.com/kb/1223/funnel>, then run the command again. Other routes need no Tailscale setting; `dalan setup` lists them.
8
8
 
9
9
  <a id="quickstart"></a>
10
10
 
11
- For a quick trial, install Dalan and run:
11
+ **Just exploring?** Run a temporary, text-only trial:
12
12
 
13
13
  ```sh
14
14
  npm install -g @tnunamak/dalan
15
15
  dalan try --public --route tailscale
16
16
  ```
17
17
 
18
- Follow the terminal instructions to add the connector, compare the sign-in codes and approve the matching code. Paste the supplied prompt into your agent's chat. Success is a report returned to your terminal.
18
+ Follow the terminal instructions to add the connector and approve only the matching sign-in code. Paste the supplied prompt into your agent's chat. Success is a report returned to your terminal.
19
19
 
20
- The trial is a text-only job with no repository access. Keep private code and secrets out of it. Ctrl-C stops the trial. A temporary demo link can change or stop without warning; Dalan ends the trial when it detects that, and the trial ends after three hours at most. For a persistent connection, follow the installation steps below.
20
+ The trial has no repository access. Keep private code and secrets out of it. It ends after three hours at most. Its public link can change or stop without warning. For a local-only trial that opens no public route, run `dalan try --local`; to connect a worker client by hand, see [manual setup](docs/manual-setup.md#worker-setup). For a persistent connection, use the installation steps below.
21
21
 
22
22
  ### Stop a trial
23
23
 
24
- Ctrl-C stops the trial. It also cancels a route that is still starting. Dalan closes its forwarding gate and attempts to remove its route. If it cannot confirm cleanup, it reports that. When Gozar cannot confirm route ownership, Dalan leaves the route alone and gives no stop command; use a different port and home for another trial.
24
+ Ctrl-C stops the trial and cancels a route that is still starting. Dalan closes its forwarding gate and attempts to remove its route. If it cannot confirm cleanup, it reports that. When Gozar cannot confirm route ownership, Dalan leaves the route alone and gives no stop command.
25
25
 
26
- If Gozar returns a cleanup-pending status for this trial, Dalan provides a recovery command that stops by port. Gozar does not bind that command to a session ID, so the route can change before the command runs. Inspect the current route before using it.
26
+ If Gozar reports cleanup as pending, Dalan prints a recovery command that stops by port. Gozar does not bind that command to a session, so inspect the current route before you run it.
27
27
 
28
- On stop, Dalan removes the connector URL file and the bridge's secret file for temporary routes. A trial prints its own home. If you run other `dalan` commands against a trial, set `DALAN_HOME` to that printed home first.
28
+ A trial prints its own home. Set `DALAN_HOME` to that home before you run other `dalan` commands against the trial. On stop, Dalan removes the connector URL file and the bridge's secret file for temporary routes.
29
29
 
30
- ### Try without a public route
30
+ <a id="expose-your-bridge"></a>
31
31
 
32
- ```sh
33
- npx -y @tnunamak/dalan try --local
34
- ```
32
+ ## Install a persistent connection
35
33
 
36
- This runs a self-check with a built-in demo worker and then lets you connect a client on this computer. It does not open a public route. To connect a worker client by hand, see [manual setup](docs/manual-setup.md#worker-setup).
34
+ This example names your hosted worker `assistant`; use that name consistently.
37
35
 
38
- <a id="expose-your-bridge"></a>
36
+ If you plan repository jobs, include `--enable-workspace` in the service install command below.
39
37
 
40
- ## Install a persistent connection
38
+ If you tried the temporary trial first, save any results you want (see [service setup](docs/service-setup.md)), stop it with Ctrl-C, and unset the trial's `DALAN_HOME` before you install:
39
+
40
+ ```sh
41
+ unset DALAN_HOME
42
+ ```
41
43
 
42
- The same commands work on macOS and Linux. This example names your worker `assistant`; use that name consistently.
44
+ The persistent service uses a fresh home and needs a new sign-in. Do not reuse the trial home.
43
45
 
44
46
  ```sh
45
47
  npm install -g @tnunamak/dalan
@@ -59,44 +61,64 @@ dalan connect approve CODE --worker assistant
59
61
 
60
62
  Keep the connector URL and pairing codes private. You are ready to send a job when the client finishes sign-in.
61
63
 
62
- Dalan runs in the background as a user service. On macOS it starts at login and stops at logout. On Linux it follows the systemd user manager; starting before login needs administrator setup. Installing a service does not start your AI agent. On macOS, host checks are unavailable and jobs run with `--execution none`.
64
+ Dalan runs as a user service. On macOS it starts at login and stops at logout. On Linux it follows the systemd user manager; starting before login needs administrator setup. Installing a service does not start your AI agent. On macOS, jobs run with `--execution none`.
63
65
 
64
66
  Automatic updates are enabled by default. Updates that change the tools exposed to your agent require approval and a connector refresh. See [service setup](docs/service-setup.md) for diagnostics, update controls, other routes and recovery.
65
67
 
66
68
  ## Give your connected agent a job
67
69
 
68
- In another terminal, replace `WORKER` with the name of your connected worker:
70
+ In another terminal, send a text-only job to the worker you just connected. If you chose a name other than `assistant`, use it instead. `--execution none` lets the job run no commands on your computer; `--deliver none` sends the result nowhere except back to Dalan, where you read it:
69
71
 
70
72
  ```sh
71
- dalan submit --worker WORKER --execution none --deliver none --brief "Explain what a database index does. Do not read files, run commands or call external services."
73
+ dalan submit --worker assistant --execution none --deliver none --brief "Explain what a database index does. Do not read files, run commands or call external services."
72
74
  ```
73
75
 
74
- Send the agent the request ID that Dalan prints. Ask it to claim that job, follow its brief and return a report. Queuing a job does not start the agent.
76
+ This first job needs no repository and returns a report, not a patch. Copy the request ID that Dalan prints. In the connected agent's chat, send this, replacing `REQUEST_ID` with that ID:
77
+
78
+ > Use Dalan to claim job REQUEST_ID, follow its brief, report progress, and finish with your answer. Do not expand its permissions.
75
79
 
76
- Replace `REQUEST_ID` with that ID, then wait and read the result:
80
+ Queuing a job does not start the agent. After you have prompted it, replace `REQUEST_ID` with the same ID, then wait and read the result:
77
81
 
78
82
  ```sh
79
83
  dalan wait REQUEST_ID
80
84
  dalan get REQUEST_ID --json
81
85
  ```
82
86
 
83
- Read the report before recording your decision:
87
+ Read the answer in `report.result` and its outcome in `report.outcome`. A missing or null report means there is no report yet. A blocked or failed outcome is not a successful answer.
88
+
89
+ `wait` defaults to 300 seconds. Exit 0 means finished, 3 a question or blocker, 4 cancelled, 5 the worker is on a usage break, and 124 timed out with the job still open. After a nonzero exit, inspect the job with `dalan get` before you continue. Do not submit again only because the wait timed out.
90
+
91
+ Only after you read a finished answer and find it useful, record your decision:
84
92
 
85
93
  ```sh
86
94
  dalan decide REQUEST_ID accepted
87
95
  ```
88
96
 
89
- A finished job and an accepted result are separate steps. Acceptance does not apply a patch. After review, apply a finished job's patch with:
97
+ A finished job and an accepted result are separate steps. Acceptance records your review; it does not change your files.
98
+
99
+ The text-only job above returns no patch to apply. A later [repository job](#separate-repository-assignment) can return one. Inspect it first, then replace `REQUEST_ID` with that job's ID and `PATH` with your local repository directory:
90
100
 
91
101
  ```sh
92
102
  dalan apply REQUEST_ID --dir PATH
93
103
  ```
94
104
 
105
+ <a id="send-jobs-from-your-local-agent"></a>
106
+
107
+ ## Send jobs from your local agent
108
+
109
+ A local coding agent with a shell (Claude Code, Codex CLI) can be the requester. It runs `dalan submit`, `wait`, `get` and `decide`. The hosted agent, such as Muse, stays the worker: it connects over MCP and claims the job. The requester needs no MCP connection. Copy the [instruction block](docs/local-agent-requester.md#instructions-to-paste) into your agent's instructions.
110
+
95
111
  <a id="separate-repository-assignment"></a>
96
112
 
97
113
  ## Give a worker a repository job
98
114
 
99
- The first job needs no repository. Repository jobs need Git and Python 3.8 or newer on the bridge computer, workspaces enabled, and an exact repository grant for the worker. The hosted demo does not enable repository work. A repository grant and a job's read/write scope are separate limits; host checks are another capability.
115
+ The text-only job proves pairing and reporting, not coding access. Keep using the same persistent bridge home and connected worker from the installation above. Before submitting a repository job, install Git and Python 3.8 or newer on the bridge computer, provide a host GitHub credential that can read the repository, and enable workspace access for both the host and worker. Then grant only the repository below. A repository grant alone does not enable workspaces.
116
+
117
+ The [manual setup guide](docs/manual-setup.md#owner-and-requester-setup) creates a separate loopback bridge in a new home; it is not an upgrade path for your persistent service. If your existing service has no workspace access, stop before submitting a repository job. Reinstalling with `--enable-workspace` is refused because the saved service configuration must match; it cannot enable workspace access in place.
118
+
119
+ The first repository job below reads one file at a pinned commit. It does not edit files or run checks. The trial has no repository access.
120
+
121
+ Replace `WORKER` with your worker's name (`assistant` above) and `OWNER/REPO` with the repository:
100
122
 
101
123
  ```sh
102
124
  dalan worker allow WORKER OWNER/REPO
@@ -109,7 +131,7 @@ Revoke access when the worker no longer needs it:
109
131
  dalan worker deny WORKER OWNER/REPO
110
132
  ```
111
133
 
112
- For a read-only repository job, replace the request ID, repository and full commit SHA below. Choose a file that exists at that commit:
134
+ For a read-only repository job, replace the request ID (`req_` plus a new lowercase UUID), repository and full commit SHA below. Choose a file that exists at that commit:
113
135
 
114
136
  ```json
115
137
  {
@@ -123,12 +145,28 @@ For a read-only repository job, replace the request ID, repository and full comm
123
145
  }
124
146
  ```
125
147
 
126
- Save it as `repository-job.json`, then submit, wait, read the report and record your decision:
148
+ Save it as `repository-job.json`. Replace `WORKER` as above, then submit:
127
149
 
128
150
  ```sh
129
151
  dalan submit --worker WORKER --execution none --deliver none --file repository-job.json --json
152
+ ```
153
+
154
+ Copy the request ID that `submit` prints. In your connected hosted agent's chat, send this, replacing `REQUEST_ID` with that ID:
155
+
156
+ > Use Dalan to claim job REQUEST_ID, follow its brief, report progress, and finish with your answer. Do not expand its permissions.
157
+
158
+ Queuing does not start the agent. After you have prompted it, use the same bridge home and request ID to wait and read the report:
159
+
160
+ ```sh
130
161
  dalan wait REQUEST_ID
131
- dalan get REQUEST_ID
162
+ dalan get REQUEST_ID --json
163
+ ```
164
+
165
+ Inspect `report.result` and `report.outcome`. A missing or null report means there is no report yet; a blocked or failed outcome is not a successful answer. After a nonzero `wait` exit, inspect the job before continuing, as described for the first job above.
166
+
167
+ Pause here to review the finished report. Only if you find it useful, record acceptance:
168
+
169
+ ```sh
132
170
  dalan decide REQUEST_ID accepted
133
171
  ```
134
172
 
@@ -139,7 +177,7 @@ The host's GitHub credential must be able to read the repository. For local clon
139
177
 
140
178
  ## Connect any MCP worker
141
179
 
142
- Any client that speaks HTTP MCP and completes the bridge's OAuth sign-in can be a worker. Start with the [worker guide](docs/worker-clients.md); client recipes add registration details, while job tools and grant rules stay the same.
180
+ Any client that speaks HTTP MCP and completes the bridge's OAuth sign-in can be a worker. Start with the [worker guide](docs/worker-clients.md).
143
181
 
144
182
  | Client | Guide |
145
183
  |---|---|
@@ -158,6 +196,8 @@ For an older or manually managed installation, follow the [upgrade guide](docs/d
158
196
 
159
197
  ## Reference
160
198
 
199
+ Replace `REQUEST_ID` with a job's ID.
200
+
161
201
  | Need | Command or guide |
162
202
  | --- | --- |
163
203
  | Command help | `dalan help --all` |
package/bin/dalan.mjs CHANGED
@@ -10,7 +10,7 @@ import { followTarget, handOver } from '../src/follow-current.mjs';
10
10
  import { readDefaultHome } from '../src/default-home.mjs';
11
11
  import { resolveHelp } from '../src/cli-help.mjs';
12
12
  // Follow the version the service runs, so the CLI and the service never drift. Then find the recorded home without DALAN_HOME.
13
- const followed = followTarget({ ownBin: fileURLToPath(import.meta.url) });
13
+ const followed = followTarget({ ownBin: fileURLToPath(import.meta.url), argv: process.argv.slice(2) });
14
14
  if (followed) handOver(followed);
15
15
  else {
16
16
  if (!process.env.DALAN_HOME && !['try', 'service', 'setup'].includes(process.argv[2])) { const recorded = readDefaultHome(); if (recorded) process.env.DALAN_HOME = recorded; }
@@ -33,10 +33,13 @@ import { workerPrompt } from '../src/worker-prompt.mjs';
33
33
  import { stoppedTrialFix } from '../src/try-command.mjs';
34
34
  import { formatGetSummary, formatWaitLine } from '../src/get-summary.mjs';
35
35
  import { cliCommand } from '../src/cli-name.mjs';
36
- import { applyPatch } from '../src/patch-apply.mjs';
36
+ import { applyPatch, listPatchFiles, patchMatchesWorktree, worktreeRoot } from '../src/patch-apply.mjs';
37
37
  import { terminalSafe, jsonTerminalSafe } from '../src/terminal-safe.mjs';
38
- import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
38
+ import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, ensureWorkerRelationship, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
39
39
  import { adminSocketPathError } from '../src/admin-socket.mjs';
40
+ import { answerThroughJournal } from '../src/answer-journal.mjs';
41
+ // An answer reply that takes longer than this counts as lost; the journaled envelope is sent again.
42
+ const ANSWER_TIMEOUT_MS=30000;
40
43
 
41
44
  // Every line this command writes to stderr can quote a worker's report, error or path. JSON lines stay JSON; the rest is made inert.
42
45
  const writeStderr=console.error.bind(console);
@@ -63,7 +66,7 @@ const FIRST_JOB_URL=docsUrl('docs/manual-setup.md','submit-finish-and-read-the-r
63
66
  const cli=json?'dalan':cliCommand(process.argv[1]);
64
67
  // Every option a command reads. An option it does not know is refused, so a typo is not ignored in silence.
65
68
  const SUBMIT_FLAGS=['--stdin','--json','--review','--wait','--dry-run','--queue-anyway','--refuse-defer','--allow-scope-prune','--fix-scope','--background','--allow-main','--exclude-sensitive'];
66
- const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
69
+ const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--revises','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
67
70
  const SUBMIT_OPTIONS=[...SUBMIT_FLAGS,...SUBMIT_VALUES];
68
71
  function refuseUnknownOptions(name,{flags=[],values=[]}) {
69
72
  for(let i=0;i<args.length;i++) {
@@ -86,7 +89,7 @@ function bridgeNotRunning(error) {
86
89
  if(selected) return Object.assign(error,{message:`cannot reach the bridge: no bridge is running for DALAN_HOME=${selected} (${cause})`,fix:[`start the bridge for this home the way you set it up (${docsUrl('docs/manual-setup.md','owner-and-requester-setup')}), then run this command again`]});
87
90
  return Object.assign(error,{message:`cannot reach the bridge: DALAN_HOME is not set and no bridge is running in ${home} (${cause})`,fix:[`export DALAN_HOME=DIR for the bridge home you made, or start a trial bridge with: ${cli} try`]});
88
91
  }
89
- function request(route, method = 'GET', payload, headers={}) {
92
+ function request(route, method = 'GET', payload, headers={}, timeoutMs=0) {
90
93
  return new Promise((resolve, reject) => {
91
94
  const bytes = payload ? JSON.stringify(payload) : '';
92
95
  const transportFailure=error=>reject(Object.assign(error.syscall==='connect'&&['ENOENT','ECONNREFUSED'].includes(error.code)?bridgeNotRunning(error):error,{kind:'transport'}));
@@ -104,6 +107,7 @@ function request(route, method = 'GET', payload, headers={}) {
104
107
  else resolve(value);
105
108
  });
106
109
  });
110
+ if(timeoutMs>0) req.setTimeout(timeoutMs,()=>req.destroy(Object.assign(new Error(`admin request timed out after ${timeoutMs} ms`),{code:'ETIMEDOUT'})));
107
111
  req.on('error',transportFailure); req.end(bytes);
108
112
  });
109
113
  }
@@ -130,12 +134,12 @@ function acpReceipt(id) {
130
134
  if(secret.length<32) return null;
131
135
  return {request_id:id,token:createHmac('sha256',secret).update(id).digest('hex'),acp:true};
132
136
  }
133
- function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null) {
137
+ function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null, revises=null) {
134
138
  fs.mkdirSync(receipts,{recursive:true,mode:0o700});
135
139
  const file=receiptPath(id);
136
140
  try {
137
141
  const fd=fs.openSync(file,'wx',0o600);
138
- try { fs.writeSync(fd,JSON.stringify({request_id:id,token,body,delivery,...(delivery.startsWith('t3:')?{thread:delivery.slice(3)}:{}),...(review?{review:true}:{}),...(background?{background:true}:{}),...(meta?{meta}:{}),...(producer?{producer}:{}),...(routing?{routing,destination_revisions:destinationRevisions??{}}:{})})+'\n'); fs.fsyncSync(fd); }
142
+ try { fs.writeSync(fd,JSON.stringify({request_id:id,token,body,delivery,...(delivery.startsWith('t3:')?{thread:delivery.slice(3)}:{}),...(review?{review:true}:{}),...(background?{background:true}:{}),...(meta?{meta}:{}),...(producer?{producer}:{}),...(routing?{routing,destination_revisions:destinationRevisions??{}}:{}),...(revises?{revises}:{})})+'\n'); fs.fsyncSync(fd); }
139
143
  finally { fs.closeSync(fd); }
140
144
  } catch(e) { if(e.code!=='EEXIST') throw e; }
141
145
  const dir=fs.openSync(receipts,'r'); try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
@@ -348,6 +352,19 @@ async function main() {
348
352
  else result={config_dir:selectors['--config-root'](),data_dir:root,state_dir:selectors['--state-root'](),workspace_root:workspaceRoot(home),...(json?{warnings}:{})};
349
353
  break;
350
354
  }
355
+ case 'relationships': {
356
+ const [action,relationshipId,...extra]=args.filter(a=>a!=='--json');
357
+ const headers={'x-operator-key':operator()};
358
+ if(action==='list'&&!relationshipId&&!extra.length) result=await request('/relationships','GET',null,headers);
359
+ else if(action==='end'&&relationshipId&&!extra.length) result=await request('/relationships/end','POST',{relationship_id:relationshipId},headers);
360
+ else throw new Error('usage: dalan relationships list | end RELATIONSHIP_ID [--json]');
361
+ break;
362
+ }
363
+ case 'grants': {
364
+ if(args.some(a=>a!=='--json')) throw new Error('usage: dalan grants [--json]');
365
+ result=await request('/grants','GET',null,{'x-operator-key':operator()});
366
+ break;
367
+ }
351
368
  case 'worker': {
352
369
  const [action,name,repo,...extra]=args.filter(a=>a!=='--json');
353
370
  if(args.filter(a=>a==='--json').length>1) throw new Error('usage: dalan worker allow|deny NAME OWNER/REPO [--json] | worker list [NAME] [--json]');
@@ -380,6 +397,14 @@ async function main() {
380
397
  break;
381
398
  }
382
399
  if(!['allow','deny'].includes(action)||!name||!repo||extra.length) throw new Error('usage: dalan worker allow|deny NAME OWNER/REPO [--json]');
400
+ // Enroll first: a database failure must not leave newly granted repository authority without a relationship.
401
+ if(action==='allow'&&fs.existsSync(path.join(root,'bridge.db'))) {
402
+ const db=new DatabaseSync(path.join(root,'bridge.db'));
403
+ try {
404
+ db.exec('PRAGMA busy_timeout=5000');
405
+ if(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='relationships'").get()) ensureWorkerRelationship(db,name);
406
+ } finally { db.close(); }
407
+ }
383
408
  result=updateWorkerRepoPolicy(file,name,action,repo);
384
409
  if(!json) { result=`${name}: ${result.mode}${result.repos?.length?` (${result.repos.join(', ')})`:''}${result.denied?.length?` except ${result.denied.join(', ')}`:''}${result.reset_to_audited?.length?`\nthe audit log failed its checkpoint, so workers.json was reset to the audited grants; allow again: ${result.reset_to_audited.map(item=>`${item.worker}${item.repos.length?` (${item.repos.join(', ')})`:''}`).join('; ')}`:''}`; plainOutput=true; }
385
410
  break;
@@ -435,6 +460,10 @@ async function main() {
435
460
  for(const flag of ['--objective-key','--revision','--task-kind','--source']) if(args.includes(flag)&&(!option(flag)||option(flag).startsWith('--'))) throw new Error(`${flag} requires a value`);
436
461
  // Objective identity travels beside the assignment, never inside it; a plain dalan submit is an agent's.
437
462
  const given=normalizeMeta({objective_key:option('--objective-key'),revision:option('--revision'),task_kind:option('--task-kind'),source:option('--source')});
463
+ // --revises PRIOR_ID: this job corrects a job this home submitted. It cancels nothing; the prior job's result can no longer be accepted.
464
+ if(args.includes('--revises')&&(!option('--revises')||option('--revises').startsWith('--'))) throw new Error('--revises requires the request ID of the job this one corrects');
465
+ const revisesGiven=option('--revises')??null;
466
+ if(revisesGiven&&routing) throw new Error('--revises needs one worker: it cannot be combined with --eligible or --policy');
438
467
  const dryRun=args.includes('--dry-run'), queueAnyway=args.includes('--queue-anyway'), refuseDefer=args.includes('--refuse-defer');
439
468
  if(dryRun&&queueAnyway) throw new Error('--dry-run stores nothing; it cannot be combined with --queue-anyway');
440
469
  if(dryRun&&args.includes('--wait')) throw new Error('--dry-run stores nothing; it cannot be combined with --wait');
@@ -454,7 +483,7 @@ async function main() {
454
483
  }
455
484
  }
456
485
  const token=randomBytes(32).toString('hex');
457
- const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions);
486
+ const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions,revisesGiven);
458
487
  let saved;
459
488
  if(dryRun) {
460
489
  try { saved=receipt(id); }
@@ -465,7 +494,7 @@ async function main() {
465
494
  // Receipts written by earlier releases may carry the old spelling of a source; compare the normalized form.
466
495
  const savedMeta=()=>{ try { return normalizeMeta(saved.meta); } catch { return {}; } };
467
496
  const conflicts=()=>{ const savedDelivery=saved.delivery ?? (saved.thread ? `t3:${saved.thread}` : null);
468
- return JSON.stringify(canonical(saved.routing??null))!==JSON.stringify(canonical(routing))||JSON.stringify(canonical(saved.destination_revisions??{}))!==JSON.stringify(canonical(destinationRevisions))||JSON.stringify(canonical(JSON.parse(saved.body)))!==JSON.stringify(canonical(body))||savedDelivery!==delivery||!!saved.review!==review||!!saved.background!==background||metaFields.some(k=>savedMeta()[k]!=null&&given[k]!==null&&savedMeta()[k]!==given[k]); };
497
+ return JSON.stringify(canonical(saved.routing??null))!==JSON.stringify(canonical(routing))||JSON.stringify(canonical(saved.destination_revisions??{}))!==JSON.stringify(canonical(destinationRevisions))||JSON.stringify(canonical(JSON.parse(saved.body)))!==JSON.stringify(canonical(body))||savedDelivery!==delivery||!!saved.review!==review||!!saved.background!==background||metaFields.some(k=>savedMeta()[k]!=null&&given[k]!==null&&savedMeta()[k]!==given[k])||saved.revises!=null&&revisesGiven!==null&&saved.revises!==revisesGiven; };
469
498
  const conflict=()=>Object.assign(new Error('request_id conflict with local receipt'),{local_code:'receipt_conflict'});
470
499
  // A refused submit stores no assignment, so its receipt guards nothing. Replace it instead of refusing a corrected retry.
471
500
  if(dryRun&&conflicts()) throw conflict();
@@ -477,7 +506,8 @@ async function main() {
477
506
  }
478
507
  // A retry inherits what the receipt recorded for any flag it omits, so replaying a drainer request by hand stays one request.
479
508
  const meta=Object.fromEntries(metaFields.map(k=>[k,given[k]??savedMeta()[k]??(k==='source'?'agent':null)]));
480
- const send=()=>request(dryRun?'/submit-preview':'/submit', 'POST', { ...(worker?{worker}:{}), ...(routing?{routing,destination_revisions:destinationRevisions}:{}), delivery, assignment: body, owner_token:saved.token, review, ...(background?{background:true}:{}), meta, ...(args.includes('--sensitive-scope-override')?{sensitive_scope_override:option('--sensitive-scope-override')}:{}), ...(args.includes('--allow-main')?{allow_main:true}:{}), ...(args.includes('--exclude-sensitive')?{exclude_sensitive:true}:{}), ...(execution?{execution}:{}), ...(requiredCapabilities?{required_capabilities:requiredCapabilities}:{}), ...(dryRun?{dry_run:true}:{...(refuseDefer?{refuse_defer:true}:{}),...(queueAnyway?{queue_anyway:true}:{})}), ...(args.includes('--defer-if-queued')?{defer_queued:Number(option('--defer-if-queued'))}:{}) },args.includes('--allow-main')?{'x-operator-key':operator()}:{});
509
+ const revisesId=revisesGiven??saved.revises??null;
510
+ const send=()=>request(dryRun?'/submit-preview':'/submit', 'POST', { ...(worker?{worker}:{}), ...(routing?{routing,destination_revisions:destinationRevisions}:{}), delivery, assignment: body, owner_token:saved.token, review, ...(background?{background:true}:{}), meta, ...(revisesId?{revises:{prior_id:revisesId,prior_token:receipt(revisesId).token}}:{}), ...(args.includes('--sensitive-scope-override')?{sensitive_scope_override:option('--sensitive-scope-override')}:{}), ...(args.includes('--allow-main')?{allow_main:true}:{}), ...(args.includes('--exclude-sensitive')?{exclude_sensitive:true}:{}), ...(execution?{execution}:{}), ...(requiredCapabilities?{required_capabilities:requiredCapabilities}:{}), ...(dryRun?{dry_run:true}:{...(refuseDefer?{refuse_defer:true}:{}),...(queueAnyway?{queue_anyway:true}:{})}), ...(args.includes('--defer-if-queued')?{defer_queued:Number(option('--defer-if-queued'))}:{}) },args.includes('--allow-main')?{'x-operator-key':operator()}:{});
481
511
  try {
482
512
  try { result=await send(); }
483
513
  catch(error) {
@@ -562,7 +592,14 @@ async function main() {
562
592
  case 'wait': { refuseUnknownOptions('wait',{flags:['--json','--drained'],values:['--timeout','--producer-thread','--max-claimed','--max-queued']}); if(args.includes('--drained')) { result=await waitDrained(); waitOutput=true; process.exitCode=drainedExitCodes[result.status]; break; } const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`wait needs a request ID: ${cli} wait REQUEST_ID (list your jobs with: ${cli} inbox --all)`); result=await waitForAssignment(id,option('--timeout')); indexArtifacts(id,result); waitOutput=true; process.exitCode=waitExitCode(result.status); if(!json&&process.stdout.isTTY) { result=formatWaitLine(result,{id,cli,seconds:option('--timeout')===null?300:Number(option('--timeout'))}); plainOutput=true; } else if(!json) waitTimeoutNote(id,result); break; }
563
593
  case 'note': { if(args.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('note accepts only --json as an option'); const [id,...parts]=args.filter(a=>a!=='--json'),text=parts.join(' '); if(!id||!text) throw new Error('note requires request id and text'); result=await request('/note','POST',{id,text},{'x-owner-capability':receipt(id).token}); break; }
564
594
  case 'questions': { const ids=args.filter(a=>a!=='--json');if(ids.length!==1||ids[0].startsWith('-')) throw new Error('questions requires one request id (optional --json)');result=await request('/questions?id='+encodeURIComponent(ids[0]),'GET',null,{'x-owner-capability':receipt(ids[0]).token});break; }
565
- case 'answer': { if(args.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('answer accepts only --json as an option');const [id,questionId,...parts]=args.filter(a=>a!=='--json'),text=parts.join(' ');if(!id||!questionId||!text) throw new Error('answer requires request id, question id and text');result=await request('/answer','POST',{id,question_id:questionId,text},{'x-owner-capability':receipt(id).token});break; }
595
+ case 'answer': { if(args.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('answer accepts only --json as an option');const [id,questionId,...parts]=args.filter(a=>a!=='--json'),text=parts.join(' ');if(!id||!questionId||!text) throw new Error('answer requires request id, question id and text');
596
+ // Every answer goes through the journal: the key and expected revision are saved before the first send, so a crash or a lost reply is retried with the same envelope.
597
+ const owner=()=>({'x-owner-capability':receipt(id).token});
598
+ result=await answerThroughJournal({receiptsDir:receipts,job:id,questionId,text,
599
+ readRevision:async()=>{const got=await request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,owner());return Number.isSafeInteger(got.protocol_revision)?got.protocol_revision:null;},
600
+ post:envelope=>request('/answer','POST',envelope,owner(),ANSWER_TIMEOUT_MS),
601
+ readQuestion:async()=>(await request('/questions?id='+encodeURIComponent(id),'GET',null,owner())).questions.find(q=>q.question_id===questionId)});
602
+ break; }
566
603
  case 'tell': { const worker=option('--worker'),rest=args.filter((a,i)=>a!=='--worker'&&args[i-1]!=='--worker');if(rest.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('tell accepts --worker NAME and --json');const text=rest.filter(a=>a!=='--json').join(' ');if(!text) throw new Error('tell requires text');result=await request('/tell','POST',{text,...(worker?{worker}:{})});break; }
567
604
  case 'untell': { const worker=option('--worker'),rest=args.filter((a,i)=>a!=='--worker'&&args[i-1]!=='--worker'&&a!=='--json');if(rest.length!==1||rest[0].startsWith('-')) throw new Error('untell requires message ID (optional --worker NAME, --json)');result=await request('/untell','POST',{message_id:rest[0],...(worker?{worker}:{})});break; }
568
605
  case 'audit': { const since=option('--since'); result=await request('/audit'+(since?'?since='+encodeURIComponent(since):''),'GET',null,{'x-operator-key':operator()}); break; }
@@ -603,20 +640,82 @@ async function main() {
603
640
  break;
604
641
  }
605
642
  case 'apply': {
606
- const id=args[0]; if(!id||id.startsWith('-')) throw new Error('apply requires request id (optional --dir PATH, default the current directory)');
643
+ const id=args[0]; if(!id||id.startsWith('-')) throw new Error('apply requires request id (optional --dir PATH, default the current directory; --release gives up an uncertain apply)');
607
644
  if(args.includes('--dir')&&!option('--dir')) throw new Error('--dir requires a path');
608
- const dir=path.resolve(option('--dir')??process.cwd()), headers={'x-owner-capability':receipt(id).token};
645
+ const headers={'x-owner-capability':receipt(id).token};
609
646
  const got=await request('/get?id='+encodeURIComponent(id),'GET',null,headers); indexArtifacts(id,got);
647
+ const open=got.apply?.state==='applying';
648
+ if(args.includes('--release')) {
649
+ // Gives up an uncertain apply on purpose, without writing or restoring any file. The job stays not applied.
650
+ if(!open) throw new Error(`no apply in progress for ${id}; nothing to release`);
651
+ await request('/decide','POST',{id,decision:'applied',phase:'release',force:true,reason:'released by the owner (dalan apply --release)',via:'apply'},headers);
652
+ result={request_id:id,released:true};
653
+ if(!json) { result=`released the apply in progress for ${id}; it is not applied and no file was changed`; plainOutput=true; }
654
+ break;
655
+ }
656
+ const dir=path.resolve(option('--dir')??process.cwd());
657
+ // A job revised before any reservation is refused here, and again by the bridge when the apply is reserved. An open
658
+ // reservation is not trusted from this read: it may have been released or taken over since, so every run reserves.
659
+ if(got.revised_by&&!open) throw Object.assign(new Error(`${id} was revised by ${got.revised_by.request_id}; its patch is not applied. Apply the patch of ${got.revised_by.request_id} instead (dalan get ${got.revised_by.request_id}).`),{local_code:'stale_revision'});
610
660
  const ev=got.report?.workspace_evidence, art=ev?.patch_artifact;
611
661
  if(!art?.artifact_id||!art.size) throw new Error('this result has no patch artifact (nothing to apply)');
612
662
  const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'dot-apply-')), file=path.join(tmp,'patch.diff');
663
+ const phase=(name,extra={})=>request('/decide','POST',{id,decision:'applied',phase:name,via:'apply',...extra},headers);
664
+ const reserve=async()=>{ try { return await phase('reserve'); } catch(e) { if(e.http_status===400&&/^stale_revision/.test(e.message)) throw e; throw new Error(`not applied: the bridge did not reserve the apply (${e.message}), so ${dir} is unchanged`); } };
665
+ const confirm=async attempt=>{ try { return await phase('confirm',{attempt}); } catch(e) { throw new Error(`the patch is in ${dir}, but the bridge did not confirm it (${e.message}). ${id} still shows an apply in progress. Run dalan apply ${id} again: if the tree still holds the patch it confirms without writing.`); } };
613
666
  try {
614
667
  await download(art.artifact_id,file);
615
- const files=applyPatch({dir,patch:fs.readFileSync(file),sha256:art.sha256,baseSha:ev.base_sha??got.assignment?.inputs?.[0]?.base_sha});
616
- let decided; try { decided=await request('/decide','POST',{id,decision:'applied',via:'apply'},headers); } catch(e) { throw new Error(`patch applied in ${dir}, but recording the decision failed: ${e.message}; run dalan decide ${id} applied`); }
617
- result={request_id:id,applied:true,dir,files,decision:decided.decision};
668
+ const patch=fs.readFileSync(file), patchArgs={dir,patch,sha256:art.sha256,baseSha:ev.base_sha??got.assignment?.inputs?.[0]?.base_sha};
669
+ // Two phases, so the bridge never records an effect before it happens, and a fencing token so that only the run that
670
+ // reserved last can write or confirm. Every run reserves, fresh or resumed: the bridge's stale check and the new token
671
+ // share one transaction, so a correction that landed since any earlier read makes it refuse and nothing is written. The
672
+ // patch is written only with a token from this run (every touched file is restored if the write fails), then confirmed.
673
+ // If the tree already holds the patch (a run died after the write), only the confirm is missing.
674
+ let files=[], written=false;
675
+ if(open&&patchMatchesWorktree(dir,patch)) {
676
+ // The tree already holds the patch. The bridge still checks for a correction: a revised job's result is never recorded.
677
+ let reserved;
678
+ try { reserved=await reserve(); }
679
+ catch(e) {
680
+ if(!/^stale_revision/.test(e.message)) throw e;
681
+ const correction=got.revised_by?.request_id??/revised by (\S+?);/.exec(e.message)?.[1]??'(see dalan get '+id+')';
682
+ const keep=path.join(os.tmpdir(),`dalan-revised-${id}.diff`); fs.writeFileSync(keep,patch,{mode:0o600});
683
+ throw Object.assign(new Error(`${e.message}\nThe working tree contains the superseded patch from request ${id}; the correction is ${correction}. Nothing was recorded and the reservation is still open.\n`
684
+ +`To undo it: git -C ${worktreeRoot(dir)??dir} apply -R ${keep}\n`
685
+ +`Or run dalan apply ${id} --release (it changes no file), then revert the files by hand.`),{local_code:'stale_revision'});
686
+ }
687
+ if(reserved.state!=='applied') { const decided=await confirm(reserved.attempt); result={request_id:id,applied:true,dir,files,already_present:true,decision:decided.decision}; }
688
+ else result={request_id:id,applied:true,dir,files,already_present:true,decision:'applied'};
689
+ } else {
690
+ try { applyPatch({...patchArgs,checkOnly:true}); }
691
+ catch(e) {
692
+ // An open reservation and a tree that fits neither the base nor the patch: a run may have died mid-write.
693
+ if(!open||!/git apply --check failed/.test(e.message)) throw e;
694
+ let names; try { names=listPatchFiles(dir,patch); } catch { names=[]; }
695
+ const top=worktreeRoot(dir)??dir;
696
+ const list=names.map(n=>/^[\w@%+=:,./-]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`).join(' ');
697
+ throw new Error(`${id} has an apply in progress from an earlier run, and ${dir} matches neither the patch nor the base it applies to: the checkout may be partly changed (${e.message.replace(/^not applied: /,'')}).\n`
698
+ +`Files the patch touches: ${names.join(', ')||'(not listed)'}.\n`
699
+ +`To recover: (1) inspect them: git -C ${top} diff -- ${list}\n`
700
+ +` (2) restore them: git -C ${top} checkout -- ${list} (this discards edits to those files only; delete any of them that the patch created, and keep unrelated edits)\n`
701
+ +` (3) run: dalan apply ${id} --dir ${dir}\n`
702
+ +`To give up without applying: dalan apply ${id} --release (it changes no file).`);
703
+ }
704
+ const reserved=await reserve();
705
+ if(reserved.state==='applied') { files=applyPatch(patchArgs); written=true; result={request_id:id,applied:true,dir,files,decision:'applied'}; }
706
+ else {
707
+ try { files=applyPatch(patchArgs); written=true; }
708
+ catch(e) {
709
+ let released=true; try { await phase('release',{attempt:reserved.attempt,reason:`apply_failed: ${e.message}`.slice(0,500)}); } catch { released=false; }
710
+ throw Object.assign(new Error(`apply_failed: ${e.message}${released?`. ${id} is not applied and can be applied again.`:`. The bridge could not be told; ${id} still shows an apply in progress: run dalan apply ${id} --release, or run it again.`}`),{local_code:'apply_failed'});
711
+ }
712
+ const decided=await confirm(reserved.attempt);
713
+ result={request_id:id,applied:true,dir,files,already_present:false,decision:decided.decision};
714
+ }
715
+ }
618
716
  } finally { fs.rmSync(tmp,{recursive:true,force:true}); }
619
- if(!json) { const {files}=result; result=`applied ${files.length} file${files.length===1?'':'s'} in ${dir}; recorded decision applied for ${id}\n${files.map(f=>' '+f).join('\n')}`; plainOutput=true; }
717
+ if(!json&&result.already_present) { result=`the patch was already in ${dir}; recorded decision applied for ${id} without writing`; plainOutput=true; }
718
+ else if(!json) { const {files}=result; result=`applied ${files.length} file${files.length===1?'':'s'} in ${dir}; recorded decision applied for ${id}\n${files.map(f=>' '+f).join('\n')}`; plainOutput=true; }
620
719
  break;
621
720
  }
622
721
  case 'integrate': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('integrate requires request id'); result=await request('/lifecycle','POST',{id,type:'integrated',...(option('--reason')?{reason:option('--reason')}:{})},{'x-operator-key':operator()}); break; }