@tnunamak/dalan 0.8.0 → 0.8.2

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 (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -44,7 +44,6 @@ This is a conservative source inventory of every explicit `homedir()` and `userI
44
44
  | --- | --- |
45
45
  | `scripts/acp-prose-check-test.mjs` | 10, 109 |
46
46
  | `scripts/adapter-conformance-test.mjs` | 19, 20 |
47
- | `scripts/admin-socket-path-test.mjs` | 35 |
48
47
  | `scripts/admission-measure-test.mjs` | 8 |
49
48
  | `scripts/admission-measure.mjs` | 84 |
50
49
  | `scripts/answer-journal-e2e.mjs` | 20, 23 |
@@ -80,6 +79,7 @@ This is a conservative source inventory of every explicit `homedir()` and `userI
80
79
  | `scripts/deadman-publication-crash-test.mjs` | 9 |
81
80
  | `scripts/deadman-readonly-status-test.mjs` | 10 |
82
81
  | `scripts/doctor-auth-test.mjs` | 15 |
82
+ | `scripts/finish-handoff-test.mjs` | 13 |
83
83
  | `scripts/generic-client-journey-e2e.mjs` | 16 |
84
84
  | `scripts/generic-profile-test.mjs` | 12 |
85
85
  | `scripts/gozar-migration-e2e.mjs` | 21 |
@@ -100,6 +100,7 @@ This is a conservative source inventory of every explicit `homedir()` and `userI
100
100
  | `scripts/integrator-safety-test.mjs` | 14, 15 |
101
101
  | `scripts/integrator-verifier-test.mjs` | 13 |
102
102
  | `scripts/integrator-worktree-filter-context-test.mjs` | 12 |
103
+ | `scripts/lease-deadline-clock-origin-test.mjs` | 10 |
103
104
  | `scripts/lease-deadline-restart-test.mjs` | 8 |
104
105
  | `scripts/lease-migrated-null-deadline-test.mjs` | 7 |
105
106
  | `scripts/legacy-acquisition-guidance-test.mjs` | 12 |
@@ -138,6 +139,7 @@ This is a conservative source inventory of every explicit `homedir()` and `userI
138
139
  | `scripts/regrant-effects-e2e.mjs` | 12 |
139
140
  | `scripts/regrant-waiter-fencing-test.mjs` | 32 |
140
141
  | `scripts/remote-loopback-callback-test.mjs` | 47, 56 |
142
+ | `scripts/route-setup-discard-test.mjs` | 10 |
141
143
  | `scripts/sandbox-probe-e2e.mjs` | 27 |
142
144
  | `scripts/sandbox-source-exemption-test.mjs` | 10 |
143
145
  | `scripts/schema-fixture-guard-test.mjs` | 10 |
@@ -170,6 +172,7 @@ This is a conservative source inventory of every explicit `homedir()` and `userI
170
172
  | `scripts/work-order-test.mjs` | 6 |
171
173
  | `scripts/worker-bridge-setup.mjs` | 89, 105, 228, 231, 758 |
172
174
  | `scripts/worker-isolation-test.mjs` | 22 |
175
+ | `scripts/worker-route-reference-test.mjs` | 54 |
173
176
  | `scripts/worker-repo-cache-test.mjs` | 7 |
174
177
  | `scripts/worker-repo-policy-e2e.mjs` | 14 |
175
178
  | `scripts/workspace-disk-test.mjs` | 8 |
@@ -186,19 +189,18 @@ This is a conservative source inventory of every explicit `homedir()` and `userI
186
189
  | `src/integrator.mjs` | 19 |
187
190
  | `src/limits.mjs` | 8, 16, 25 |
188
191
  | `src/paths.mjs` | 52, 56 |
189
- | `src/pr-head-reviewer.mjs` | 15 |
190
192
  | `src/prepared-node-modules.mjs` | 10 |
191
193
  | `src/projects.mjs` | 15, 90 |
192
194
  | `src/route-setting.mjs` | 14 |
193
- | `src/server.mjs` | 56 |
195
+ | `src/server.mjs` | 57 |
194
196
  | `src/service-launchd.mjs` | 23 |
195
197
  | `src/service-update-gate.mjs` | 9 |
196
- | `src/service-update-runtime.mjs` | 249 |
198
+ | `src/service-update-runtime.mjs` | 250 |
197
199
  | `src/service-update.mjs` | 118 |
198
200
  | `src/service.mjs` | 109, 347, 403 |
199
201
  | `src/store.mjs` | 149, 252, 253 |
200
202
  | `src/submission-policy.mjs` | 101 |
201
203
  | `src/t3-transport.mjs` | 30 |
202
- | `src/try-hosted.mjs` | 106 |
203
- | `src/try.mjs` | 55, 84, 273 |
204
+ | `src/try-hosted.mjs` | 109 |
205
+ | `src/try.mjs` | 55, 84, 271 |
204
206
  | `src/workers.mjs` | 170, 179 |
@@ -0,0 +1,47 @@
1
+ # ChatGPT agent hosted-performer acceptance
2
+
3
+ ## Purpose
4
+ Prove that the ChatGPT agent can claim and finish bounded work over MCP after the requester stops, without substituting a local worker.
5
+
6
+ ## Setup
7
+ Freeze this sheet and its revision before the first submission. Record RUN_ID, bridge revision, hosted client version, worker name and trial home.
8
+ Install Node.js 24 or newer and Dalan. In an interactive terminal, run `dalan try --public`, connect the ChatGPT agent over HTTP MCP with OAuth, and approve only the matching connection. Keep its private URL out of evidence. These are one-time setup touches, not routine intervention.
9
+
10
+ Set DALAN_HOME to the printed trial home for every observation below. Keep the bridge and its public route running independently of the requester.
11
+ Record `dalan status` before submitting work. Sign-in must be complete; a pairing window alone is insufficient.
12
+ The requester submits; the hosted performer claims. Queuing alone does not start the performer. Count the initial manual prompt explicitly (docs/local-agent-requester.md#instructions-to-paste).
13
+
14
+ ## Order of jobs
15
+ 1. **Harmless job.** Use the harmless brief defined by src/try.mjs#BRIEF: “Report the exact phrase: bridge first report. Do not read files, run commands or call external services.”
16
+ src/try.mjs#runTry submits a schema-version-1 request with a generated request ID, empty inputs, read-only scope, expected text containing that phrase, execution none and delivery none. The performer must claim that request over MCP and finish with exactly `bridge first report`.
17
+ The local flow first runs a built-in demo and a repository self-check before its own-worker job. Neither is hosted evidence. Public mode dispatches separately; save the actual hosted request from `dalan get REQUEST_ID --json` and require the same harmless contract. A mismatch stops this gate.
18
+ 2. **Continuing research.** Submit one text-only job: “From the inline facts Alpha takes 2 days and Beta takes 3 days, recommend one option. After the requester turn ends, ask exactly once whether speed or capacity matters. Wait for the answer. Use no outside sources.”
19
+ End the parent turn before the question. Answer “speed” once in the hosted conversation, as docs/local-agent-requester.md#instructions-to-paste prescribes. Continue the same request; expect Alpha, citing 2 versus 3 days. This is a persistence probe, not a research-quality benchmark.
20
+ 3. **Interruption cuts.** Use three separate text-only copies of the harmless job. Restart the hosted worker after claim but before finish. For the next, drop the finish reply after submission and reconcile before retrying. For the last, stop the parent session before the result, leaving bridge and worker running. Record cut timestamps and request IDs. Do not kill the bridge to simulate a stopped parent.
21
+
22
+ ## Acceptance criteria
23
+ Replace REQUEST_ID with the captured ID; never invent or reuse another job's ID.
24
+ - `dalan status` before and after each cut shows the bridge remains available. Save both outputs.
25
+ - `dalan get REQUEST_ID --json` proves the hosted worker claimed the intended immutable brief. Save claim identity and activity; setup screenshots alone fail.
26
+ - For each harmless job, that command shows status finished and report.result exactly `bridge first report`. Require completed outcome, not a blocker presented as success (src/try.mjs#finishedNotice).
27
+ - For research, successive get snapshots show one question after the saved parent-end timestamp, then the completed answer. Save the single answer and hosted transcript timestamps alongside them. A command snapshot alone cannot prove the parent ended.
28
+ - After restart or lost reply, get snapshots show reconciliation of the same request, not a replacement submission or contradictory report. Record any changed claim or expiry. If continuity cannot be demonstrated, fail.
29
+ - `dalan inbox` and get after parent restart expose the stored result without resubmission. Worker completion is not owner acceptance; save the later owner decision separately.
30
+ - Any missing observation is not tested, never pass. Another hosted performer passing does not pass this one. CLI or API impersonation does not count.
31
+
32
+ ## Allowed disclosure
33
+ No repositories or files are granted to the performer. Only these inline briefs, synthetic facts, request state and its own progress/results may be seen. No credentials, private URLs, unrelated history or external services. Operators retain sanitized evidence privately.
34
+
35
+ ## Cadence and timeouts
36
+ Request a 60-second claim lease; record the actual granted expiry before continuing. Unsupported duration blocks the cut until the sheet is revised before a new run.
37
+ Expect harmless jobs within 2 minutes, research within 5 minutes including the answer, each cut within 5 minutes. Observe every 15 seconds. Declare a stall after 60 seconds without new activity; stop at the job deadline. These are trial limits, not product defaults.
38
+
39
+ ## Spend ceiling
40
+ Five hosted jobs, no replacement submissions, 30-minute run limit excluding setup. Money ceiling: ______; owner must fill it before execution. No metered execution is authorized by this sheet.
41
+
42
+ ## Human touches to count
43
+ Count every manual start, prompt, approval, answer, restart, retry and review decision. Separate setup from routine touches; never erase failed attempts.
44
+
45
+ ## Result record
46
+ Save this frozen sheet, sanitized command outputs, request IDs, timestamps, hosted transcript, touch ledger, actual lease and spend, and per-criterion pass/fail/not-tested reasons under `trial-results/chatgpt-agent/RUN_ID/`.
47
+ Keep secrets out. Check public wording against scripts/public-scan.mjs#GENERIC_RULES. This document records no trial pass.
@@ -0,0 +1,68 @@
1
+ # Claude Code local requester acceptance sheet
2
+
3
+ ## Purpose
4
+
5
+ Prove that a local Claude Code requester can hand off bounded work, recover a question and retrieve a result without becoming the worker.
6
+
7
+ ## Setup
8
+
9
+ Freeze this sheet at revision e4bad12768abee7d114a23922cf6594e82c07123 before running anything; record the actual checkout SHA separately and correct any mismatch before starting.
10
+ Use Node 24 or newer, installed Dalan, and an interactive Claude Code session.
11
+ Complete the selected performer's sign-in once.
12
+ Record its exact worker name, bridge home, database path as BRIDGE_DB, versions and granted scope.
13
+ Use the same DALAN_HOME for every command.
14
+ The requester must never register as a worker or claim work.
15
+
16
+ Configure local stdio MCP once:
17
+
18
+ ```sh
19
+ claude mcp add --scope user dalan --env DALAN_HOME="/absolute/trial/home" -- "$(command -v dalan)" mcp
20
+ ```
21
+
22
+ Replace the home before running. Verify `dalan status --json` matches it.
23
+ Local MCP has local admin-socket authority, not separate worker credentials.
24
+ Sources: docs/local-agent-requester.md#instructions-to-paste; docs/local-agent-mcp.md#claude-code; src/mcp-stdio.mjs#TOOLS.
25
+
26
+ This document authorizes no run, paid session, approval or permission change. Obtain the owner's separate trial authorization.
27
+
28
+ ## Order of jobs
29
+
30
+ 1. Run the harmless `dalan try` path first. Use the actual selected performer, not the built-in demo, for the worker gate. The fixed brief is: “Report the exact phrase: bridge first report. Do not read files, run commands or call external services.” The assignment has empty inputs, read-only scope, expected text containing that phrase, execution none and delivery none. The worker claims, follows that brief and finishes. Require status finished and report.result exactly `bridge first report`. The built-in OAuth demo and optional pinned README demo are setup checks, not evidence that the selected performer worked. Sources: src/try.mjs#BRIEF, #REPORT, #runTry, #finishedNotice.
31
+
32
+ 2. Submit one continuing-research job through local `dalan_submit`, execution none and delivery none. Freeze these public synthetic inputs in its brief: “Record A: January 1, released. Record B: January 2, withdrawn. Record C: January 3, revised.” Ask for a chronology and one clarification: whether withdrawn records belong in the final summary. End the requester turn before the worker asks. Save both timestamps. Recover the question in a new requester turn and give exactly one answer: “Include withdrawn records and label them withdrawn.” Require a three-record chronology with that label.
33
+
34
+ Queuing never starts a hosted performer. Count the manual start and confirmation before waiting. CLI `dalan wait REQUEST_ID` exit 3 means a question or blocker, not completion. Inspect and stop; do not decide. For a structured question, use `dalan answer REQUEST_ID QUESTION_ID 'Include withdrawn records and label them withdrawn.'`. A generic blocker needs conversation resolution, not a fabricated question ID. At this pin there is no answer MCP tool. This sheet switches to `dalan_answer` once PR B5 ships and its contract is verified. Sources: src/mcp-stdio.mjs#TOOLS; src/cli-help.mjs#resolveHelp; src/answer-journal.mjs#prepare.
35
+
36
+ 3. Run three separate copies of the bounded research job. Restart the worker mid-job; lose one answer reply; stop the requester before the result. Recover each original request ID. Do not replace a job after an uncertain submission. Retry an answer only with its saved envelope. Read back before retrying any uncertain action. Source: src/answer-journal.mjs#send, #reconcile.
37
+
38
+ ## Acceptance criteria
39
+
40
+ - `dalan status --json` identifies the intended bridge and worker. No alternate performer substitutes.
41
+ - `dalan get REQUEST_ID --json` shows the original ID, claim, progress and terminal report after each cut. No duplicate terminal report or unsupported success claim is accepted.
42
+ - `dalan inbox --all --since all --json` reveals the waiting question or recovered result after the requester stops.
43
+ - For the research question, run:
44
+ `sqlite3 -readonly "$BRIDGE_DB" "SELECT request_id,question_id,asked_at,answered_at,answer FROM job_questions ORDER BY asked_at;"`
45
+ Require one question row for that job, asked after the saved parent-turn end, and one matching answer.
46
+ - `dalan get REQUEST_ID --json` must show the required phrase or chronology in report.result. Owner review precedes any decision.
47
+
48
+ Each hosted performer has its own gate. A local CLI/API simulation cannot pass a hosted trial. This sheet evaluates Claude Code only as requester.
49
+
50
+ ## Allowed disclosure
51
+
52
+ Only the exact synthetic briefs and their answers may reach the selected performer. No private repositories, files, credentials or connector data. The optional built-in demo may read only dalan-demo/hello README.md at its pinned revision. It grants no production repository access.
53
+
54
+ ## Cadence and timeouts
55
+
56
+ Record the granted claim lease from `dalan get REQUEST_ID --json`; never infer it from the wait timeout. Target five minutes per job. CLI wait defaults to 300 seconds; after two further timeouts declare a stall at fifteen minutes. MCP wait defaults to 120 seconds, capped at 300. Inspect at each timeout. Stop on cancellation, usage break or authority loss. Source: src/mcp-stdio.mjs#TOOLS.
57
+
58
+ ## Spend ceiling
59
+
60
+ Five performer jobs; ninety minutes total including setup. No automatic replacements. Money ceiling: ______, owner-approved before starting.
61
+
62
+ ## Human touches to count
63
+
64
+ Log every manual start, sign-in, approval, answer, restart and retry. Separate setup from routine interventions. A recovered job is not hands-free if a person rescued it.
65
+
66
+ ## Result record
67
+
68
+ Save the frozen sheet, SHA, sanitized command outputs, IDs, timestamps, lease, question/answer evidence, report and touch/spend log under `trial-results/claude-code-requester/RUN_ID/`. Record each criterion as pass, fail or untested. Never save credentials or private connector URLs.
@@ -0,0 +1,46 @@
1
+ # Muse hosted-performer acceptance sheet
2
+
3
+ ## Purpose
4
+ Prove that Muse can complete and resume bounded research jobs through its hosted MCP connection without depending on a live requester turn.
5
+
6
+ ## Setup
7
+ Freeze this sheet and record its revision before starting. This is a test plan, not a passing trial.
8
+
9
+ Use Node.js 24 or newer and a private, disposable Dalan trial home. Start `dalan try --public` in an interactive terminal. Complete Muse's MCP sign-in and approve the intended connection. Keep the connector URL private. Record the actual worker name; never infer it from the product name.
10
+
11
+ Export the printed trial home as DALAN_HOME in each observer shell. Keep the bridge running separately from the requester session. Capture `dalan status` before each job. Initial installation, connection approval and route setup are setup touches, recorded separately from routine touches.
12
+
13
+ Sources: src/try.mjs#runTry; docs/local-agent-requester.md#Instructions-to-paste. Public mode delegates to the hosted flow; a local self-check is not hosted evidence.
14
+
15
+ ## Order of jobs
16
+ 1. **Harmless report.** The source's submit helper creates a version-1 request with a fresh request ID, empty inputs, read-only execution scope, and expected output “Text report containing: bridge first report.” Its exact brief is: “Report the exact phrase: bridge first report. Do not read files, run commands or call external services.” Submission uses execution none and delivery none. Muse must claim the hosted job and finish with exactly `bridge first report`. Record the actual assignment from `dalan get REQUEST_ID --json`; stop if the hosted job differs instead of silently changing the criterion. The built-in demo's report does not qualify. Sources: src/try.mjs#BRIEF, src/try.mjs#REPORT, src/try.mjs#runTry.
17
+
18
+ 2. **Continuing research.** Submit one text-only job with this supplied packet: “Option A takes two days and costs three units. Option B takes four days and costs one unit.” Ask Muse to compare the options. After the requester turn ends, Muse must ask exactly one question: “Which matters more: time or cost?” Answer once: “Time.” Muse must then recommend A, cite the supplied durations and costs, and explain the tradeoff. No external research is permitted. Use the existing scoped question/answer flow; inability to do this is a failed gate, not permission to substitute a different interface.
19
+
20
+ 3. **Interruption cuts.** Use three separate copies of the same packet job. Restart the hosted worker after its claim and progress, before completion. In the second copy, interrupt observation of the completion reply and reconcile the same request ID before retrying. In the third, stop the requester session before Muse finishes while leaving the bridge alive. Record the precise cut and its evidence. Do not kill unrelated processes or manufacture a lost transport reply by merely hiding terminal output.
21
+
22
+ ## Acceptance criteria
23
+ Run `dalan get REQUEST_ID --json` before and after every cut. Save both outputs.
24
+ - Harmless job: status is finished, report outcome is completed, and report result equals the exact phrase.
25
+ - Research: recorded question occurs after the logged parent-turn end; one answer precedes the retained result; recommendation and cited packet facts are correct. Correlate get output with timestamped hosted transcripts.
26
+ - Restart: get shows one logical request and a valid current claim history; resumed work finishes without conflicting terminal reports.
27
+ - Lost reply: get recovers the retained report under the same ID. No replacement submission or repeated effect is needed.
28
+ - Parent stopped: get from a new observer session retrieves the finished result without restarting the requester.
29
+ - `dalan status` remains reachable throughout. A missing report, unverifiable cut, manual repair or conflicting result fails the affected gate.
30
+
31
+ Muse is its own gate. Success by the ChatGPT agent or any other performer does not pass Muse. CLI/API execution may observe or submit; it cannot impersonate the hosted worker.
32
+
33
+ ## Allowed disclosure
34
+ Muse may see only these text briefs, the synthetic packet, the single answer, and its own assignment/progress/result metadata. No repositories, files, credentials, personal records or other jobs are authorized. The code citations are operator documentation, not worker read grants.
35
+
36
+ ## Cadence and timeouts
37
+ Record the granted claim lease and expiry from get; do not assume a default. Require progress at least every minute and before expiry. Expected wall time: two minutes for the report; five minutes per research/cut job, excluding a recorded answer delay. No claim after 60 seconds triggers inspection; five minutes without progress or a missed lease is a stall. Stop at the time ceiling rather than retry indefinitely.
38
+
39
+ ## Spend ceiling
40
+ At most five hosted jobs, one attempt per cut, and 30 minutes after setup. Money ceiling: ______ (owner fills before starting). No automatic extra jobs or paid upgrades.
41
+
42
+ ## Human touches to count
43
+ Log every manual start, approval, prompt, answer, restart, retry and repair with timestamp and reason. Label planned cuts separately; do not omit them from totals.
44
+
45
+ ## Result record
46
+ Save the frozen sheet, source revision, worker identity, request IDs, sanitized get/status outputs, hosted transcripts, lease evidence, cut timestamps, touch ledger, elapsed time, actual spend and per-gate verdict under `trial-results/muse/RUN_ID/`. Exclude connector URLs and credentials. Missing evidence means not verified. Authoring this sheet is not user validation.
package/docs/usage.md CHANGED
@@ -42,9 +42,9 @@ Acceptance is your event, never the worker's: `finish` records `completed` (the
42
42
 
43
43
  Always select the intended worker explicitly: A multi-worker profile refuses an omitted `--worker` with the list of configured workers (`use --worker NAME; configured: ...`); a single-worker profile defaults to its only worker, and a host without `workers.json` (legacy) defaults to `dot`. `--execution` is a submit option, distinct from the assignment's `execution_scope`. The CLI writes a private owner receipt before submitting and keeps it in the selected bridge home. Quiet submit alone registers no wake. After a restart, use `dalan inbox --producer SAVED --json` or `dalan inbox --all --json`, then `dalan get REQUEST_ID --json`; do not guess that a new session label is the old producer. `--thread THREAD_ID` remains an alias for `--deliver t3:THREAD_ID`, not part of this quiet first-job path.
44
44
 
45
- **Objective identity and `--source`.** `dalan submit` also takes `--objective-key`, `--revision`, `--task-kind` and `--source`, which label work for metrics in an orchestration setup. A first job does not need them; see [Objective identity](t3-integration.md#objective-identity).
45
+ **Objective identity and `--source`.** `dalan submit` also takes `--objective-key`, `--revision`, `--task-kind` and `--source`, which label work for metrics in an orchestration setup. A first job does not need them; see [Objective identity](t3-integration.md#objective-identity). To resend corrected work, use `--revises REQUEST_ID` with a new `--revision`; the earlier result can then no longer be accepted or applied.
46
46
 
47
- **Priority.** Direct submissions are `normal`. Use `dalan submit --background` for feeder or backlog work. Priority is set by the bridge, never read from assignment text. `list_pending` shows normal work first, then background work. Priority only orders the queue: background work stays listed and claimable while normal work waits. `~/.config/dalan/limits.json` may set `background_max_in_flight` (default `4`), which limits queued plus claimed background assignments only. `dalan status --json` and `--explain` show queued and claimed counts for both classes.
47
+ **Priority.** Direct submissions are `normal`. Use `dalan submit --background` for feeder or backlog work. Priority is set by the bridge, never read from assignment text. `list_pending` shows normal work first, then background work. Each item also lists the pinned repository (`repos`), `execution_scope`, the first 10 `scope_paths` and `output_paths` (with totals), `priority` and `review`, so a worker can tell which queued jobs are independent. When a total is larger than the list shown (the lists stop at 10), or a job names no scope, overlap is unknown: do not treat it as safe to run together. A destination-blocked item shows only its ID, title and time, plus `blocked: true`. Priority only orders the queue: background work stays listed and claimable while normal work waits. `~/.config/dalan/limits.json` may set `background_max_in_flight` (default `4`), which limits queued plus claimed background assignments only. `dalan status --json` and `--explain` show queued and claimed counts for both classes.
48
48
 
49
49
  <a id="queue-wake-ups"></a>
50
50
 
@@ -54,8 +54,8 @@ Always select the intended worker explicitly: A multi-worker profile refuses an
54
54
 
55
55
  If work stays queued, run `dalan status --json` and inspect its subscription, free lanes, dispatch state and unresolved deliveries. Ask the worker to inspect `list_pending` and claim only work it can start within its authority. Use [Recovery and operation](operations.md#recovery-and-operation) for delivery reconciliation and lease recovery. Scheduler settings and detailed eligibility rules are in [Lifecycle events and metrics](operations.md#lifecycle-events-and-metrics).
56
56
 
57
- **Dispatch gap.** `finish` and `claim` results carry `next_queued` (up to one `{request_id, title}` per free lane, oldest first, never the item just claimed) and a one-line `next_action`, omitted when nothing is queued or no lane is free. When a claimed assignment leaves its lane (finish, abandon, owner cancel of a claimed item, lease takeover), the next drain tick (500 ms) sends one availability wake without waiting out `queue_rewake_ms`; a paused bridge, an owner-confirmed break, a capacity hold, no free lane or an outstanding wake still suppresses it. `status` carries Default-worker-scoped `dispatch: {state, free_lanes, queued_live, oldest_unclaimed_age_ms}` where `state` is `dispatch_gap` (free lanes and live queued work: the worker should claim), `supply_gap` (free lanes, nothing queued), `full`, `paused` or `unknown` (no active subscription proves capacity); `status --explain` shows `dispatch=<state>(free:F,queued:Q,oldest:Nm)` and the metrics line adds `idle_no_queue24h`/`7d` (time with nothing queued) next to `idle_while_queued`.
58
- `status --json` also exposes `by_worker`: each worker has its own assignment counts, active claims, live queue, call timestamps, stale claims and queue liveness. Top-level assignment and priority counts remain global (`counts_scope` and `priority_counts_scope` are `global`). Each worker's `capacity` is bridge subscription-policy evidence, not vendor quota, availability or productive capacity. Without an active valid subscription, `free_lanes` is `null` and `state` is `unknown`; duplicate subscriptions do not add lanes, and conflicting historical principal scopes remain unknown. Top-level dispatch and liveness retain their scope (`dispatch.scope` and `liveness_scope`).
57
+ **Dispatch gap.** A `finish` response may return a live handoff as `next_job` (or `next_jobs`). If `already_claimed` is true, begin that job in the same run with its supplied `claim_id` and `epoch`; do not claim it again. Otherwise, `finish` and `claim` results carry `next_queued` (up to one item per free lane, oldest first, never the item just claimed; each item is `{request_id, title}` plus the same triage fields as a `list_pending` item: `execution_scope`, `repos`, `scope_paths`, `output_paths` with their `_total` counts, `priority`, `review`) and a one-line `next_action`, omitted when nothing is queued or no lane is free. When a claimed assignment leaves its lane (finish, abandon, owner cancel of a claimed item, lease takeover), the next drain tick (500 ms) sends one availability wake without waiting out `queue_rewake_ms`; a paused bridge, an owner-confirmed break, a capacity hold, no free lane or an outstanding wake still suppresses it. `status` carries Default-worker-scoped `dispatch: {state, free_lanes, queued_live, oldest_unclaimed_age_ms, oldest_unclaimed_request_id}` where `state` is `dispatch_gap` (free lanes and live queued work: the worker should claim), `supply_gap` (free lanes, nothing queued), `full`, `paused` or `unknown` (no active subscription proves capacity); `status --explain` shows `dispatch=<state>(free:F,queued:Q,oldest:Nm)` and the metrics line adds `idle_no_queue24h`/`7d` (time with nothing queued) next to `idle_while_queued`.
58
+ `status --json` also exposes `by_worker`: each worker has its own assignment counts, active claims, live queue, call timestamps, stale claims and queue liveness. Top-level assignment and priority counts remain global (`counts_scope` and `priority_counts_scope` are `global`). Each worker's `capacity` is bridge subscription-policy evidence, not vendor quota, availability or productive capacity. Without an active valid subscription, `free_lanes` is `null` and `state` is `unknown`; duplicate subscriptions do not add lanes, and conflicting historical principal scopes remain unknown. `dispatch.by_worker` separately describes each configured worker with `state`, `free_lanes`, `queued_live`, `oldest_unclaimed_age_ms`, and `oldest_unclaimed_request_id` (the same oldest eligible row, or null; equal timestamps use request ID order). Its live queue excludes cancelled, expired and skipped rows; its free lanes are the same subscription-policy evidence, not worker utilization. The top-level legacy dispatch fields and liveness retain their scope (`dispatch.scope` and `liveness_scope`). A worker with a caller reserve (`worker_caller_reserve` in limits.json, which holds lanes back for caller jobs while other jobs may use only the rest) also reports `reserve_idle_minutes_24h` in its `capacity`: the minutes in the last 24 hours when at least one reserved lane sat free and no caller job was waiting for that worker, approximated by 1-minute buckets from the recorded lifecycle events; a worker with no reserve has no such field.
59
59
 
60
60
  <a id="recover-results-after-a-restart"></a>
61
61
 
@@ -105,6 +105,18 @@ Native protocol leases instead expire at their fixed deadline and require explic
105
105
 
106
106
  `dalan abandon ID --reason TEXT --json` returns a claimed assignment to the queue, and the old `claim_id` stops working; a successor still waits for the old deadline. Abandon and takeover are refused while a delivery for the assignment is uncertain or sending; reconcile it first.
107
107
 
108
+ **Control events and their scope.** `dalan cancel`, `dalan cancel-if-queued` and `dalan abandon` print a `scope` block. `scope.ref` names what the command acted on, `scope.controlled` says what changed, and `scope.not_controlled` says what the command did not touch. Cancel controls the job and not the worker's compute. Abandon controls the claim and not the worker's session. The same facts go to the lifecycle log as typed events, in the transaction of the change:
109
+
110
+ | Event | Written by | Scope ref | Outcome |
111
+ |---|---|---|---|
112
+ | `withdraw_work` | `cancel`, `cancel-if-queued` | `job:REQUEST_ID` | `done` (the store withdrew the job) |
113
+ | `detach` | `abandon` | `claim:CLAIM_ID@EPOCH` | `done` (the store released the claim) |
114
+ | `interrupt_foreground` | a request to stop a foreground run (`Store.recordControl`) | `thread:ENV/THREAD#run:N` | `unknown`, or `confirmed` only with an observation |
115
+ | `revoke_grant` | a grant revocation (`Store.recordControl`) | `grant:NAME` | `unknown`, or `confirmed` only with an observation |
116
+ | `wake_held` | a wake held because the parent stopped | `wake:NOTIFICATION_ID` | `unknown` (the wake is not delivered) |
117
+
118
+ A request to something outside the store is `unknown` until an observation says otherwise. A denied stop is `unknown` too: a denial does not prove that nothing stopped, so it is never recorded as success. `interrupt_foreground` and `revoke_grant` have no automatic caller yet; the stop observer and grant revocation will call `Store.recordControl`. A `withdraw_work` or `detach` event comes just before the `cancelled` or `abandoned` event it describes, so the existing event order for those is unchanged.
119
+
108
120
  ### Metrics
109
121
 
110
122
  `dalan metrics [--since RFC3339] [--json]` (default window: 30 days) derives queue latency, claim-to-first-activity, working/blocked/waiting/idle time against claimed time, lane utilization (see below), completed reports per day by kind, rework, duplicates and objective coverage, orphaned claims, check outcomes and owner acceptance from the lifecycle event table; `dalan status --explain` adds a one-line summary. A value the events cannot show is `{"value":null,"unknown_reason":"..."}`, never zero.
@@ -135,7 +147,7 @@ The bridge fetches the pinned commit into a private worktree. Fresh generic prof
135
147
 
136
148
  Before an implementation request with `execution=host` is admitted, the bridge validates check metadata and probes the `default` check's `prerequisites` (binaries in the host `/usr/bin`, lockfile at `base_sha`, `node>=N` runtime) and, only when the default has current owner authorization, refuses the submit with `BLOCKED: check prerequisites unmet: ...` instead of queueing work the default worker cannot verify. Current authorization requires an exact repository/check allowlist entry, an owner-configured definition and a valid owner budget; unmet prerequisites of an unauthorized default or other checks are warnings. For `execution=none` or `worker`, host probes are skipped and unreadable metadata does not block admission. `readiness_argv` is recorded as skipped, not executed on the host. In every execution mode, an implementation assignment that asks for a regression test must list a test path (for example `tests`, `scripts/foo-test.mjs`, or a directory that already holds colocated tests such as `internal/foo` with `bar_test.go`) in `scope_paths`, or it is refused with `regression_test_scope`. `dalan get ID --json` shows `check_metadata` (prerequisites, readiness_argv, test_paths and their `*_reason` when unknown); see [operations](operations.md#github-workspaces) for the override fields.
137
149
 
138
- `run_check` returns within about 20 seconds; a longer check returns `{check_run_id,status:"running"}`; poll `workspace_result` or `get` until it completes. Retrying the same check and diff while it runs returns the same ID. A restarted service marks an unfinished check `interrupted`, so start a new run after inspecting it. The worker can upload sealed evidence with `artifact_chunk` for any claimed assignment, including read-only work with no GitHub workspace. Both `workspace_result` and `get` list sealed uploads. The owner runs `dalan get ID --json` before `dalan artifact ARTIFACT_ID --output PATH` to establish the local artifact index.
150
+ `run_check` takes `request_id`, `claim_id` and `check_id`, all required. An unknown `check_id` returns the available IDs. If `run_check` is not exposed in the active worker catalog, the bridge can return `unknown tool` instead. This is not an unknown check ID, an executed check, or a reason to retry with different arguments; record it as unavailable and use the owner-approved test handoff. It returns within about 20 seconds; a longer check returns `{check_run_id,status:"running"}`; poll `workspace_result` or `get` until it completes. Retrying the same check and diff while it runs returns the same ID. A restarted service marks an unfinished check `interrupted`, so start a new run after inspecting it. The worker can upload sealed evidence with `artifact_chunk` for any claimed assignment, including read-only work with no GitHub workspace. Both `workspace_result` and `get` list sealed uploads. The owner runs `dalan get ID --json` before `dalan artifact ARTIFACT_ID --output PATH` to establish the local artifact index.
139
151
 
140
152
  ## Worker questions and owner notes
141
153
 
@@ -208,6 +220,14 @@ Partial check-definition example showing `argv` and `test_paths` only. This is n
208
220
  }}}}
209
221
  ```
210
222
 
223
+ ### Checks the requester names
224
+
225
+ An implementation assignment may carry `checks`: up to eight commands, each exactly `node <repo-relative .js, .mjs or .cjs path>`, for example `"checks": ["node scripts/a-test.mjs"]`. The worker sees them as `named/1` to `named/8` in `available_checks` and can run them with `run_check` until they pass.
226
+
227
+ - Submit refuses a malformed entry, a sensitive path, or a file that is not a regular file at the pinned revision (a new file must be in `output_paths`) with `invalid_named_check` and the entry number.
228
+ - The owner keeps authority. A named check runs only when the host allowlist permits the pair (repository, `named`) and the repository has an owner-configured `default` check; it takes that check's install step, limits and `host_budget`. Otherwise it is listed with the reason, for example `host_check_not_allowlisted: allow (repo, named) to run requester-declared checks`.
229
+ - At run time the bridge checks the stored entry, the allowlist pair and the owner's current `default` check again. Evidence records the exact argv as requester-declared, not as owner configuration.
230
+
211
231
  `dalan doctor --checks [--json]` lints the owner's `checks.json` against each repo's mirror on this host (files at HEAD and at the newest ref). For each repo it prints every check id with the test files its `argv` names, and warns when an id sounds like a test file that `argv` does not run (for example id `api-contract-check` and file `tests/api-contract.test.mjs` absent from `argv`). Invalid definitions print as `ERROR` and make the command exit 1; warnings never change the exit code. The name match is a heuristic on file stems and id words, so read each warning as a prompt to look, not a proof. A repo without a local mirror gets the file listing only. Run it after you edit `checks.json`.
212
232
 
213
233
  ## Work orders: dry run, verdicts, exit codes
@@ -272,11 +292,13 @@ The bridge logs every refused submit as `submit_rejected` (request ID, reason, s
272
292
  **Submit refuses instead of changing your request.** Implementation scope stays as declared unless you opt into a scope fix. Eligible free-form read-only and review jobs may grow scope automatically as described below. A refused submit stores nothing, keeps no receipt, and exits 2 (reject), 3 (clarify) or 4 (defer; see **Work orders** above) when the bridge returns a verdict (local validation failures exit 1), so a corrected retry under the same `request_id` goes through. Resubmitting an already accepted request with the same payload is still a duplicate match; the lint does not run again.
273
293
 
274
294
  - An implementation brief keeps `scope_paths` as its repository write allow-list, with explicit `output_paths` separately authorizing new files; a repository file the brief names outside those declared paths refuses as `undeclared instruction path`. A scope entry the tree lacks refuses as `unknown scope path`; a file the job should create belongs in `output_paths` (below). The refusal lists every such path and the fix, for example `fix: add these to scope_paths: web/app.js`, `fix: remove these from scope_paths: nope/a.md, nope/b.md` and `fix: corrected scope_paths: [...]` (`--json` carries the lines as `fix`; the 400 body carries `suggested_scope_paths`). A host path, `..` traversal or invalid name in the same brief withholds the suggestion: change the brief.
275
- - `--allow-scope-prune` is the opt-in for callers that want the old behaviour: submit applies `suggested_scope_paths` (adds the named files, drops unknown entries), retries once with the same `request_id`, and prints `changed scope_paths (added ...; removed ...)` to stderr. `--fix-scope` is the old spelling of the same opt-in; `--no-fix-scope` is now a no-op. The PR head reviewer passes `--allow-scope-prune`.
295
+ - `--allow-scope-prune` is the opt-in for callers that want the old behaviour: submit applies `suggested_scope_paths` (adds the named files, drops unknown entries), retries once with the same `request_id`, and prints `changed scope_paths (added ...; removed ...)` to stderr. `--fix-scope` is the old spelling of the same opt-in; `--no-fix-scope` is now a no-op.
276
296
  - A mention that predicts a broken job refuses with the fix in one message listing every offender: `ambiguous bare filename "dup.txt": it matches 2 repository paths outside scope_paths (...). Write the full path of the one you mean, for example docs/dup.txt instead of dup.txt`; `ambiguous abbreviated path "x/util.txt"` (same fix); `unknown bare filename "other.txt": it is not in the repository tree. Write the full repository path of the file (a new file needs its full path too; ./name names a file at the repository root), or remove the mention`. For jobs whose scope cannot grow automatically, a bare filename that resolves to one tree file outside scope names the full path to write: `undeclared instruction path: src/a.ts (the brief names it as "a.ts"; write the full path)`. A match already in scope satisfies the mention. For a new root file, mention `./name` and declare canonical `name` in `output_paths`.
277
297
  - Warnings that still queue are printed to stderr as `dalan: WARNING: ...` and returned as `submission_warnings`: a bare word that matches a path outside scope (prose, not a path); a directory outside scope; a route or host directory (`/tmp`) named in prose; a slash path the tree lacks (a new file or a branch name); an excluded file the brief does not name; no room for the allow-list; sensitive files dropped by `--exclude-sensitive`; and scope growth (below).
278
298
  - Still automatic, and reported as a warning: free-form read-only and `--review` work without structured objectives or explicit `read_paths` or `read_list` grows `scope_paths` by the files the brief names and the PR changes, and a free-form brief gets the allow-list appended (see below).
279
299
 
300
+ **Admission answer.** Every submit and `--dry-run` response carries `admission`: `start` (always `queued`; Dalan reserves no lane, so it never promises `now`), `ahead` (`count` and `oldest_age_ms` of the live queued jobs a claim serves first: every normal job before a background one, and within a class the jobs the worker has not passed over, oldest first), `latency` (claimed and started waits for this worker and job kind over 7 days, each `{n, p50_ms, p90_ms, insufficient_history}`, with expired, cancelled, never-started and finished-without-a-note jobs counted apart in `censored`), `track_record` (how this worker's ended jobs of the same kind finished over 7 days, each counted once in `outcomes`: `landed` (integrated, or the owner recorded `applied`), `check_passed`, `checks_failed`, `refused_by_provider` (an explicit provider-refusal report), `unable_to_run`, `owner_cancelled` and `finished_unchecked`; a plain acceptance is not counted as landed), `worker_state` (`live`, `paused`, `break` with `until`, or `no_live_subscription`) and `at`. Below 5 samples a latency has no numbers. These are measured facts, not a promise; cancel and route elsewhere if they do not suit you. The T3 child task prints them as its first line.
301
+
280
302
  ## Creating new files (output_paths)
281
303
 
282
304
  `scope_paths` names files or directories that already exist at `base_sha`. A new file cannot itself be a scope entry (`unknown scope path`). Explicit `output_paths` separately authorize new files as readable and writable outputs, including outputs outside `scope_paths`. A read-only job may write only these declared outputs; it may not change existing scoped inputs or arbitrary files. Without `output_paths`, it has no writable files.
@@ -321,14 +343,18 @@ Every result you request gets one recorded decision. `dalan decide ID WORD [--no
321
343
 
322
344
  After reading a finished result, record your decision with `dalan decide ID WORD`. The ACP adapter also includes a decision command in its reply.
323
345
 
324
- **`dalan apply ID [--dir PATH]`** (default the current directory) downloads the patch artifact and checks its sha256 against the build evidence, then checks that the job's base commit is an ancestor of the checkout's HEAD (or HEAD itself), then runs `git apply --check` and `git apply`. Any failed gate prints the reason and changes nothing. On success it records `applied`. If the decision call fails after the patch applied, the error says so and gives the `decide` command.
346
+ **`dalan apply ID [--dir PATH]`** (default the current directory) downloads the patch artifact and checks its sha256 against the build evidence, then checks that the job's base commit is an ancestor of the checkout's HEAD (or HEAD itself), then runs `git apply --check`. It then works in two phases, so that the bridge never records an apply that did not happen. (1) The bridge reserves the apply and returns an attempt token. Every run reserves, a first run and a resumed one alike, and the stale check is made in the same transaction: the bridge refuses with `stale_revision` if a correction of the job (`--revises`) exists, including one that landed while the patch was downloading or after an earlier run's reservation, and the directory is untouched. A reserve on an open reservation takes it over with a new token, and the earlier run's token is then refused. A correction that lands after this run's reservation is new work and does not stop this apply: the stale fence is at the reservation. (2) The CLI writes the patch, only with a token from this run. If the write fails part-way, it puts every touched file back, releases the reservation and prints `apply_failed`; the tree is as it was and the job is not applied. (3) The CLI asks the bridge to record `applied`, with its token. If the process dies or the answer is lost between the write and the confirm, `dalan get` shows `apply.state: applying` with `uncertain: true`. Run `dalan apply ID` again: when the tree already holds the patch (a reverse `git apply --check` passes), it reserves again (the stale check still runs) and confirms without writing; otherwise it writes the patch and confirms. A process killed during the write itself can leave a partly changed tree that the CLI cannot restore. With an open reservation and a tree that matches neither the patch nor its base, the CLI changes nothing, keeps the reservation, and prints that the checkout may be partly changed, the request, the files the patch touches and the recovery steps: inspect them with `git diff -- FILES`, restore them with `git checkout -- FILES` (this discards edits to those files only; delete any of them that the patch created), then run `dalan apply ID` again. If a correction landed after the crash, the re-run is refused with `stale_revision` and records nothing: it prints that the working tree contains the superseded patch, names the correction, and gives the undo command (`git apply -R` of the saved patch) or `dalan apply ID --release` and a revert by hand. **`dalan apply ID --release`** gives up an uncertain apply on purpose: the reservation is released, the job stays not applied, and no file is touched.
347
+
348
+ **`dalan materialize ID --dry-run [--json]`** lists the repository, base, and touched files of a current finished patch and previews the grant decision. It reads the owner's `materialize.json` beside `checks.json`: `{"mode":"standing","grant":["org:example-owner","repo:another-owner/example-repo"]}`. Use `per_pr` to require per-PR approval for a matching repository. Matches are exact and case-insensitive; no file means no standing grant. Invalid, symlinked, or non-private grants are refused. The preview does not claim the result, apply the patch, open a PR, or push.
349
+
350
+ **`dalan materialize ID [--dir PATH] [--approve] [--json]`** uses the same grant. `--approve` authorizes a matching per-PR grant for this invocation, not an unlisted repository. On an eligible result it creates a temporary detached worktree, commits with the local Git identity, and pushes only `dalan/ID` to the exact GitHub repository before opening a draft PR. It refuses to overwrite an existing branch with different content. If the draft cannot be confirmed after the push, the command reports the remaining branch. It does not merge or mark the job applied.
325
351
 
326
- **ACP adapter.** After a build result with a patch, the adapter remembers it for the session (the last 5). On the next prompt it checks whether the patch reverses cleanly against the working directory. A match produces an advisory message once. It never records an owner decision: the same change could predate the build or be a rejected trial. Only an explicit decision or a successful `dalan apply` records `applied`; neither proves verified owner use.
352
+ **ACP adapter.** Before saving a finished build answer, the adapter checks the owner's `materialize.json`. With a standing grant, a sealed patch, one repository and a pinned base, it publishes `dalan/ID` and opens a draft PR, then includes the branch and PR URL before the patch. The session working directory must be a Git checkout with exactly one matching GitHub push remote. If the base commit is missing, the adapter fetches that commit from the matching remote. A per-PR grant never authorizes automatic publication. Without a standing grant, or on any publication failure, the answer keeps the patch and adds `Not published: REASON`. Saved completion text is replayed without publishing again; a retry before saving reuses a matching branch without another push. After a build result with a patch, the adapter remembers it for the session (the last 5). On the next prompt it checks whether the patch reverses cleanly against the working directory. A match produces an advisory message once. It never records an owner decision: the same change could predate the build or be a rejected trial. Only an explicit decision or a successful `dalan apply` records `applied`; neither proves verified owner use.
327
353
 
328
354
 
329
355
  ## Directory scopes and sensitive files
330
356
 
331
- A directory in `scope_paths` can hold a sensitive file the submitter never named (for example `.env` or a credential file). By default the whole submit fails with `sensitive scope path: <file>`. `dalan submit --exclude-sensitive` drops those files from the scope instead: the stored `scope_paths` becomes the smallest list of directories and files that covers everything else, and `scope_excluded` (path and reason, one entry per file) is stored with the assignment, logged as `scope_excluded`, and returned in the submit response. The brief gets a one-line note naming them. `scope_paths` is enforced by bridge workspace tools: `list_files` omits excluded paths and `read_file` refuses them. This does not sandbox an agent's unrelated external tools. `read_paths` and `read_list` follow the narrowed scope. This only narrows the scope, and only for read-only work: an implementation scope is not narrowed, because a file list would forbid new files. The narrowing also covers the files a PR's diff touches, and the instruction size limit applies to the narrowed result. A submitter cannot send `scope_excluded` itself. A retry's response repeats it from the stored assignment. A path the submitter named still fails: an explicit scope entry, a path in the brief or read list, or a file in the diff. If narrowing would need more than 200 entries, the original scope (including `.`) remains and `scope_excluded` still denies every dropped file. If every file is sensitive, submission still fails. The flag is not part of the request identity: a retry with or without it is a duplicate.
357
+ A directory in `scope_paths` can hold a sensitive file the submitter never named. A file whose name only looks sensitive (the soft rule: names with auth, secret, credential, signing or a credential-style token word; code and Markdown files are exempt) is dropped from a read-only scope by default, with the reason `soft sensitive name (dropped, not refused)`; the rest of this paragraph applies to it without the flag. A hard-named file (for example `.env`, a key or a credential store) or a path under the owner's `sensitive_paths` still fails the whole submit with `hard sensitive path exclusion: <file>` or `sensitive scope path: <file>`, and an implementation scope still fails on any of them. `dalan submit --exclude-sensitive` drops those files from the scope instead: the stored `scope_paths` becomes the smallest list of directories and files that covers everything else, and `scope_excluded` (path and reason, one entry per file) is stored with the assignment, logged as `scope_excluded`, and returned in the submit response. The brief gets a one-line note naming them. `scope_paths` is enforced by bridge workspace tools: `list_files` omits excluded paths and `read_file` refuses them. This does not sandbox an agent's unrelated external tools. `read_paths` and `read_list` follow the narrowed scope. This only narrows the scope, and only for read-only work: an implementation scope is not narrowed, because a file list would forbid new files. The narrowing also covers the files a PR's diff touches, and the instruction size limit applies to the narrowed result. A submitter cannot send `scope_excluded` itself. A retry's response repeats it from the stored assignment. A path the submitter named still fails: an explicit scope entry, a path in the brief or read list, or a file in the diff. For a soft or owner-listed name, the refusal names the rule it matched and says to rename or redact the file, or leave it out of `scope_paths`. If narrowing would need more than 200 entries, the original scope (including `.`) remains and `scope_excluded` still denies every dropped file. If every file is sensitive, submission still fails. The flag is not part of the request identity: a retry with or without it is a duplicate.
332
358
 
333
359
 
334
360
  **Allow-list in the brief.** The bridge documents the authorized read allow-list in the brief: it appends `Read allow-list (scope_paths; ...)` with every scope path to a free-form brief (structured briefs already have one), subject to the size limits. A brief that mentions an excluded file without naming it gets a submission warning. A retry with the original assignment still matches.
@@ -181,7 +181,7 @@ Each native attempt is approved by its own code, and a later attempt cannot take
181
181
 
182
182
  ### Worked example: Codex CLI on another computer
183
183
 
184
- This example uses a bridge from `dalan service install --worker NAME --route tailscale` ([service setup](service-setup.md)) and Codex CLI on the worker computer. No reverse proxy and no domain of your own are involved.
184
+ This example uses a bridge from `dalan service install --worker NAME` ([service setup](service-setup.md)) and Codex CLI on the worker computer. No reverse proxy and no domain of your own are involved.
185
185
 
186
186
  1. On the bridge computer, allow the callback and open a pairing window:
187
187
 
@@ -9,5 +9,9 @@ export const createRefuse = RequestError => (message, data) => data === undefine
9
9
  export const T3_CANCEL_WINDOW_MS = 10_000;
10
10
  export const CANCEL_BUDGET_MS = 5_000;
11
11
  export const CANCEL_CLEANUP_MS = 2_000;
12
- // A positive finite number (for example from an environment variable), else the default.
13
- export const cancelBudgetMs = raw => Number.isFinite(Number(raw)) && Number(raw) > 0 ? Number(raw) : CANCEL_BUDGET_MS;
12
+ // An override must leave the cancellation cleanup budget inside T3's response window.
13
+ export function cancelBudgetMs(raw) {
14
+ const requested = Number(raw);
15
+ const max = T3_CANCEL_WINDOW_MS - CANCEL_CLEANUP_MS;
16
+ return Number.isFinite(requested) && requested > 0 && requested <= max ? requested : CANCEL_BUDGET_MS;
17
+ }
@@ -1,6 +1,6 @@
1
1
  // Single-owner session lock that works on Linux and macOS without flock.
2
2
  //
3
- // The lock is a file created with O_EXCL (open 'wx', mode 0600) that holds JSON { pid, start_time, token, host }.
3
+ // The lock is a complete mode-0600 file published with an exclusive hard link that holds JSON { pid, start_time, token, host }.
4
4
  // start_time an opaque string for the owner process's start (Linux: boot id + /proc/<pid>/stat field 22;
5
5
  // macOS: `ps -o lstart=`). Two processes with one pid have different start_time values.
6
6
  // token random; release removes the file only while it still holds our token.
@@ -10,14 +10,14 @@
10
10
  // left by the earlier flock-based adapter).
11
11
  //
12
12
  // Race-safe takeover. Naive "unlink the stale file, then create" lets a slow taker unlink a lock that a fast taker just
13
- // created. So a taker first creates a guard file `<lock>.takeover.<key>.<n>` with O_EXCL, where <key> names the stale
13
+ // created. So a taker first publishes a guard file `<lock>.takeover.<key>.<n>` exclusively, where <key> names the stale
14
14
  // generation it saw (the stale record's token). Under the guard it re-reads the lock; it unlinks only if the file is still
15
- // that same stale generation. Then it creates the lock with O_EXCL. Why this holds:
16
- // - Only a guard holder deletes a stale lock, and a guard name is created by one process at a time (O_EXCL); a guard is
15
+ // that same stale generation. Then it creates the lock exclusively. Why this holds:
16
+ // - Only a guard holder deletes a stale lock, and a guard name is published by one process at a time; a guard is
17
17
  // removed only by its creator when done, so two takers are never inside the section for one (key, n).
18
18
  // - A guard whose creator is dead is never removed by others; takers move on to n+1. A late taker that reuses a name after
19
19
  // the first taker finished re-reads the lock, sees a different generation and backs off.
20
- // - Lock creation is always O_EXCL, so if a third process creates the lock first, the taker loses and reports busy.
20
+ // - Lock publication never overwrites an existing name, so if a third process creates the lock first, the taker loses and reports busy.
21
21
  // - A live owner is never stale, so nobody deletes a live owner's lock; the owner's own release checks the token.
22
22
  import { randomBytes } from 'node:crypto';
23
23
  import { execFileSync } from 'node:child_process';
@@ -28,11 +28,12 @@ import path from 'node:path';
28
28
  export const UNREADABLE_GRACE_MS = 3000;
29
29
 
30
30
  export class LockBusyError extends Error {
31
- constructor(owner) {
31
+ constructor(owner, reason = 'holder_live') {
32
32
  super(`this session is active in another adapter (pid ${owner?.pid ?? 'unknown'})`);
33
33
  this.name = 'LockBusyError';
34
34
  this.code = 'session_busy';
35
35
  this.pid = owner?.pid ?? null;
36
+ this.reason = reason;
36
37
  }
37
38
  }
38
39
 
@@ -86,10 +87,24 @@ const held = new Set();
86
87
  process.once('exit', () => { for (const release of [...held]) release(); });
87
88
 
88
89
  function createExclusive(file, record) {
89
- let fd;
90
- try { fd = fs.openSync(file, 'wx', 0o600); } catch (error) { if (error.code === 'EEXIST') return false; throw error; }
91
- try { fs.writeSync(fd, JSON.stringify(record)); } finally { fs.closeSync(fd); }
92
- return true;
90
+ const staged = `${file}.write-${randomBytes(12).toString('hex')}`;
91
+ const fd = fs.openSync(staged, 'wx', 0o600);
92
+ try {
93
+ try {
94
+ const text = JSON.stringify(record);
95
+ if (fs.writeSync(fd, text) !== Buffer.byteLength(text)) throw new Error('short lock record write');
96
+ } finally { fs.closeSync(fd); }
97
+ // Link publishes a complete record and can never replace a different owner.
98
+ try { fs.linkSync(staged, file); }
99
+ catch (error) { if (error.code === 'EEXIST') return false; throw error; }
100
+ return true;
101
+ } catch (error) {
102
+ throw new Error(`could not publish lock record: ${error.message}`, { cause: error });
103
+ } finally {
104
+ // Always remove this call's private name, never the shared lock path.
105
+ try { fs.rmSync(staged, { force: true }); }
106
+ catch { console.warn('could not remove private lock staging file'); }
107
+ }
93
108
  }
94
109
 
95
110
  // Returns true when we removed the stale generation `seen`; false when it changed or a live taker is working on it.
@@ -111,7 +126,14 @@ async function takeOver(file, seen, guardWaitMs) {
111
126
  }
112
127
  try {
113
128
  const now = inspect(file);
114
- if (now && now.key === seen.key && now.stale) fs.rmSync(file, { force: true });
129
+ if (now && now.key === seen.key && now.stale) {
130
+ try { fs.rmSync(file, { force: true }); }
131
+ catch (error) {
132
+ // A directory is not a lock record; report a busy path without deleting it.
133
+ if (error.code === 'ERR_FS_EISDIR') return false;
134
+ throw error;
135
+ }
136
+ }
115
137
  return true; // the generation we saw is gone (by us, or already replaced); the caller retries creation
116
138
  } finally {
117
139
  fs.rmSync(guard, { force: true });
@@ -128,7 +150,9 @@ function cleanupGuards(file, key) {
128
150
  }
129
151
  }
130
152
 
131
- // Acquire the lock at `file`. Resolves { token, release } or rejects with LockBusyError while a live owner holds it.
153
+ // Acquire the lock at `file`. Resolves { token, release } or rejects with LockBusyError (code session_busy).
154
+ // The error's `reason` is 'holder_live' when a live owner holds the lock and 'takeover_timeout' when a
155
+ // stale lock could not be taken over within the wait/attempt budget.
132
156
  export async function acquireLock(file, { attempts = 8, guardWaitMs = 2000 } = {}) {
133
157
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
134
158
  const token = randomBytes(16).toString('hex');
@@ -138,8 +162,13 @@ export async function acquireLock(file, { attempts = 8, guardWaitMs = 2000 } = {
138
162
  if (createExclusive(file, record)) {
139
163
  const release = () => {
140
164
  held.delete(release);
141
- const now = inspect(file);
142
- if (now?.record?.token === token) fs.rmSync(file, { force: true });
165
+ try {
166
+ const now = inspect(file);
167
+ if (now?.record?.token === token) fs.rmSync(file, { force: true });
168
+ } catch (error) {
169
+ // A replaced parent means the old lock is no longer at this path.
170
+ if (error.code !== 'ENOTDIR') throw error;
171
+ }
143
172
  };
144
173
  held.add(release);
145
174
  return { token, release };
@@ -147,9 +176,9 @@ export async function acquireLock(file, { attempts = 8, guardWaitMs = 2000 } = {
147
176
  const seen = inspect(file);
148
177
  if (!seen) continue; // removed between our create and read: try again
149
178
  lastOwner = seen.record;
150
- if (!seen.stale) throw new LockBusyError(seen.record);
151
- if (!(await takeOver(file, seen, guardWaitMs))) throw new LockBusyError(seen.record);
179
+ if (!seen.stale) throw new LockBusyError(seen.record, 'holder_live');
180
+ if (!(await takeOver(file, seen, guardWaitMs))) throw new LockBusyError(seen.record, 'takeover_timeout');
152
181
  cleanupGuards(file, seen.key);
153
182
  }
154
- throw new LockBusyError(lastOwner);
183
+ throw new LockBusyError(lastOwner, 'takeover_timeout');
155
184
  }
@@ -23,14 +23,26 @@ export const sessionPath = (dir, id, suffix = '.json') => path.join(dir, `${asse
23
23
  export function writeJsonPrivate(file, value, { pretty = false } = {}) {
24
24
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
25
25
  const tmp = `${file}.${process.pid}.tmp`;
26
- fs.writeFileSync(tmp, pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value), { mode: 0o600 });
27
- fs.renameSync(tmp, file);
26
+ const json = pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
27
+ try {
28
+ fs.writeFileSync(tmp, json, { mode: 0o600 });
29
+ fs.renameSync(tmp, file);
30
+ } catch (error) {
31
+ // The destination is unchanged; do not strand this attempt's temp file.
32
+ try { fs.rmSync(tmp, { force: true }); } catch { /* preserve the original failure */ }
33
+ throw error;
34
+ }
28
35
  }
29
36
 
30
37
  // null when the file does not exist; throws state_permissions when it is not exactly 0600.
31
38
  export function readJsonPrivate(file) {
32
39
  try { assertPrivate(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
33
- return JSON.parse(fs.readFileSync(file, 'utf8'));
40
+ let text;
41
+ try { text = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
42
+ try { return JSON.parse(text); } catch (error) {
43
+ if (!(error instanceof SyntaxError)) throw error;
44
+ throw Object.assign(new Error('Saved session is unreadable; start a new session or restore the saved state.'), { code: 'invalid_session_state' });
45
+ }
34
46
  }
35
47
 
36
48
  export const removePrivate = file => fs.rmSync(file, { force: true });
@@ -19,6 +19,8 @@ export function unwrapUserRequest(prompt) {
19
19
  const open = '<user_request>\n';
20
20
  if (!rest.startsWith(open)) return stripTrailingT3Blocks(rest);
21
21
  const body = rest.slice(open.length);
22
+ // The opening newline also separates the tags when the request is empty.
23
+ if (body.startsWith(CLOSE) && TRAILING_T3_BLOCKS.test(body.slice(CLOSE.length))) return '';
22
24
  for (let at = body.lastIndexOf(CLOSE); at > 0; at = body.lastIndexOf(CLOSE, at - 1)) {
23
25
  if (body[at - 1] === '\n' && TRAILING_T3_BLOCKS.test(body.slice(at + CLOSE.length))) return body.slice(0, at - 1);
24
26
  }
@@ -49,6 +51,10 @@ export function promptText(blocks) {
49
51
  // T3's delegate_task puts this before the task for every role except general (and none).
50
52
  const rolePreamble = /^Act as the (?:implementation|research|review|design|test) sub-agent for this task\.\n\n/;
51
53
  export const stripRolePreamble = text => text.replace(rolePreamble, '');
54
+ // When an agent (not the user) sends the task, T3 first adds one attribution line naming the sending thread.
55
+ // Only a leading copy is removed; the same words later in a brief are the requester's own text.
56
+ const agentAttribution = /^\[T3 Code: the agent in T3 thread "[^"\n]{1,300}" sent this message, not the user\.\][ \t]*\r?\n(?:[ \t]*\r?\n)*/;
57
+ export const stripAgentAttribution = text => text.replace(agentAttribution, '');
52
58
 
53
59
  // Identity from a first line `[<prefix>:<id>]`. `prefix` is the adapter's tag (`dot-decision`, `example-request`); `idPattern`
54
60
  // decides which ids are valid (an invalid id gives id null; the token line is still removed from `brief`).
@@ -56,7 +62,9 @@ export const stripRolePreamble = text => text.replace(rolePreamble, '');
56
62
  // no token); `brief` is `text` without the token line, trimmed.
57
63
  export function parseIdentity(input, { prefix, idPattern = /^[-\w]{8,128}$/ }) {
58
64
  if (!/^[\w-]+$/.test(prefix)) throw new Error('prefix must be word characters and hyphens');
59
- const text = stripRolePreamble(input.replace(/^\s*\n/, ''));
65
+ const text = stripRolePreamble(stripAgentAttribution(input.replace(/^\s*\n/, '')));
60
66
  const m = new RegExp(`^\\[${prefix}:([^\\]\\s]+)\\][ \\t]*(?:\\r?\\n|$)`).exec(text);
61
- return { id: m && idPattern.test(m[1]) ? m[1] : null, text, brief: (m ? text.slice(m[0].length) : text).trim() };
67
+ // RegExp.test mutates global and sticky patterns; each ID starts at offset zero.
68
+ const matcher = idPattern.global || idPattern.sticky ? new RegExp(idPattern) : idPattern;
69
+ return { id: m && matcher.test(m[1]) ? m[1] : null, text, brief: (m ? text.slice(m[0].length) : text).trim() };
62
70
  }