@tnunamak/dalan 0.0.0-stage → 0.5.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 (182) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +339 -0
  5. package/README.md +348 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +38 -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 +755 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/connect-chatgpt.md +78 -0
  17. package/docs/connection-longevity.md +37 -0
  18. package/docs/dalan-upgrade.md +242 -0
  19. package/docs/deadman.md +59 -0
  20. package/docs/dot-pr-reviewer.config.example.json +9 -0
  21. package/docs/durability-audit.md +27 -0
  22. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  23. package/docs/keycloak-oauth-setup.md +30 -0
  24. package/docs/local-agent-mcp.md +39 -0
  25. package/docs/manual-setup.md +135 -0
  26. package/docs/mirror-fetch.md +98 -0
  27. package/docs/operations.md +751 -0
  28. package/docs/operator-duties.md +68 -0
  29. package/docs/owner-integrator.md +27 -0
  30. package/docs/portable-auth-profile.md +109 -0
  31. package/docs/pr-head-reviewer.md +54 -0
  32. package/docs/pr-preflight.md +26 -0
  33. package/docs/pull-workers.md +97 -0
  34. package/docs/redaction.md +27 -0
  35. package/docs/service-setup.md +166 -0
  36. package/docs/setup-reference.md +80 -0
  37. package/docs/t3-connector-icon.png +0 -0
  38. package/docs/t3-integration.md +49 -0
  39. package/docs/t3-result-retry-delivery.md +41 -0
  40. package/docs/t3-reverse-control.md +107 -0
  41. package/docs/usage.md +439 -0
  42. package/docs/worker-clients.md +285 -0
  43. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  44. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  45. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  46. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  47. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  48. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  49. package/package.json +65 -4
  50. package/packages/job-core/README.md +18 -0
  51. package/packages/job-core/index.mjs +2 -0
  52. package/packages/job-core/package.json +8 -0
  53. package/packages/job-core/protocol/canonical.mjs +11 -0
  54. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  55. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  56. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  57. package/packages/job-core/transitions.mjs +25 -0
  58. package/scripts/daily-selfcheck.mjs +135 -0
  59. package/scripts/lib/expose-tailscale.mjs +408 -0
  60. package/scripts/live-trial/common.mjs +272 -0
  61. package/scripts/monitor-targets.mjs +44 -0
  62. package/scripts/upgrade-drain.mjs +39 -0
  63. package/scripts/worker-bridge-setup.mjs +925 -0
  64. package/src/ack-ledger.mjs +37 -0
  65. package/src/acp-bridge.mjs +412 -0
  66. package/src/acp-context.mjs +138 -0
  67. package/src/admin-socket.mjs +14 -0
  68. package/src/alerts.mjs +147 -0
  69. package/src/artifact-journal.mjs +75 -0
  70. package/src/as-files.mjs +347 -0
  71. package/src/as-store.mjs +456 -0
  72. package/src/as.mjs +497 -0
  73. package/src/auth.mjs +166 -0
  74. package/src/builtin-http.mjs +22 -0
  75. package/src/check-coverage.mjs +38 -0
  76. package/src/check-lint.mjs +88 -0
  77. package/src/check-readiness.mjs +112 -0
  78. package/src/check-response.mjs +19 -0
  79. package/src/claim-command-ledger.mjs +51 -0
  80. package/src/cli-help.mjs +172 -0
  81. package/src/cli-name.mjs +16 -0
  82. package/src/connect-cli.mjs +126 -0
  83. package/src/consumers.mjs +61 -0
  84. package/src/deadman.mjs +329 -0
  85. package/src/delivery.mjs +19 -0
  86. package/src/demo-worker.mjs +150 -0
  87. package/src/destinations/index.mjs +23 -0
  88. package/src/destinations/none.mjs +15 -0
  89. package/src/destinations/t3.mjs +109 -0
  90. package/src/diagnostic.mjs +78 -0
  91. package/src/docs-url.mjs +9 -0
  92. package/src/drain-runner.mjs +9 -0
  93. package/src/drained-slot.mjs +53 -0
  94. package/src/drained.mjs +40 -0
  95. package/src/durable-waiters.mjs +236 -0
  96. package/src/env.mjs +19 -0
  97. package/src/execution.mjs +112 -0
  98. package/src/failure-type.mjs +28 -0
  99. package/src/get-summary.mjs +32 -0
  100. package/src/git-env.mjs +15 -0
  101. package/src/host-budget-receipts.mjs +154 -0
  102. package/src/host-budget-seccomp.py +33 -0
  103. package/src/host-budget-service.mjs +54 -0
  104. package/src/host-budget-stop.mjs +26 -0
  105. package/src/host-budget-storage.py +259 -0
  106. package/src/host-budget.mjs +149 -0
  107. package/src/host-cgroup.mjs +23 -0
  108. package/src/host-check-allowlist.mjs +42 -0
  109. package/src/host-execution-policy.mjs +38 -0
  110. package/src/host-health.mjs +34 -0
  111. package/src/host-stop-reverify.mjs +44 -0
  112. package/src/inbox.mjs +55 -0
  113. package/src/integrator.mjs +322 -0
  114. package/src/job-retention.mjs +69 -0
  115. package/src/legacy-names.mjs +8 -0
  116. package/src/lifecycle.mjs +291 -0
  117. package/src/limits.mjs +31 -0
  118. package/src/loopback.mjs +9 -0
  119. package/src/mcp-outcome.mjs +70 -0
  120. package/src/mcp-stdio.mjs +191 -0
  121. package/src/mirror-fetch-lock.py +164 -0
  122. package/src/mirror-fetch.mjs +174 -0
  123. package/src/notify-ledger.mjs +82 -0
  124. package/src/objectives.mjs +129 -0
  125. package/src/owner-report-artifact.mjs +66 -0
  126. package/src/patch-apply.mjs +84 -0
  127. package/src/path-syntax.mjs +16 -0
  128. package/src/paths.mjs +67 -0
  129. package/src/pr-head-reviewer.mjs +596 -0
  130. package/src/pr-preflight.mjs +51 -0
  131. package/src/prepared-node-modules.mjs +129 -0
  132. package/src/projects.mjs +480 -0
  133. package/src/protocol-artifact-commands.mjs +52 -0
  134. package/src/protocol-delivery-driver.mjs +167 -0
  135. package/src/protocol-finish.mjs +100 -0
  136. package/src/protocol-owner-command.mjs +35 -0
  137. package/src/protocol-owner-mutations.mjs +22 -0
  138. package/src/protocol-owner-waiters.mjs +67 -0
  139. package/src/protocol-retention.mjs +52 -0
  140. package/src/protocol-services.mjs +61 -0
  141. package/src/protocol-stop-observer.mjs +131 -0
  142. package/src/publish-plan.mjs +245 -0
  143. package/src/redaction.mjs +763 -0
  144. package/src/rejections.mjs +18 -0
  145. package/src/request-log.mjs +102 -0
  146. package/src/restore-check.mjs +90 -0
  147. package/src/result-binding.mjs +65 -0
  148. package/src/runtime-check.mjs +13 -0
  149. package/src/sandbox-supervisor.mjs +105 -0
  150. package/src/schema-subset.mjs +186 -0
  151. package/src/scopes.mjs +15 -0
  152. package/src/server.mjs +1340 -0
  153. package/src/shutdown-signal.mjs +12 -0
  154. package/src/signal-sandbox-processes.py +56 -0
  155. package/src/signal.mjs +119 -0
  156. package/src/status-evidence.mjs +47 -0
  157. package/src/status-summary.mjs +54 -0
  158. package/src/store.mjs +3057 -0
  159. package/src/submission-policy.mjs +623 -0
  160. package/src/subscription-storage.mjs +64 -0
  161. package/src/t3-audit.mjs +120 -0
  162. package/src/t3-control.mjs +102 -0
  163. package/src/t3-transport.mjs +158 -0
  164. package/src/t3.mjs +209 -0
  165. package/src/terminal-safe.mjs +19 -0
  166. package/src/tool-registry.mjs +451 -0
  167. package/src/try-command.mjs +11 -0
  168. package/src/try.mjs +589 -0
  169. package/src/webhooks.mjs +86 -0
  170. package/src/work-order.mjs +265 -0
  171. package/src/worker-instructions.mjs +26 -0
  172. package/src/worker-prompt.mjs +4 -0
  173. package/src/workers.mjs +622 -0
  174. package/src/workspace.mjs +1058 -0
  175. package/systemd/dot-bridge-heartbeat.service +18 -0
  176. package/systemd/dot-bridge-heartbeat.timer +10 -0
  177. package/systemd/dot-bridge-selfcheck.service +12 -0
  178. package/systemd/dot-bridge-selfcheck.timer +11 -0
  179. package/systemd/dot-bridge.service +17 -0
  180. package/systemd/dot-deadman.service +30 -0
  181. package/systemd/dot-pr-reviewer.service +11 -0
  182. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,131 @@
1
+ // Private native stop observations. Store installs the versioned state;
2
+ // runtime composition supplies scoped authority and trusted evidence.
3
+ const fail = code => { throw Object.assign(new Error(code), {code}); };
4
+ const text = x => typeof x === 'string' && x.length > 0 && x.length <= 512;
5
+ const nat = x => Number.isSafeInteger(x) && x >= 0;
6
+ function canonical(x) {
7
+ if (x === null || typeof x === 'string' || typeof x === 'boolean') return x;
8
+ if (typeof x === 'number' && Number.isFinite(x)) return x;
9
+ if (Array.isArray(x)) return x.map(canonical);
10
+ if (x && Object.getPrototypeOf(x) === Object.prototype)
11
+ return Object.fromEntries(Object.keys(x).sort().map(k => [k, canonical(x[k])]));
12
+ fail('invalid_input');
13
+ }
14
+ const json = x => JSON.stringify(canonical(x));
15
+ function closed(x, keys) {
16
+ if (!x || Object.getPrototypeOf(x) !== Object.prototype ||
17
+ Object.keys(x).length !== keys.length || keys.some(k => !Object.hasOwn(x,k))) fail('invalid_input');
18
+ }
19
+ export function migrateProtocolStopObserver(db) {
20
+ if (!db.isTransaction) fail('transaction_required');
21
+ db.exec(`
22
+ CREATE TABLE IF NOT EXISTS protocol_stop_enrollments (
23
+ job TEXT PRIMARY KEY, binding TEXT NOT NULL);
24
+ CREATE TABLE IF NOT EXISTS protocol_stop_observations (
25
+ job TEXT PRIMARY KEY REFERENCES protocol_stop_enrollments(job),
26
+ binding TEXT NOT NULL, observation TEXT NOT NULL);
27
+ CREATE TABLE IF NOT EXISTS protocol_stop_receipts (
28
+ job TEXT NOT NULL, observer TEXT NOT NULL, command_key TEXT NOT NULL,
29
+ identity TEXT NOT NULL, reply TEXT NOT NULL, PRIMARY KEY(job,observer,command_key));
30
+ `);
31
+ }
32
+ export function createProtocolStopObserver(store, {authorize,resolveEvidence} = {}) {
33
+ if (typeof authorize !== 'function' || typeof resolveEvidence !== 'function') fail('callbacks_required');
34
+ const db=store.db;
35
+ function principal(job,action,authority) {
36
+ if (!text(job)) fail('invalid_job');
37
+ const id=authorize({job,action,authority});
38
+ if (!text(id)) fail('unauthorized');
39
+ store.assertProtocolAvailable(job);
40
+ if (!store.isProtocolJob(job)) fail('protocol_required');
41
+ return id;
42
+ }
43
+ const current = job => db.prepare('SELECT * FROM claims WHERE request_id=?').get(job);
44
+ function binding(job,observer) {
45
+ const row=db.prepare('SELECT binding FROM protocol_stop_enrollments WHERE job=?').get(job);
46
+ if (!row) fail('execution_not_enrolled');
47
+ const b=JSON.parse(row.binding), c=current(job);
48
+ if (!c || c.claim_id!==b.claim || c.epoch!==b.epoch || b.observer!==observer) fail('stale_observer');
49
+ return b;
50
+ }
51
+ function cached(job,input,identity) {
52
+ const {observer}=JSON.parse(identity);
53
+ const row=db.prepare('SELECT identity,reply FROM protocol_stop_receipts WHERE job=? AND observer=? AND command_key=?').get(job,observer,input.key);
54
+ if (!row) return null;
55
+ if (row.identity!==identity) fail('command_conflict');
56
+ return JSON.parse(row.reply);
57
+ }
58
+ function enroll(job,authority,execution) {
59
+ closed(execution,['claim','epoch','invocation','scope']);
60
+ if (!text(execution.claim)||!nat(execution.epoch)||execution.epoch<1||
61
+ !text(execution.invocation)||!text(execution.scope)) fail('invalid_execution');
62
+ return store.transaction(()=>{
63
+ const observer=principal(job,'enroll',authority),c=current(job);
64
+ const status=db.prepare('SELECT status FROM assignments WHERE request_id=?').get(job)?.status;
65
+ if (!c || c.claim_id!==execution.claim || c.epoch!==execution.epoch ||
66
+ c.state!=='active' || status!=='claimed' || store.leaseExpired(c)) fail('stale_authority');
67
+ const b={job,...execution,observer}, encoded=json(b);
68
+ const old=db.prepare('SELECT binding FROM protocol_stop_enrollments WHERE job=?').get(job);
69
+ if (old) {
70
+ const prior=JSON.parse(old.binding);
71
+ if (prior.epoch===b.epoch) {
72
+ if (old.binding!==encoded) fail('enrollment_conflict');
73
+ return b;
74
+ }
75
+ if (prior.epoch>b.epoch) fail('stale_authority');
76
+ db.prepare('DELETE FROM protocol_stop_observations WHERE job=?').run(job);
77
+ }
78
+ db.prepare('INSERT INTO protocol_stop_enrollments VALUES(?,?) ON CONFLICT(job) DO UPDATE SET binding=excluded.binding').run(job,encoded);
79
+ return b;
80
+ });
81
+ }
82
+ async function observeStop(job,authority,input) {
83
+ closed(input,['key','revision','stop','evidence']);
84
+ if (!text(input.key)||!nat(input.revision)||!['confirmed','unverified'].includes(input.stop)||!text(input.evidence)) fail('invalid_input');
85
+ const prepare=()=> {
86
+ const observer=principal(job,'observe_stop',authority);
87
+ const identity=json({job,observer,operation:'observe_stop',input});
88
+ const replay=cached(job,input,identity);
89
+ return {observer,b:replay?null:binding(job,observer),identity,replay};
90
+ };
91
+ const first=store.transaction(prepare);
92
+ if (first.replay) return first.replay;
93
+ // The label is only a lookup key for a trusted dependency, never proof.
94
+ const resolved=await resolveEvidence({...first.b},input.evidence);
95
+ const evidence=resolved===undefined?null:canonical(resolved);
96
+ return store.transaction(()=>{
97
+ const next=prepare();
98
+ if (next.replay) return next.replay;
99
+ if (next.identity!==first.identity||json(next.b)!==json(first.b)) fail('stale_observer');
100
+ if (store.protocolRevision(job)!==input.revision) fail('revision_conflict');
101
+ const status=db.prepare('SELECT status FROM assignments WHERE request_id=?').get(job)?.status;
102
+ if (!['cancelled','finished'].includes(status)) fail('terminal_required');
103
+ if (!evidence || evidence.verified!==true || json(evidence.binding)!==json(next.b) ||
104
+ typeof evidence.stopped!=='boolean' || !Array.isArray(evidence.remaining_pids) ||
105
+ evidence.remaining_pids.some(p=>!Number.isSafeInteger(p)||p<=0) ||
106
+ (input.stop==='confirmed' && (!evidence.stopped || evidence.remaining_pids.length!==0)) ||
107
+ (input.stop==='unverified' && evidence.stopped)) fail('stop_evidence_invalid');
108
+ const old=db.prepare('SELECT observation FROM protocol_stop_observations WHERE job=?').get(job);
109
+ if (old && JSON.parse(old.observation).stop==='confirmed' && input.stop!=='confirmed') fail('stop_regression');
110
+ const revision=store.advanceProtocolRevisionInTransaction(job);
111
+ const observation={stop:input.stop,assurance:'product-owned-observation',scope:next.b.scope,
112
+ observer:next.observer,claim:next.b.claim,epoch:next.b.epoch,invocation:next.b.invocation,
113
+ evidence:input.evidence,verified:evidence.verified,remaining_pids:evidence.remaining_pids,revision};
114
+ db.prepare('INSERT INTO protocol_stop_observations VALUES(?,?,?) ON CONFLICT(job) DO UPDATE SET binding=excluded.binding,observation=excluded.observation')
115
+ .run(job,json(next.b),json(observation));
116
+ store.protocolEventInTransaction(job,'stop_observed',observation,next.b.epoch);
117
+ const reply={revision,stop:input.stop};
118
+ db.prepare('INSERT INTO protocol_stop_receipts VALUES(?,?,?,?,?)').run(job,next.observer,input.key,next.identity,json(reply));
119
+ return reply;
120
+ });
121
+ }
122
+ function getObservation(job) {
123
+ store.assertProtocolAvailable(job);
124
+ if (!store.isProtocolJob(job)) fail('protocol_required');
125
+ const row=db.prepare('SELECT binding,observation FROM protocol_stop_observations WHERE job=?').get(job);
126
+ if (!row) return null;
127
+ const b=JSON.parse(row.binding),c=current(job);
128
+ return c&&c.claim_id===b.claim&&c.epoch===b.epoch?JSON.parse(row.observation):null;
129
+ }
130
+ return {enroll,observeStop,getObservation};
131
+ }
@@ -0,0 +1,245 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ /**
4
+ * Pure, explicit owner-invoked publication planning. This is not a writer.
5
+ *
6
+ * API: createPublicationPlan({ selection, candidate, presentation }). The caller
7
+ * must authenticate the owner and obtain immutable metadata before calling.
8
+ * selection.binding pins the candidate.binding fields below; neither is inferred
9
+ * from lifecycle observations. selection.required_checks and verified_receipts
10
+ * are independently owner-selected evidence, not copied from worker assertions.
11
+ * The planner checks consistency, not authenticity, freshness or remote state.
12
+ * A coherent forgery cannot be authenticated by this data-only boundary.
13
+ *
14
+ * Inputs are plain JSON data (not executable objects). Only github.com, exact
15
+ * same-repository/source-base planning and a new branch plus draft PR are
16
+ * supported in v1. Rebase, forks, other hosts and other operations fail closed.
17
+ * Text fields are plain text; consumers must not interpret them as HTML or shell.
18
+ * canonical_json ends in LF; sha256 covers exactly its UTF-8 bytes, excluding the
19
+ * digest envelope. Branch identity binds the version, full binding and PR text.
20
+ * Evidence changes may change plan bytes but do not create another branch intent.
21
+ */
22
+ export const PLANNER_VERSION = 'dalan-publish-plan/1';
23
+
24
+ const BINDING_KEYS = ['request_id', 'result_receipt', 'artifact_id', 'artifact_sha256',
25
+ 'source_base_sha', 'source_repository', 'target_repository', 'target_base_ref',
26
+ 'target_base_sha', 'intended_operation'];
27
+ const OBSERVATIONS = ['finished', 'accepted', 'applied', 'repository_read_admitted', 'tool_success'];
28
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
29
+ const fail = message => { throw new TypeError(message); };
30
+ const hash = text => createHash('sha256').update(text, 'utf8').digest('hex');
31
+
32
+ // Copy only data descriptors; toJSON and accessors are never evaluated.
33
+ function jsonData(value, ancestors = new Set(), budget = { nodes: 0 }, depth = 0) {
34
+ if (++budget.nodes > 20000 || depth > 24) fail('JSON input exceeds bounds');
35
+ if (value === null || typeof value === 'boolean') return value;
36
+ if (typeof value === 'string') {
37
+ if (value.length > 50000) fail('JSON string exceeds bounds');
38
+ return value;
39
+ }
40
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
41
+ if (typeof value !== 'object') fail('plain JSON data required');
42
+ if (ancestors.has(value)) fail('cyclic JSON input');
43
+ const array = Array.isArray(value), proto = Object.getPrototypeOf(value);
44
+ if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) fail('plain JSON data required');
45
+ const descriptors = Object.getOwnPropertyDescriptors(value);
46
+ if (Reflect.ownKeys(descriptors).some(key => typeof key !== 'string')) fail('JSON symbol keys are unsupported');
47
+ for (const [key, descriptor] of Object.entries(descriptors)) {
48
+ if (!Object.hasOwn(descriptor, 'value') || (!descriptor.enumerable && !(array && key === 'length'))) fail('JSON data descriptors required; no accessors');
49
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) fail('unsafe JSON key');
50
+ }
51
+ ancestors.add(value);
52
+ let result;
53
+ if (array) {
54
+ const size = descriptors.length.value;
55
+ if (size > 1000 || Object.keys(descriptors).length !== size + 1) fail('dense bounded JSON array required');
56
+ result = [];
57
+ for (let n = 0; n < size; n++) {
58
+ if (!Object.hasOwn(descriptors, n)) fail('dense JSON array required');
59
+ result.push(jsonData(descriptors[n].value, ancestors, budget, depth + 1));
60
+ }
61
+ } else {
62
+ result = {};
63
+ for (const key of Object.keys(descriptors).sort(compare)) {
64
+ result[key] = jsonData(descriptors[key].value, ancestors, budget, depth + 1);
65
+ }
66
+ }
67
+ ancestors.delete(value);
68
+ return result;
69
+ }
70
+
71
+ function shape(value, required, optional, label) {
72
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(`${label}: object required`);
73
+ for (const key of required) if (!Object.hasOwn(value, key)) fail(`${label}.${key}: required`);
74
+ for (const key of Object.keys(value)) if (!required.includes(key) && !optional.includes(key)) fail(`${label}: unknown field ${key}`);
75
+ return value;
76
+ }
77
+
78
+ function matches(value, pattern, label, maximum = 256) {
79
+ if (typeof value !== 'string' || value.length > maximum || !pattern.test(value)) fail(`${label}: invalid value`);
80
+ return value;
81
+ }
82
+
83
+ const id = (value, label) => matches(value, /^[A-Za-z0-9][A-Za-z0-9_-]*$/, label, 128);
84
+ const commit = (value, label) => matches(value, /^[a-f0-9]{40}$/, label, 40);
85
+ const digest = (value, label) => matches(value, /^[a-f0-9]{64}$/, label, 64);
86
+
87
+ function repository(value, label) {
88
+ shape(value, ['host', 'id', 'owner_id', 'owner', 'name'], [], label);
89
+ if (value.host !== 'github.com') fail(`${label}.host: unsupported host; URLs are not accepted`);
90
+ matches(value.id, /^[1-9][0-9]*$/, `${label}.id`, 32);
91
+ matches(value.owner_id, /^[1-9][0-9]*$/, `${label}.owner_id`, 32);
92
+ matches(value.owner, /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/, `${label}.owner`, 39);
93
+ matches(value.name, /^[A-Za-z0-9][A-Za-z0-9_.-]*$/, `${label}.name`, 100);
94
+ if (value.owner.includes('--') || value.name.includes('..') || value.name.endsWith('.') || /\.git$/i.test(value.name)) fail(`${label}: traversal-like name`);
95
+ return value;
96
+ }
97
+
98
+ function baseRef(value, label) {
99
+ matches(value, /^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._/-]*$/, label, 240);
100
+ if (value.includes('..') || value.endsWith('.') || value.split('/').some(part => !part || part.startsWith('.') || part.endsWith('.lock'))) fail(`${label}: invalid ref`);
101
+ return value;
102
+ }
103
+
104
+ function binding(value, label) {
105
+ shape(value, BINDING_KEYS, [], label);
106
+ for (const key of ['request_id', 'result_receipt', 'artifact_id']) id(value[key], `${label}.${key}`);
107
+ digest(value.artifact_sha256, `${label}.artifact_sha256`);
108
+ commit(value.source_base_sha, `${label}.source_base_sha`);
109
+ commit(value.target_base_sha, `${label}.target_base_sha`);
110
+ repository(value.source_repository, `${label}.source_repository`);
111
+ repository(value.target_repository, `${label}.target_repository`);
112
+ baseRef(value.target_base_ref, `${label}.target_base_ref`);
113
+ if (value.intended_operation !== 'create-branch-and-draft-pr') fail(`${label}: unsupported intended operation`);
114
+ return value;
115
+ }
116
+
117
+ function setOfIds(value, label) {
118
+ if (!Array.isArray(value) || value.length > 128) fail(`${label}: bounded array required`);
119
+ const result = value.map(item => id(item, label)).sort(compare);
120
+ if (new Set(result).size !== result.length) fail(`${label}: duplicate value`);
121
+ return result;
122
+ }
123
+
124
+ function text(value, label, maximum, multiline) {
125
+ if (typeof value !== 'string' || value.length > maximum || (!multiline && !value.trim())) fail(`${label}: invalid text`);
126
+ const controls = multiline ? /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/ : /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
127
+ if (controls.test(value) || !value.isWellFormed()) fail(`${label}: unsafe text controls`);
128
+ return value;
129
+ }
130
+
131
+ function canonical(value) {
132
+ const sort = item => Array.isArray(item) ? item.map(sort) : item && typeof item === 'object'
133
+ ? Object.fromEntries(Object.keys(item).sort(compare).map(key => [key, sort(item[key])])) : item;
134
+ return JSON.stringify(sort(value)).replace(/[<>&\u2028\u2029]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`) + '\n';
135
+ }
136
+
137
+ function frozen(value) {
138
+ if (value && typeof value === 'object') { Object.values(value).forEach(frozen); Object.freeze(value); }
139
+ return value;
140
+ }
141
+
142
+ // Human-readable literal text, deliberately not Markdown, HTML or shell quoting.
143
+ function literal(value) {
144
+ return JSON.stringify(value).replace(/[<>&`$\[\]()*_#!|~@]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
145
+ }
146
+
147
+ function evidence(candidate, selection, bound) {
148
+ const required = setOfIds(selection.required_checks ?? [], 'selection.required_checks');
149
+ const selectedReceipts = setOfIds(selection.verified_receipts ?? [], 'selection.verified_receipts');
150
+ const raw = candidate.checks ?? [];
151
+ if (!Array.isArray(raw) || raw.length > 128) fail('candidate.checks: bounded array required');
152
+ const blockers = [], checks = [], ids = new Set(), receipts = new Set();
153
+ const block = (code, check_id = null) => blockers.push({ code, check_id });
154
+ if (candidate.artifact_sealed !== true) block('artifact_not_sealed');
155
+ if (required.length === 0) block('required_check_policy_missing');
156
+ for (const rawCheck of raw) {
157
+ shape(rawCheck, ['check_id', 'status'], ['receipt_id', 'provenance', 'binding'], 'check');
158
+ const check_id = id(rawCheck.check_id, 'check.check_id');
159
+ if (ids.has(check_id)) fail('duplicate check_id');
160
+ ids.add(check_id);
161
+ if (!['passed', 'failed', 'skipped', 'pending'].includes(rawCheck.status)) fail('check.status: invalid status');
162
+ const receipt_id = rawCheck.receipt_id == null ? null : id(rawCheck.receipt_id, 'check.receipt_id');
163
+ if (receipt_id && receipts.has(receipt_id)) fail('duplicate evidence receipt');
164
+ if (receipt_id) receipts.add(receipt_id);
165
+ const provenance = rawCheck.provenance ?? null;
166
+ if (provenance) {
167
+ shape(provenance, ['kind', 'actor_id'], [], 'check.provenance');
168
+ id(provenance.actor_id, 'check.provenance.actor_id');
169
+ if (!['owner-verified', 'worker-attested', 'tool-reported'].includes(provenance.kind)) fail('check.provenance: invalid kind');
170
+ }
171
+ const checkBinding = rawCheck.binding == null ? null : binding(rawCheck.binding, 'check.binding');
172
+ if (rawCheck.status !== 'passed') block(`check_${rawCheck.status}`, check_id);
173
+ if (checkBinding === null || canonical(checkBinding) !== canonical(bound)) block('check_binding_mismatch', check_id);
174
+ if (provenance?.kind !== 'owner-verified') block('check_not_owner_verified', check_id);
175
+ if (receipt_id === null || !selectedReceipts.includes(receipt_id)) block('check_receipt_not_owner_selected', check_id);
176
+ checks.push({ check_id, receipt_id, status: rawCheck.status, provenance, binding: checkBinding });
177
+ }
178
+ for (const checkId of required) if (!ids.has(checkId)) block('required_check_missing', checkId);
179
+ for (const receipt of selectedReceipts) if (!receipts.has(receipt)) block('selected_receipt_missing', receipt);
180
+ checks.sort((a, b) => compare(a.check_id, b.check_id));
181
+ blockers.sort((a, b) => compare(a.check_id ?? '', b.check_id ?? '') || compare(a.code, b.code));
182
+ return {
183
+ status: blockers.length ? 'blocked' : 'owner-evidence-satisfied',
184
+ independently_verified: false,
185
+ basis: 'Owner-selected receipts and supplied provenance only; the planner does not authenticate or run checks.',
186
+ required_checks: required, owner_selected_receipts: selectedReceipts, checks, blockers,
187
+ };
188
+ }
189
+
190
+ export function createPublicationPlan(input) {
191
+ const data = jsonData(input);
192
+ shape(data, ['selection', 'candidate', 'presentation'], [], 'input');
193
+ shape(data.selection, ['binding'], ['required_checks', 'verified_receipts'], 'selection');
194
+ shape(data.candidate, ['binding'], ['checks', 'artifact_sealed', 'observations'], 'candidate');
195
+ shape(data.presentation, ['title', 'body'], [], 'presentation');
196
+ const selected = binding(data.selection.binding, 'selection.binding');
197
+ const supplied = binding(data.candidate.binding, 'candidate.binding');
198
+ if (canonical(selected) !== canonical(supplied)) fail('selection/candidate binding mismatch');
199
+ if (canonical(selected.source_repository) !== canonical(selected.target_repository)) fail('same repository required; no implicit fork');
200
+ if (selected.source_base_sha !== selected.target_base_sha) fail('source/target base mismatch; no implicit rebase');
201
+ if (data.candidate.artifact_sealed !== undefined && typeof data.candidate.artifact_sealed !== 'boolean') fail('candidate.artifact_sealed: boolean required');
202
+ const observations = data.candidate.observations ?? {};
203
+ shape(observations, [], OBSERVATIONS, 'candidate.observations');
204
+ for (const value of Object.values(observations)) if (typeof value !== 'boolean') fail('observation: boolean required');
205
+ const presentation = {
206
+ title: text(data.presentation.title, 'presentation.title', 200, false),
207
+ body: text(data.presentation.body, 'presentation.body', 20000, true),
208
+ };
209
+ const intentDigest = hash(canonical({ planner_version: PLANNER_VERSION, binding: selected, presentation }));
210
+ const branchName = `dalan/plan-${intentDigest}`;
211
+ const branchRef = `refs/heads/${branchName}`;
212
+ if (selected.target_base_ref === branchRef) fail('proposed branch must differ from target base ref');
213
+ const verification = evidence(data.candidate, data.selection, selected);
214
+ const plan = {
215
+ schema_version: 1, planner_version: PLANNER_VERSION, mode: 'dry-run', authorized_to_publish: false,
216
+ execution: 'not-executed', receipt_kind: 'plan-only', intent_sha256: intentDigest,
217
+ binding: selected, observations,
218
+ branch: { name: branchName, ref: branchRef, source_base_sha: selected.source_base_sha,
219
+ artifact_id: selected.artifact_id, artifact_sha256: selected.artifact_sha256,
220
+ resulting_commit_sha: null, existence: 'not-checked', update_existing: false },
221
+ pull_request: { repository: selected.target_repository, base_ref: selected.target_base_ref,
222
+ base_sha: selected.target_base_sha, head_ref: branchRef, draft: true, content_format: 'plain-text',
223
+ title_text: presentation.title, body_text: presentation.body },
224
+ verification,
225
+ limitations: [
226
+ 'This is a plan, not publication authority or an executed-write receipt.',
227
+ 'No patch bytes, resulting commit, remote ref freshness or branch availability were checked.',
228
+ 'A human must review the exact artifact and current target, obtain separate publication authority, and create any branch or draft PR independently.',
229
+ 'Acceptance, application, finish, read admission and tool success grant no publication authority.',
230
+ ],
231
+ };
232
+ const canonical_json = canonical(plan);
233
+ const explanation = [
234
+ 'DRY RUN ONLY — not authorized to publish; nothing executed.',
235
+ `Repository: ${literal(`${selected.target_repository.host}/${selected.target_repository.owner}/${selected.target_repository.name}`)} (ID ${selected.target_repository.id}).`,
236
+ `Proposed branch: ${literal(branchRef)}; target: ${literal(selected.target_base_ref)} at ${selected.target_base_sha}.`,
237
+ `Artifact: ${literal(selected.artifact_id)} SHA-256 ${selected.artifact_sha256}; result: ${literal(selected.result_receipt)}.`,
238
+ `Draft PR title (literal text): ${literal(presentation.title)}`,
239
+ `Draft PR body (literal text): ${literal(presentation.body)}`,
240
+ `Evidence: ${verification.status}. ${verification.basis}`,
241
+ ...verification.blockers.map(item => `Blocker: ${item.code}${item.check_id ? ` (${literal(item.check_id)})` : ''}.`),
242
+ ...plan.limitations,
243
+ ].join('\n') + '\n';
244
+ return frozen({ plan, canonical_json, sha256: hash(canonical_json), explanation });
245
+ }