@tnunamak/dalan 0.9.10 → 0.9.11
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 +14 -0
- package/bin/dot-acp-agent.mjs +146 -29
- package/bin/dot-worker.mjs +17 -4
- package/docs/design/target-architecture-v2.md +71 -5
- package/docs/design/target-architecture-v3.md +151 -0
- package/docs/local-agent-requester.md +52 -0
- package/docs/pull-workers.md +8 -2
- package/package.json +1 -1
- package/src/acp-bridge.mjs +23 -11
- package/src/as-files.mjs +6 -3
- package/src/cli-help.mjs +4 -2
- package/src/get-summary.mjs +5 -0
- package/src/local-attachment-authority.mjs +174 -0
- package/src/local-attachment-capture.mjs +136 -0
- package/src/local-attachment-cli.mjs +46 -0
- package/src/local-attachment-gateway.mjs +93 -0
- package/src/local-attachment-owner-verify.mjs +152 -0
- package/src/local-attachment-result.mjs +64 -0
- package/src/local-attachment-snapshot.mjs +142 -0
- package/src/mcp-stdio.mjs +189 -7
- package/src/patch-apply.mjs +28 -6
- package/src/publication-authority.mjs +1 -0
- package/src/pull-pacing.mjs +42 -0
- package/src/requester-local-context.mjs +113 -0
- package/src/server.mjs +96 -33
- package/src/store.mjs +225 -35
- package/src/work-recovery.mjs +143 -0
- package/src/worker-runs.mjs +25 -0
- package/src/workspace.mjs +17 -10
package/src/as-files.mjs
CHANGED
|
@@ -37,8 +37,8 @@ export function assertPrivateDir(dir) {
|
|
|
37
37
|
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) fail(`directory ${dir} must belong to the bridge user`);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
//
|
|
41
|
-
export function writeAtomic(file, text) {
|
|
40
|
+
// Publish a complete 0600 file. A create-only writer keeps any existing file.
|
|
41
|
+
export function writeAtomic(file, text, {createOnly=false}={}) {
|
|
42
42
|
const temp = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
43
43
|
const fd = fs.openSync(temp, 'wx', 0o600);
|
|
44
44
|
try {
|
|
@@ -50,7 +50,10 @@ export function writeAtomic(file, text) {
|
|
|
50
50
|
throw error;
|
|
51
51
|
}
|
|
52
52
|
fs.closeSync(fd);
|
|
53
|
-
|
|
53
|
+
if(createOnly) {
|
|
54
|
+
try { fs.linkSync(temp, file); }
|
|
55
|
+
finally { fs.rmSync(temp, { force: true }); }
|
|
56
|
+
} else fs.renameSync(temp, file);
|
|
54
57
|
const dirFd = fs.openSync(path.dirname(file), 'r');
|
|
55
58
|
try { fs.fsyncSync(dirFd); } finally { fs.closeSync(dirFd); }
|
|
56
59
|
}
|
package/src/cli-help.mjs
CHANGED
|
@@ -6,6 +6,8 @@ import { docsUrl } from './docs-url.mjs';
|
|
|
6
6
|
// commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
|
|
7
7
|
// `dalan help --internal`. Every command runs and has its own help either way.
|
|
8
8
|
export const COMMANDS = [
|
|
9
|
+
{ name:'attachment', summary:'Preview selected unpublished text locally', usage:'dalan attachment preview --repo OWNER/REPO --base SHA --path FILE [--path FILE ...] [--dir DIR] [--json]',
|
|
10
|
+
detail:['Shows changed and omitted paths for the specified published base. Nothing is sent. Local attachment sending requires a future compatible bridge route.'] },
|
|
9
11
|
{ name: 'jobs', summary: 'Read a versioned page of jobs', usage: 'dalan jobs --json [--worker W] [--status S] [--since T] [--kind K] [--source S] [--limit N] [--cursor C]', detail: ['Reads local state without changing it. Default page size 100, maximum 1000. Pass next_cursor to --cursor for the next page. --since filters creation time (Nh, Nd, RFC3339, or all). See docs/operations.md#stable-read-interface for fields and compatibility.'] },
|
|
10
12
|
{ name: 'events', summary: 'Read a versioned page of lifecycle events', usage: 'dalan events --json [--since T] [--worker W] [--type TYPE] [--limit N] [--cursor C]', detail: ['Reads retained lifecycle events in ID order without changing state. Default page size 100, maximum 1000. --since takes Nh, Nd, RFC3339, or all. Pass next_cursor to --cursor for the next page. See docs/operations.md#stable-read-interface.'] },
|
|
11
13
|
{ name: 'relationships', group: 'operator', summary: 'Manage relationships and their publication grants', usage: 'dalan relationships list | end RELATIONSHIP_ID | publish RELATIONSHIP_ID (--grant org:NAME|repo:OWNER/NAME)... | publish RELATIONSHIP_ID --revoke [--json]', detail: ['Use publish RELATIONSHIP_ID --revoke to withdraw permission to publish results. Ending a relationship blocks new work. Existing jobs and read grants retain their own lifetimes.'] },
|
|
@@ -81,8 +83,8 @@ export const COMMANDS = [
|
|
|
81
83
|
detail: ['Lists what needs you. A producer is the shell or agent session that submitted the job. Inside a Claude Code or Codex session, plain dalan inbox lists that session\'s jobs.', 'Outside a Claude Code or Codex session, plain dalan inbox lists every producer\'s jobs on this bridge home.', '--all lists every producer anywhere; --producer ID lists one.', '', 'Options:', ' --since, --before an RFC3339 time or a duration such as 72h or 3d', '', 'Default window: jobs updated in the last 72 hours. Questions are always listed. To see older results: dalan inbox --all --since all', '', 'A line marked "wake held: parent_stopped" is a result or question that did not reach your T3 thread because the thread\'s latest run was stopped. It stays queued and sends when the thread runs again; read it now with dalan get.', '', 'Example: dalan inbox --all, then dalan get REQUEST_ID'] },
|
|
82
84
|
{ name: 'decide', group: 'everyday', summary: 'Record your decision on a finished job', usage: 'dalan decide ID WORD [--note TEXT]',
|
|
83
85
|
detail: ['Records your decision on a finished job. Review the report or patch first.', '', 'WORD is one of: accepted, applied, useful_no_change, useful_negative, not_useful.', 'Example: dalan decide REQUEST_ID accepted'] },
|
|
84
|
-
{ name: 'materialize', summary: 'Publish a finished job\'s patch as a draft pull request, or preview the decision', usage: 'dalan materialize ID
|
|
85
|
-
detail: ['Reads a current finished job and the owner grant
|
|
86
|
+
{ name: 'materialize', summary: 'Publish a finished job\'s patch as a draft pull request, or preview the decision', usage: 'dalan materialize ID [--dir PATH] [--approve | --standing-only] [--dry-run] [--json]',
|
|
87
|
+
detail: ['Reads a current finished job and the owner grant for the selected bridge home.', 'Use --standing-only for completed jobs that already have standing publication permission.', 'With --dry-run it prints the decision and the patch files, and changes nothing.', 'Otherwise, when the grant covers the repository (or asks for approval and you pass --approve), it commits the patch at the job\'s base commit in a temporary worktree of the clone in --dir (default: the current directory), pushes a new branch dalan/ID and opens a draft pull request.', 'It never replaces an existing branch, never merges and records no decision.'] },
|
|
86
88
|
{ name: 'apply', group: 'everyday', summary: 'Apply a finished job\'s patch to a directory', usage: 'dalan apply ID [--dir PATH] [--release]',
|
|
87
89
|
detail: ['Applies the patch from a finished job to a directory (default: the current directory) and records the decision "applied" for you, after the patch is written.', 'There is no need to accept the job first.', 'If the write fails, the files are put back and the job stays not applied. If the process dies before the bridge confirms, `dalan get` shows the apply as uncertain; run apply again to resolve it. If the checkout was left partly changed, the error names the files and the recovery steps; "dalan apply ID --release" gives up the uncertain apply on purpose and touches no file.'] },
|
|
88
90
|
{ name: 'mcp', group: 'everyday', summary: 'Serve submit, wait, result and status as local MCP tools over stdio', usage: 'dalan mcp',
|
package/src/get-summary.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { workerRunEvidenceLines } from './worker-runs.mjs';
|
|
1
2
|
|
|
2
3
|
// The short terminal view of `dalan get`. Report text comes from a worker, so the caller prints it through
|
|
3
4
|
// terminalSafe. A job that is not finished gets the command that moves it on, never a decision.
|
|
@@ -7,9 +8,13 @@ export function formatGetSummary(job, { id, cli }) {
|
|
|
7
8
|
const lines = [`Job ${id}: ${state}`];
|
|
8
9
|
if (job.revised_by?.request_id) lines.push(`Correction: ${job.revised_by.request_id}`);
|
|
9
10
|
if (job.target_worker) lines.push(`Worker: ${job.target_worker}`);
|
|
11
|
+
if (job.host_check_availability?.cause === 'job_execution_mode')
|
|
12
|
+
lines.push(`Owner-host checks: not requested (execution=${job.host_check_availability.execution}). ${job.host_check_availability.owner_action}`);
|
|
10
13
|
if (report?.outcome && report.outcome !== 'done') lines.push(`Outcome: ${report.outcome}`);
|
|
11
14
|
if (report?.summary) lines.push(`Summary: ${report.summary}`);
|
|
12
15
|
if (report?.result) lines.push('', report.result);
|
|
16
|
+
const workerRuns = workerRunEvidenceLines(job);
|
|
17
|
+
if (workerRuns.length) lines.push('', ...workerRuns);
|
|
13
18
|
// BLOCKED: and QUESTION: progress notes are how a worker asks the owner for something; a running job shows them.
|
|
14
19
|
const asks = state === 'finished' || state === 'cancelled' ? [] : (job.progress ?? []).map(p => p?.note).filter(n => typeof n === 'string' && /^\s*(?:BLOCKED:|QUESTION:)/i.test(n));
|
|
15
20
|
if (asks.length) lines.push('', 'Worker asks or is blocked:', ...asks.slice(-3).map(n => ` ${n.trim()}`), `Answer with: ${cli} note ${id} "TEXT"`);
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
3
|
+
|
|
4
|
+
const id = v => typeof v==='string'&&v.length>0&&v.length<=512&&!/[\x00-\x1f\x7f]/.test(v);
|
|
5
|
+
const digest = v => typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
6
|
+
const tree = v => typeof v==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v);
|
|
7
|
+
const fail = code => { throw Object.assign(new Error(code),{code}); };
|
|
8
|
+
const audience = v => {
|
|
9
|
+
if(!v||!['relationship_side','principal','route','adapter_binding','address'].every(k=>id(v[k]))) fail('attachment_invalid_audience');
|
|
10
|
+
return Object.fromEntries(['relationship_side','principal','route','adapter_binding','address'].map(k=>[k,v[k]]));
|
|
11
|
+
};
|
|
12
|
+
const identity = v => createHash('sha256').update(canonicalJson(v)).digest('hex');
|
|
13
|
+
const epoch = v => Number.isSafeInteger(v)&&v>=1;
|
|
14
|
+
const ordinary = v => typeof v==='string'&&v.length>0&&v.length<=512;
|
|
15
|
+
|
|
16
|
+
// Invoke migration and each state-changing method inside the authoritative Store transaction.
|
|
17
|
+
export function migrateLocalAttachments(db) {
|
|
18
|
+
if(!db.isTransaction) fail('transaction_required');
|
|
19
|
+
db.exec(`CREATE TABLE IF NOT EXISTS local_attachment_bindings(
|
|
20
|
+
work TEXT PRIMARY KEY, identity TEXT NOT NULL, binding TEXT NOT NULL,
|
|
21
|
+
first_served_at INTEGER, last_served_at INTEGER, revoked_at INTEGER, finished TEXT
|
|
22
|
+
);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS local_attachment_receipts(
|
|
24
|
+
work TEXT NOT NULL, kind TEXT NOT NULL, receipt_key TEXT NOT NULL,
|
|
25
|
+
intent TEXT NOT NULL, reply TEXT NOT NULL,
|
|
26
|
+
PRIMARY KEY(work,kind)
|
|
27
|
+
);`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// This store never persists bytes or credentials. Callbacks are trusted adapters over the current
|
|
31
|
+
// Store, scoped sealed artifacts, and owner-verification receipts, not caller-supplied claims.
|
|
32
|
+
export function localAttachmentAuthority({db,now,ownerHasAuthority,workerHasAuthority,findSealedArtifact,
|
|
33
|
+
verifyOwnerResult,parentsForWork,retentionMs}) {
|
|
34
|
+
if([now,ownerHasAuthority,workerHasAuthority,findSealedArtifact,verifyOwnerResult,parentsForWork].some(f=>typeof f!=='function')||
|
|
35
|
+
!Number.isSafeInteger(retentionMs)||retentionMs<1) fail('attachment_adapters_required');
|
|
36
|
+
const tx = () => {if(!db.isTransaction) fail('transaction_required');};
|
|
37
|
+
const clock = () => {const t=now();if(!Number.isSafeInteger(t)||t<0)fail('attachment_clock_unavailable');return t;};
|
|
38
|
+
const row = work => db.prepare('SELECT * FROM local_attachment_bindings WHERE work=?').get(work);
|
|
39
|
+
const required = work => {const r=row(work);if(!r)fail('attachment_missing');return [r,JSON.parse(r.binding)];};
|
|
40
|
+
const owner = (work,capability) => {if(ownerHasAuthority(work,capability)!==true)fail('attachment_owner_required');};
|
|
41
|
+
function seal({work,capability,recipient,repo,published_base,published_tree,input_tree,manifest_sha256,artifact_id,patch_sha256,expires_at}) {
|
|
42
|
+
tx();owner(work,capability);
|
|
43
|
+
if(!id(work)||!id(artifact_id)||typeof repo!=='string'||!/^[\w.-]+\/[\w.-]+$/.test(repo)||
|
|
44
|
+
![published_base,published_tree,input_tree].every(tree)||!digest(manifest_sha256)||!digest(patch_sha256)||!Number.isSafeInteger(expires_at))
|
|
45
|
+
fail('attachment_invalid_binding');
|
|
46
|
+
const binding={work,recipient:audience(recipient),repo,published_base,published_tree,input_tree,manifest_sha256,artifact_id,patch_sha256,expires_at};
|
|
47
|
+
const key=identity(binding),prev=row(work);
|
|
48
|
+
if(prev){if(prev.identity!==key)fail('attachment_binding_conflict');return {binding_sha256:key,expires_at};}
|
|
49
|
+
const t=clock();
|
|
50
|
+
if(expires_at<=t||expires_at-t>retentionMs)fail('attachment_invalid_expiry');
|
|
51
|
+
const artifact=findSealedArtifact({work,artifact_id,mode:'metadata'});
|
|
52
|
+
if(artifact?.work!==work||artifact?.sealed!==true||artifact?.patch_sha256!==patch_sha256||artifact?.expires_at<expires_at||!Number.isSafeInteger(artifact?.expires_at))
|
|
53
|
+
fail('attachment_artifact_mismatch');
|
|
54
|
+
db.prepare('INSERT INTO local_attachment_bindings(work,identity,binding) VALUES(?,?,?)').run(work,key,canonicalJson(binding));
|
|
55
|
+
return {binding_sha256:key,expires_at};
|
|
56
|
+
}
|
|
57
|
+
function admit({work,recipient}) {
|
|
58
|
+
const [r,b]=required(work);
|
|
59
|
+
if(identity(audience(recipient))!==identity(b.recipient))fail('attachment_audience_mismatch');
|
|
60
|
+
if(r.revoked_at!==null)fail('attachment_revoked');
|
|
61
|
+
if(clock()>=b.expires_at)fail('attachment_expired');
|
|
62
|
+
if(r.finished!==null)fail('attachment_terminal');
|
|
63
|
+
return {binding_sha256:r.identity,expires_at:b.expires_at};
|
|
64
|
+
}
|
|
65
|
+
function worker(request,mode) {
|
|
66
|
+
const [r,b]=required(request.work);
|
|
67
|
+
if(!id(request.claim_id)||!epoch(request.epoch)||identity(audience(request.recipient))!==identity(b.recipient)||
|
|
68
|
+
workerHasAuthority({work:request.work,claim_id:request.claim_id,epoch:request.epoch,recipient:b.recipient,mode})!==true)
|
|
69
|
+
fail('attachment_claim_mismatch');
|
|
70
|
+
return [r,b];
|
|
71
|
+
}
|
|
72
|
+
function live(r,b,t) {
|
|
73
|
+
if(r.revoked_at!==null)fail('attachment_revoked');
|
|
74
|
+
if(t>=b.expires_at)fail('attachment_expired');
|
|
75
|
+
if(r.finished!==null)fail('attachment_terminal');
|
|
76
|
+
}
|
|
77
|
+
function bytes(b) {
|
|
78
|
+
const item=findSealedArtifact({work:b.work,artifact_id:b.artifact_id,mode:'bytes'});
|
|
79
|
+
if(item?.work!==b.work||item.sealed!==true||item.patch_sha256!==b.patch_sha256||!Buffer.isBuffer(item.bytes)||
|
|
80
|
+
createHash('sha256').update(item.bytes).digest('hex')!==b.patch_sha256) fail('attachment_artifact_mismatch');
|
|
81
|
+
return Buffer.from(item.bytes);
|
|
82
|
+
}
|
|
83
|
+
function assertLiveWorker(request) {
|
|
84
|
+
tx();
|
|
85
|
+
const [r,b]=worker(request,'live');
|
|
86
|
+
live(r,b,clock());
|
|
87
|
+
}
|
|
88
|
+
function read(request) {
|
|
89
|
+
tx();
|
|
90
|
+
const [r,b]=worker(request,'live'),t=clock();
|
|
91
|
+
live(r,b,t);const data=bytes(b);
|
|
92
|
+
live(r,b,clock());
|
|
93
|
+
// “Served” means the bridge made bytes available, not that the worker observed them.
|
|
94
|
+
db.prepare('UPDATE local_attachment_bindings SET first_served_at=coalesce(first_served_at,?),last_served_at=? WHERE work=?').run(t,t,b.work);
|
|
95
|
+
return {binding_sha256:r.identity,patch_sha256:b.patch_sha256,bytes:data};
|
|
96
|
+
}
|
|
97
|
+
function receipt(work,kind,key,intent) {
|
|
98
|
+
const found=db.prepare('SELECT * FROM local_attachment_receipts WHERE work=? AND kind=?').get(work,kind);
|
|
99
|
+
if(!found)return null;
|
|
100
|
+
if(found.receipt_key!==key||found.intent!==intent)fail('attachment_receipt_conflict');
|
|
101
|
+
return JSON.parse(found.reply);
|
|
102
|
+
}
|
|
103
|
+
function save(work,kind,key,intent,reply) {
|
|
104
|
+
db.prepare('INSERT INTO local_attachment_receipts VALUES(?,?,?,?,?)').run(work,kind,key,intent,canonicalJson(reply));
|
|
105
|
+
return JSON.parse(canonicalJson(reply));
|
|
106
|
+
}
|
|
107
|
+
function finish(request) {
|
|
108
|
+
tx();
|
|
109
|
+
const {work,key,input_tree,output_tree,result_sha256}=request;
|
|
110
|
+
if(!ordinary(key)||!tree(input_tree)||!tree(output_tree)||!digest(result_sha256))fail('attachment_invalid_finish');
|
|
111
|
+
const [r,b]=worker(request,rMode(work));
|
|
112
|
+
if(input_tree!==b.input_tree)fail('attachment_result_basis_mismatch');
|
|
113
|
+
const intent=identity({input_tree,output_tree,result_sha256,claim:request.claim_id,epoch:request.epoch});
|
|
114
|
+
const prior=receipt(work,'finish',key,intent);
|
|
115
|
+
if(prior)return prior;
|
|
116
|
+
const t=clock(),authoritative=r.revoked_at===null&&t<b.expires_at;
|
|
117
|
+
const reply={at:t,authoritative,input_tree,output_tree,result_sha256};
|
|
118
|
+
if(authoritative)db.prepare('UPDATE local_attachment_bindings SET finished=? WHERE work=?').run(canonicalJson(reply),work);
|
|
119
|
+
return save(work,'finish',key,intent,reply);
|
|
120
|
+
}
|
|
121
|
+
function rMode(work) {
|
|
122
|
+
return db.prepare("SELECT 1 FROM local_attachment_receipts WHERE work=? AND kind='finish'").get(work)?'receipt':'live';
|
|
123
|
+
}
|
|
124
|
+
function accept({work,capability,key,verification_id,result_sha256}) {
|
|
125
|
+
tx();owner(work,capability);
|
|
126
|
+
if(!ordinary(key)||!id(verification_id)||!digest(result_sha256))fail('attachment_invalid_acceptance');
|
|
127
|
+
const intent=identity({verification_id,result_sha256}),prior=receipt(work,'accept',key,intent);
|
|
128
|
+
if(prior)return prior;
|
|
129
|
+
const [r,b]=required(work);
|
|
130
|
+
const liveAcceptance=()=>{
|
|
131
|
+
if(r.revoked_at!==null)fail('attachment_revoked');
|
|
132
|
+
const t=clock();
|
|
133
|
+
if(t>=b.expires_at)fail('attachment_expired');
|
|
134
|
+
return t;
|
|
135
|
+
};
|
|
136
|
+
liveAcceptance();
|
|
137
|
+
const finished=r.finished&&JSON.parse(r.finished);
|
|
138
|
+
if(!finished||finished.result_sha256!==result_sha256||
|
|
139
|
+
verifyOwnerResult({work,verification_id,binding_sha256:r.identity,input_tree:b.input_tree,
|
|
140
|
+
output_tree:finished.output_tree,result_sha256})!==true)fail('attachment_result_unverified');
|
|
141
|
+
const acceptedAt=liveAcceptance();
|
|
142
|
+
return save(work,'accept',key,intent,{accepted:true,at:acceptedAt,result_sha256,input_tree:b.input_tree,output_tree:finished.output_tree});
|
|
143
|
+
}
|
|
144
|
+
function revoke({work,capability}) {
|
|
145
|
+
tx();owner(work,capability);
|
|
146
|
+
const [r]=required(work),t=r.revoked_at??clock();
|
|
147
|
+
if(r.revoked_at===null)db.prepare('UPDATE local_attachment_bindings SET revoked_at=? WHERE work=?').run(t,work);
|
|
148
|
+
return {revoked_at:t};
|
|
149
|
+
}
|
|
150
|
+
function reopen({work,capability,includeBytes=false}) {
|
|
151
|
+
owner(work,capability);
|
|
152
|
+
const [r,b]=required(work);
|
|
153
|
+
const data=includeBytes&&clock()<b.expires_at?bytes(b):null;
|
|
154
|
+
return {binding_sha256:r.identity,recipient:b.recipient,manifest_sha256:b.manifest_sha256,
|
|
155
|
+
expires_at:b.expires_at,revoked_at:r.revoked_at,first_served_at:r.first_served_at,last_served_at:r.last_served_at,
|
|
156
|
+
worker_access:false,...(data&&clock()<b.expires_at?{bytes:data}:{})};
|
|
157
|
+
}
|
|
158
|
+
function assertStandingPublicationAllowed(work) {
|
|
159
|
+
const visited=new Set(),stack=[work];
|
|
160
|
+
while(stack.length){
|
|
161
|
+
const current=stack.pop();
|
|
162
|
+
if(!id(current)||visited.size>=1024)fail('attachment_lineage_unverified');
|
|
163
|
+
if(visited.has(current))continue;
|
|
164
|
+
visited.add(current);
|
|
165
|
+
if(row(current))fail('attachment_standing_publication_forbidden');
|
|
166
|
+
const parents=parentsForWork(current);
|
|
167
|
+
if(!Array.isArray(parents)||parents.length>1024)fail('attachment_lineage_unverified');
|
|
168
|
+
stack.push(...parents);
|
|
169
|
+
}
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return {seal,admit,read,finish,accept,revoke,reopen,assertStandingPublicationAllowed,
|
|
173
|
+
assertLiveWorker,assertOwner:(work,capability)=>owner(work,capability)};
|
|
174
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { gitEnv } from './git-env.mjs';
|
|
7
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
8
|
+
import { isLiteralScopePath, withheldRepoPath, matchesCredentialPathTerm } from './submission-policy.mjs';
|
|
9
|
+
import { artifactSecretRule, hasSecretContent, hasCredentialFieldText } from './redaction.mjs';
|
|
10
|
+
|
|
11
|
+
const maxFile = 1024 * 1024, maxPatch = 4 * maxFile, maxSelection = 128;
|
|
12
|
+
const oid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
13
|
+
const digest = data => createHash('sha256').update(data).digest('hex');
|
|
14
|
+
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
15
|
+
const text = data => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(data);
|
|
16
|
+
const sameFile = (a,b) => a?.dev===b?.dev && a?.ino===b?.ino && a?.size===b?.size &&
|
|
17
|
+
a?.mode===b?.mode && a?.mtimeNs===b?.mtimeNs && a?.ctimeNs===b?.ctimeNs;
|
|
18
|
+
const secret = bytes => artifactSecretRule(bytes) || hasSecretContent(text(bytes)) || hasCredentialFieldText(text(bytes));
|
|
19
|
+
const stockGit = gitEnv();
|
|
20
|
+
|
|
21
|
+
function git(cwd,args,{env=stockGit,input,ok=[0],buffer=maxPatch+maxFile}={}) {
|
|
22
|
+
const r=spawnSync('git',args,{cwd,env:{...env,GIT_TERMINAL_PROMPT:'0'},input,maxBuffer:buffer,timeout:15000});
|
|
23
|
+
if(!ok.includes(r.status)) fail('attachment_git_read_failed');
|
|
24
|
+
return r;
|
|
25
|
+
}
|
|
26
|
+
function entry(root,sha,rel) {
|
|
27
|
+
const v=text(git(root,['--literal-pathspecs','ls-tree','-z',sha,'--',rel]).stdout);
|
|
28
|
+
if(!v) return null;
|
|
29
|
+
const m=/^(\d+) (\S+) ([a-f0-9]+)\t([^\0]+)\0$/.exec(v);
|
|
30
|
+
if(!m||m[4]!==rel) fail('attachment_invalid_base_entry');
|
|
31
|
+
return {mode:m[1],type:m[2],oid:m[3]};
|
|
32
|
+
}
|
|
33
|
+
function current(root,rel) {
|
|
34
|
+
const parts=rel.split('/');
|
|
35
|
+
let at=root;
|
|
36
|
+
for(const [i,part] of parts.entries()) {
|
|
37
|
+
at=path.join(at,part);
|
|
38
|
+
const s=fs.lstatSync(at,{throwIfNoEntry:false,bigint:true});
|
|
39
|
+
if(!s) return {bytes:null};
|
|
40
|
+
if(s.isSymbolicLink()) return {omit:'symbolic_path'};
|
|
41
|
+
if(i<parts.length-1&&!s.isDirectory()) return {omit:'unsupported_path'};
|
|
42
|
+
if(i<parts.length-1) continue;
|
|
43
|
+
if(!s.isFile()) return {omit:'unsupported_file'};
|
|
44
|
+
if(s.size>BigInt(maxFile)) return {omit:'file_too_large'};
|
|
45
|
+
const fd=fs.openSync(at,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
|
|
46
|
+
try {
|
|
47
|
+
const before=fs.fstatSync(fd,{bigint:true});
|
|
48
|
+
if(!sameFile(s,before)||fs.realpathSync(at)!==at) fail('attachment_capture_changed');
|
|
49
|
+
const bytes=Buffer.alloc(Number(before.size)+1);
|
|
50
|
+
let n=0;
|
|
51
|
+
while(n<bytes.length) {
|
|
52
|
+
const got=fs.readSync(fd,bytes,n,bytes.length-n,null);
|
|
53
|
+
if(!got) break;
|
|
54
|
+
n+=got;
|
|
55
|
+
}
|
|
56
|
+
if(n!==Number(before.size)||!sameFile(before,fs.fstatSync(fd,{bigint:true}))||!sameFile(before,fs.lstatSync(at,{bigint:true}))) fail('attachment_capture_changed');
|
|
57
|
+
return {bytes:bytes.subarray(0,n),mode:(before.mode&0o100n)?'100755':'100644'};
|
|
58
|
+
} finally { fs.closeSync(fd); }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function validText(b) {
|
|
62
|
+
if(!b) return true;
|
|
63
|
+
try { const value=text(b);return !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value); }
|
|
64
|
+
catch {return false;}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The caller supplies a published commit that it verified through its existing anchor policy;
|
|
68
|
+
// ancestry is checked locally. This helper never contacts a forge or reads an unselected worktree file.
|
|
69
|
+
export function captureLocalAttachment({checkout,repo,publishedBase,paths,policy}) {
|
|
70
|
+
if(!path.isAbsolute(checkout??'')||!/^[\w.-]+\/[\w.-]+$/.test(repo??'')||!oid.test(publishedBase??'')||
|
|
71
|
+
!Array.isArray(paths)||!paths.length||paths.length>maxSelection||
|
|
72
|
+
paths.some(p=>typeof p!=='string'||!isLiteralScopePath(p)||p.split('/').some(x=>x.toLowerCase()==='.git')||/[\x00-\x1f\x7f]/.test(p))) fail('invalid_attachment_selection');
|
|
73
|
+
if(!policy||policy.error||!Array.isArray(policy.excludedPaths)||!Array.isArray(policy.credentialPathTerms)||
|
|
74
|
+
[...policy.excludedPaths,...policy.credentialPathTerms].some(s=>typeof s!=='string'||!s)) fail('attachment_policy_unavailable');
|
|
75
|
+
if(new Set(paths.map(p=>p.normalize('NFC').toLowerCase())).size!==paths.length) fail('ambiguous_attachment_selection');
|
|
76
|
+
const selection=[...paths].sort(),root=fs.realpathSync(checkout);
|
|
77
|
+
const query=(...args)=>text(git(root,args).stdout).trimEnd();
|
|
78
|
+
if(query('rev-parse','--show-toplevel')!==root||query('rev-parse',publishedBase+'^{commit}')!==publishedBase||
|
|
79
|
+
git(root,['merge-base','--is-ancestor',publishedBase,'HEAD'],{ok:[0,1]}).status!==0) fail('invalid_attachment_anchor');
|
|
80
|
+
const tip=query('rev-parse','HEAD'), publishedTree=query('rev-parse',publishedBase+'^{tree}');
|
|
81
|
+
const objects=query('rev-parse','--path-format=absolute','--git-path','objects');
|
|
82
|
+
const format=query('rev-parse','--show-object-format');
|
|
83
|
+
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-local-capture-'));
|
|
84
|
+
try {
|
|
85
|
+
git(scratch,['init','--quiet','--bare','--object-format='+format,'repo']);
|
|
86
|
+
const env={...stockGit,GIT_ALTERNATE_OBJECT_DIRECTORIES:JSON.stringify(objects),GIT_INDEX_FILE:path.join(scratch,'index')};
|
|
87
|
+
const pgit=(args,input)=>git(scratch,['--git-dir='+path.join(scratch,'repo'),...args],{env,input}).stdout;
|
|
88
|
+
pgit(['read-tree',publishedTree]);
|
|
89
|
+
const entries=[], omissions=[], reads=[];
|
|
90
|
+
let total=0;
|
|
91
|
+
for(const rel of selection) {
|
|
92
|
+
const omit=reason=>omissions.push({path:rel,reason});
|
|
93
|
+
if(secret(Buffer.from(rel))) fail('attachment_selection_contains_sensitive_value');
|
|
94
|
+
if(withheldRepoPath(rel,policy.excludedPaths)||matchesCredentialPathTerm(rel,policy.credentialPathTerms)) {omit('withheld_path');continue;}
|
|
95
|
+
const old=entry(root,publishedTree,rel);
|
|
96
|
+
if(old&&(old.type!=='blob'||!['100644','100755'].includes(old.mode))) {omit('unsupported_base_entry');continue;}
|
|
97
|
+
const head=old?null:entry(root,tip,rel);
|
|
98
|
+
const indexed=!old&&!head&&git(root,['--literal-pathspecs','ls-files','--stage','-z','--',rel]).stdout.length>0;
|
|
99
|
+
if(!old&&!head&&!indexed&&git(root,['check-ignore','-q','--',rel],{ok:[0,1]}).status===0) {omit('ignored');continue;}
|
|
100
|
+
const snap=current(root,rel);
|
|
101
|
+
if(snap.omit) {omit(snap.omit);continue;}
|
|
102
|
+
reads.push([rel,snap]);
|
|
103
|
+
if(!old&&!snap.bytes) {omit('not_present');continue;}
|
|
104
|
+
if(old&&Number(query('cat-file','-s',old.oid))>maxFile) {omit('file_too_large');continue;}
|
|
105
|
+
const before=old?git(root,['cat-file','blob',old.oid]).stdout:null;
|
|
106
|
+
const after=snap.bytes;
|
|
107
|
+
if(before&&after&&before.equals(after)&&old.mode===snap.mode) continue;
|
|
108
|
+
if(!validText(before)||!validText(after)) {omit('non_text');continue;}
|
|
109
|
+
if((before&&secret(before))||(after&&secret(after))) {omit('credential_content');continue;}
|
|
110
|
+
total+=(before?.length??0)+(after?.length??0);
|
|
111
|
+
if(total>maxPatch) fail('attachment_too_large');
|
|
112
|
+
const mode=after?snap.mode:'0';
|
|
113
|
+
const hash=after?text(pgit(['hash-object','--no-filters','-w','--stdin'],after)).trim():publishedBase.replace(/./g,'0');
|
|
114
|
+
pgit(['update-index','-z','--index-info'],Buffer.from(`${mode} ${hash}\t${rel}\0`));
|
|
115
|
+
entries.push({path:rel,disposition:!before?'added':!after?'deleted':'modified',
|
|
116
|
+
before_sha256:before?digest(before):null,after_sha256:after?digest(after):null,
|
|
117
|
+
before_mode:old?.mode??null,after_mode:after?snap.mode:null});
|
|
118
|
+
}
|
|
119
|
+
const inputTree=text(pgit(['write-tree'])).trim();
|
|
120
|
+
const patch=pgit(['diff-tree','--no-commit-id','--full-index','--no-ext-diff','--no-textconv',
|
|
121
|
+
'--no-renames','--text','--no-color','--diff-algorithm=myers','--src-prefix=a/','--dst-prefix=b/','-r','-p',publishedTree,inputTree]);
|
|
122
|
+
if(patch.length>maxPatch) fail('attachment_too_large');
|
|
123
|
+
if(!validText(patch)||secret(patch)) fail('attachment_patch_withheld');
|
|
124
|
+
for(const [rel,snap] of reads) {
|
|
125
|
+
const next=current(root,rel);
|
|
126
|
+
if(next.omit||next.mode!==snap.mode||(next.bytes===null)!==(snap.bytes===null)||
|
|
127
|
+
(next.bytes&&!next.bytes.equals(snap.bytes))) fail('attachment_capture_changed');
|
|
128
|
+
}
|
|
129
|
+
if(query('rev-parse','HEAD')!==tip) fail('attachment_capture_changed');
|
|
130
|
+
const manifest={version:1,repo,published_base:publishedBase,published_tree:publishedTree,input_tree:inputTree,patch_sha256:digest(patch),entries,omissions};
|
|
131
|
+
return {patch,manifest,manifest_sha256:digest(Buffer.from(canonicalJson(manifest)))};
|
|
132
|
+
} catch(error) {
|
|
133
|
+
if(error.code==='ENOENT'||error.code==='ELOOP'||error.code==='ENOTDIR') fail('attachment_capture_changed');
|
|
134
|
+
throw error;
|
|
135
|
+
} finally { fs.rmSync(scratch,{recursive:true,force:true}); }
|
|
136
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { captureLocalAttachment } from './local-attachment-capture.mjs';
|
|
3
|
+
import { sensitivePolicyPaths } from './submission-policy.mjs';
|
|
4
|
+
|
|
5
|
+
const oid=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
6
|
+
const digest=/^[a-f0-9]{64}$/;
|
|
7
|
+
const repo=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*\/[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
|
|
8
|
+
const fail=(local_code,message)=>{throw Object.assign(new Error(message),{local_code});};
|
|
9
|
+
const invalid=()=>fail('invalid_attachment_arguments','use attachment preview --repo OWNER/REPO --base SHA --path FILE [--path FILE ...], or attachment send --work ID --confirm-manifest SHA256');
|
|
10
|
+
export function localAttachmentCommand(argv,{cwd=process.cwd(),capture=captureLocalAttachment,readPolicy=sensitivePolicyPaths}={}) {
|
|
11
|
+
const [action,...args]=argv;
|
|
12
|
+
if(!['preview','send'].includes(action))invalid();
|
|
13
|
+
const options=new Map(),paths=[];
|
|
14
|
+
const allowed=action==='preview'?['--repo','--base','--dir','--path']:['--work','--confirm-manifest'];
|
|
15
|
+
for(let i=0;i<args.length;i++){
|
|
16
|
+
const flag=args[i];
|
|
17
|
+
if(flag==='--json'){if(options.has(flag))invalid();options.set(flag,true);continue;}
|
|
18
|
+
if(!allowed.includes(flag)||options.has(flag))invalid();
|
|
19
|
+
const value=args[++i];
|
|
20
|
+
if(!value||value.startsWith('-')||/[\x00-\x1f\x7f]/.test(value))invalid();
|
|
21
|
+
if(flag==='--path'){paths.push(value);continue;}
|
|
22
|
+
options.set(flag,value);
|
|
23
|
+
}
|
|
24
|
+
if(action==='send'){
|
|
25
|
+
if(!/^[-\w]{8,128}$/.test(options.get('--work')??'')||!digest.test(options.get('--confirm-manifest')??''))invalid();
|
|
26
|
+
// No compatible owner/recipient route is advertised in this build. Never turn this into normal submit.
|
|
27
|
+
fail('local_attachment_send_unavailable','This bridge does not support sending local attachments. Nothing was read or sent.');
|
|
28
|
+
}
|
|
29
|
+
const publishedBase=options.get('--base'),name=options.get('--repo');
|
|
30
|
+
if(!oid.test(publishedBase??'')||!repo.test(name??'')||!paths.length)invalid();
|
|
31
|
+
const policy=readPolicy();
|
|
32
|
+
if(!policy||policy.error||!Array.isArray(policy.paths))fail('local_attachment_policy_unavailable','The local attachment policy could not be read. Nothing was sent.');
|
|
33
|
+
let prepared;
|
|
34
|
+
try {
|
|
35
|
+
prepared=capture({checkout:path.resolve(cwd,options.get('--dir')??'.'),repo:name,publishedBase,paths,
|
|
36
|
+
policy:{excludedPaths:policy.paths,credentialPathTerms:[]}});
|
|
37
|
+
} catch(e) {
|
|
38
|
+
fail(/^attachment_[a-z_]+$/.test(e.code??'')?e.code:'local_attachment_preview_failed','Could not freeze the selected local changes. Nothing was sent.');
|
|
39
|
+
}
|
|
40
|
+
const {manifest,manifest_sha256}=prepared;
|
|
41
|
+
// Deliberately return an explicit metadata projection; do not print the patch or the local filesystem root.
|
|
42
|
+
return {status:'preview',sent:false,send_available:false,repo:name,published_base:publishedBase,
|
|
43
|
+
manifest_sha256,patch_bytes:prepared.patch.length,
|
|
44
|
+
selected:manifest.entries.map(({path,disposition})=>({path,disposition})),
|
|
45
|
+
omitted:manifest.omissions.map(({path,reason})=>({path,reason}))};
|
|
46
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {canonicalJson} from '../packages/job-core/protocol/canonical.mjs';
|
|
3
|
+
import {createArtifactDownloadGuard} from './protocol-artifact-commands.mjs';
|
|
4
|
+
|
|
5
|
+
const bindingFields=['relationship_side','principal','route','adapter_binding','address'];
|
|
6
|
+
const invalid=code=>{throw Object.assign(new Error(code),{code});};
|
|
7
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
8
|
+
const digest=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
|
|
9
|
+
const chunkSize=18*1024;
|
|
10
|
+
function exact(value) {
|
|
11
|
+
if(!value||!bindingFields.every(key=>typeof value[key]==='string'&&value[key]&&value[key].length<=512&&
|
|
12
|
+
!/[\x00-\x1f\x7f]/.test(value[key])))invalid('attachment_recipient_unavailable');
|
|
13
|
+
return Object.fromEntries(bindingFields.map(k=>[k,value[k]]));
|
|
14
|
+
}
|
|
15
|
+
// No route constructor can self-attest. Both callbacks look up independent trusted facts;
|
|
16
|
+
// do not use request bodies or a requester result-delivery address for either lookup.
|
|
17
|
+
// The private owner artifact adapter must not expose its staged bytes on a public artifact URL.
|
|
18
|
+
export function createLocalAttachmentArtifactGateway({
|
|
19
|
+
transaction,snapshots,registeredDestination,authenticatedDestination,
|
|
20
|
+
downloadGuard=createArtifactDownloadGuard(),
|
|
21
|
+
}) {
|
|
22
|
+
function configured() {
|
|
23
|
+
if([transaction,registeredDestination,authenticatedDestination,downloadGuard,
|
|
24
|
+
snapshots?.seal,snapshots?.read,snapshots?.authorizeRead,snapshots?.verify].some(f=>typeof f!=='function'))
|
|
25
|
+
invalid('attachment_recipient_unavailable');
|
|
26
|
+
}
|
|
27
|
+
function route(work) {
|
|
28
|
+
if(typeof work!=='string'||!work)invalid('attachment_recipient_unavailable');
|
|
29
|
+
return exact(registeredDestination(work));
|
|
30
|
+
}
|
|
31
|
+
function match(actual,expected) {
|
|
32
|
+
if(canonicalJson(exact(actual))!==canonicalJson(expected))invalid('attachment_audience_mismatch');
|
|
33
|
+
}
|
|
34
|
+
function seal(options) {
|
|
35
|
+
configured();
|
|
36
|
+
return transaction(()=>{
|
|
37
|
+
const registered=route(options.work);
|
|
38
|
+
match(options.approval?.recipient,registered); // no checkout read or upload for unsupported routes
|
|
39
|
+
const receipt=snapshots.seal(options);
|
|
40
|
+
match(route(options.work),registered);
|
|
41
|
+
return receipt;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function read({work,actor,claim_id,epoch,binding_sha256,offset=0,patch_sha256}) {
|
|
45
|
+
configured();
|
|
46
|
+
if(!digest(binding_sha256)||!Number.isSafeInteger(offset)||offset<0||offset%chunkSize!==0||
|
|
47
|
+
(offset!==0&&!digest(patch_sha256))||(patch_sha256!==undefined&&!digest(patch_sha256)))
|
|
48
|
+
invalid('attachment_invalid_artifact_read');
|
|
49
|
+
return transaction(()=>{
|
|
50
|
+
const expected=route(work);
|
|
51
|
+
const context={work,actor,claim_id,epoch};
|
|
52
|
+
const recheck=()=>{
|
|
53
|
+
match(route(work),expected);
|
|
54
|
+
match(authenticatedDestination(context),expected);
|
|
55
|
+
const current=snapshots.authorizeRead(context);
|
|
56
|
+
if(current.binding_sha256!==binding_sha256)invalid('attachment_artifact_mismatch');
|
|
57
|
+
};
|
|
58
|
+
recheck();
|
|
59
|
+
const selected=snapshots.read(context);
|
|
60
|
+
if(selected.binding_sha256!==binding_sha256||
|
|
61
|
+
(patch_sha256!==undefined&&patch_sha256!==selected.manifest.patch_sha256))
|
|
62
|
+
invalid('attachment_artifact_mismatch');
|
|
63
|
+
const bytes=selected.bytes, patchHash=selected.manifest.patch_sha256;
|
|
64
|
+
downloadGuard({bytes,sha256:patchHash,id:binding_sha256,requestId:work});
|
|
65
|
+
if(offset>bytes.length||(offset===bytes.length&&offset>0))invalid('attachment_invalid_artifact_read');
|
|
66
|
+
const end=Math.min(offset+chunkSize,bytes.length);
|
|
67
|
+
// Omitted names are owner-only; publish just the count with a separately
|
|
68
|
+
// identified worker manifest. The receipt still binds the exact owner manifest.
|
|
69
|
+
const {omissions,...visible}=selected.manifest;
|
|
70
|
+
const manifest={...visible,omitted_count:omissions.length};
|
|
71
|
+
const metadata=Buffer.from(canonicalJson(manifest));
|
|
72
|
+
const manifestHash=sha(metadata);
|
|
73
|
+
downloadGuard({bytes:metadata,sha256:manifestHash,id:binding_sha256,requestId:work});
|
|
74
|
+
recheck(); // after storage/scanner work, before releasing even metadata
|
|
75
|
+
return {binding_sha256,manifest,manifest_sha256:manifestHash,
|
|
76
|
+
owner_manifest_sha256:sha(Buffer.from(canonicalJson(selected.manifest))),sha256:patchHash,
|
|
77
|
+
size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function verify(options) {
|
|
81
|
+
configured();
|
|
82
|
+
return transaction(()=>{
|
|
83
|
+
const expected=route(options.work);
|
|
84
|
+
const receipt=snapshots.verify(options);
|
|
85
|
+
match(route(options.work),expected);
|
|
86
|
+
return {...receipt,assertCallerUnchanged(){
|
|
87
|
+
match(route(options.work),expected);
|
|
88
|
+
return receipt.assertCallerUnchanged();
|
|
89
|
+
}};
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return {seal,read,verify};
|
|
93
|
+
}
|