@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,112 @@
1
+ import { readEnv } from './env.mjs';
2
+ import fs from 'node:fs';
3
+ import { hostCheckRefusal } from './host-execution-policy.mjs';
4
+ import { withCheckCoverage } from './check-coverage.mjs';
5
+
6
+ // Per-job execution capability (design section 3) and the declared capabilities of the one executor the bridge has.
7
+ // none nobody on the bridge host runs checks
8
+ // worker the worker runs checks in its own sandbox; the bridge stores those claims as worker_attested
9
+ // host operator-enabled Linux checks use bwrap + systemd budgets; results are bridge_verified
10
+ export const EXECUTIONS = Object.freeze(['none', 'worker', 'host']);
11
+ export const TRUST = Object.freeze({ bridge: 'bridge_verified', worker: 'worker_attested' });
12
+
13
+ export const parseExecution = (value, what = 'execution') => {
14
+ if (!EXECUTIONS.includes(value)) throw new Error(`invalid ${what}: expected one of ${EXECUTIONS.join(', ')}`);
15
+ return value;
16
+ };
17
+
18
+ // Vocabulary of design section 13. A check may require any of these.
19
+ export const CAPABILITY_NAMES = Object.freeze([
20
+ 'private_loopback', 'host_loopback_denied', 'lan_denied', 'unix_sockets_denied', 'credential_services_denied',
21
+ 'closed_inherited_fds', 'read_scope_enforced', 'write_scope_enforced', 'full_tree_cancel_verified',
22
+ 'offline_transition_revokes_connections', 'artifact_export_no_follow', 'runner_observed_evidence', 'native_darwin_execution', 'immutable_input_snapshot']);
23
+ export const CAPABILITY_STATES = Object.freeze(['verified', 'unsupported', 'unknown']);
24
+
25
+ export function parseRequiredCapabilities(value) {
26
+ if (value === undefined || value === null) return null;
27
+ if (!Array.isArray(value) || value.length > CAPABILITY_NAMES.length || value.some(c => !CAPABILITY_NAMES.includes(c))) {
28
+ throw new Error(`invalid required_capabilities: expected a list of ${CAPABILITY_NAMES.join(', ')}`);
29
+ }
30
+ return value.length ? [...new Set(value)].sort() : null;
31
+ }
32
+
33
+ // The legacy pasta backend has no systemd control-group stop receipt, so it cannot
34
+ // verify that the full process tree has stopped. The opted-in systemd backend records
35
+ // a recursive control-group scan in a durable receipt, reconciled by Workspace.check.
36
+ const SYSTEMD_CAPABILITIES = Object.freeze({
37
+ private_loopback: 'verified', host_loopback_denied: 'verified', lan_denied: 'verified', unix_sockets_denied: 'verified',
38
+ credential_services_denied: 'verified', closed_inherited_fds: 'verified', read_scope_enforced: 'verified',
39
+ write_scope_enforced: 'verified', full_tree_cancel_verified: 'verified', offline_transition_revokes_connections: 'verified',
40
+ artifact_export_no_follow: 'verified', runner_observed_evidence: 'verified', native_darwin_execution: 'unsupported', immutable_input_snapshot: 'unsupported',
41
+ });
42
+ export const SYSTEMD_BACKEND = Object.freeze({ name: 'linux-bwrap-systemd', version: '1' });
43
+ export const BACKENDS = Object.freeze({
44
+ 'linux-bwrap-pasta': Object.freeze({
45
+ // Neither pasta version writes the systemd control-group receipt used as full-tree stop proof.
46
+ '1': Object.freeze({
47
+ measured_by: Object.freeze({ script: 'scripts/sandbox-probe-e2e.mjs' }),
48
+ capabilities: Object.freeze({
49
+ private_loopback: 'verified', host_loopback_denied: 'verified', lan_denied: 'verified', unix_sockets_denied: 'verified',
50
+ credential_services_denied: 'verified', closed_inherited_fds: 'unsupported', read_scope_enforced: 'verified',
51
+ write_scope_enforced: 'verified', full_tree_cancel_verified: 'unsupported', offline_transition_revokes_connections: 'verified',
52
+ artifact_export_no_follow: 'verified', runner_observed_evidence: 'verified', native_darwin_execution: 'unsupported', immutable_input_snapshot: 'unsupported' }) }),
53
+ // The v2 process-tree helpers are retained for tests; production uses the systemd control-group receipt.
54
+ '2': Object.freeze({
55
+ measured_by: Object.freeze({ script: 'scripts/sandbox-probe-e2e.mjs' }),
56
+ capabilities: Object.freeze({
57
+ private_loopback: 'verified', host_loopback_denied: 'verified', lan_denied: 'verified', unix_sockets_denied: 'verified',
58
+ credential_services_denied: 'verified', closed_inherited_fds: 'verified', read_scope_enforced: 'verified',
59
+ write_scope_enforced: 'verified', full_tree_cancel_verified: 'unsupported', offline_transition_revokes_connections: 'verified',
60
+ artifact_export_no_follow: 'verified', runner_observed_evidence: 'verified', native_darwin_execution: 'unsupported', immutable_input_snapshot: 'unsupported' }) }) }),
61
+ 'linux-bwrap-systemd': Object.freeze({
62
+ '1': Object.freeze({
63
+ measured_by: Object.freeze({ script: 'scripts/sandbox-probe-e2e.mjs', full_tree_cancel_verified: 'scripts/host-stop-production-path-test.mjs' }),
64
+ capabilities: SYSTEMD_CAPABILITIES,
65
+ }),
66
+ }),
67
+ });
68
+ export const HOST_BACKEND = Object.freeze({ name: 'linux-bwrap-pasta', version: '2' });
69
+
70
+ export function hostBackend(readiness=hostReadiness()) {
71
+ const selected=readEnv('DALAN_HOST_CHECKS')==='1'?SYSTEMD_BACKEND:HOST_BACKEND;
72
+ const entry = BACKENDS[selected.name][selected.version];
73
+ const capabilities=Object.fromEntries(Object.entries(entry.capabilities).map(([name,state])=>[name,readiness.ready?state:'unknown']));
74
+ // The budgeted backend gives no phase a network, so no probe can show a connection being revoked at the install-to-check switch.
75
+ // A declaration may trail a measurement but never lead it: this one is reported unknown, not verified.
76
+ if(selected===SYSTEMD_BACKEND) capabilities.offline_transition_revokes_connections='unknown';
77
+ return { ...selected, capabilities, measured_by: { ...entry.measured_by } };
78
+ }
79
+
80
+ // Baseline platform prerequisites retained for legacy admission compatibility.
81
+ // Presence does not authorize execution: policy and the budget service verify
82
+ // opt-in, scope, Python, systemd and effective cgroup limits at launch.
83
+ // DALAN_TEST_HIDE_BWRAP=1 only makes the answer stricter (tests use it to model a host without an executor); nothing can make it looser.
84
+ export function hostReadiness(exists = fs.existsSync) {
85
+ if (readEnv('DALAN_TEST_HIDE_BWRAP') === '1') exists = () => false;
86
+ if (process.platform !== 'linux') return { ready: false, reason: `no host executor on ${process.platform}` };
87
+ if (!exists('/usr/bin/bwrap')) return { ready: false, reason: 'bwrap not found' };
88
+ // Preserve the historical bash prerequisite; budgeted commands instead use
89
+ // Python close_fds and never fall back to the historical launcher.
90
+ if (!exists('/usr/bin/bash')) return { ready: false, reason: 'bash not found (the fd-closing launcher needs it)' };
91
+ const refusal=hostCheckRefusal();
92
+ return { ready: !refusal, reason: refusal };
93
+ }
94
+
95
+ const capabilityError = (capability, detail) => Object.assign(new Error(`capability_not_available: ${capability} (${detail})`), { code: 'capability_not_available' });
96
+
97
+ // Throws capability_not_available naming the first thing a host job cannot get.
98
+ export function admitHostExecution(required, { readiness = hostReadiness(), backend = hostBackend(readiness) } = {}) {
99
+ if (!readiness.ready) throw capabilityError('host_execution', readiness.reason);
100
+ for (const capability of required || []) {
101
+ const state = backend.capabilities[capability] ?? 'unknown';
102
+ if (state !== 'verified') throw capabilityError(capability, `${backend.name} v${backend.version} declares ${state}`);
103
+ }
104
+ }
105
+
106
+ export const capabilityNotAvailable = (execution, reason) => ({ status: 'capability_not_available', capability: 'host_execution', reason: reason || `this job has execution=${execution}; run_check needs execution=host`, execution });
107
+
108
+ // A check row as shown to the worker and the owner: the evidence JSON parsed, and trust taken from it (null when the bridge recorded none).
109
+ export function withEvidence(row) {
110
+ const evidence = row.evidence ? JSON.parse(row.evidence) : null;
111
+ return withCheckCoverage({ ...row, evidence, trust: evidence?.trust ?? null });
112
+ }
@@ -0,0 +1,28 @@
1
+ // Read-only failure labels keep bridge facts separate from text reported by a worker.
2
+ export const failureTypes=Object.freeze(['expired','owner_cancelled','lease_expired','skipped_by_bridge','worker_blocked','usage_break','guardian_denied','transport_error','adapter_error','check_failed','unknown']);
3
+
4
+ const reportRules=[
5
+ ['usage_break',/usage[- ]?(?:limit|break|cap)|rate[- ]?limit|quota (?:exceeded|exhausted)|worker_break|try again (?:after|at) \d/i],
6
+ ['guardian_denied',/auto-?review|guardian|not approved|paused out of precaution|(?:denied|refused|rejected) by (?:the )?(?:safety|policy|reviewer|approval)/i],
7
+ ['transport_error',/\bE(?:CONNRESET|CONNREFUSED|TIMEDOUT|PIPE|NOTFOUND|HOSTUNREACH)\b|socket hang up|fetch failed|network (?:error|unreachable)|\bHTTP 5\d\d\b|bad gateway|deadline exceeded/i],
8
+ ['adapter_error',/\b(?:adapter|acp)\b[^.\n]{0,40}\b(?:error|failed|crash|refused|invalid)\b|\b(?:error|failed|crash|refused|invalid)\b[^.\n]{0,40}\b(?:adapter|acp)\b/i],
9
+ ];
10
+
11
+ // This describes worker text only. It does not prove why the work stopped.
12
+ export function inferWorkerReport({outcome,summary='',result=''}={}) {
13
+ if(outcome==='completed'||outcome==null) return null;
14
+ const text=`${summary}\n${result}`;
15
+ for(const [type,pattern] of reportRules) if(pattern.test(text)) return {type,source:'worker_text_inference'};
16
+ if(/^\s*BLOCKED:/im.test(text)||outcome==='blocked') return {type:'worker_blocked',source:'worker_text_inference'};
17
+ return {type:'unknown',source:'worker_text_inference'};
18
+ }
19
+
20
+ // Only facts observed at bridge transitions receive bridge provenance.
21
+ export function observeTransition({status,reason,cancelActor,leaseExpired=false,checkFailed=false}={}) {
22
+ if(checkFailed) return {type:'check_failed',source:'bridge_observed_transition'};
23
+ if(status==='cancelled'&&reason==='expired'&&cancelActor==='system') return {type:'expired',source:'bridge_observed_transition'};
24
+ if(status==='cancelled'&&cancelActor==='owner') return {type:'owner_cancelled',source:'bridge_observed_transition'};
25
+ if(leaseExpired) return {type:'lease_expired',source:'bridge_observed_transition'};
26
+ if(status==='cancelled'&&(reason==='skipped_by_worker'||reason==='skipped_by_dot')&&cancelActor==='system') return {type:'skipped_by_bridge',source:'bridge_observed_transition'};
27
+ return null;
28
+ }
@@ -0,0 +1,32 @@
1
+
2
+ // The short terminal view of `dalan get`. Report text comes from a worker, so the caller prints it through
3
+ // terminalSafe. A job that is not finished gets the command that moves it on, never a decision.
4
+ export function formatGetSummary(job, { id, cli }) {
5
+ const state = job.status ?? 'unknown';
6
+ const report = job.report ?? null;
7
+ const lines = [`Job ${id}: ${state}`];
8
+ if (job.target_worker) lines.push(`Worker: ${job.target_worker}`);
9
+ if (report?.outcome && report.outcome !== 'done') lines.push(`Outcome: ${report.outcome}`);
10
+ if (report?.summary) lines.push(`Summary: ${report.summary}`);
11
+ if (report?.result) lines.push('', report.result);
12
+ // BLOCKED: and QUESTION: progress notes are how a worker asks the owner for something; a running job shows them.
13
+ const asks = state === 'finished' || state === 'cancelled' ? [] : (job.progress ?? []).map(p => p?.note).filter(n => typeof n === 'string' && /^\s*(?:BLOCKED:|QUESTION:)/i.test(n));
14
+ if (asks.length) lines.push('', 'Worker asks or is blocked:', ...asks.slice(-3).map(n => ` ${n.trim()}`), `Answer with: ${cli} note ${id} "TEXT"`);
15
+ const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
16
+ const artifacts = (job.artifacts?.length ?? 0) || (job.artifact_ids?.length ?? 0), checks = job.checks?.length ?? 0;
17
+ if (artifacts || checks) lines.push('', `Evidence: ${[artifacts && count(artifacts, 'artifact'), checks && count(checks, 'check')].filter(Boolean).join(', ')}`);
18
+ const next = state === 'finished' ? `${cli} decide ${id} accepted`
19
+ : state === 'cancelled' ? null
20
+ : `${cli} wait ${id} --timeout 3600, then ${cli} get ${id}`;
21
+ if (next) lines.push('', `Next: ${next}`);
22
+ lines.push(`Full record: ${cli} get ${id} --json`);
23
+ return lines.join('\n');
24
+ }
25
+
26
+ // `dalan wait` on a terminal: one line, in place of the JSON status document.
27
+ export function formatWaitLine(result, { id, cli, seconds }) {
28
+ const state = result?.status ?? 'unknown';
29
+ if (state === 'timeout') return `Job ${id}: still open after ${seconds} s. Wait longer with: ${cli} wait ${id} --timeout 3600`;
30
+ const tail = state === 'cancelled' ? '' : `. Read it with: ${cli} get ${id}`;
31
+ return `Job ${id}: ${state}${tail}`;
32
+ }
@@ -0,0 +1,15 @@
1
+ // Environment for the bridge's own git calls on mirrors and workspaces. They run outside the check sandbox, so neither the host's
2
+ // git configuration nor repository content may choose code for them to run: no system or global config (hooks via core.hooksPath,
3
+ // filter and LFS drivers, fsmonitor, external diff, url rewrites), no system attributes, and hooks and fsmonitor are off even if a
4
+ // repository-level config names them. Inherited GIT_* variables (GIT_CONFIG_PARAMETERS from a parent `git -c`, GIT_EXTERNAL_DIFF,
5
+ // GIT_DIR, ...) are dropped, except the two the bridge sets itself for private-repository fetches. Environment-supplied config outranks
6
+ // every config file. Mirror-local config is bridge-owned: the bridge creates it, and neither a worker nor the check sandbox can reach it.
7
+ // Git reads $XDG_CONFIG_HOME/git/ignore and git/attributes (default <config>/git/) even with no global config file, so both are
8
+ // pointed at /dev/null: a host ignore pattern such as CLAUDE.md must not drop a worker-written file from the patch.
9
+ const kept=new Set(['GIT_ASKPASS','GIT_TERMINAL_PROMPT']);
10
+ export function gitEnv(base=process.env) {
11
+ const env=Object.fromEntries(Object.entries(base).filter(([key])=>!key.startsWith('GIT_')||kept.has(key)));
12
+ return {...env,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_ATTR_NOSYSTEM:'1',
13
+ GIT_CONFIG_COUNT:'4',GIT_CONFIG_KEY_0:'core.hooksPath',GIT_CONFIG_VALUE_0:'/dev/null',GIT_CONFIG_KEY_1:'core.fsmonitor',GIT_CONFIG_VALUE_1:'false',
14
+ GIT_CONFIG_KEY_2:'core.excludesFile',GIT_CONFIG_VALUE_2:'/dev/null',GIT_CONFIG_KEY_3:'core.attributesFile',GIT_CONFIG_VALUE_3:'/dev/null'};
15
+ }
@@ -0,0 +1,154 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+
5
+ const MAX_BYTES=4096;
6
+ const own=stat=>stat.uid===process.getuid();
7
+ const syncDir=dir=>{const fd=fs.openSync(dir,fs.constants.O_RDONLY|fs.constants.O_DIRECTORY|fs.constants.O_NOFOLLOW);try{fs.fsyncSync(fd);}finally{fs.closeSync(fd);}};
8
+ function checkId(checkRunId) {
9
+ if(typeof checkRunId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(checkRunId)) throw new Error('invalid host receipt checkRunId');
10
+ }
11
+ export function validateReceiptIdentity(checkRunId,invocationId) {
12
+ checkId(checkRunId);
13
+ if(typeof invocationId!=='string'||!/^[a-f0-9]{32}$/.test(invocationId)) throw new Error('invalid host receipt invocation');
14
+ }
15
+ function root(dir,create=false) {
16
+ if(typeof dir!=='string'||!path.isAbsolute(dir)||path.resolve(dir)!==dir||/[\x00-\x1f\x7f$]/.test(dir)) throw new Error('invalid host receipt directory');
17
+ const parent=path.dirname(dir);
18
+ if(parent===dir||fs.realpathSync(parent)!==parent) throw new Error('host receipt parent must be canonical');
19
+ if(create&&!fs.existsSync(dir)){fs.mkdirSync(dir,{mode:0o700});syncDir(parent);}
20
+ const stat=fs.lstatSync(dir);
21
+ if(!stat.isDirectory()||!own(stat)||(stat.mode&0o777)!==0o700||fs.realpathSync(dir)!==dir) throw new Error('host receipt directory must be private and owned');
22
+ return dir;
23
+ }
24
+ export function prepareHostReceipts({checkRunId,receiptDir}={}) {
25
+ if(checkRunId===undefined&&receiptDir===undefined) return null;
26
+ if(checkRunId===undefined||receiptDir===undefined) throw new Error('host receipts require checkRunId and receiptDir');
27
+ checkId(checkRunId);
28
+ return {checkRunId,receiptDir:root(receiptDir,true)};
29
+ }
30
+ function fileFor(dir,checkRunId,invocationId,kind) {
31
+ validateReceiptIdentity(checkRunId,invocationId);
32
+ // A check launches one envelope. Its immutable start record is also the
33
+ // durable check -> invocation lookup, published before any guest can run.
34
+ const key=createHash('sha256').update(JSON.stringify(kind==='start'?[checkRunId]:[checkRunId,invocationId])).digest('hex');
35
+ return path.join(dir,key+'.'+kind+'.json');
36
+ }
37
+ const unlinkTemp=file=>{try{fs.unlinkSync(file);}catch(error){if(error.code!=='ENOENT')throw error;}};
38
+ function recoverPrivateAliases(dir,fd) {
39
+ let stat=fs.fstatSync(fd);
40
+ if(stat.nlink===1) return true;
41
+ const aliases=[];
42
+ for(const name of fs.readdirSync(dir)) {
43
+ if(!/^\.receipt-[a-f0-9-]{36}\.tmp$/.test(name)) continue;
44
+ const file=path.join(dir,name);let alias;
45
+ try{alias=fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')continue;throw error;}
46
+ if(alias.isFile()&&own(alias)&&(alias.mode&0o777)===0o600&&alias.dev===stat.dev&&alias.ino===stat.ino) aliases.push(file);
47
+ }
48
+ stat=fs.fstatSync(fd);
49
+ if(stat.nlink===1) return true; // A concurrent publisher finished its unlink.
50
+ if(stat.nlink!==aliases.length+1) return false; // An unexplained external alias stays refused.
51
+ for(const file of aliases) unlinkTemp(file);
52
+ syncDir(dir);
53
+ return fs.fstatSync(fd).nlink===1;
54
+ }
55
+ function readRecord(dir,checkRunId,invocationId,kind) {
56
+ // Start lookup needs only the bridge-generated check ID after a crash.
57
+ const file=fileFor(root(dir),checkRunId,invocationId??'0'.repeat(32),kind);
58
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
59
+ try {
60
+ const stat=fs.fstatSync(fd);
61
+ if(!stat.isFile()||!own(stat)||(stat.mode&0o777)!==0o600||stat.nlink<1||stat.size<2||stat.size>MAX_BYTES) return null;
62
+ const bytes=Buffer.alloc(MAX_BYTES+1);
63
+ let total=0,n;
64
+ while(total<bytes.length&&(n=fs.readSync(fd,bytes,total,bytes.length-total,null))>0)total+=n;
65
+ if(total>MAX_BYTES) return null;
66
+ const record=JSON.parse(bytes.subarray(0,total).toString('utf8'));
67
+ if(record?.version!==1||record.kind!==kind||record.checkRunId!==checkRunId||(invocationId!==undefined&&record.invocationId!==invocationId)) return null;
68
+ validateReceiptIdentity(checkRunId,record.invocationId);
69
+ if(!recoverPrivateAliases(dir,fd)) return null;
70
+ return record;
71
+ } finally {fs.closeSync(fd);}
72
+ }
73
+ function publish(dir,checkRunId,invocationId,kind,fields={}) {
74
+ root(dir);validateReceiptIdentity(checkRunId,invocationId);
75
+ const record={version:1,kind,checkRunId,invocationId,...fields};
76
+ const bytes=Buffer.from(JSON.stringify(record)+'\n');
77
+ if(bytes.length>MAX_BYTES) throw new Error('host receipt too large');
78
+ const dest=fileFor(dir,checkRunId,invocationId,kind),temp=path.join(dir,'.receipt-'+randomUUID()+'.tmp');
79
+ let fd,created=false;
80
+ try {
81
+ fd=fs.openSync(temp,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_NOFOLLOW,0o600);created=true;
82
+ fs.fchmodSync(fd,0o600);
83
+ let written=0;while(written<bytes.length)written+=fs.writeSync(fd,bytes,written,bytes.length-written);
84
+ fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
85
+ // link is atomic and refuses an existing destination; rename would overwrite.
86
+ fs.linkSync(temp,dest);syncDir(dir);
87
+ unlinkTemp(temp);created=false;syncDir(dir);
88
+ return record;
89
+ } finally {if(fd!==undefined)fs.closeSync(fd);if(created)unlinkTemp(temp);}
90
+ }
91
+ const BOOT_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
92
+ export const validBootId=value=>typeof value==='string'&&BOOT_ID.test(value);
93
+ const validCgroup=value=>typeof value==='string'&&/^\/[\x21-\x7e]*$/.test(value)&&!value.split('/').includes('..');
94
+ // The boot id and cgroup path let a later scan prove the unit's processes are gone after the unit itself is collected.
95
+ export function writeHostStart({receiptDir,checkRunId,invocationId,bootId,cgroup}) {
96
+ if(invocationId==='0'.repeat(32)) throw new Error('null systemd invocation');
97
+ const fields={};
98
+ if(bootId!==undefined){if(!validBootId(bootId))throw new Error('invalid boot id');fields.boot_id=bootId;}
99
+ if(cgroup!==undefined){if(!validCgroup(cgroup))throw new Error('invalid cgroup path');fields.cgroup=cgroup;}
100
+ return publish(receiptDir,checkRunId,invocationId,'start',fields);
101
+ }
102
+ export function readHostStart({receiptDir,checkRunId}) {
103
+ try {checkId(checkRunId);return readRecord(receiptDir,checkRunId,undefined,'start');} catch {return null;}
104
+ }
105
+ export const REVERIFY_BASES=Object.freeze(['boot_changed','cgroup_empty']);
106
+ // Separate from the stop receipt, which is link-once and keeps the original verdict. Written only after a fresh proof.
107
+ export function writeHostReverify({receiptDir,checkRunId,invocationId,basis,bootId,currentBootId}) {
108
+ if(!REVERIFY_BASES.includes(basis)||!validBootId(bootId)||!validBootId(currentBootId)) throw new Error('invalid host re-verification evidence');
109
+ const start=readRecord(receiptDir,checkRunId,invocationId,'start');
110
+ if(!start||start.notStarted) throw new Error('matching host start receipt required');
111
+ return publish(receiptDir,checkRunId,invocationId,'reverify',{verified:true,remaining_pids:[],basis,boot_id:bootId,current_boot_id:currentBootId,verified_at:new Date().toISOString()});
112
+ }
113
+ export function writeHostStop({receiptDir,checkRunId,invocationId,verified,remaining_pids}) {
114
+ if(typeof verified!=='boolean'||!Array.isArray(remaining_pids)||remaining_pids.some(pid=>!Number.isSafeInteger(pid)||pid<=0)) throw new Error('invalid host stop evidence');
115
+ const start=readRecord(receiptDir,checkRunId,invocationId,'start');
116
+ if(!start||start.notStarted) throw new Error('matching host start receipt required');
117
+ return publish(receiptDir,checkRunId,invocationId,'stop',{verified,remaining_pids});
118
+ }
119
+ export function readVerifiedHostStop({receiptDir,checkRunId,invocationId}) {
120
+ try {
121
+ checkId(checkRunId);
122
+ const start=readRecord(receiptDir,checkRunId,invocationId,'start');
123
+ if(!start) return null;
124
+ if(start.notStarted===true) return start.invocationId==='0'.repeat(32)?{...start,verified:true,remaining_pids:[]}:null;
125
+ let stop=null;
126
+ try {stop=readRecord(receiptDir,checkRunId,start.invocationId,'stop');} catch {}
127
+ if(stop&&stop.verified===true&&Array.isArray(stop.remaining_pids)&&stop.remaining_pids.length===0) return stop;
128
+ // A failed or missing stop verdict is released only by separate fresh evidence.
129
+ const again=readRecord(receiptDir,checkRunId,start.invocationId,'reverify');
130
+ return again&&again.verified===true&&REVERIFY_BASES.includes(again.basis)&&Array.isArray(again.remaining_pids)&&again.remaining_pids.length===0?{...again,reverified:true}:null;
131
+ } catch {return null;}
132
+ }
133
+
134
+ // Every host path the guest can see must be disjoint from the trusted ledger.
135
+ // The workspace is copied; rejecting overlap also keeps receipts out of that copy.
136
+ export function assertHostReceiptIsolation(receiptDir,exposedPaths) {
137
+ const inside=(a,b)=>a===b||a.startsWith(b+path.sep);
138
+ for(const exposed of exposedPaths) {
139
+ if(!fs.existsSync(exposed)) continue;
140
+ const actual=fs.realpathSync(exposed);
141
+ if(inside(receiptDir,actual)||inside(actual,receiptDir)) throw new Error('host receipt directory overlaps a guest source or runtime path');
142
+ }
143
+ }
144
+
145
+ // Race the trusted service for the same immutable admission slot. If this wins,
146
+ // a late service cannot publish its start and must exit before guest launch.
147
+ // Only callers which durably enrolled this check in the receipt protocol may seal.
148
+ export function sealHostNotStarted({receiptDir,checkRunId}) {
149
+ try {
150
+ prepareHostReceipts({receiptDir,checkRunId});
151
+ publish(receiptDir,checkRunId,'0'.repeat(32),'start',{notStarted:true});
152
+ } catch {}
153
+ return readVerifiedHostStop({receiptDir,checkRunId});
154
+ }
@@ -0,0 +1,33 @@
1
+ """Deny guest allocations charged to shared per-user kernel quotas."""
2
+ import ctypes
3
+ import errno
4
+
5
+
6
+ def install(prctl=None):
7
+ libc = ctypes.CDLL(None, use_errno=True)
8
+ prctl = prctl or libc.prctl
9
+ if prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS
10
+ raise RuntimeError('seccomp unavailable: no_new_privs failed')
11
+ try:
12
+ sec = ctypes.CDLL('libseccomp.so.2', use_errno=True)
13
+ except OSError as error:
14
+ raise RuntimeError('seccomp unavailable: libseccomp missing') from error
15
+ sec.seccomp_init.argtypes = [ctypes.c_uint32]
16
+ sec.seccomp_init.restype = ctypes.c_void_p
17
+ sec.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
18
+ sec.seccomp_rule_add.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint]
19
+ sec.seccomp_load.argtypes = [ctypes.c_void_p]
20
+ sec.seccomp_release.argtypes = [ctypes.c_void_p]
21
+ context = sec.seccomp_init(0x7fff0000) # SCMP_ACT_ALLOW
22
+ if not context:
23
+ raise RuntimeError('seccomp unavailable: initialization failed')
24
+ try:
25
+ for name in (b'inotify_init', b'inotify_init1', b'fanotify_init', b'mq_open',
26
+ b'add_key', b'request_key', b'keyctl'):
27
+ number = sec.seccomp_syscall_resolve_name(name)
28
+ if number < 0 or sec.seccomp_rule_add(context, 0x00050000 | errno.EPERM, number, 0) != 0:
29
+ raise RuntimeError('seccomp unavailable: cannot deny ' + name.decode())
30
+ if sec.seccomp_load(context) != 0:
31
+ raise RuntimeError('seccomp unavailable: filter installation failed')
32
+ finally:
33
+ sec.seccomp_release(context)
@@ -0,0 +1,54 @@
1
+ // Trusted systemd main process. Configuration travels over a bounded pipe;
2
+ // optional private receipts record positive launch/stop identity, never TTL-based release.
3
+ import fs from 'node:fs';
4
+ import {writeHostStart,validateReceiptIdentity} from './host-budget-receipts.mjs';
5
+ import {spawn} from 'node:child_process';
6
+ import {fileURLToPath} from 'node:url';
7
+ import readline from 'node:readline';
8
+ const lines=readline.createInterface({input:process.stdin});
9
+ let child=null;
10
+ let monitor=null;
11
+ lines.on('line',line=>{
12
+ if(child){child.stdin.write(line+'\n');return;}
13
+ const config=JSON.parse(line);
14
+ const relative=fs.readFileSync('/proc/self/cgroup','utf8').split('\n').find(l=>l.startsWith('0::'))?.slice(3);
15
+ if(!relative||relative.includes('..')) throw new Error('unified cgroup required');
16
+ const cgroup='/sys/fs/cgroup'+relative;
17
+ const limit=name=>fs.readFileSync(cgroup+'/'+name,'utf8').trim();
18
+ const cpuMax=limit('cpu.max').split(/\s+/);
19
+ const cpuBounded=cpuMax.length===2&&cpuMax.every(value=>/^[1-9]\d*$/.test(value)&&Number.isSafeInteger(Number(value)))&&Number(cpuMax[0])<=Number(cpuMax[1]);
20
+ if(limit('memory.max')!==String(config.budgets.memory_bytes)||limit('memory.swap.max')!=='0'||limit('pids.max')!==String(config.budgets.processes)||!cpuBounded) throw new Error('required cgroup limits unavailable');
21
+ // Keep kernel-enforced whole-group OOM kills even though systemd must not
22
+ // turn them into the desktop's misleading system-wide shortage notice.
23
+ fs.writeFileSync(cgroup+'/memory.oom.group','1');
24
+ if(limit('memory.oom.group')!=='1') throw new Error('whole-group OOM kill unavailable');
25
+ let guestLine=line,childEnv=process.env;
26
+ if(config.receipts!==undefined) {
27
+ const {checkRunId,receiptDir}=config.receipts??{};
28
+ validateReceiptIdentity(checkRunId,process.env.INVOCATION_ID);
29
+ // The ledger stays outside the copied workspace and every read-only guest
30
+ // mount. maskPaths contains workspace-relative files, never host directories.
31
+ // The ID is supplied by systemd, but existence is proved by this durable
32
+ // trusted write after cgroup limits are checked and before any guest launch.
33
+ writeHostStart({receiptDir,checkRunId,invocationId:process.env.INVOCATION_ID,bootId:fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim(),cgroup:relative});
34
+ const {receipts,...guestConfig}=config;
35
+ guestLine=JSON.stringify(guestConfig);
36
+ const {INVOCATION_ID,...environment}=process.env;
37
+ childEnv=environment;
38
+ }
39
+ process.stdout.write(JSON.stringify({event:'pid',pid:process.pid})+'\n');
40
+ child=spawn('/usr/bin/python3',[fileURLToPath(new URL('./host-budget-storage.py',import.meta.url)),guestLine,cgroup],{stdio:['pipe','inherit','inherit'],env:childEnv});
41
+ // This observer stays outside the guest and also covers archive preparation,
42
+ // when the namespace supervisor may be blocked reading/extracting input.
43
+ monitor=setInterval(()=>{
44
+ const cpu=Number(limit('cpu.stat').match(/^usage_usec (\d+)/m)?.[1])/1000;
45
+ if(cpu>=config.budgets.cpu_ms){
46
+ process.stdout.write(JSON.stringify({event:'result',result:{error:'budget exceeded: cpu',exit:{code:125},phases:[],usage:{cpu_ms:cpu}}})+'\n');
47
+ process.exit(125);
48
+ }
49
+ },10);
50
+ child.stdin.on('error',()=>{});
51
+ child.once('error',()=>process.exit(125));
52
+ child.once('exit',code=>{clearInterval(monitor);process.exit(code??125);});
53
+ });
54
+ lines.on('close',()=>{if(child)child.kill('SIGKILL');else process.exit(125);});
@@ -0,0 +1,26 @@
1
+ // systemd runs this after stopping the service's control group. Check for
2
+ // unkillable survivors instead of treating a stop request as proof of cessation.
3
+ import fs from 'node:fs';
4
+ import {writeHostStop,validateReceiptIdentity} from './host-budget-receipts.mjs';
5
+ import {readCgroupProcesses} from './host-cgroup.mjs';
6
+ const relative=fs.readFileSync('/proc/self/cgroup','utf8').split('\n').find(l=>l.startsWith('0::')).slice(3);
7
+ const remaining=readCgroupProcesses('/sys/fs/cgroup'+relative);
8
+ const events=fs.readFileSync('/sys/fs/cgroup'+relative+'/memory.events','utf8');
9
+ const oom_kill=Number(events.match(/^oom_kill (\d+)$/m)?.[1] ?? 0);
10
+ const stop={verified:remaining.length===0,remaining_pids:remaining,invocation_id:process.env.INVOCATION_ID,result:process.env.SERVICE_RESULT,exit_code:process.env.EXIT_CODE,exit_status:process.env.EXIT_STATUS,oom_kill};
11
+ try {
12
+ const args=process.argv.slice(2);
13
+ if(args.length) {
14
+ if(args.length!==4||args[0]!=='--check-run-id'||args[2]!=='--receipt-dir') throw new Error('invalid host receipt recorder arguments');
15
+ const checkRunId=args[1],receiptDir=args[3],invocationId=process.env.INVOCATION_ID;
16
+ validateReceiptIdentity(checkRunId,invocationId);
17
+ writeHostStop({receiptDir,checkRunId,invocationId,verified:stop.verified,remaining_pids:remaining});
18
+ }
19
+ } catch {
20
+ process.stderr.write('durable host stop receipt unavailable\n');
21
+ stop.verified=false;
22
+ process.exitCode=1;
23
+ } finally {
24
+ // A pipe event is advisory. A failed durable write cannot assert a stop.
25
+ process.stdout.write(JSON.stringify({event:'stopped',stop})+'\n');
26
+ }