@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.
- package/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- 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
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {createHash, timingSafeEqual, randomBytes,createCipheriv,createDecipheriv} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
4
|
+
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
|
|
5
|
+
export const PULL_PAGE_PREFIX='pullpage_';
|
|
6
|
+
export function routingPolicy(value,assignment) {
|
|
7
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(key=>!['version','allowed_workers','fan_out','deadline_at'].includes(key))) throw new Error('invalid routing policy: supported fields are version, allowed_workers, fan_out, deadline_at');
|
|
8
|
+
if(value.version!==1||value.fan_out!==undefined&&value.fan_out!==1) throw new Error('routing v1 supports version=1 and fan_out=1 only');
|
|
9
|
+
const names=value.allowed_workers;
|
|
10
|
+
if(!Array.isArray(names)||!names.length||names.length>100||names.some(name=>typeof name!=='string'||!(/^[a-z][a-z0-9_-]{0,31}$/).test(name))||new Set(names).size!==names.length) throw new Error('routing requires 1-100 distinct explicit allowed_workers');
|
|
11
|
+
if(assignment.execution_scope!=='read-only'||Object.hasOwn(assignment,'protocol')) throw new Error('routing v1 supports read-only assignments without protocol only');
|
|
12
|
+
const deadline=value.deadline_at??assignment.valid_until;
|
|
13
|
+
if(typeof deadline!=='string'||!/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(deadline)||!Number.isFinite(Date.parse(deadline))) throw new Error('routing requires an explicit RFC3339 deadline_at or assignment.valid_until');
|
|
14
|
+
const assignmentDeadline=assignment.valid_until===undefined?null:Date.parse(assignment.valid_until);
|
|
15
|
+
if(assignmentDeadline!==null&&!Number.isFinite(assignmentDeadline))throw new Error('invalid assignment valid_until');
|
|
16
|
+
return {version:1,allowed_workers:[...names].sort(),fan_out:1,deadline_at:new Date(Math.min(Date.parse(deadline),assignmentDeadline??Infinity)).toISOString()};
|
|
17
|
+
}
|
|
18
|
+
export function migratePullQueue(db) {
|
|
19
|
+
db.exec(`CREATE TABLE policy_work_orders (
|
|
20
|
+
work_order_id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE, intent_digest TEXT NOT NULL,
|
|
21
|
+
owner_hash TEXT NOT NULL, payload TEXT NOT NULL, options TEXT NOT NULL, routing TEXT NOT NULL,
|
|
22
|
+
approvals TEXT NOT NULL, created_at TEXT NOT NULL, priority TEXT NOT NULL,
|
|
23
|
+
state TEXT NOT NULL DEFAULT 'queued', owner_read_at TEXT, cancelled_at TEXT, cancelled_reason TEXT,
|
|
24
|
+
child_request_id TEXT UNIQUE REFERENCES assignments(request_id),
|
|
25
|
+
receipt TEXT, worker TEXT, subject TEXT, connection_id TEXT, acquisition_id TEXT
|
|
26
|
+
); CREATE INDEX policy_work_backlog ON policy_work_orders(state,priority,created_at);
|
|
27
|
+
CREATE TRIGGER policy_work_intent_immutable BEFORE UPDATE OF work_order_id,request_id,intent_digest,owner_hash,payload,options,routing,approvals,created_at,priority ON policy_work_orders BEGIN SELECT RAISE(ABORT,'policy work intent is immutable'); END;`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A work order reserves the submitted request ID. Its one execution child takes
|
|
31
|
+
// that ID at acquisition, so the owner's durable capability and wait path survive.
|
|
32
|
+
export class PullQueue {
|
|
33
|
+
constructor(store) {
|
|
34
|
+
this.store=store;this.db=store.db;
|
|
35
|
+
this.db.prepare("INSERT OR IGNORE INTO bridge_state(key,value) VALUES('pull_cursor_key',?)").run(randomBytes(32).toString('hex'));
|
|
36
|
+
this.cursorKey=Buffer.from(this.db.prepare("SELECT value FROM bridge_state WHERE key='pull_cursor_key'").get().value,'hex');
|
|
37
|
+
}
|
|
38
|
+
cursor(worker,value) {
|
|
39
|
+
const nonce=randomBytes(12),cipher=createCipheriv('aes-256-gcm',this.cursorKey,nonce);cipher.setAAD(Buffer.from(worker));
|
|
40
|
+
const encrypted=Buffer.concat([cipher.update(JSON.stringify(value)),cipher.final()]);
|
|
41
|
+
return PULL_PAGE_PREFIX+Buffer.concat([nonce,cipher.getAuthTag(),encrypted]).toString('base64url');
|
|
42
|
+
}
|
|
43
|
+
readCursor(worker,cursor) {
|
|
44
|
+
try {
|
|
45
|
+
const bytes=Buffer.from(cursor.slice(PULL_PAGE_PREFIX.length),'base64url'),decipher=createDecipheriv('aes-256-gcm',this.cursorKey,bytes.subarray(0,12));
|
|
46
|
+
decipher.setAAD(Buffer.from(worker));decipher.setAuthTag(bytes.subarray(12,28));
|
|
47
|
+
const value=JSON.parse(Buffer.concat([decipher.update(bytes.subarray(28)),decipher.final()]).toString());
|
|
48
|
+
if(!Array.isArray(value)||value.length!==3||value.some(n=>!Number.isSafeInteger(n)||n<0)||value[1]>1||value[2]>value[0])throw new Error();
|
|
49
|
+
return value;
|
|
50
|
+
}catch{throw new Error('assignment not found');}
|
|
51
|
+
}
|
|
52
|
+
row(id) { return this.db.prepare('SELECT rowid AS sequence,* FROM policy_work_orders WHERE request_id=?').get(id); }
|
|
53
|
+
ownerRow(id) { return this.row(id); }
|
|
54
|
+
inbox(id) {
|
|
55
|
+
const row=this.row(id);if(!row||row.child_request_id)return null;
|
|
56
|
+
const projected=this.project(row);
|
|
57
|
+
return {target_worker:null,work_order_id:row.work_order_id,brief:projected.assignment.brief,created_at:row.created_at,finished_at:null,outcome:null,consumed:false,decision:null,delivered_t3:false,
|
|
58
|
+
cancelled_at:projected.cancelled_at,cancelled_reason:projected.cancelled_reason,cancelled_by_owner:row.state==='cancelled',read:row.owner_read_at!==null,failure_type:projected.cancelled_reason==='expired'?'expired':row.state==='cancelled'?'owner_cancelled':null,failure_type_source:projected.cancelled_reason==='expired'?'bridge_observed_transition':row.state==='cancelled'?'bridge_observed_transition':null,unanswered_blocker:null};
|
|
59
|
+
}
|
|
60
|
+
consume(id) {
|
|
61
|
+
const row=this.row(id);if(!row||row.child_request_id)return;
|
|
62
|
+
if(this.project(row).status==='cancelled')this.db.prepare('UPDATE policy_work_orders SET owner_read_at=COALESCE(owner_read_at,?) WHERE request_id=?').run(this.store.stamp(),id);
|
|
63
|
+
}
|
|
64
|
+
assertOwner(row,token) {
|
|
65
|
+
const got=createHash('sha256').update(token??'').digest();
|
|
66
|
+
if(!row||!timingSafeEqual(got,Buffer.from(row.owner_hash,'hex'))) throw new Error('invalid owner capability');
|
|
67
|
+
}
|
|
68
|
+
project(row) {
|
|
69
|
+
const assignment=JSON.parse(row.payload),routing=JSON.parse(row.routing),options=JSON.parse(row.options);
|
|
70
|
+
const expired=row.state==='queued'&&Date.parse(routing.deadline_at)<=this.store.nowMs();
|
|
71
|
+
return {request_id:row.request_id,work_order_id:row.work_order_id,child_request_id:row.child_request_id,
|
|
72
|
+
status:expired?'cancelled':row.state,assignment,routing,created_at:row.created_at,
|
|
73
|
+
target_worker:null,execution:options.execution,delivery_mode:options.delivery.mode==='t3'?`t3:${options.delivery.threadId}`:'none',
|
|
74
|
+
thread_id:options.delivery.threadId??null,environment_id:options.environmentId??null,
|
|
75
|
+
valid_until:routing.deadline_at,cancelled_at:row.cancelled_at,cancelled_reason:row.cancelled_reason??(expired?'expired':null),
|
|
76
|
+
claim:null,report:null,progress:[],owner_notes:[],delivery:[],lifecycle_events:[],required_capabilities:[]};
|
|
77
|
+
}
|
|
78
|
+
submit(payload,identity,options,routing,approvals,ownerToken,{dryRun=false}={}) {
|
|
79
|
+
const ownerHash=createHash('sha256').update(ownerToken).digest('hex');
|
|
80
|
+
const intent=digest(canonical({identity,options,routing,approvals}));
|
|
81
|
+
return this.store.inTransaction(()=>{
|
|
82
|
+
const old=this.row(payload.request_id);
|
|
83
|
+
if(old) {
|
|
84
|
+
this.assertOwner(old,ownerToken);
|
|
85
|
+
if(old.intent_digest!==intent) throw new Error('request_id conflict');
|
|
86
|
+
return {request_id:old.request_id,work_order_id:old.work_order_id,status:old.child_request_id?this.store.get(old.child_request_id).status:this.project(old).status,duplicate:true,...(dryRun?{dry_run:true,stored:false,verdict:'admissible'}:{})};
|
|
87
|
+
}
|
|
88
|
+
if(this.store.hasAssignment(payload.request_id)) throw new Error('request_id conflict');
|
|
89
|
+
if(Date.parse(routing.deadline_at)<=this.store.nowMs()) throw new Error('routing deadline expired');
|
|
90
|
+
const workId='work_'+digest(payload.request_id).slice(0,32);
|
|
91
|
+
if(!dryRun) this.db.prepare('INSERT INTO policy_work_orders(work_order_id,request_id,intent_digest,owner_hash,payload,options,routing,approvals,created_at,priority) VALUES(?,?,?,?,?,?,?,?,?,?)').run(workId,payload.request_id,intent,ownerHash,JSON.stringify(payload),JSON.stringify(options),JSON.stringify(routing),JSON.stringify(approvals),this.store.stamp(),options.priority);
|
|
92
|
+
return {request_id:payload.request_id,work_order_id:workId,status:'queued',duplicate:false,...(dryRun?{dry_run:true,stored:false,verdict:'admissible'}:{})};
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
eligible(row,worker,admit) {
|
|
96
|
+
if(!row||!JSON.parse(row.routing).allowed_workers.includes(worker)) return false;
|
|
97
|
+
try { admit(worker,JSON.parse(row.payload),JSON.parse(row.options).execution,JSON.parse(row.approvals)[worker]); return true; } catch { return false; }
|
|
98
|
+
}
|
|
99
|
+
get(id,worker,admit) {
|
|
100
|
+
const row=this.row(id);
|
|
101
|
+
if(!row||row.state!=='queued'||Date.parse(JSON.parse(row.routing).deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) throw new Error('assignment not found');
|
|
102
|
+
return {...this.project(row),guidance:'Claim this request_id with a fresh acquisition_id. The receipt names the immutable execution child; use its request_id and claim_id for all later tools.'};
|
|
103
|
+
}
|
|
104
|
+
list(worker,admit,cursor=null) {
|
|
105
|
+
let after=0,rank=0,snapshot=this.db.prepare('SELECT COALESCE(max(rowid),0) n FROM policy_work_orders').get().n;
|
|
106
|
+
if(cursor)[snapshot,rank,after]=this.readCursor(worker,cursor);
|
|
107
|
+
const rows=this.db.prepare("SELECT rowid AS sequence,CASE priority WHEN 'normal' THEN 0 ELSE 1 END AS rank,* FROM policy_work_orders WHERE state='queued' AND rowid<=? AND (CASE priority WHEN 'normal' THEN 0 ELSE 1 END>? OR (CASE priority WHEN 'normal' THEN 0 ELSE 1 END=? AND rowid>?)) ORDER BY rank,rowid").iterate(snapshot,rank,rank,after);
|
|
108
|
+
const items=[];let next=null;
|
|
109
|
+
for(const row of rows) {
|
|
110
|
+
if(Date.parse(JSON.parse(row.routing).deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) continue;
|
|
111
|
+
if(items.length===50) { const last=items.at(-1);next=this.cursor(worker,[snapshot,last._rank,last._sequence]);break; }
|
|
112
|
+
items.push({request_id:row.request_id,work_order_id:row.work_order_id,title:JSON.parse(row.payload).brief.slice(0,160),created_at:row.created_at,priority:row.priority,deadline_at:JSON.parse(row.routing).deadline_at,remaining_result_slots:1,_sequence:row.sequence,_rank:row.rank});
|
|
113
|
+
}
|
|
114
|
+
return {items:items.map(({_sequence,_rank,...item})=>item),next_page_request_id:next,guidance:'Use get with next_page_request_id to read the next page. Use claim with an offered request_id and fresh acquisition_id to acquire its single result slot. Capacity limits claims, not this backlog.'};
|
|
115
|
+
}
|
|
116
|
+
acquire(id,{worker,subject,connectionId,claimant,acquisitionId,leaseMs,capacity,preflight,admit}) {
|
|
117
|
+
if(typeof acquisitionId!=='string'||!(/^[A-Za-z0-9_-]{1,128}$/).test(acquisitionId)) throw new Error('policy work requires a fresh acquisition_id');
|
|
118
|
+
return this.store.transaction(()=>{
|
|
119
|
+
const row=this.row(id);
|
|
120
|
+
if(!row||!JSON.parse(row.routing).allowed_workers.includes(worker)) throw new Error('assignment not found');
|
|
121
|
+
if(row.child_request_id) {
|
|
122
|
+
if(row.worker!==worker||row.subject!==subject||row.connection_id!==(connectionId??null)||row.acquisition_id!==acquisitionId) throw new Error('work order already acquired');
|
|
123
|
+
if(this.store.get(id).status!=='claimed')throw new Error('assignment finished or cancelled');
|
|
124
|
+
const receipt=JSON.parse(row.receipt),held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
125
|
+
if(held?.claimant!==claimant||held?.lease_ms!==(leaseMs??this.store.limits.leaseMs))throw new Error('acquisition_id conflict');
|
|
126
|
+
this.store.assertClaim(id,receipt.claim_id,subject,worker);
|
|
127
|
+
this.store.assertRetryConnection(id,held,worker,connectionId);
|
|
128
|
+
return {...receipt,duplicate:true};
|
|
129
|
+
}
|
|
130
|
+
if(row.state!=='queued') throw new Error('assignment cancelled');
|
|
131
|
+
const payload=JSON.parse(row.payload),options=JSON.parse(row.options),routing=JSON.parse(row.routing),approval=JSON.parse(row.approvals)[worker];
|
|
132
|
+
if(Date.parse(routing.deadline_at)<=this.store.nowMs()) throw new Error('routing deadline expired');
|
|
133
|
+
admit(worker,payload,options.execution,approval);
|
|
134
|
+
// Both insert and ordinary claim join this transaction. A failed capacity,
|
|
135
|
+
// destination or preflight check leaves no child and no consumed slot.
|
|
136
|
+
this.store.submitInTransaction({...payload,valid_until:routing.deadline_at},options.delivery,options.environmentId,'',options.review,preflight,options.priority,options.meta,payload,null,worker,options.execution,options.execution,null,null,null,null,approval??null,row.owner_hash);
|
|
137
|
+
const claimed=this.store.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs??this.store.limits.leaseMs,connectionId);
|
|
138
|
+
if(!claimed.claim_id) throw new Error('policy child admission refused');
|
|
139
|
+
const held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
140
|
+
const receipt={...claimed,lease_expires_at:this.store.leaseExpiresAt(held),work_order_id:row.work_order_id,child_request_id:id};
|
|
141
|
+
this.db.prepare("UPDATE policy_work_orders SET state='acquired',child_request_id=?,receipt=?,worker=?,subject=?,connection_id=?,acquisition_id=? WHERE request_id=?").run(id,JSON.stringify(receipt),worker,subject,connectionId??null,acquisitionId,id);
|
|
142
|
+
return receipt;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
cancel(id,reason=null) {
|
|
146
|
+
return this.store.inTransaction(()=>{
|
|
147
|
+
const row=this.row(id);if(!row||row.child_request_id) return null;
|
|
148
|
+
this.db.prepare("UPDATE policy_work_orders SET state='cancelled',cancelled_at=COALESCE(cancelled_at,?),cancelled_reason=COALESCE(cancelled_reason,?) WHERE request_id=?").run(this.store.stamp(),reason,id);
|
|
149
|
+
return {request_id:id,status:'cancelled',cancellation_requested:true,authority_revoked:true,compute_stopped:false};
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
sweepExpired(limit=100) {
|
|
153
|
+
return this.store.inTransaction(()=>{
|
|
154
|
+
const rows=this.db.prepare("SELECT request_id FROM policy_work_orders WHERE state='queued' AND json_extract(routing,'$.deadline_at')<=? ORDER BY json_extract(routing,'$.deadline_at'),rowid LIMIT ?").all(this.store.stamp(),limit);
|
|
155
|
+
for(const row of rows)this.cancel(row.request_id,'expired');
|
|
156
|
+
return rows.map(row=>row.request_id);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|