@tnunamak/dalan 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +351 -0
  5. package/README.md +215 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +43 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +764 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/codex-to-muse.md +175 -0
  17. package/docs/connect-chatgpt.md +83 -0
  18. package/docs/connection-longevity.md +43 -0
  19. package/docs/dalan-upgrade.md +246 -0
  20. package/docs/deadman.md +61 -0
  21. package/docs/dot-pr-reviewer.config.example.json +9 -0
  22. package/docs/durability-audit.md +27 -0
  23. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  24. package/docs/keycloak-oauth-setup.md +30 -0
  25. package/docs/local-agent-mcp.md +41 -0
  26. package/docs/manual-setup.md +135 -0
  27. package/docs/mirror-fetch.md +97 -0
  28. package/docs/operations.md +799 -0
  29. package/docs/operator-duties.md +68 -0
  30. package/docs/owner-integrator.md +27 -0
  31. package/docs/portable-auth-profile.md +107 -0
  32. package/docs/pr-head-reviewer.md +70 -0
  33. package/docs/pr-preflight.md +28 -0
  34. package/docs/pull-queue.md +131 -0
  35. package/docs/pull-workers.md +94 -0
  36. package/docs/redaction.md +27 -0
  37. package/docs/service-setup.md +219 -0
  38. package/docs/setup-reference.md +80 -0
  39. package/docs/t3-connector-icon.png +0 -0
  40. package/docs/t3-integration.md +51 -0
  41. package/docs/t3-result-retry-delivery.md +41 -0
  42. package/docs/t3-reverse-control.md +107 -0
  43. package/docs/usage.md +443 -0
  44. package/docs/worker-clients.md +290 -0
  45. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  46. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  47. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  48. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  49. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  50. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  51. package/package.json +67 -4
  52. package/packages/job-core/README.md +18 -0
  53. package/packages/job-core/index.mjs +2 -0
  54. package/packages/job-core/package.json +8 -0
  55. package/packages/job-core/protocol/canonical.mjs +11 -0
  56. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  57. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  58. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  59. package/packages/job-core/transitions.mjs +25 -0
  60. package/scripts/daily-selfcheck.mjs +135 -0
  61. package/scripts/dalan-try-selfcheck.mjs +29 -0
  62. package/scripts/lib/expose-tailscale.mjs +408 -0
  63. package/scripts/live-trial/common.mjs +272 -0
  64. package/scripts/monitor-targets.mjs +44 -0
  65. package/scripts/upgrade-drain.mjs +39 -0
  66. package/scripts/worker-bridge-setup.mjs +925 -0
  67. package/src/ack-ledger.mjs +37 -0
  68. package/src/acp-bridge.mjs +418 -0
  69. package/src/acp-context.mjs +138 -0
  70. package/src/admin-socket.mjs +14 -0
  71. package/src/alerts.mjs +147 -0
  72. package/src/artifact-journal.mjs +75 -0
  73. package/src/as-files.mjs +347 -0
  74. package/src/as-store.mjs +456 -0
  75. package/src/as.mjs +538 -0
  76. package/src/auth.mjs +166 -0
  77. package/src/builtin-http.mjs +22 -0
  78. package/src/check-coverage.mjs +38 -0
  79. package/src/check-lint.mjs +88 -0
  80. package/src/check-readiness.mjs +112 -0
  81. package/src/check-response.mjs +19 -0
  82. package/src/child-exit.mjs +18 -0
  83. package/src/child-registry.mjs +94 -0
  84. package/src/claim-command-ledger.mjs +51 -0
  85. package/src/cli-help.mjs +186 -0
  86. package/src/cli-name.mjs +16 -0
  87. package/src/connect-cli.mjs +126 -0
  88. package/src/consumers.mjs +61 -0
  89. package/src/deadman.mjs +329 -0
  90. package/src/delivery.mjs +19 -0
  91. package/src/demo-worker.mjs +150 -0
  92. package/src/destinations/index.mjs +23 -0
  93. package/src/destinations/none.mjs +15 -0
  94. package/src/destinations/t3.mjs +109 -0
  95. package/src/diagnostic.mjs +78 -0
  96. package/src/docs-url.mjs +9 -0
  97. package/src/drain-runner.mjs +9 -0
  98. package/src/drained-owner.mjs +26 -0
  99. package/src/drained-slot.mjs +70 -0
  100. package/src/drained.mjs +40 -0
  101. package/src/durable-waiters.mjs +236 -0
  102. package/src/env.mjs +19 -0
  103. package/src/execution.mjs +112 -0
  104. package/src/failure-type.mjs +28 -0
  105. package/src/get-summary.mjs +32 -0
  106. package/src/git-env.mjs +15 -0
  107. package/src/host-budget-receipts.mjs +154 -0
  108. package/src/host-budget-seccomp.py +33 -0
  109. package/src/host-budget-service.mjs +54 -0
  110. package/src/host-budget-stop.mjs +26 -0
  111. package/src/host-budget-storage.py +259 -0
  112. package/src/host-budget.mjs +149 -0
  113. package/src/host-cgroup.mjs +23 -0
  114. package/src/host-check-allowlist.mjs +42 -0
  115. package/src/host-execution-policy.mjs +38 -0
  116. package/src/host-health.mjs +34 -0
  117. package/src/host-stop-reverify.mjs +44 -0
  118. package/src/inbox.mjs +55 -0
  119. package/src/integrator.mjs +322 -0
  120. package/src/job-retention.mjs +69 -0
  121. package/src/legacy-names.mjs +8 -0
  122. package/src/lifecycle.mjs +291 -0
  123. package/src/limits.mjs +31 -0
  124. package/src/loopback.mjs +9 -0
  125. package/src/mcp-outcome.mjs +79 -0
  126. package/src/mcp-sse.mjs +62 -0
  127. package/src/mcp-stdio.mjs +191 -0
  128. package/src/mirror-fetch-lock.py +164 -0
  129. package/src/mirror-fetch.mjs +174 -0
  130. package/src/notify-ledger.mjs +82 -0
  131. package/src/objectives.mjs +129 -0
  132. package/src/owner-report-artifact.mjs +66 -0
  133. package/src/patch-apply.mjs +84 -0
  134. package/src/path-syntax.mjs +16 -0
  135. package/src/paths.mjs +67 -0
  136. package/src/pr-head-reviewer.mjs +596 -0
  137. package/src/pr-preflight.mjs +51 -0
  138. package/src/prepared-node-modules.mjs +129 -0
  139. package/src/process-inspection.mjs +36 -0
  140. package/src/projects.mjs +480 -0
  141. package/src/protocol-artifact-commands.mjs +52 -0
  142. package/src/protocol-delivery-driver.mjs +167 -0
  143. package/src/protocol-finish.mjs +100 -0
  144. package/src/protocol-owner-command.mjs +35 -0
  145. package/src/protocol-owner-mutations.mjs +22 -0
  146. package/src/protocol-owner-waiters.mjs +67 -0
  147. package/src/protocol-retention.mjs +52 -0
  148. package/src/protocol-services.mjs +61 -0
  149. package/src/protocol-stop-observer.mjs +131 -0
  150. package/src/publish-plan.mjs +245 -0
  151. package/src/pull-queue.mjs +159 -0
  152. package/src/redaction.mjs +763 -0
  153. package/src/rejections.mjs +18 -0
  154. package/src/request-log.mjs +102 -0
  155. package/src/restore-check.mjs +90 -0
  156. package/src/result-binding.mjs +65 -0
  157. package/src/route-setting.mjs +24 -0
  158. package/src/runtime-check.mjs +13 -0
  159. package/src/sandbox-supervisor.mjs +105 -0
  160. package/src/schema-subset.mjs +186 -0
  161. package/src/scopes.mjs +15 -0
  162. package/src/server.mjs +1468 -0
  163. package/src/service-migrate-workers.mjs +113 -0
  164. package/src/service.mjs +388 -0
  165. package/src/setup.mjs +63 -0
  166. package/src/shutdown-signal.mjs +12 -0
  167. package/src/signal-sandbox-processes.py +56 -0
  168. package/src/signal.mjs +119 -0
  169. package/src/status-evidence.mjs +47 -0
  170. package/src/status-summary.mjs +54 -0
  171. package/src/store.mjs +3069 -0
  172. package/src/submission-policy.mjs +623 -0
  173. package/src/subscription-storage.mjs +64 -0
  174. package/src/t3-audit.mjs +120 -0
  175. package/src/t3-control.mjs +102 -0
  176. package/src/t3-transport.mjs +158 -0
  177. package/src/t3.mjs +209 -0
  178. package/src/terminal-safe.mjs +19 -0
  179. package/src/tool-registry.mjs +453 -0
  180. package/src/try-command.mjs +11 -0
  181. package/src/try-exposure.mjs +908 -0
  182. package/src/try-hosted-clients.mjs +46 -0
  183. package/src/try-hosted.mjs +444 -0
  184. package/src/try-selfcheck.mjs +168 -0
  185. package/src/try.mjs +635 -0
  186. package/src/webhooks.mjs +86 -0
  187. package/src/work-order.mjs +265 -0
  188. package/src/worker-instructions.mjs +26 -0
  189. package/src/worker-prompt.mjs +4 -0
  190. package/src/workers.mjs +632 -0
  191. package/src/workspace.mjs +1065 -0
  192. package/systemd/dot-bridge-heartbeat.service +18 -0
  193. package/systemd/dot-bridge-heartbeat.timer +10 -0
  194. package/systemd/dot-bridge-selfcheck.service +12 -0
  195. package/systemd/dot-bridge-selfcheck.timer +11 -0
  196. package/systemd/dot-bridge.service +17 -0
  197. package/systemd/dot-deadman.service +30 -0
  198. package/systemd/dot-pr-reviewer.service +11 -0
  199. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,186 @@
1
+ // Help text and command lookup for the `dalan` CLI. Its only I/O is reading the package version for docs links, so `bin/dalan.mjs` can answer help
2
+ // requests before it loads the rest of the CLI.
3
+ import { docsUrl } from './docs-url.mjs';
4
+
5
+ // Order matters: it is the order of the help screens. `group` is where a command shows on the short screen;
6
+ // commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
7
+ // `dalan help --internal`. Every command runs and has its own help either way.
8
+ export const COMMANDS = [
9
+ { name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--client chatgpt|claude] [--route auto|gozar|localhost.run|tailscale]] [--home DIR] [--port N] [--callback PATTERN]...',
10
+ detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client such as ChatGPT or claude.ai (the default). `auto` honors a saved temporary-relay choice; otherwise it uses a usable Tailscale route and selects Gozar if no Tailscale route is usable. When it selects Gozar, Dalan names tunnl.gg, links its terms and privacy notice, and asks for consent before exposure. After consent, bundled Gozar creates an installation-owned key and opens the temporary demo link through tunnl.gg. Dalan never uses your SSH keys. The relay ends TLS and can see the connector URL and traffic; the link can stop or change without warning, including within minutes.',
11
+ 'Dalan checks the original public address and ends the trial when it detects a change or route loss. The trial itself ends after 3 hours at most. Ctrl-C stops the run; Dalan closes its forwarding gate and attempts to remove its route. If cleanup cannot be confirmed, it reports this and prints a recovery command. Keep private work out of the demo. A Tailscale route is separate from the temporary relay. Choose this computer only, or pass --local, for a',
12
+ 'self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
13
+ 'Options:', ' --local this computer only', ' --public public trial with the chatgpt or claude sign-in profile (other clients: see Connect any MCP worker in the README)', ' --client NAME chatgpt (default) or claude; implies --public',
14
+ '', 'When `auto` selects Gozar because a temporary-relay choice was saved or Tailscale is unavailable, Gozar supplies the tunnl.gg key-bound relay; Dalan keeps OAuth sign-in and identity checks. After consent, Gozar creates a private key for this installation. Dalan does not use your SSH keys. Gozar is bundled; no separate install is needed.',
15
+ ' --route NAME auto (saved temporary-relay choice, otherwise usable Tailscale, then bundled Gozar with relay consent), gozar, localhost.run or tailscale; implies --public', ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
16
+ ' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN local mode only: allow one more OAuth callback pattern; repeatable', '',
17
+ 'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a public trial creates a new home, and a usable Tailscale route on this computer uses ~/.local/share/dalan-hosted-<client>. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
18
+ { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
19
+ detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
20
+ 'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
21
+ { name: 'service', group: 'operator', summary: 'Install or migrate a long-running bridge service', usage: 'dalan service install|migrate-workers [options]',
22
+ detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
23
+ 'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]',
24
+ 'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
25
+ 'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
26
+ 'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
27
+ 'See docs/service-setup.md for routing and worker migration details.'] },
28
+ { name: 'init', group: 'start', summary: 'Create a bridge home and its first worker profile', usage: 'dalan init --public-url URL (--worker NAME [--enable-workspace] | --legacy) [--json]',
29
+
30
+ detail: ['Writes the built-in authorization server files and the first worker profile into the bridge home (DALAN_HOME).', 'It needs no running bridge.', '',
31
+ 'Options:', ' --public-url URL the address clients will use to reach the bridge: https://HOST, or',
32
+ ' http://127.0.0.1:PORT when DALAN_LOOPBACK=1 is set', ' --worker NAME create the first worker profile with this name', ' --enable-workspace allow this worker to use repository tools when the bridge enables them', ' --legacy keep the settings of an older single-worker host instead of creating a profile', ' --json print the result as JSON', '',
33
+ 'Example (a bridge on this computer only):', ' export DALAN_HOME="$HOME/.local/share/dalan-manual-trial"', ' export DALAN_LOOPBACK=1', ' dalan init --worker local --public-url http://127.0.0.1:8799'] },
34
+ { name: 'connect', group: 'start', summary: 'Pair a worker client with the bridge', usage: 'dalan connect <subcommand> [options]',
35
+ detail: ['Subcommands:', ' start --worker NAME [--minutes N] open a pairing window for a worker', ' pending [--json] show connection attempts waiting for approval',
36
+ ' approve CODE --worker NAME approve only the attempt with this code', ' [--confirm-redirect URI] required for a native client: the redirect you expect', ' [--replace] replace an existing connection for the worker',
37
+ ' list [--json] show connected workers', ' revoke NAME disconnect a worker', ' stop close the pairing window', ' reset clear pairing state',
38
+ ' add-client --redirect-uri URI [--name NAME] [--json] register an OAuth client', ' clients [--json] list OAuth clients', ' remove-client CLIENT_ID [--json] remove an OAuth client',
39
+ ' allow-callback PATTERN allow another OAuth callback pattern', ' signal-token [--worker NAME] [--rotate] [--json] show or rotate a worker signal token', '',
40
+ 'Examples (pair a worker named local):', ' dalan connect start --worker local', ' dalan connect pending', ' dalan connect approve CODE --worker local --confirm-redirect URI',
41
+ 'Replace CODE with the code that pending and the browser page both show.', 'For URI, use the callback you expect from your client\'s own configuration and compare it', 'with pending: do not approve when they differ or you cannot verify it.'] },
42
+ { name: 'submit', group: 'everyday', summary: 'Queue a job for a worker', usage: 'dalan submit (--file PATH | --stdin | --brief TEXT) [options]',
43
+ detail: ['Queues a job. Give it a JSON assignment (request_id, inputs, brief, ...) or, with --brief, plain text for a question that needs no files.', 'Prints the request ID.', '',
44
+ 'Options:', ' --file PATH | --stdin | --brief TEXT', ' where the job comes from (exactly one). --brief makes a read-only job with', ' no repository from TEXT, used exactly as typed', ' --eligible LIST route one read-only result to explicit workers; job needs valid_until', ' --policy PATH JSON routing policy and optional destination_revisions', ` pool setup and worker flow: ${docsUrl('docs/pull-queue.md')}`, ' --worker NAME queue for a named worker (default: the profile\'s only worker;', ' required when the profile has several)',
45
+ ' --thread ID deliver the result to a T3 Code thread (optional integration)', ' --deliver none|t3:ID delivery target (default: none; not with --thread)', ' --review ask for a review of work already done',
46
+ ' --wait wait for the result before returning', ' --timeout S with --wait: seconds to wait, 1 to 3600 (default: 300)', ' --dry-run check the assignment and store nothing',
47
+ ' --queue-anyway queue even when the bridge would defer or warn', ' --refuse-defer fail instead of deferring',
48
+ ' --allow-scope-prune when submit rejects the brief for naming files outside scope_paths, let it fix scope_paths and retry once',
49
+ ' --execution none|worker|host execution capability for the job (default: the profile\'s default_execution, none for a new profile)',
50
+ ' --require-capability LIST comma-separated backend capabilities the job needs (default: none)', ' --json print JSON', '',
51
+ 'Examples (the first job):',
52
+ ' dalan submit --worker local --execution none --deliver none --file first-job.json --json', ' dalan wait REQUEST_ID', ' dalan get REQUEST_ID', ' dalan decide REQUEST_ID accepted',
53
+ '', 'Example (a question that needs no files):', ' dalan submit --worker local --brief "What does a database index do?"', '',
54
+ 'Replace REQUEST_ID with the request_id that submit prints. Read the report before you accept it.', `first-job.json and the full walk-through: ${docsUrl('docs/manual-setup.md', 'submit-finish-and-read-the-result')}`] },
55
+ { name: 'status', group: 'everyday', summary: 'Show the bridge, queue and worker state', usage: 'dalan status [--explain] [--json]',
56
+ detail: ['Prints the bridge state.', '', 'Options:', ' --explain describe the state and recent metrics in plain words', ' --json print JSON', '', 'Example: dalan status, then dalan inbox --all'] },
57
+ { name: 'get', group: 'everyday', summary: 'Show one job (or message) by ID', usage: 'dalan get ID [--json]',
58
+ detail: ['Prints the job\'s state, progress, report and artifacts, and marks a finished result as read.', 'On a terminal it prints a short view; piped, or with --json, it prints the full JSON record.', '', 'Example: dalan get REQUEST_ID'] },
59
+ { name: 'wait', group: 'everyday', summary: 'Wait for a job to finish', usage: 'dalan wait ID [--timeout S] | wait --drained --producer-thread ID [--max-claimed N] [--max-queued N] [--timeout S]',
60
+ detail: ['Waits until job ID reaches a final state, or until the timeout. With --drained, waits until your queue has drained.', '',
61
+ 'Options:', ' --timeout S seconds to wait: 1 to 3600 for a job (default: 300); 1 to 86400 with --drained (default: 1740)', '',
62
+ '--drained needs --producer-thread ID unless the command runs inside a Claude Code or Codex session, which supplies it.', '',
63
+ 'Exit status for a job: 0 finished, 3 blocker or question, 4 cancelled, 5 the worker is on a usage break, 124 timeout (the job is still open), 1 error.', '', 'Example: dalan wait REQUEST_ID --timeout 3600, then dalan get REQUEST_ID.', 'Exit 124 leaves the job open; inspect it with dalan get before waiting again.'] },
64
+ { name: 'inbox', group: 'everyday', summary: 'List jobs and messages that need you', usage: 'dalan inbox [--all | --producer ID] [--since RFC3339] [--json] | dalan inbox --mark-read [ID...] [--before RFC3339]',
65
+ detail: ['Lists what needs you. A producer is the shell or agent session that submitted the job. Inside a Claude Code or Codex session, plain dalan inbox lists that session\'s jobs.', 'Outside a Claude Code or Codex session, plain dalan inbox lists every producer\'s jobs on this bridge home.', '--all lists every producer anywhere; --producer ID lists one.', '', 'Options:', ' --since, --before an RFC3339 time or a duration such as 72h or 3d', '', 'Default window: jobs updated in the last 72 hours. Questions are always listed. To see older results: dalan inbox --all --since all', '', 'Example: dalan inbox --all, then dalan get REQUEST_ID'] },
66
+ { name: 'decide', group: 'everyday', summary: 'Record your decision on a finished job', usage: 'dalan decide ID WORD [--note TEXT]',
67
+ detail: ['Records your decision on a finished job. Review the report or patch first.', '', 'WORD is one of: accepted, applied, useful_no_change, useful_negative, not_useful.', 'Example: dalan decide REQUEST_ID accepted'] },
68
+ { name: 'apply', group: 'everyday', summary: 'Apply a finished job\'s patch to a directory', usage: 'dalan apply ID [--dir PATH]',
69
+ detail: ['Applies the patch from a finished job to a directory (default: the current directory) and records the decision "applied" for you.', 'There is no need to accept the job first.'] },
70
+ { name: 'mcp', group: 'everyday', summary: 'Serve submit, wait, result and status as local MCP tools over stdio', usage: 'dalan mcp',
71
+ detail: ['Runs a local MCP server on standard input and output for an agent on this computer (Claude Code, Codex).', 'Tools: dalan_submit, dalan_wait, dalan_result, dalan_status. They run the same CLI commands, with the same access to the admin socket.', 'Only protocol messages go to standard output; logs go to standard error. See docs/local-agent-mcp.md.'] },
72
+ { name: 'worker', group: 'operator', summary: 'Choose which repositories a worker may use', usage: 'dalan worker allow|deny NAME OWNER/REPO [--json] | worker list [NAME] [--json] | worker migrate-repos [--json]',
73
+ detail: ['Subcommands:', ' allow NAME OWNER/REPO let a worker use a repository', ' deny NAME OWNER/REPO stop a worker using it', ' list [NAME] show each worker\'s repository access', ' migrate-repos convert an old repository policy; stop the service first'] },
74
+ { name: 'tool', group: 'operator', summary: 'Register tools and choose which workers may call them', usage: 'dalan tool add --file PATH | remove NAME | list | grant NAME WORKER | revoke NAME WORKER [--json]',
75
+ detail: ['Manages the owner-side tool registry. A worker sees and calls only the tools granted to it. Changing the registry never changes the advertised MCP tool list.', '', 'Subcommands:', ' add --file PATH register a tool from a JSON file: name, description, class (read|write), inputSchema, handler', ' remove NAME remove a tool and its grants', ' list show tools, classes, schema hashes and granted workers', ' grant NAME WORKER let a worker call a tool', ' revoke NAME WORKER stop a worker calling a tool'] },
76
+ { name: 'doctor', group: 'operator', summary: 'Check the host setup', usage: 'dalan doctor [--checks] [--json]',
77
+ detail: ['Reports whether this host can run jobs.', '', 'Options:', ' --checks lint the owner\'s checks.json instead (local only)', ' --json print JSON'] },
78
+ { name: 'paths', group: 'operator', summary: 'Print where Dalan keeps its files', usage: 'dalan paths [--json | --workspace-root | --config-root | --data-root | --state-root]' },
79
+ { name: 'pause', group: 'operator', summary: 'Stop handing out new jobs', usage: 'dalan pause --reason TEXT' },
80
+ { name: 'resume', group: 'operator', summary: 'Resume handing out jobs', usage: 'dalan resume' },
81
+ // Reachable, but not on the first screen.
82
+ { name: 'artifact', summary: 'Download a job artifact', usage: 'dalan artifact ID --output PATH' },
83
+ { name: 'cancel', summary: 'Cancel a job', usage: 'dalan cancel ID [--reason TEXT]' },
84
+ { name: 'cancel-if-queued', summary: 'Cancel a job only if it has not started', usage: 'dalan cancel-if-queued ID' },
85
+ { name: 'accept', summary: 'same as: dalan decide REQUEST_ID accepted', usage: 'dalan accept ID [--note TEXT]' },
86
+ { name: 'reject', summary: 'same as: dalan decide REQUEST_ID not_useful', usage: 'dalan reject ID [--note TEXT]' },
87
+ { name: 'note', summary: 'Add a note to a job', usage: 'dalan note ID TEXT [--json]' },
88
+ { name: 'questions', summary: 'List a job\'s open worker questions', usage: 'dalan questions ID [--json]' },
89
+ { name: 'answer', summary: 'Answer a worker question', usage: 'dalan answer ID QUESTION_ID TEXT [--json]' },
90
+ { name: 'tell', summary: 'Send a message to workers', usage: 'dalan tell [--worker NAME] TEXT [--json]' },
91
+ { name: 'untell', summary: 'Withdraw a message', usage: 'dalan untell MESSAGE_ID [--worker NAME] [--json]' },
92
+ { name: 'audit', summary: 'Show the audit trail', usage: 'dalan audit [--since RFC3339]' },
93
+ { name: 'claims', summary: 'List active worker claims', usage: 'dalan claims [--json]' },
94
+ { name: 'abandon', summary: 'Release a stuck claim', usage: 'dalan abandon ID [--reason TEXT]' },
95
+ { name: 'reconcile', internal: true, summary: 'Reconcile one job record with the bridge', usage: 'dalan reconcile ID [--adopt]' },
96
+ { name: 'verify-stops', internal: true, summary: 'Re-check host stop evidence for a job whose claim reports claim_effects_unverified', usage: 'dalan verify-stops [ID] [--json]' },
97
+ { name: 'integrate', summary: 'Mark a job as integrated', usage: 'dalan integrate ID [--reason TEXT]' },
98
+ { name: 'metrics', summary: 'Show bridge metrics', usage: 'dalan metrics [--since RFC3339] [--json]' },
99
+ { name: 'rejections', summary: 'Summarize rejected jobs', usage: 'dalan rejections [--since RFC3339] [--json]' },
100
+ { name: 'backfill-objectives', internal: true, summary: 'Backfill objective records', usage: 'dalan backfill-objectives [--dry-run] [--json]' },
101
+ { name: 'break', summary: 'Record or clear a capacity break', usage: 'dalan break --reason TEXT [--since RFC3339] | dalan break --clear' },
102
+ { name: 'breaks', summary: 'List capacity breaks', usage: 'dalan breaks [--json]' },
103
+ { name: 'learned', summary: 'Show or clear learned limits', usage: 'dalan learned [--clear] [--json]' },
104
+ { name: 'break-usage-backfill', internal: true, summary: 'Backfill usage for a capacity break', usage: 'dalan break-usage-backfill --id N [--log PATH] [--json]' },
105
+ { name: 'as-init', internal: true, summary: 'Create built-in authorization server files (older form of init)', usage: 'dalan as-init --public-url https://HOST [--json]' },
106
+ { name: 'as-rotate-keys', summary: 'Rotate the authorization server keys', usage: 'dalan as-rotate-keys [--jwks-only|--cookies-only] [--json] (stop the bridge first)' },
107
+ { name: 'prepare-deps', internal: true, summary: 'Prepare dependencies for a source directory', usage: 'dalan prepare-deps SOURCE_DIRECTORY [--json] [--replace-invalid]' },
108
+ ];
109
+
110
+ const GROUPS = [['start', 'Getting started'], ['everyday', 'Everyday'], ['operator', 'Operator']];
111
+ const find = name => COMMANDS.find(c => c.name === name);
112
+ const section = (title, rows) => [`${title}:`, ...rows.map(c => ` ${c.name.padEnd(10)} ${c.summary}`)];
113
+
114
+ export function shortHelp() {
115
+ return ['Dalan: hand bounded jobs to a worker agent, follow their progress and review the results.', '',
116
+ 'Usage: dalan <command> [options]', '',
117
+ ...GROUPS.flatMap(([key, title]) => [...section(title, COMMANDS.filter(c => c.group === key)), '']),
118
+ 'Environment:', ' DALAN_HOME bridge home commands use: the Home line a run prints (local: ~/.local/share/dalan-trial)', '',
119
+ 'Start here: dalan try',
120
+ 'Details: dalan <command> --help', 'More: dalan help --all', 'Version: dalan --version', ''].join('\n').trimEnd();
121
+ }
122
+
123
+ const width = Math.max(...COMMANDS.map(c => c.name.length)) + 2;
124
+ const rows = commands => commands.map(c => ` ${c.name.padEnd(width)}${c.summary}`);
125
+
126
+ export function fullHelp() {
127
+ return [shortHelp(), '', 'Other commands:', ...rows(COMMANDS.filter(c => !c.group && !c.internal)), '',
128
+ 'Internal maintenance commands: dalan help --internal'].join('\n');
129
+ }
130
+
131
+ export function internalHelp() {
132
+ return ['Internal maintenance commands. Operators run these for recovery or upgrades; a normal setup does not need them.', '',
133
+ ...rows(COMMANDS.filter(c => c.internal)), '', 'Details: dalan <command> --help'].join('\n');
134
+ }
135
+
136
+ export function commandHelp(name) {
137
+ const c = find(name);
138
+ if (!c) return null;
139
+ return [`${c.summary}.`, '', `Usage: ${c.usage}`, ...(c.detail ? ['', ...c.detail] : []), '', 'Other commands: dalan help --all. Internal maintenance commands: dalan help --internal.'].join('\n');
140
+ }
141
+
142
+ function distance(a, b) {
143
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
144
+ for (let i = 1; i <= a.length; i++) {
145
+ const row = [i];
146
+ for (let j = 1; j <= b.length; j++) row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
147
+ prev = row;
148
+ }
149
+ return prev[b.length];
150
+ }
151
+
152
+ export function suggest(name) {
153
+ const scored = COMMANDS.map(c => ({ name: c.name, d: c.name.startsWith(name) && name.length >= 2 ? 1 : distance(name, c.name) }));
154
+ const best = scored.sort((a, b) => a.d - b.d)[0];
155
+ return best && best.d <= Math.max(1, Math.min(2, Math.floor(name.length / 3))) ? best.name : null;
156
+ }
157
+
158
+ const FREE_TEXT = new Set(['note', 'answer', 'tell']);
159
+ // Free-text commands keep rejecting option-like words (`tell --help` is an error); `dalan help tell` shows their usage.
160
+ const wantsHelp = (command, rest) => !FREE_TEXT.has(command) && (rest[0] === '-h' || rest.includes('--help'));
161
+
162
+ // Decide whether argv (after the node and script names) is a help request or an unknown command.
163
+ // Returns null when the command should run normally; otherwise { stream, code, text }.
164
+ export function resolveHelp(argv) {
165
+ const [command, ...rest] = argv;
166
+ if (command === undefined) return { stream: 'stdout', code: 0, text: shortHelp() };
167
+ if (command === '--help' || command === '-h') return { stream: 'stdout', code: 0, text: shortHelp() };
168
+ if (command === 'help') {
169
+ const topic = rest.find(a => !a.startsWith('-'));
170
+ if (topic) {
171
+ const text = commandHelp(topic);
172
+ if (!text) return unknown(topic, rest.includes('--json'));
173
+ return { stream: 'stdout', code: 0, text };
174
+ }
175
+ return { stream: 'stdout', code: 0, text: rest.includes('--internal') ? internalHelp() : rest.includes('--all') ? fullHelp() : shortHelp() };
176
+ }
177
+ if (!find(command)) return unknown(command, rest.includes('--json'));
178
+ if (wantsHelp(command, rest)) return { stream: 'stdout', code: 0, text: commandHelp(command) };
179
+ return null;
180
+ }
181
+
182
+ function unknown(name, json) {
183
+ const hint = suggest(name);
184
+ if (json) return { stream: 'stderr', code: 1, text: JSON.stringify({ error: `unknown command "${name}"${hint ? `; did you mean "${hint}"?` : ''}`, kind: 'local' }) };
185
+ return { stream: 'stderr', code: 1, text: `dalan: unknown command "${name}"${hint ? `. Did you mean "${hint}"?` : ''}\nRun 'dalan --help' for usage.` };
186
+ }
@@ -0,0 +1,16 @@
1
+ // How to tell the user to run this CLI again: `dalan` when that name on PATH is this same file (a normal npm install),
2
+ // `npx @tnunamak/dalan` under npx or `npm exec` (npm sets npm_command=exec): that PATH entry is npx's temporary bin, which the
3
+ // user's shell does not have. Otherwise node and the absolute path, so a checkout works without being on PATH.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ const defaultBin = path.resolve(import.meta.dirname, '..', 'bin/dalan.mjs');
8
+ const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
9
+
10
+ export function cliCommand(argv1, env = process.env) {
11
+ const real = p => { try { return fs.realpathSync(p); } catch { return null; } };
12
+ const self = real(path.resolve(argv1 ?? defaultBin));
13
+ const onPath = self && (env.PATH ?? '').split(path.delimiter).some(dir => dir && real(path.join(dir, 'dalan')) === self);
14
+ if (onPath) return env.npm_command === 'exec' ? 'npx @tnunamak/dalan' : 'dalan';
15
+ return `node ${shellQuote(self ?? path.resolve(argv1 ?? defaultBin))}`;
16
+ }
@@ -0,0 +1,126 @@
1
+ import { defaultPath } from './paths.mjs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { assertPrivateDir, untrusted, writeAtomic } from './as-files.mjs';
5
+ import { normalizeCode, PAIRING_MINUTES } from './as-files.mjs';
6
+ import { pollIntervalSeconds, readExposureRecords, WAKE_POLL_SECONDS_NGROK } from '../scripts/lib/expose-tailscale.mjs';
7
+
8
+ // `dalan connect ...`: the owner's side of the built-in authorization server. Every call goes through the owner Unix
9
+ // socket with the operator key; none of it exists on the public listener.
10
+ const USAGE = 'usage: dalan connect add-client --redirect-uri URI [--name NAME] [--json] | clients [--json] | remove-client CLIENT_ID | start --worker NAME [--minutes N] | stop | reset | pending | approve CODE --worker NAME [--confirm-redirect URI] [--replace] | list | revoke NAME | allow-callback PATTERN | signal-token [--worker NAME] [--rotate] [--json]';
11
+
12
+ // Terminal-safe text: vendor-supplied strings never reach the terminal as raw bytes.
13
+ const q = value => JSON.stringify(String(value ?? '').replace(/[\p{C}\p{Z}]+/gu, ' ').trim());
14
+
15
+ export function formatPending(result) {
16
+ if (!result.window) return 'No pairing window is open. Run: dalan connect start --worker NAME';
17
+ const lines = [`Pairing window open for worker ${result.window.worker} until ${result.window.expires_at}`];
18
+ if (!result.pending.length) lines.push('No pending connections.');
19
+ for (const p of result.pending) {
20
+ lines.push('', `code ${p.code}`, `worker ${p.worker}`, `client_id ${q(p.client_id)}`, `client_name [untrusted, set by the app] ${q(p.client_name)}`,
21
+ `redirect ${q(p.redirect_uri)}`, `resource ${q(p.resource)}`, `scopes ${p.scopes.map(q).join(' ')}`, `age ${p.age_seconds}s (expires in ${p.expires_in_seconds}s)`,
22
+ ...(p.superseded ? [`SUPERSEDED by the newer attempt ${p.superseded_by}; an app that registered again cannot finish this one, so approve the newest code`] : []),
23
+ ...(p.native ? ['WARNING native client, identity not verified: host and name prove nothing; teammate must read this code from the browser page on their own machine and compare it over a trusted channel', ' redirect confirmation is a typo check only; it is not identity proof', `APPROVE dalan connect approve ${p.code} --worker ${p.worker} (approves this code only; other pending codes are unaffected. A native client also needs the exact redirect shown above.)`] : []));
24
+ }
25
+ if (result.pending.length) lines.push('', 'Compare the code the teammate reads from their browser page over a trusted channel. Approve only that matching transaction. The code of a native client is approved by that code only; confirm the exact redirect shown above as a typo check.');
26
+ return lines.join('\n');
27
+ }
28
+
29
+ export function formatClients(result) {
30
+ if (!result.clients.length) return 'No OAuth clients are registered.';
31
+ return result.clients.map(client => [
32
+ `client_id ${q(client.client_id)}`, `type ${client.type}`, `client_name [untrusted] ${q(client.client_name)}`,
33
+ `redirect_uris ${client.redirect_uris.map(q).join(' ')}`, `created_at ${client.created_at}`,
34
+ ].join('\n')).join('\n\n');
35
+ }
36
+
37
+ export async function connectCommand(args, { request, operator, option, json }) {
38
+ const sub = args.shift();
39
+ const headers = () => ({ 'x-operator-key': operator() });
40
+ const flags = new Set(['--json', '--replace', '--rotate']);
41
+ const valued = new Set(['--worker', '--minutes', '--redirect-uri', '--name', '--confirm-redirect']);
42
+ const positional = [];
43
+ for (let i = 0; i < args.length; i++) {
44
+ if (valued.has(args[i])) {
45
+ if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`${args[i]} requires a value`);
46
+ i++; continue;
47
+ }
48
+ if (flags.has(args[i])) continue;
49
+ if (args[i].startsWith('--')) throw new Error(`unknown option ${args[i]}; ${USAGE}`);
50
+ positional.push(args[i]);
51
+ }
52
+ if (sub !== 'add-client' && (args.includes('--redirect-uri') || args.includes('--name'))) throw new Error(`${sub} does not accept --redirect-uri or --name; ${USAGE}`);
53
+ if (sub !== 'approve' && args.includes('--confirm-redirect')) throw new Error(`${sub} does not accept --confirm-redirect; ${USAGE}`);
54
+ const worker = option('--worker');
55
+ if (args.includes('--worker') && (!worker || worker.startsWith('--'))) throw new Error('--worker requires a name');
56
+ switch (sub) {
57
+ case 'add-client': {
58
+ const redirectUri = option('--redirect-uri'), name = option('--name');
59
+ if (!redirectUri || positional.length || args.includes('--worker') || args.includes('--minutes') || args.includes('--replace')
60
+ || args.filter(arg => arg === '--redirect-uri').length !== 1 || args.filter(arg => arg === '--name').length > 1) throw new Error(USAGE);
61
+ const result = await request('/connect/add-client', 'POST', { redirect_uri: redirectUri, ...(name !== null ? { name } : {}) }, headers());
62
+ return json ? { result } : { result: `Created public client.\nclient_id ${q(result.client_id)}`, plain: true };
63
+ }
64
+ case 'clients': {
65
+ if (positional.length || args.some(arg => arg !== '--json')) throw new Error(USAGE);
66
+ const result = await request('/connect/clients', 'GET', null, headers());
67
+ return json ? { result } : { result: formatClients(result), plain: true };
68
+ }
69
+ case 'remove-client': {
70
+ if (positional.length !== 1 || args.some(arg => arg.startsWith('--') && arg !== '--json')) throw new Error(USAGE);
71
+ const result = await request('/connect/remove-client', 'POST', { client_id: positional[0] }, headers());
72
+ return json ? { result } : { result: `Removed static client ${q(result.client_id)}.`, plain: true };
73
+ }
74
+ case 'start': {
75
+ if (!worker || positional.length) throw new Error(USAGE);
76
+ const minutes = option('--minutes');
77
+ if (args.includes('--minutes') && (!/^\d+$/.test(minutes ?? ''))) throw new Error('--minutes requires an integer');
78
+ return { result: await request('/connect/start', 'POST', { worker, ...(minutes ? { minutes: Number(minutes) } : {}) }, headers()) };
79
+ }
80
+ case 'reset': if (positional.length) throw new Error(USAGE); return { result: await request('/connect/reset', 'POST', {}, headers()) };
81
+ case 'stop': if (positional.length) throw new Error(USAGE); return { result: await request('/connect/stop', 'POST', {}, headers()) };
82
+ case 'pending': {
83
+ if (positional.length) throw new Error(USAGE);
84
+ const result = await request('/connect/pending', 'GET', null, headers());
85
+ return json ? { result } : { result: formatPending(result), plain: true };
86
+ }
87
+ case 'approve': {
88
+ if (positional.length !== 1 || !worker) throw new Error(USAGE);
89
+ const view = await request('/connect/pending', 'GET', null, headers());
90
+ const matches = view.pending.filter(item => normalizeCode(item.code) === normalizeCode(positional[0]));
91
+ if (matches.length !== 1) {
92
+ const reason = matches.length ? 'More than one pending pairing matches this code. Run dalan connect pending and compare codes before approval.'
93
+ : `No pending pairing matches this code. The attempt may have expired (attempts last ${PAIRING_MINUTES} minutes) or the code may be mistyped. Start the sign-in again in the client, then compare codes with dalan connect pending before approval.`;
94
+ throw new Error(`${reason}\n\n${formatPending({ ...view, pending: matches.length ? matches : view.pending })}`);
95
+ }
96
+ const pairing = matches[0];
97
+ const confirmRedirect = option('--confirm-redirect');
98
+ if (pairing.native) {
99
+ const review = formatPending({ ...view, pending: [pairing] });
100
+ if (confirmRedirect === null) throw new Error(`Native callback needs explicit redirect typo confirmation. Compare the full URI with the browser page and compare the code the teammate reads from that page over a trusted channel; this flag does not prove identity. Rerun with --confirm-redirect ${q(pairing.redirect_uri)}.\n\n${review}`);
101
+ if (confirmRedirect !== pairing.redirect_uri) throw new Error(`confirmed redirect does not match the pending callback ${q(pairing.redirect_uri)}; this flag is only a typo check, not identity proof.\n\n${review}`);
102
+ } else if (confirmRedirect !== null) throw new Error('--confirm-redirect is only valid for a native callback');
103
+ const approval = await request('/connect/approve', 'POST', { code: positional[0], worker, replace: args.includes('--replace'), ...(confirmRedirect !== null ? { confirm_redirect: confirmRedirect } : {}) }, headers());
104
+ const review = formatPending({ ...view, pending: [pairing] });
105
+ return json ? { result: approval, review } : { result: `${review}\n\nApproved ${q(pairing.code)} for worker ${q(pairing.worker)}.${approval.replaced ? ` Replaced connection ${q(approval.replaced)}: this client now gets every queued and future job for worker ${q(pairing.worker)}, including briefs approved before the switch.` : ''}`, plain: true };
106
+ }
107
+ case 'list': if (positional.length) throw new Error(USAGE); return { result: await request('/connect/list', 'GET', null, headers()) };
108
+ case 'revoke': if (positional.length !== 1 || worker) throw new Error(USAGE); return { result: await request('/connect/revoke', 'POST', { worker: positional[0] }, headers()) };
109
+ case 'signal-token': {
110
+ if (positional.length || args.some((arg, i) => arg !== '--json' && arg !== '--rotate' && arg !== '--worker' && args[i - 1] !== '--worker')) throw new Error(USAGE);
111
+ const result = await request('/connect/signal-token', 'POST', { rotate: args.includes('--rotate'), ...(worker ? { worker } : {}) }, headers());
112
+ // The poll interval comes from the exposure record in this home (ngrok = 300 s, otherwise 60 s). It is set in the hook, not on the bridge.
113
+ const seconds = pollIntervalSeconds(readExposureRecords(os.homedir()));
114
+ const dir = defaultPath(os.homedir(),'.config/dot-bridge');
115
+ assertPrivateDir(dir);
116
+ const file = path.join(dir, `signal-url.${result.worker}`);
117
+ writeAtomic(file, `${result.url}\n`);
118
+ // stdout contains only the private file path; the hook owner can read it without exposing the URL in logs.
119
+ if (json) return { result: { path: file, worker: result.worker, rotated: result.rotated, poll_interval_seconds: seconds } };
120
+ process.stderr.write(`Hook poll interval: ${seconds} s or more. ${seconds === WAKE_POLL_SECONDS_NGROK ? 'For this exposure, do not poll faster than 300 s.' : 'Do not poll faster than every 60 s.'}\n`);
121
+ return { result: file, plain: true };
122
+ }
123
+ case 'allow-callback': if (positional.length !== 1) throw new Error(USAGE); return { result: await request('/connect/allow-callback', 'POST', { pattern: positional[0] }, headers()) };
124
+ default: throw new Error(USAGE);
125
+ }
126
+ }
@@ -0,0 +1,61 @@
1
+ // Who a result is for, and how urgent that makes it. Code decides, never the submitter.
2
+ //
3
+ // A submitter can lie about anything it writes: a manifest field, a payload key, a --source flag. So the consumer type
4
+ // and the tier come only from facts the code path owns: the request id that proves a drainer or fix-loop identity
5
+ // (verifyObjective), and the priority the bridge enforces for that identity. A self-declared consumer, severity or tier
6
+ // is refused, not ignored, so a producer that tries it learns at once. Naming a requester (consumer.type thread or lane) is
7
+ // not refused; nothing reads it yet.
8
+ import { verifyObjective, fixLoopSource, fromStoredSource } from './objectives.mjs';
9
+
10
+ // Pseudo-consumers belong to the code path that owns them. A submitter never names one.
11
+ // fix_pipeline fix-loop assignments (proved by the fix-loop request id)
12
+ // reserve work nobody asked for: the drainer's audits and PR reviews (proved by the drainer request id)
13
+ // ledger no code path assigns it yet, so nothing can hold it
14
+ export const systemConsumers = Object.freeze(['fix_pipeline', 'ledger', 'reserve']);
15
+
16
+ // Fields that would let a submitter pick its own consumer or promote its own work. `value_tier` and `tier` are never the
17
+ // submitter's. `consumer` may name a requester (a thread or lane, for later) but never a system consumer. `severity` is the
18
+ // producer's own claim about its finding: a drainer or fix-loop submission cannot use it to rank itself, and an agent's
19
+ // severity hint is harmless (agent work is already tier 0) and passes.
20
+ export const forbiddenDeclarations = Object.freeze(['value_tier', 'tier']);
21
+
22
+ // Tier 0 is work an agent asked for; a lower number runs first. Only these three exist until the data justify more.
23
+ const tiers = { agent: 0, fix_pipeline: 1, reserve: 5 };
24
+
25
+ // The forbidden declarations at the top level of a manifest, assignment or request body. Empty when clean.
26
+ // `source` is the submitter's claimed source; without one the value is treated as an agent's.
27
+ export function declaredConsumerFields(value, source = 'agent') {
28
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return [];
29
+ const found = forbiddenDeclarations.filter(key => Object.hasOwn(value, key));
30
+ const named = typeof value.consumer === 'string' ? value.consumer : value.consumer?.type;
31
+ if (Object.hasOwn(value, 'consumer') && (systemConsumers.includes(named) || typeof named !== 'string')) found.push('consumer');
32
+ if (Object.hasOwn(value, 'severity') && source !== 'agent') found.push('severity');
33
+ return found;
34
+ }
35
+
36
+ export function assertNoDeclaredConsumer(value, label, source = 'agent') {
37
+ const found = declaredConsumerFields(value, source);
38
+ if (found.length) throw new Error(`${label} declares ${found.join(', ')}; the bridge assigns the consumer and tier from the code path, never from the submitter`);
39
+ }
40
+
41
+ // row: {request_id, payload (object or JSON), meta: {objective_key, revision, task_kind, source}}.
42
+ // Returns {type, tier, proven} and, when not proven, the reason verifyObjective gives. A claim of source drainer or fix-loop that the request id does not prove is not a consumer
43
+ // at all: the caller must refuse it (see unprovenSource).
44
+ export function consumerOf(row) {
45
+ const source = row.meta?.source ?? 'agent', normalizedSource = fromStoredSource(source);
46
+ if (normalizedSource === fixLoopSource || normalizedSource === 'drainer') {
47
+ const type = normalizedSource === fixLoopSource ? 'fix_pipeline' : 'reserve';
48
+ const reason = verifyObjective({ request_id: row.request_id, payload: row.payload }, row.meta);
49
+ return { type, tier: tiers[type], proven: reason === null, ...(reason === null ? {} : { reason }) };
50
+ }
51
+ return { type: 'agent', tier: tiers.agent, proven: true };
52
+ }
53
+
54
+ // Why this submission may not use its claimed source, or null. A drainer or fix-loop identity needs its request id proof, and
55
+ // drainer work is always background: no manifest can put itself ahead of agent-requested work.
56
+ export function unprovenSource(row, priority) {
57
+ const consumer = consumerOf(row);
58
+ if (!consumer.proven) return `source ${row.meta.source} is proven by the request id of its own code path, and this one is not: ${consumer.reason}`;
59
+ if (consumer.type === 'reserve' && priority !== 'background') return 'drainer work is always background priority';
60
+ return null;
61
+ }