@tnunamak/dalan 0.8.1 → 0.8.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 (124) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +64 -19
  100. package/src/service-update.mjs +193 -48
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -3,17 +3,27 @@ import {createHash, timingSafeEqual, randomBytes,createCipheriv,createDecipheriv
3
3
  const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
4
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
5
  export const PULL_PAGE_PREFIX='pullpage_';
6
+ const MAX_PAGE_ITEMS=50, MAX_PAGE_SCAN=200;
7
+ const priorityRank="CASE priority WHEN 'normal' THEN 0 ELSE 1 END";
8
+ const absoluteTime=/^(\d{4}-\d\d-\d\d)T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
9
+ function parseDeadline(value) {
10
+ const day=typeof value==='string'&&absoluteTime.exec(value)?.[1];
11
+ if(!day) return NaN;
12
+ const midnight=new Date(day+'T00:00:00Z');
13
+ if(!Number.isFinite(midnight.getTime())||midnight.toISOString().slice(0,10)!==day) return NaN;
14
+ return Date.parse(value);
15
+ }
6
16
  export function routingPolicy(value,assignment) {
7
17
  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
18
  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
19
  const names=value.allowed_workers;
10
20
  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
21
  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);
22
+ const deadline=parseDeadline(value.deadline_at??assignment.valid_until);
23
+ if(!Number.isFinite(deadline)) throw new Error('routing requires an explicit RFC3339 deadline_at or assignment.valid_until');
24
+ const assignmentDeadline=assignment.valid_until===undefined?null:parseDeadline(assignment.valid_until);
15
25
  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()};
26
+ return {version:1,allowed_workers:[...names].sort(),fan_out:1,deadline_at:new Date(Math.min(deadline,assignmentDeadline??Infinity)).toISOString()};
17
27
  }
18
28
  export function migratePullQueue(db) {
19
29
  db.exec(`CREATE TABLE policy_work_orders (
@@ -32,6 +42,8 @@ export function migratePullQueue(db) {
32
42
  export class PullQueue {
33
43
  constructor(store) {
34
44
  this.store=store;this.db=store.db;
45
+ // The secondary index orders a single rank by rowid, so paging need not sort all queued rows.
46
+ this.db.exec(`CREATE INDEX IF NOT EXISTS policy_work_scan ON policy_work_orders(state,(${priorityRank}))`);
35
47
  this.db.prepare("INSERT OR IGNORE INTO bridge_state(key,value) VALUES('pull_cursor_key',?)").run(randomBytes(32).toString('hex'));
36
48
  this.cursorKey=Buffer.from(this.db.prepare("SELECT value FROM bridge_state WHERE key='pull_cursor_key'").get().value,'hex');
37
49
  }
@@ -42,7 +54,13 @@ export class PullQueue {
42
54
  }
43
55
  readCursor(worker,cursor) {
44
56
  try {
45
- const bytes=Buffer.from(cursor.slice(PULL_PAGE_PREFIX.length),'base64url'),decipher=createDecipheriv('aes-256-gcm',this.cursorKey,bytes.subarray(0,12));
57
+ // The nonce, tag and three safe integers encode to 47–87 base64url characters.
58
+ if(typeof cursor!=='string'||!cursor.startsWith(PULL_PAGE_PREFIX)||cursor.length>PULL_PAGE_PREFIX.length+87) throw new Error();
59
+ const encoded=cursor.slice(PULL_PAGE_PREFIX.length);
60
+ if(!/^[A-Za-z0-9_-]{47,87}$/.test(encoded)) throw new Error();
61
+ const bytes=Buffer.from(encoded,'base64url');
62
+ if(bytes.toString('base64url')!==encoded) throw new Error();
63
+ const decipher=createDecipheriv('aes-256-gcm',this.cursorKey,bytes.subarray(0,12));
46
64
  decipher.setAAD(Buffer.from(worker));decipher.setAuthTag(bytes.subarray(12,28));
47
65
  const value=JSON.parse(Buffer.concat([decipher.update(bytes.subarray(28)),decipher.final()]).toString());
48
66
  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();
@@ -54,8 +72,11 @@ export class PullQueue {
54
72
  inbox(id) {
55
73
  const row=this.row(id);if(!row||row.child_request_id)return null;
56
74
  const projected=this.project(row);
75
+ // A reason supplied by the owner can also say "expired". The deadline distinguishes an earlier cancellation.
76
+ const expired=projected.cancelled_reason==='expired'&&(row.state==='queued'||row.cancelled_at>=projected.valid_until);
77
+ const ownerCancelled=row.state==='cancelled'&&!expired;
57
78
  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};
79
+ cancelled_at:projected.cancelled_at,cancelled_reason:projected.cancelled_reason,cancelled_by_owner:ownerCancelled,read:row.owner_read_at!==null,failure_type:expired?'expired':ownerCancelled?'owner_cancelled':null,failure_type_source:expired||ownerCancelled?'bridge_observed_transition':null,unanswered_blocker:null};
59
80
  }
60
81
  consume(id) {
61
82
  const row=this.row(id);if(!row||row.child_request_id)return;
@@ -99,19 +120,31 @@ export class PullQueue {
99
120
  get(id,worker,admit) {
100
121
  const row=this.row(id);
101
122
  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.'};
123
+ const offer=this.project(row);
124
+ if(offer.status!=='queued') throw new Error('assignment not found');
125
+ return {...offer,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
126
  }
104
127
  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});
128
+ let after=0,rank=0,snapshot;
129
+ if(cursor!==null) [snapshot,rank,after]=this.readCursor(worker,cursor);
130
+ else snapshot=this.db.prepare('SELECT COALESCE(max(rowid),0) n FROM policy_work_orders').get().n;
131
+ const query=this.db.prepare(`SELECT rowid AS sequence,* FROM policy_work_orders
132
+ WHERE state='queued' AND (${priorityRank})=? AND rowid>? AND rowid<=? ORDER BY rowid LIMIT ?`);
133
+ const items=[];let scanned=0,last=null,next=null;
134
+ pages: for(;rank<=1;rank++,after=0) {
135
+ for(const row of query.iterate(rank,after,snapshot,MAX_PAGE_SCAN-scanned+1)) {
136
+ if(scanned===MAX_PAGE_SCAN||items.length===MAX_PAGE_ITEMS) {
137
+ next=this.cursor(worker,last);
138
+ break pages;
139
+ }
140
+ scanned++;
141
+ last=[snapshot,rank,row.sequence];
142
+ const {deadline_at}=JSON.parse(row.routing);
143
+ if(Date.parse(deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) continue;
144
+ 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,remaining_result_slots:1});
145
+ }
113
146
  }
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.'};
147
+ return {items,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
148
  }
116
149
  acquire(id,{worker,subject,connectionId,claimant,acquisitionId,leaseMs,capacity,preflight,admit}) {
117
150
  if(typeof acquisitionId!=='string'||!(/^[A-Za-z0-9_-]{1,128}$/).test(acquisitionId)) throw new Error('policy work requires a fresh acquisition_id');
@@ -142,17 +175,19 @@ export class PullQueue {
142
175
  return receipt;
143
176
  });
144
177
  }
145
- cancel(id,reason=null) {
178
+ cancel(id,reason=null,at=this.store.stamp()) {
146
179
  return this.store.inTransaction(()=>{
147
180
  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);
181
+ const expired=row.state==='queued'&&JSON.parse(row.routing).deadline_at<=at;
182
+ this.db.prepare("UPDATE policy_work_orders SET state='cancelled',cancelled_at=COALESCE(cancelled_at,?),cancelled_reason=COALESCE(cancelled_reason,?) WHERE request_id=?").run(at,expired?'expired':reason,id);
149
183
  return {request_id:id,status:'cancelled',cancellation_requested:true,authority_revoked:true,compute_stopped:false};
150
184
  });
151
185
  }
152
186
  sweepExpired(limit=100) {
153
187
  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');
188
+ const at=this.store.stamp();
189
+ 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(at,limit);
190
+ for(const row of rows)this.cancel(row.request_id,'expired',at);
156
191
  return rows.map(row=>row.request_id);
157
192
  });
158
193
  }
@@ -0,0 +1,127 @@
1
+ // Local operator reads. Keep SQL and storage names behind this versioned CLI interface.
2
+ import { DatabaseSync } from 'node:sqlite';
3
+ import { defaultPath } from './paths.mjs';
4
+ import { canonicalMetaValue, canonicalKindSql } from './objectives.mjs';
5
+ import { parseWhen } from './inbox.mjs';
6
+ import { lifecycleTypes } from './lifecycle.mjs';
7
+
8
+ export const READ_API_SCHEMA_VERSION = 1;
9
+ export const READ_API_COMMANDS = ['jobs', 'events'];
10
+ const jobStatuses = ['queued', 'claimed', 'finished', 'cancelled'];
11
+ const jobSources = ['agent', 'drainer', 'fix-loop', 'unknown'];
12
+ const defaultKinds = ['build', 'fix-loop', 'review'];
13
+ const eventTypes = lifecycleTypes;
14
+
15
+ function requireAllowed(flag, value, allowed) {
16
+ if (value !== undefined && !allowed.includes(value)) {
17
+ throw new Error(`invalid --${flag}; allowed values: ${allowed.join(', ')}`);
18
+ }
19
+ }
20
+
21
+ function optionsFor(command, args) {
22
+ const allowed = new Set(['worker', 'since', 'cursor', 'limit', ...(command === 'jobs' ? ['status', 'kind', 'source'] : ['type'])]);
23
+ const options = {};
24
+ for (let i = 0; i < args.length; i++) {
25
+ if (args[i] === '--json') continue;
26
+ const match = /^--([^=]+)(?:=(.*))?$/.exec(args[i]);
27
+ if (!match || !allowed.has(match[1])) throw new Error(`unknown ${command} option: ${args[i]}`);
28
+ const value = match[2] ?? args[++i];
29
+ if (!value || value.startsWith('--') || Object.hasOwn(options, match[1])) throw new Error(`--${match[1]} needs one value`);
30
+ options[match[1]] = value;
31
+ }
32
+ requireAllowed('status', options.status, jobStatuses);
33
+ requireAllowed('source', options.source === undefined ? undefined : canonicalMetaValue('source', options.source), jobSources);
34
+ requireAllowed('type', options.type, eventTypes);
35
+ const limit = options.limit === undefined ? 100 : Number(options.limit);
36
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new Error('--limit must be an integer from 1 to 1000');
37
+ const since = options.since === undefined ? null : parseWhen(options.since);
38
+ return { ...options, limit, since: since === null ? null : new Date(since).toISOString() };
39
+ }
40
+
41
+ function positionFor(cursor, command) {
42
+ if (!cursor) return null;
43
+ const invalid = () => new Error(`invalid ${command} cursor`);
44
+ let value;
45
+ try { value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); }
46
+ catch { throw invalid(); }
47
+ if (value?.command !== command || !Number.isSafeInteger(value.schema_version)) throw invalid();
48
+ if (value.schema_version !== READ_API_SCHEMA_VERSION) {
49
+ throw new Error(`${command} cursor schema version ${value.schema_version}; expected ${READ_API_SCHEMA_VERSION}`);
50
+ }
51
+ if (command === 'events' ? !Number.isSafeInteger(value.id) || value.id < 1 :
52
+ typeof value.at !== 'string' || !Number.isFinite(Date.parse(value.at)) || typeof value.id !== 'string') throw invalid();
53
+ return value;
54
+ }
55
+
56
+ export function readPage(file, command, options) {
57
+ const position = positionFor(options.cursor, command);
58
+ const where = [], params = [];
59
+ const filter = (sql, value) => { if (value !== undefined && value !== null) { where.push(sql); params.push(value); } };
60
+ let select, order;
61
+ if (command === 'jobs') {
62
+ filter('a.target_worker=?', options.worker);
63
+ filter('a.status=?', options.status);
64
+ filter('a.created_at>=?', options.since);
65
+ // Normalize the legacy spelling just as the existing metadata readers do.
66
+ for (const [flag, column] of [['kind', 'task_kind'], ['source', 'source']]) {
67
+ if (options[flag] !== undefined) {
68
+ const value = canonicalMetaValue(column, options[flag]);
69
+ filter(`${canonicalKindSql(`a.${column}`)}=?`, value);
70
+ }
71
+ }
72
+ if (position) { where.push('(a.created_at>? OR (a.created_at=? AND a.request_id>?))'); params.push(position.at, position.at, position.id); }
73
+ select = `SELECT a.request_id,a.status,a.target_worker AS worker,a.priority,a.task_kind,a.source,a.objective_key,
74
+ a.created_at,c.claimed_at,r.created_at AS finished_at,r.outcome,r.summary,r.result,a.payload,
75
+ a.cancelled_at,a.valid_until,a.skipped_at,c.worker AS claim_worker,c.state AS claim_state,
76
+ c.abandoned_at,c.last_claim_activity_at,c.acquisition_id,r.worker AS report_worker,
77
+ (SELECT decision FROM decisions d WHERE d.request_id=a.request_id ORDER BY d.id DESC LIMIT 1) AS decision,
78
+ (SELECT type FROM lifecycle_events e WHERE e.request_id=a.request_id AND
79
+ (e.type='accepted' OR e.type='consumed' AND e.reason LIKE 'rejected%') ORDER BY e.id DESC LIMIT 1) AS legacy_decision
80
+ FROM assignments a LEFT JOIN claims c USING(request_id) LEFT JOIN reports r USING(request_id)`;
81
+ order = 'a.created_at,a.request_id';
82
+ } else {
83
+ filter('worker=?', options.worker);
84
+ filter('at>=?', options.since);
85
+ filter('type=?', options.type);
86
+ filter('id>?', position?.id);
87
+ select = 'SELECT id,request_id,claim_id,epoch,type,at,actor,source,reason,worker,scope,outcome FROM lifecycle_events';
88
+ order = 'id';
89
+ }
90
+ const db = new DatabaseSync(file, { readOnly: true });
91
+ try {
92
+ db.exec('PRAGMA busy_timeout=5000');
93
+ if (command === 'jobs' && options.kind !== undefined) {
94
+ // Unlike the other vocabularies, task_kind is open submission metadata.
95
+ const present = db.prepare('SELECT DISTINCT task_kind FROM assignments WHERE task_kind IS NOT NULL').all();
96
+ const recorded = new Set(present.map(row => canonicalMetaValue('task_kind', row.task_kind)));
97
+ const canonical = canonicalMetaValue('task_kind', options.kind);
98
+ if (!defaultKinds.includes(canonical) && !recorded.has(canonical)) {
99
+ const additional = [...recorded].filter(kind => !defaultKinds.includes(kind)).length;
100
+ throw new Error(`invalid --kind; allowed values: ${defaultKinds.join(', ')}${additional ? ` and ${additional} recorded kinds` : ''}`);
101
+ }
102
+ }
103
+ const rows = db.prepare(`${select}${where.length ? ' WHERE ' + where.join(' AND ') : ''} ORDER BY ${order} LIMIT ?`).all(...params, options.limit + 1);
104
+ const more = rows.length > options.limit;
105
+ const page = rows.slice(0, options.limit);
106
+ const last = page.at(-1);
107
+ const next = more ? Buffer.from(JSON.stringify({ schema_version: READ_API_SCHEMA_VERSION, command,
108
+ ...(command === 'jobs' ? { at: last.created_at, id: last.request_id } : { id: last.id }) })).toString('base64url') : null;
109
+ const items = command === 'jobs' ? page.map(({ legacy_decision, ...row }) => ({ ...row,
110
+ task_kind: canonicalMetaValue('task_kind', row.task_kind), source: canonicalMetaValue('source', row.source),
111
+ objective_key: canonicalMetaValue('objective_key', row.objective_key), payload: JSON.parse(row.payload),
112
+ decision: row.decision ?? (legacy_decision === 'accepted' ? 'accepted' : legacy_decision === 'consumed' ? 'not_useful' : null),
113
+ })) : page;
114
+ return { schema_version: READ_API_SCHEMA_VERSION, [command]: items, next_cursor: next };
115
+ } finally { db.close(); }
116
+ }
117
+
118
+ export function readMain(command, args, home) {
119
+ try {
120
+ const options = optionsFor(command, args);
121
+ const page = readPage(defaultPath(home, '.local/share/dot-bridge/bridge.db'), command, options);
122
+ process.stdout.write(JSON.stringify(page) + '\n');
123
+ } catch (error) {
124
+ process.stderr.write(JSON.stringify({ schema_version: READ_API_SCHEMA_VERSION, error: error.message, kind: 'local' }) + '\n');
125
+ process.exitCode = 1;
126
+ }
127
+ }
package/src/redaction.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import {crc32,gunzipSync,inflateRawSync} from 'node:zlib';
2
+
1
3
  // One content policy for admission and every worker-visible text path.
2
4
  // Known-prefix families match even glued to a word character; the generic shapes keep a leading word boundary.
3
5
  const tokenContent=/(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{30,}|AKIA[A-Z0-9]{16}|\bsk-[A-Za-z0-9_-]{24,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|rk_live_[A-Za-z0-9]{16,}|(?:xoxe\.)?(?:xox[abposr]|xapp)-[A-Za-z0-9-]{10,}|xoxe-[A-Za-z0-9-]{10,}|AIza[A-Za-z0-9_-]{35}|whsec_[A-Za-z0-9+/=_-]{8,}|glpat-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36}|(?:https:\/\/)?hooks\.slack\.com\/services\/T[A-Z0-9]{8,}\/B[A-Z0-9]{8,}\/[A-Za-z0-9]{20,}|\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}|GOCSPX-[A-Za-z0-9_-]{20,}|\bya29\.[A-Za-z0-9_-]{20,}|\b1\/\/[A-Za-z0-9_-]{30,}|\b\d{8,10}:[A-Za-z0-9_-]{35}|\b[A-Za-z0-9_-]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27})\b|(?<![a-z0-9+.-])\b[a-z][a-z0-9+.-]*:\/\/[^\s:@\/]+:[^\s@\/]+@(?!(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|db|postgres|mysql|redis|mongo|example\.(?:com|org|net)|host\.docker\.internal)\b)[^\s\/]+/i;
@@ -541,6 +543,8 @@ const realCookie = raw => {
541
543
  const knownSecrets = new Set();
542
544
  const registeredValues = new Set();
543
545
  let knownPattern = null;
546
+ let artifactRuleEpoch = 0;
547
+ export const artifactSecretRuleEpoch = () => artifactRuleEpoch;
544
548
  const base64At = (bytes, offset) => {
545
549
  const text = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').replace(/=+$/, '');
546
550
  return text.slice(Math.ceil(offset * 8 / 6), Math.floor((offset + bytes.length) * 8 / 6));
@@ -560,6 +564,7 @@ export function registerSecret(value) {
560
564
  if (knownSecrets.size === before) return;
561
565
  // Longest first, so an encoded form that contains a shorter one is masked whole.
562
566
  knownPattern = new RegExp([...knownSecrets].sort((a, b) => b.length - a.length).map(form => form.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g');
567
+ artifactRuleEpoch++;
563
568
  }
564
569
  // A worker thread starts with its own module state; pass it these values so it masks and refuses the same secrets.
565
570
  export const registeredSecrets = () => [...registeredValues];
@@ -600,6 +605,140 @@ export function hasCredentialHints(value, depth = 0) {
600
605
  return Object.entries(value).some(([key, item]) => (typeof item === 'string' && isCredentialField(key) && explicitValue(item)) || hasCredentialHints(item, depth + 1));
601
606
  }
602
607
 
608
+ // Scan verified artifact bytes before any output slice. Only recognized gzip
609
+ // and ZIP containers are decoded; other formats keep the existing text scan.
610
+ const artifactArchiveLimit=64*1024*1024;
611
+ const artifactMemberLimit=256;
612
+ const archiveRefusal=reason=>({unscannable:reason});
613
+
614
+ function archiveError(reason){throw Object.assign(new Error(reason),{archiveReason:reason});}
615
+ function ensureArchive(ok,reason='invalid_archive'){if(!ok)archiveError(reason);}
616
+ function archiveBudget(budget,packed){
617
+ return Math.min(budget.remaining,Math.max(1,packed)*100);
618
+ }
619
+ function debitArchive(budget,amount){
620
+ ensureArchive(amount<=budget.remaining,'output_limit');
621
+ budget.remaining-=amount;
622
+ }
623
+ function checkedInflate(input,budget,decode){
624
+ const limit=archiveBudget(budget,input.length);
625
+ try {
626
+ const {buffer,engine}=decode(input,{maxOutputLength:Math.max(1,limit),info:true});
627
+ ensureArchive(engine.bytesWritten===input.length);
628
+ ensureArchive(buffer.length<=limit,'output_limit');
629
+ debitArchive(budget,buffer.length);
630
+ return buffer;
631
+ } catch(error) {
632
+ if(error.archiveReason) throw error;
633
+ archiveError(error.code==='ERR_BUFFER_TOO_LARGE'?'output_limit':'invalid_archive');
634
+ }
635
+ }
636
+
637
+ function zipDirectoryEnd(bytes){
638
+ const u16=o=>bytes.readUInt16LE(o),u32=o=>bytes.readUInt32LE(o);
639
+ let end=-1;
640
+ for(let p=bytes.length-22;p>=Math.max(0,bytes.length-22-0xffff);p--){
641
+ if(u32(p)===0x06054b50&&p+22+u16(p+20)===bytes.length){
642
+ ensureArchive(end===-1);
643
+ end=p;
644
+ }
645
+ }
646
+ return end;
647
+ }
648
+
649
+ function* zipArtifactMembers(bytes,budget,end){
650
+ ensureArchive(end>=0);
651
+ const u16=o=>bytes.readUInt16LE(o),u32=o=>bytes.readUInt32LE(o);
652
+ const count=u16(end+10),start=end-u32(end+12),base=start-u32(end+16);
653
+ ensureArchive(u16(end+4)===0&&u16(end+6)===0&&u16(end+8)===count,'unsupported_zip');
654
+ ensureArchive(count<=budget.members,'member_limit');
655
+ budget.members-=count;
656
+ ensureArchive(base>=0&&start>=base);
657
+ let p=start;
658
+ const entries=[];
659
+ for(let i=0;i<count;i++){
660
+ ensureArchive(p+46<=end&&u32(p)===0x02014b50);
661
+ const flags=u16(p+8),method=u16(p+10),crc=u32(p+16),packed=u32(p+20),size=u32(p+24);
662
+ const nameLength=u16(p+28),offset=base+u32(p+42);
663
+ const next=p+46+nameLength+u16(p+30)+u16(p+32);
664
+ ensureArchive(nameLength>0&&next<=end&&offset+30<=start);
665
+ ensureArchive(u16(p+34)===0&&(flags&~0x080e)===0&&(method===0||method===8),'unsupported_zip');
666
+ ensureArchive(u32(offset)===0x04034b50&&u16(offset+6)===flags&&u16(offset+8)===method);
667
+ ensureArchive(u16(offset+26)===nameLength);
668
+ const data=offset+30+nameLength+u16(offset+28);
669
+ ensureArchive(data+packed<=start);
670
+ ensureArchive(bytes.subarray(offset+30,offset+30+nameLength).equals(bytes.subarray(p+46,p+46+nameLength)));
671
+ if(!(flags&8))ensureArchive(u32(offset+14)===crc&&u32(offset+18)===packed&&u32(offset+22)===size);
672
+ entries.push({flags,method,crc,packed,size,offset,data});
673
+ p=next;
674
+ }
675
+ ensureArchive(p===end);
676
+ entries.sort((a,b)=>a.offset-b.offset);
677
+ // A leading prefix is allowed, but no gaps or overlaps among local members.
678
+ let previousEnd=entries[0]?.offset??start;
679
+ for(let i=0;i<entries.length;i++){
680
+ const {flags,method,crc,packed,size,offset,data}=entries[i];
681
+ const next=entries[i+1]?.offset??start;
682
+ const payloadEnd=data+packed;
683
+ ensureArchive(offset===previousEnd&&payloadEnd<=next);
684
+ if(flags&8){
685
+ const hasSignature=next-payloadEnd===16&&u32(payloadEnd)===0x08074b50;
686
+ const desc=payloadEnd+(hasSignature?4:0);
687
+ ensureArchive(next-desc===12&&u32(desc)===crc&&u32(desc+4)===packed&&u32(desc+8)===size);
688
+ } else ensureArchive(payloadEnd===next);
689
+ previousEnd=next;
690
+ ensureArchive(size<=archiveBudget(budget,packed),'output_limit');
691
+ const payload=bytes.subarray(data,payloadEnd);
692
+ let output;
693
+ if(method===0){
694
+ ensureArchive(packed===size);
695
+ debitArchive(budget,size);
696
+ output=payload;
697
+ } else {
698
+ // Also cap actual deflate output at the declared member size.
699
+ const memberBudget={remaining:Math.min(budget.remaining,size)};
700
+ output=checkedInflate(payload,memberBudget,inflateRawSync);
701
+ debitArchive(budget,output.length);
702
+ ensureArchive(output.length===size);
703
+ }
704
+ ensureArchive(crc32(output)===crc);
705
+ yield output;
706
+ }
707
+ ensureArchive(previousEnd===start);
708
+ }
709
+
710
+ function scanArtifactBytes(bytes,budget,depth){
711
+ const signature=bytes.length>=4?bytes.readUInt32LE(0):0;
712
+ const gzip=bytes[0]===0x1f&&bytes[1]===0x8b;
713
+ const leadingZip=[0x04034b50,0x06054b50,0x08074b50,0x02014b50].includes(signature);
714
+ const rawRule=artifactTextRule(bytes);
715
+ if(rawRule)return rawRule;
716
+ const end=gzip?-1:zipDirectoryEnd(bytes);
717
+ if(!gzip&&!leadingZip&&end<0)return null;
718
+ ensureArchive(depth<=1,'nesting_limit');
719
+ if(gzip)return scanArtifactBytes(checkedInflate(bytes,budget,gunzipSync),budget,depth+1);
720
+ for(const member of zipArtifactMembers(bytes,budget,end)){
721
+ const rule=scanArtifactBytes(member,budget,depth+1);
722
+ if(rule)return rule;
723
+ }
724
+ return null;
725
+ }
726
+
727
+ export function artifactSecretRule(bytes) {
728
+ try{return scanArtifactBytes(bytes,{remaining:artifactArchiveLimit,members:artifactMemberLimit},0);}
729
+ catch(error){return archiveRefusal(error.archiveReason??'invalid_archive');}
730
+ }
731
+
732
+ function artifactTextRule(bytes) {
733
+ const text=bytes.toString('utf8');
734
+ if(knownPattern&&text.search(knownPattern)!==-1) return 'registered_credential';
735
+ if(privateKeyHeader.test(text)||pemBodyRanges(text).next().done===false) return 'private_key_armor';
736
+ if(text.search(bearerText)!==-1) return 'bearer_credential';
737
+ if(text.search(basicText)!==-1) return 'basic_credential';
738
+ if(tokenContent.test(text)) return 'token_format';
739
+ return null;
740
+ }
741
+
603
742
  // The text core every sink shares: known values, strong formats, then labelled values. JSON text first gets the
604
743
  // structural split check, so a credential split across its fields or elements is masked like a structured one.
605
744
  const maskCore = text => maskCredentialFields(redactSecrets(text).text);
@@ -607,7 +746,41 @@ export const maskText = text => maskCore(splitSafeJson(text) ?? String(text));
607
746
 
608
747
  // A credential may be split across sibling strings ("Bearer" / value, "password=" / value). If scanning the
609
748
  // siblings joined masks more than scanning each alone, none of them can be trusted.
749
+ // Keep armor context when a header and its body occupy separate fields. The
750
+ // ordinary sibling pass intentionally joins already-masked text, which otherwise
751
+ // erases the header before a short/truncated body can be recognized.
752
+ function maskArmorContinuations(raws, cleaned) {
753
+ let header = null;
754
+ for (let i = 0; i < raws.length; i++) {
755
+ const raw = raws[i];
756
+ if (typeof raw !== 'string') { header = null; continue; }
757
+ // Only an isolated, recognized BEGIN banner starts cross-field context.
758
+ // Complete secrets in one field must not absorb unrelated neighbours.
759
+ if (/^\s*[-]+BEGIN[^\r\n]+[-]+\s*$/.test(raw) &&
760
+ [...armorMaskRanges(raw, false)].length) {
761
+ header = raw;
762
+ continue;
763
+ }
764
+ if (header === null) continue;
765
+ const lines = raw.trim().split(/\r?\n/);
766
+ const footer = line => /^[-]+END[^\r\n]+[-]+$/.test(line);
767
+ const payload = lines.filter(line => !footer(line));
768
+ // Require actual multiline/base64 material, never arbitrary prose. A short
769
+ // final line is accepted together with a footer or an earlier body line.
770
+ const material = payload.length > 0 && payload.every(line => /^[A-Za-z0-9+/]{4,}={0,2}$/.test(line)) &&
771
+ (payload.some(line => line.length >= 16) || lines.some(footer));
772
+ if (!material) { header = null; continue; }
773
+ const joined = header + '\n' + raw;
774
+ const start = header.length + 1;
775
+ if ([...armorMaskRanges(joined, false)].some(range => range.start < joined.length && range.end > start)) {
776
+ cleaned[i][1] = '[redacted secret]';
777
+ cleaned[i][2] = true;
778
+ }
779
+ if (lines.some(footer)) header = null;
780
+ }
781
+ }
610
782
  function splitSiblings(raws, cleaned) {
783
+ maskArmorContinuations(raws, cleaned);
611
784
  const at = raws.flatMap((item, i) => typeof item === 'string' && !cleaned[i][2] ? [i] : []);
612
785
  if (at.length < 2) return cleaned;
613
786
  const texts = at.map(i => raws[i]);
@@ -10,9 +10,25 @@ export function summarizeRejections(lines, sinceMs = 0) {
10
10
  let entry; try { entry = JSON.parse(line); } catch { continue; }
11
11
  if (entry.kind !== 'submit_rejected' || !(Date.parse(entry.at) >= sinceMs)) continue;
12
12
  refused++;
13
- const name = reasonClass(entry.reason), row = classes.get(name) ?? { reason: name, count: 0, example: entry.reason, request_ids: new Set() };
14
- row.count++; if (entry.request_id) row.request_ids.add(entry.request_id); classes.set(name, row);
13
+ const reasonCodes = Array.isArray(entry.reason_codes) && entry.reason_codes.length > 0 &&
14
+ entry.reason_codes.every(code => typeof code === 'string' && /^[a-z][a-z0-9_-]{0,79}$/.test(code))
15
+ ? [...new Set(entry.reason_codes)].sort() : null;
16
+ const name = reasonClass(entry.reason);
17
+ const key = reasonCodes ? JSON.stringify(['typed', ...reasonCodes]) : JSON.stringify(['legacy', name]);
18
+ const row = classes.get(key) ?? { reason: name, count: 0, example: entry.reason, request_ids: new Set(), reasonCodes };
19
+ row.count++; if (entry.request_id) row.request_ids.add(entry.request_id); classes.set(key, row);
15
20
  const source = canonicalKindLabel(entry.task_kind) ?? fromStoredSource(entry.source) ?? 'unknown'; bySource[source] = (bySource[source] ?? 0) + 1;
16
21
  }
17
- return { refused, classes: [...classes.values()].sort((a, b) => b.count - a.count).map(r => ({ reason: r.reason, count: r.count, distinct_requests: r.request_ids.size, example: r.example })), by_kind: bySource };
22
+ return { refused, classes: [...classes.values()].sort((a, b) => b.count - a.count).map(r => ({ reason: r.reason, count: r.count, distinct_requests: r.request_ids.size, example: r.example, ...(r.reasonCodes ? { reason_codes: r.reasonCodes } : {}) })), by_kind: bySource };
23
+ }
24
+
25
+ // Ordinary CLI text: typed classes carry their stable reason codes so different rules with
26
+ // identical prose stay distinguishable; legacy classes keep their readable prose alone.
27
+ export function formatRejections(summary, { since, accepted }) {
28
+ // Preserve b8d7a6e:bin/dot-worker.mjs refused_fraction (3 decimals) before its percent display.
29
+ const total = summary.refused + accepted;
30
+ const fraction = total ? Math.round(summary.refused / total * 1000) / 1000 : null;
31
+ const refusedFraction = fraction === null ? 'n/a' : `${Math.round(fraction * 100)}%`;
32
+ return [`submits since ${since}: ${accepted} accepted, ${summary.refused} refused (${refusedFraction})`,
33
+ ...summary.classes.map(c => `${String(c.count).padStart(6)} ${c.reason}${c.reason_codes ? ` [${c.reason_codes.join(', ')}]` : ''} (${c.distinct_requests} requests) e.g. ${String(c.example).slice(0, 120)}`)].join('\n');
18
34
  }
@@ -0,0 +1,90 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { writeAtomic } from './as-files.mjs';
5
+
6
+ function readPrivate(file) {
7
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
8
+ try {
9
+ const stat = fs.fstatSync(fd);
10
+ if (!stat.isFile() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid()) throw new Error('Private route custody is unavailable.');
11
+ return fs.readFileSync(fd);
12
+ } finally { fs.closeSync(fd); }
13
+ }
14
+
15
+ function privateDirectory(dir) {
16
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
17
+ const stat = fs.lstatSync(dir);
18
+ if (!stat.isDirectory() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid()) throw new Error('Private route custody is unavailable.');
19
+ }
20
+
21
+ // The per-user filesystem boundary protects the key. Only authenticated ciphertext and opaque IDs are stored.
22
+ export function routeSecretBackend(dir) {
23
+ const refPath = (scopeId, handle) => path.join(dir, createHash('sha256').update(JSON.stringify([scopeId, handle])).digest('hex'));
24
+ const keyFile = path.join(dir, 'key');
25
+ const key = (create = false) => {
26
+ if (create && !fs.existsSync(keyFile)) {
27
+ const staged = path.join(dir, randomUUID());
28
+ const bytes = randomBytes(32);
29
+ try {
30
+ writeAtomic(staged, bytes);
31
+ try { fs.linkSync(staged, keyFile); } catch (error) { if (error.code !== 'EEXIST') throw error; }
32
+ } finally { bytes.fill(0); fs.rmSync(staged, { force: true }); }
33
+ }
34
+ return readPrivate(keyFile);
35
+ };
36
+ const decode = (scopeId, handle) => {
37
+ privateDirectory(dir);
38
+ const file = refPath(scopeId, handle);
39
+ const ciphertext = readPrivate(file);
40
+ const material = key();
41
+ try {
42
+ const decipher = createDecipheriv('aes-256-gcm', material, ciphertext.subarray(0, 12));
43
+ decipher.setAAD(Buffer.from(path.basename(file)));
44
+ decipher.setAuthTag(ciphertext.subarray(12, 28));
45
+ const partial = decipher.update(ciphertext.subarray(28));
46
+ try { return Buffer.concat([partial, decipher.final()]); } finally { partial.fill(0); }
47
+ } finally { material.fill(0); }
48
+ };
49
+ return {
50
+ async put({ scopeId, bytes }) {
51
+ privateDirectory(dir);
52
+ const handle = randomUUID(), target = refPath(scopeId, handle);
53
+ const nonce = randomBytes(12), material = key(true);
54
+ try {
55
+ const cipher = createCipheriv('aes-256-gcm', material, nonce);
56
+ cipher.setAAD(Buffer.from(path.basename(target)));
57
+ const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()]);
58
+ writeAtomic(target, Buffer.concat([nonce, cipher.getAuthTag(), encrypted]));
59
+ return { handle };
60
+ } finally { material.fill(0); }
61
+ },
62
+ async withSecret({ scopeId, handle }, use) {
63
+ let bytes;
64
+ try { bytes = decode(scopeId, handle); }
65
+ catch { throw new Error('Private route credential is unavailable.'); }
66
+ try { return await use(bytes); } finally { bytes.fill(0); }
67
+ },
68
+ async presence({ scopeId, handle }) {
69
+ try { decode(scopeId, handle).fill(0); return { known: true, value: true }; }
70
+ catch (error) {
71
+ if (error.code === 'ENOENT' && error.path === refPath(scopeId, handle)) return { known: true, value: false };
72
+ return { known: false, reason: 'custody-unavailable' };
73
+ }
74
+ },
75
+ async delete({ scopeId, handle }) {
76
+ privateDirectory(dir);
77
+ try { fs.unlinkSync(refPath(scopeId, handle)); }
78
+ catch (error) { if (error.code !== 'ENOENT') throw new Error('Private route credential removal is unconfirmed.'); }
79
+ const fd = fs.openSync(dir, 'r');
80
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
81
+ return { deleted: true };
82
+ },
83
+ };
84
+ }
85
+
86
+ export function routeCustodyPath(env, gozarHome) {
87
+ const root = env.XDG_CONFIG_HOME || path.join(env.HOME, '.config');
88
+ const scope = createHash('sha256').update(gozarHome).digest('hex').slice(0, 24);
89
+ return path.join(root, 'dalan', 'route-custody', scope);
90
+ }
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { writeAtomic } from './as-files.mjs';
4
+ import { isPublished, resolveGozar } from './gozar-routes.mjs';
5
+
6
+ // A service may outlive the installer. Recheck the retained handle and withdraw
7
+ // the private handoff whenever the SDK no longer publishes the configured origin.
8
+ export function watchServicePublication({ home, configDir, origin, secret, canWrite }) {
9
+ const urlFile = path.join(home, 'resource-url');
10
+ const serviceFile = path.join(configDir, 'service-install.json');
11
+ const workerFile = path.join(configDir, 'route-reference.json');
12
+ let runtime, runtimeKey, expires, delay = 1000;
13
+ const target = fs.existsSync(serviceFile) ? serviceFile : workerFile;
14
+ const read = () => {
15
+ const value = JSON.parse(fs.readFileSync(target, 'utf8'));
16
+ return target === serviceFile ? { home: value.gozar_home, handle: value.route_handle, custody: value.route_custody } : value;
17
+ };
18
+ const withdraw = () => {
19
+ clearTimeout(expires);
20
+ fs.rmSync(urlFile, { force: true });
21
+ };
22
+ const refresh = async () => {
23
+ try {
24
+ if (!canWrite()) return;
25
+ const ref = read();
26
+ if (!ref.home || !ref.handle) { if (ref.home) withdraw(); return; }
27
+ const key = JSON.stringify([ref.home, ref.custody]);
28
+ if (key !== runtimeKey) {
29
+ runtime = await resolveGozar({ home: ref.home, custody: ref.custody });
30
+ runtimeKey = key;
31
+ }
32
+ const view = await runtime.routeStatus({ home: ref.home, handle: ref.handle });
33
+ if (!canWrite() || JSON.stringify(read()) !== JSON.stringify(ref)) return;
34
+ if (!isPublished(view) || view.published !== origin) { withdraw(); return; }
35
+ const url = `${view.published}/${secret}/mcp\n`;
36
+ let current;
37
+ try { current = fs.readFileSync(urlFile, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
38
+ if (url !== current) writeAtomic(urlFile, url);
39
+ const validity = view.verification.validUntil;
40
+ const remaining = validity?.known ? Date.parse(validity.value) - Date.now() : 1000;
41
+ clearTimeout(expires);
42
+ expires = setTimeout(() => { if (canWrite()) withdraw(); }, Math.max(0, remaining));
43
+ expires.unref();
44
+ delay = Math.max(250, Math.min(5000, remaining / 2));
45
+ } catch {
46
+ if (canWrite() && fs.existsSync(target)) withdraw();
47
+ } finally { setTimeout(refresh, delay).unref(); }
48
+ };
49
+ void refresh();
50
+ }