deadbyte-mcp 0.15.26 → 0.15.28

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.
@@ -13,8 +13,9 @@ import { openRemoteResultJournal, parseRemoteResultCursor } from './remote-resul
13
13
  import { DEADBYTE_VERSION } from './version.mjs';
14
14
  import { parseActivePointer } from './release-slot.mjs';
15
15
  import { printDoctor } from './doctor-r45.mjs';
16
- import { createLiveTimelineFilter, createLiveTimelineTracker, createLiveTimelineWriter, formatCompactAuditEvent, formatRemoteLifecycle, formatRemoteToolCall, formatRuntimeDiagnosticLine } from './remote-live-log.mjs';
16
+ import { createLiveTimelineFilter, createLiveTimelineTracker, createLiveTimelineWriter, formatCompactAuditEvent, formatRemoteLifecycle, formatRemoteToolCall, formatRuntimeDiagnosticLine, selectLiveLogNames } from './remote-live-log.mjs';
17
17
  import { prepareRemoteConsole, remoteDisplayText } from './remote-console.mjs';
18
+ import { ensureRuntimeCoherence } from './runtime-coherence.mjs';
18
19
 
19
20
  const REMOTE_COMMANDS=new Set([
20
21
  'menu','start','resume','park','stop','restart','status','url','test','fulltest','toggle','clean','machinetest',
@@ -29,12 +30,17 @@ const SESSION_STATUS=[
29
30
  ['processstatus',/^Process plane\s*:\s*ARMED\b/m],
30
31
  ['codingstatus',/^Coding plane\s*:\s*ARMED\b/m],
31
32
  ['autonomousstatus',/^Autonomous\s*:\s*ARMED\b/m],
33
+ ['desktopstatus',/^Desktop plane\s*:\s*DISARMED\b/m],
32
34
  ['hoststatus',/^Host plane\s*:\s*DISARMED\b/m]
33
35
  ];
34
- const SESSION_CLEANUP=['disarmautonomous','disarmcoding','disarmprocess','disarmhost','park'];
36
+ const SESSION_CLEANUP=['disarmautonomous','disarmcoding','disarmprocess','disarmdesktop','disarmhost','park'];
35
37
  const SUPERVISOR_COMMANDS=Object.freeze({
36
38
  start:'supervisorstart',stop:'supervisorstop',status:'supervisorstatus',recover:'supervisorrecover'
37
39
  });
40
+ const CURRENT_PACKAGE_ROOT=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
41
+ const CURRENT_DEPLOY_SCRIPT=path.join(CURRENT_PACKAGE_ROOT,'scripts','deploy-r48.mjs');
42
+ const REMOTE_UPDATE_TIMEOUT_MS=900000;
43
+ const LIVE_LOG_DISCOVERY_INTERVAL_MS=1000;
38
44
 
39
45
  function stateRoot(){return path.resolve(process.env.DEADBYTE_STATE_ROOT||path.join(os.homedir(),'.deadbyte-mcp'));}
40
46
  async function requireRegular(file,label){const info=await lstat(file);if(!info.isFile()||info.isSymbolicLink()) throw new Error(`${label} must be a regular non-symlink file`);return file;}
@@ -94,6 +100,43 @@ async function reportVersionCoherence(root,{displayMode='ascii'}={}){
94
100
  writeRemote(process.stderr,`${remoteTag('warn',displayMode)} VERSION SKEW: CLI package ${DEADBYTE_VERSION}; active runtime ${active.version} (${active.release_id})\n`,displayMode);
95
101
  return active;
96
102
  }
103
+ async function synchronizeForegroundRuntime(ctx,{displayMode='unicode'}={}){
104
+ const packageManifestSha256=createHash('sha256').update(await readFile(path.join(CURRENT_PACKAGE_ROOT,'MANIFEST.SHA256'))).digest('hex');
105
+ return ensureRuntimeCoherence({
106
+ cliVersion:DEADBYTE_VERSION,
107
+ packageManifestSha256,
108
+ readActive:()=>readActiveRuntimeBinding(ctx.root),
109
+ disarmPrivileged:async()=>{
110
+ for(const command of ['disarmhost','disarmdesktop']){
111
+ const result=invokeController(ctx,command,{capture:true,allowFailure:true,echoCaptured:false,timeoutMs:REMOTE_STATUS_TIMEOUT_MS});
112
+ if(result.status!==0) throw new Error(`runtime coherence '${command}' failed exit=${result.status}`);
113
+ }
114
+ },
115
+ activateCurrentPackage:async()=>{
116
+ const result=spawnSync(process.execPath,[CURRENT_DEPLOY_SCRIPT],{
117
+ cwd:CURRENT_PACKAGE_ROOT,
118
+ env:{...process.env,DEADBYTE_STATE_ROOT:ctx.root},
119
+ encoding:'utf8',
120
+ windowsHide:true,
121
+ shell:false,
122
+ timeout:REMOTE_UPDATE_TIMEOUT_MS,
123
+ maxBuffer:16*1024*1024
124
+ });
125
+ if(result.error){
126
+ if(result.error?.code==='ETIMEDOUT') throw new Error(`runtime coherence activation timed out after ${REMOTE_UPDATE_TIMEOUT_MS}ms`);
127
+ throw result.error;
128
+ }
129
+ if(result.status!==0){
130
+ const detail=boundedSingleLine(result.stderr||result.stdout||'no deployment output',2048);
131
+ throw new Error(`runtime coherence activation failed exit=${String(result.status)}: ${detail}`);
132
+ }
133
+ },
134
+ onEvent:event=>{
135
+ if(event.phase==='upgrade_start') writeRemote(process.stdout,`[UPDATE] Runtime ${event.from_version} -> ${event.to_version}; activating current package...\n`,displayMode);
136
+ else if(event.phase==='upgrade_complete') writeRemote(process.stdout,`[UPDATE] Runtime synchronized: ${event.release_id||event.to_version}\n`,displayMode);
137
+ }
138
+ });
139
+ }
97
140
  async function readControllerStartFailure(root,command,{maxChars=2048}={}){
98
141
  const file=path.join(root,'runtime','controller-start-failure.json');
99
142
  let raw;
@@ -158,32 +201,34 @@ function controllerRuntimeDegraded(text){
158
201
  return /^DEADBYTE MCP\s*=\s*DEGRADED\s*$/m.test(String(text||''));
159
202
  }
160
203
  async function listLogFiles(root){
161
- const files=[];
162
- const audit=path.join(root,'audit');
163
- const runtimeLogs=path.join(root,'runtime','logs');
164
- for(const [dir,accept] of [
165
- [audit,name=>/^segment-\d{8}\.jsonl$/.test(name)],
166
- [runtimeLogs,name=>/\.log$/i.test(name)]
167
- ]){
168
- let names=[];try{names=await readdir(dir);}catch(error){if(error?.code==='ENOENT') continue;throw error;}
169
- for(const name of names.sort()) if(accept(name)) files.push(path.join(dir,name));
170
- }
171
- return files;
204
+ const auditDir=path.join(root,'audit');
205
+ const runtimeDir=path.join(root,'runtime','logs');
206
+ let auditNames=[],runtimeNames=[];
207
+ try{auditNames=await readdir(auditDir);}catch(error){if(error?.code!=='ENOENT') throw error;}
208
+ try{runtimeNames=await readdir(runtimeDir);}catch(error){if(error?.code!=='ENOENT') throw error;}
209
+ const selected=selectLiveLogNames({auditNames,runtimeNames});
210
+ return [
211
+ ...selected.audit.map(name=>path.join(auditDir,name)),
212
+ ...selected.runtime.map(name=>path.join(runtimeDir,name))
213
+ ];
214
+ }
215
+ function parseAuditLogLine(file,line){
216
+ if(!/^segment-\d{8}\.jsonl$/.test(path.basename(file))||!line) return null;
217
+ try{return JSON.parse(line);}catch{return null;}
172
218
  }
173
- function formatLogLine(file,line,{activityTracker=null,sequence=null,verbose=false,displayMode='unicode'}={}){
219
+ function formatLogLine(file,line,{auditEvent=null,activityTracker=null,sequence=null,verbose=false,displayMode='unicode'}={}){
174
220
  if(!line) return null;
175
221
  if(/^segment-\d{8}\.jsonl$/.test(path.basename(file))){
176
- try{
177
- const event=JSON.parse(line);
178
- return activityTracker?activityTracker.observe(event,{sequence}):formatCompactAuditEvent(event);
179
- }catch{return null;}
222
+ const event=auditEvent??parseAuditLogLine(file,line);
223
+ if(!event) return null;
224
+ return activityTracker?activityTracker.observe(event,{sequence}):formatCompactAuditEvent(event);
180
225
  }
181
226
  return formatRuntimeDiagnosticLine(file,line,{verbose,displayMode});
182
227
  }
183
228
  function remoteResultJournalPath(root,sessionId){return path.join(root,'runtime','remote-results',`${sessionId}.json`);}
184
- function auditTimelineRecord(file,line){
185
- if(!/^segment-\d{8}\.jsonl$/.test(path.basename(file))||!line) return null;
186
- let event;try{event=JSON.parse(line);}catch{return null;}
229
+ function auditTimelineRecord(file,line,auditEvent=null){
230
+ const event=auditEvent??parseAuditLogLine(file,line);
231
+ if(!event) return null;
187
232
  if(typeof event?.request_id!=='string'||!event.request_id||typeof event.tool!=='string'||!event.tool) return null;
188
233
  const stamp=[event.ts,event.created_at_utc,event.observed_at_utc].find(value=>typeof value==='string'&&Number.isFinite(Date.parse(value)));
189
234
  const observed=stamp?new Date(Date.parse(stamp)).toISOString():new Date().toISOString();
@@ -239,7 +284,8 @@ async function readAppend(file,offset){
239
284
  }
240
285
  async function snapshotRemoteLogOffsets(root){
241
286
  const offsets=new Map();
242
- for(const file of await listLogFiles(root)){
287
+ const files=await listLogFiles(root);
288
+ for(const file of files){
243
289
  try{offsets.set(file,(await stat(file)).size);}catch{}
244
290
  }
245
291
  return offsets;
@@ -264,20 +310,28 @@ async function tailRemoteLogs(root,signal,{journal=null,offsets=null,activityTra
264
310
  ? '[LOG] Verbose live timeline. Full sanitized request detail enabled; Ctrl+C disconnects and revokes authority.\n'
265
311
  : '[LOG] Human live timeline. Transport IN/OUT hidden; full replay/audit detail remains on disk. Ctrl+C disconnects and revokes authority.\n');
266
312
  const activeOffsets=offsets??await snapshotRemoteLogOffsets(root);
313
+ let liveFiles=[...activeOffsets.keys()];
314
+ let nextDiscoveryAt=0;
267
315
  while(!signal.aborted){
268
- for(const file of await listLogFiles(root)){
316
+ const now=Date.now();
317
+ if(now>=nextDiscoveryAt){
318
+ liveFiles=await listLogFiles(root);
319
+ nextDiscoveryAt=now+LIVE_LOG_DISCOVERY_INTERVAL_MS;
320
+ }
321
+ for(const file of liveFiles){
269
322
  const prior=activeOffsets.has(file)?activeOffsets.get(file):0;
270
323
  const next=await readAppend(file,prior);
271
324
  activeOffsets.set(file,next.offset);
272
325
  for(const line of next.text.split(/\r?\n/)){
273
- const timeline=auditTimelineRecord(file,line);
326
+ const auditEvent=parseAuditLogLine(file,line);
327
+ const timeline=auditTimelineRecord(file,line,auditEvent);
274
328
  let recorded=null;
275
329
  if(timeline&&journal) recorded=timeline.event_type==='tool.call'
276
330
  ? await journal.recordCall(timeline)
277
331
  : await journal.recordTerminal(timeline);
278
332
  if(recorded?.duplicate) continue;
279
333
  const accepted=timelineFilter&&timeline?timelineFilter.accept(timelineFilterEvent(timeline)):true;
280
- const formatted=formatLogLine(file,line,{activityTracker,sequence:recorded?.event?.seq??null,verbose,displayMode});
334
+ const formatted=formatLogLine(file,line,{auditEvent,activityTracker,sequence:recorded?.event?.seq??null,verbose,displayMode});
281
335
  if(!formatted||!accepted) continue;
282
336
  const output=Array.isArray(formatted)?formatted:[formatted];
283
337
  for(const item of output) if(item){
@@ -381,11 +435,17 @@ async function runRemoteSession({resumeCursor=null,verbose=false,trace=false,fil
381
435
  const display=prepareRemoteConsole();
382
436
  const displayMode=display.mode;
383
437
  const ctx=await remoteContext();
384
- await reportVersionCoherence(ctx.root,{displayMode});
385
438
  if(displayMode==='ascii') writeRemote(process.stdout,`[DISPLAY] ASCII fallback: ${display.reason}\n`,displayMode);
386
439
  if(resumeCursor!==null) await replayRemoteResults(ctx.root,resumeCursor,{displayMode});
387
440
  await recoverRemoteSession(ctx,{displayMode});
388
441
  const marker=await claimRemoteSession(ctx);
442
+ try{
443
+ await synchronizeForegroundRuntime(ctx,{displayMode});
444
+ }catch(error){
445
+ await cleanupRemoteSession(ctx,{displayMode});
446
+ await releaseRemoteSession(ctx,marker,{displayMode});
447
+ throw error;
448
+ }
389
449
  const resultJournal=await openRemoteResultJournal({
390
450
  filePath:remoteResultJournalPath(ctx.root,marker.result_session_id),sessionId:marker.result_session_id,maxEntries:2048
391
451
  });
@@ -442,13 +502,13 @@ async function runRemoteSession({resumeCursor=null,verbose=false,trace=false,fil
442
502
  process.stdout.write('[OK] ONLINE\n');
443
503
  process.stdout.write(`${formatRemoteLifecycle('ready',{displayMode})}\n`);
444
504
  if(url) writeRemote(process.stdout,`URL: ${url}\n`,displayMode);
445
- writeRemote(process.stdout,`${remoteTag('auth',displayMode)} Verifying process, coding, autonomous; host must stay DISARMED...\n`,displayMode);
505
+ writeRemote(process.stdout,`${remoteTag('auth',displayMode)} Verifying process, coding, autonomous; desktop + host must stay DISARMED...\n`,displayMode);
446
506
  for(const [command,pattern] of SESSION_STATUS){
447
507
  const result=invokeController(ctx,command,{capture:true,echoCaptured:false});
448
508
  if(!pattern.test(result.stdout)) throw new Error(`remote session authority verification failed: ${command} state mismatch`);
449
509
  }
450
510
  ready=true;
451
- writeRemote(process.stdout,`${remoteTag('auth',displayMode)} ARMED: process, coding, autonomous | host DISARMED\n`,displayMode);
511
+ writeRemote(process.stdout,`${remoteTag('auth',displayMode)} ARMED: process, coding, autonomous | desktop, host DISARMED\n`,displayMode);
452
512
  await logTask;
453
513
  }finally{
454
514
  const wasAborted=aborter.signal.aborted;
@@ -53,6 +53,13 @@ const TOOL_ICONS_ASCII=Object.freeze({read:'R',write:'W',edit:'E',run:'>',verify
53
53
  const START_VISIBLE_PATTERNS=[/(?:^|_)file_write$/,/text_replace$/,/symbol_replace$/,/native_diff_(?:apply|preview)$/,
54
54
  /(?:command|benchmark)_run$/,/task_run$/,/goal_run$/,/goal_submit$/,/goal_approve$/,/process_session_(?:start|action|terminate)$/,/^desktop_action$/];
55
55
 
56
+ export function selectLiveLogNames({auditNames=[],runtimeNames=[]}={}){
57
+ if(!Array.isArray(auditNames)||!Array.isArray(runtimeNames)) throw new Error('live log names must be arrays');
58
+ const audit=auditNames.filter(name=>typeof name==='string'&&/^segment-\d{8}\.jsonl$/.test(name)).sort().slice(-2);
59
+ const runtime=runtimeNames.filter(name=>typeof name==='string'&&/\.log$/i.test(name)).sort();
60
+ return Object.freeze({audit:Object.freeze(audit),runtime:Object.freeze(runtime)});
61
+ }
62
+
56
63
  export function truncateUtf8(value,maxBytes,{ellipsis='…'}={}){
57
64
  if(typeof value!=='string'||!Number.isInteger(maxBytes)||maxBytes<1) return '';
58
65
  const bytes=new TextEncoder().encode(value);
@@ -312,18 +319,19 @@ export function createLiveTimelineWriter({stream=process.stdout,displayMode='uni
312
319
  return Object.freeze({write,flush,pending(){return active?{...active}:null;}});
313
320
  }
314
321
 
315
- export function createLiveTimelineTracker({clock=()=>Date.now(),verbose=false,heartbeatBurstLimit=10,heartbeatWindowMs=3000,displayMode='unicode',rootPaths={},trace=false}={}){
322
+ export function createLiveTimelineTracker({clock=()=>Date.now(),verbose=false,heartbeatBurstLimit=10,heartbeatWindowMs=3000,displayMode='unicode',rootPaths={},trace=false,slowCallMs=1000}={}){
316
323
  if(typeof clock!=='function') throw new Error('live timeline clock must be a function');
317
324
  if(!REMOTE_DISPLAY_MODES.includes(displayMode)) throw new Error('remote display mode invalid');
318
325
  if(!Number.isInteger(heartbeatBurstLimit)||heartbeatBurstLimit<2||heartbeatBurstLimit>100) throw new Error('heartbeatBurstLimit invalid');
319
326
  if(!Number.isInteger(heartbeatWindowMs)||heartbeatWindowMs<250||heartbeatWindowMs>60000) throw new Error('heartbeatWindowMs invalid');
320
327
  if(!rootPaths||typeof rootPaths!=='object'||Array.isArray(rootPaths)) throw new Error('live timeline rootPaths invalid');
321
328
  if(typeof trace!=='boolean') throw new Error('live timeline trace invalid');
329
+ if(!Number.isInteger(slowCallMs)||slowCallMs<100||slowCallMs>600000) throw new Error('live timeline slowCallMs invalid');
322
330
  const pending=new Map();
323
331
  const completed=new Set();
324
332
  const toolCounts=new Map();
325
333
  const durationSamples=[];
326
- let resultCount=0,okCount=0,errorCount=0,unknownCount=0,mutationCount=0,totalDurationMs=0,slowest=null,burst=null,foldedHeartbeatLines=0;
334
+ let resultCount=0,okCount=0,errorCount=0,unknownCount=0,mutationCount=0,totalDurationMs=0,slowest=null,burst=null,foldedHeartbeatLines=0,peakInFlight=0;
327
335
 
328
336
  function eventPrefix(event,sequence,{displayTool=null,icon=null}={}){
329
337
  const seq=Number.isSafeInteger(sequence)&&sequence>0?'#'+sequence+' ':'';
@@ -336,9 +344,11 @@ export function createLiveTimelineTracker({clock=()=>Date.now(),verbose=false,he
336
344
  const error=event.outcome?.is_error===true;
337
345
  const unknown=event.outcome?.side_effect_state==='unknown';
338
346
  const displayTool=span?.display_tool||event.tool;
339
- const duration=Number.isFinite(Number(event.outcome?.duration_ms))
340
- ?formatDuration(event.outcome.duration_ms)
347
+ const rawDuration=Number(event.outcome?.duration_ms);
348
+ const duration=Number.isFinite(rawDuration)
349
+ ?formatDuration(rawDuration)
341
350
  :span?formatDuration(Math.max(0,clock()-span.started_at_ms)):'';
351
+ const slow=Number.isFinite(rawDuration)&&rawDuration>=slowCallMs?' [SLOW]':'';
342
352
  const summary=span?.summary||'';
343
353
  const rawReason=typeof event.outcome?.reason==='string'&&event.outcome.reason?event.outcome.reason:
344
354
  (unknown&&typeof event.outcome?.recovery?.reason==='string'?event.outcome.recovery.reason:'');
@@ -353,7 +363,7 @@ export function createLiveTimelineTracker({clock=()=>Date.now(),verbose=false,he
353
363
  const prefixIcon=unknown?(displayMode==='ascii'?'WARN':'⚠️'):null;
354
364
  const evidence=receipt?' '+(displayMode==='ascii'?'RECEIPT':'🧾 receipt')+(displayMode==='ascii'?'=':'=')+receipt:'';
355
365
  const reasonSep=displayMode==='ascii'?' - ':' — ';
356
- return remoteDisplayText(eventPrefix(event,sequence,{displayTool,icon:prefixIcon})+traceSuffix(span?.trace_meta)+(summary?' '+summary:'')+(duration?' '+duration:'')+' '+marker+evidence+(reason?reasonSep+reason:''),displayMode);
366
+ return remoteDisplayText(eventPrefix(event,sequence,{displayTool,icon:prefixIcon})+traceSuffix(span?.trace_meta)+(summary?' '+summary:'')+(duration?' '+duration:'')+slow+' '+marker+evidence+(reason?reasonSep+reason:''),displayMode);
357
367
  }
358
368
  function burstLine(value){
359
369
  if(!value) return null;
@@ -396,6 +406,7 @@ export function createLiveTimelineTracker({clock=()=>Date.now(),verbose=false,he
396
406
  const summary=summarizeLiveToolArgs(displayTool,args,{rootPaths});
397
407
  const traceMeta=traceIdentity(event,args);
398
408
  pending.set(requestId,{request_id:requestId,tool,display_tool:displayTool,summary,trace_meta:traceMeta,started_at_ms:clock()});
409
+ peakInFlight=Math.max(peakInFlight,pending.size);
399
410
  if(verbose) return formatRemoteToolCall({...event,tool:displayTool},{clock,displayMode})+traceSuffix(traceMeta);
400
411
  if(visibleStart(displayTool)) return eventPrefix(event,sequence,{displayTool})+traceSuffix(traceMeta)+(summary?' '+summary:'')+' …';
401
412
  return null;
@@ -453,6 +464,7 @@ export function createLiveTimelineTracker({clock=()=>Date.now(),verbose=false,he
453
464
  ' | tool time '+(formatDuration(totalDurationMs)||'0ms')+
454
465
  (p50!==null?' | p50 '+formatDuration(p50)+' | p95 '+formatDuration(p95):'')+
455
466
  (slowest?' | slowest '+slowest.tool+' '+formatDuration(slowest.duration_ms):'')+
467
+ ' | peak in-flight '+peakInFlight+
456
468
  (foldedHeartbeatLines?' | folded '+foldedHeartbeatLines+' heartbeat lines':'')+
457
469
  (top?' | top: '+top:''),displayMode);
458
470
  }
@@ -5,7 +5,7 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { setTimeout as sleep } from 'node:timers/promises';
7
7
 
8
- const CLEANUP=['disarmautonomous','disarmcoding','disarmprocess','disarmhost','park'];
8
+ const CLEANUP=['disarmautonomous','disarmcoding','disarmprocess','disarmdesktop','disarmhost','park'];
9
9
 
10
10
  function parseArgs(argv){
11
11
  const out={};
@@ -0,0 +1,50 @@
1
+ const SEMVER=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
2
+ const HEX64=/^[0-9a-f]{64}$/;
3
+
4
+ function parseSemver(value){
5
+ const match=SEMVER.exec(String(value??''));
6
+ if(!match) throw new Error(`runtime version invalid: ${String(value)}`);
7
+ return {major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),prerelease:match[4]??null};
8
+ }
9
+ export function compareRuntimeVersions(a,b){
10
+ const left=parseSemver(a),right=parseSemver(b);
11
+ for(const key of ['major','minor','patch']) if(left[key]!==right[key]) return left[key]<right[key]?-1:1;
12
+ if(left.prerelease===right.prerelease) return 0;
13
+ if(left.prerelease===null) return 1;
14
+ if(right.prerelease===null) return -1;
15
+ return left.prerelease.localeCompare(right.prerelease,'en',{numeric:true,sensitivity:'case'});
16
+ }
17
+ function assertManifest(value,label){
18
+ if(!HEX64.test(String(value??''))) throw new Error(`${label} must be lowercase SHA-256`);
19
+ return value;
20
+ }
21
+ export async function ensureRuntimeCoherence({
22
+ cliVersion,packageManifestSha256,readActive,disarmPrivileged,activateCurrentPackage,onEvent=()=>{}
23
+ }={}){
24
+ parseSemver(cliVersion);assertManifest(packageManifestSha256,'package manifest');
25
+ if(typeof readActive!=='function'||typeof disarmPrivileged!=='function'||typeof activateCurrentPackage!=='function'||typeof onEvent!=='function') {
26
+ throw new Error('runtime coherence callbacks invalid');
27
+ }
28
+ const initial=await readActive();
29
+ if(!initial) return {status:'unbound',active:null};
30
+ const activeVersion=String(initial.version??'');
31
+ const relation=compareRuntimeVersions(cliVersion,activeVersion);
32
+ if(relation===0){
33
+ if(String(initial.manifest_sha256??'')!==packageManifestSha256) {
34
+ throw new Error(`runtime manifest skew for ${cliVersion}: package ${packageManifestSha256}; active ${String(initial.manifest_sha256??'missing')}`);
35
+ }
36
+ return {status:'coherent',active:initial};
37
+ }
38
+ if(relation<0) throw new Error(`active runtime ${activeVersion} is newer than CLI package ${cliVersion}; refusing automatic downgrade`);
39
+ onEvent({phase:'upgrade_start',from_version:activeVersion,to_version:cliVersion,from_release_id:initial.release_id??null});
40
+ await disarmPrivileged();
41
+ await activateCurrentPackage();
42
+ const active=await readActive();
43
+ if(!active) throw new Error('runtime coherence activation completed without active release pointer');
44
+ if(String(active.version??'')!==cliVersion) throw new Error(`runtime coherence activation version mismatch: expected ${cliVersion}, found ${String(active.version??'missing')}`);
45
+ if(String(active.manifest_sha256??'')!==packageManifestSha256) {
46
+ throw new Error(`runtime coherence activation manifest mismatch: expected ${packageManifestSha256}, found ${String(active.manifest_sha256??'missing')}`);
47
+ }
48
+ onEvent({phase:'upgrade_complete',from_version:activeVersion,to_version:cliVersion,release_id:active.release_id??null});
49
+ return {status:'upgraded',active};
50
+ }
package/src/version.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export const DEADBYTE_VERSION = '0.15.26';
1
+ export const DEADBYTE_VERSION = '0.15.28';
2
2
  export const MCP_PROTOCOL_VERSION = '2026-07-28';
3
3
  export const RECEIPT_SCHEMA_V1 = 'deadbyte.receipt.v1';
4
4
  export const RECEIPT_SCHEMA_V2 = 'deadbyte.receipt.v2';
@@ -39,7 +39,7 @@ async function fixture({ armed = true } = {}) {
39
39
  }
40
40
  const runtime = createCodingRuntime({ policy, signingKeyPath: keys.privateKeyPath, verifyKeyPath: keys.publicKeyPath });
41
41
  const tasks = createCodingTaskRuntime({ codingRuntime: runtime, signingKeyPath: keys.privateKeyPath, verifyKeyPath: keys.publicKeyPath });
42
- return { root, project, policy, runtime, tasks };
42
+ return { root, project, policy, runtime, tasks, keys };
43
43
  }
44
44
  test('coding plane edits files under lease and verifies signed action receipts', async () => {
45
45
  const f = await fixture();
@@ -233,3 +233,37 @@ test('coding task rejects recomputed journal content without the private signing
233
233
  await assert.rejects(() => f.tasks.status({ taskId: submitted.task_id }), /signature verification failed|hash-chain mismatch/);
234
234
  } finally { await rm(f.root, { recursive: true, force: true }); }
235
235
  });
236
+
237
+
238
+ test('R51 coding command retries reuse one in-flight execution and completed receipt', async () => {
239
+ const f = await fixture();
240
+ try {
241
+ const script = path.join(f.project, 'dedup.mjs');
242
+ await writeFile(script, "import { appendFileSync } from 'node:fs'; appendFileSync('runs.txt', process.pid+'\\n'); await new Promise(r=>setTimeout(r,250)); process.stdout.write('dedup-ok');");
243
+ const args={rootId:'project',commandId:'node_script',scriptPath:'dedup.mjs',scriptSha256:await sha256File(script),timeoutMs:5000};
244
+ const [a,b]=await Promise.all([f.runtime.commandRun(args),f.runtime.commandRun(args)]);
245
+ assert.equal(a.status,'passed',a.stderr);assert.equal(b.status,'passed',b.stderr);
246
+ assert.equal(a.request_sha256,b.request_sha256);
247
+ assert.equal(a.receipt_id,b.receipt_id,'same logical request must reuse the same signed execution receipt');
248
+ const c=await f.runtime.commandRun(args);
249
+ assert.equal(c.receipt_id,a.receipt_id,'completed retry must reuse bounded cached execution result');
250
+ const runs=(await readFile(path.join(f.project,'runs.txt'),'utf8')).trim().split(/\\r?\\n/).filter(Boolean);
251
+ assert.equal(runs.length,1,'retry spawned duplicate child process');
252
+ } finally { await rm(f.root,{recursive:true,force:true}); }
253
+ });
254
+
255
+ test('R51 coding command single-flight spans independent runtime instances sharing evidence state', async () => {
256
+ const f = await fixture();
257
+ try {
258
+ const script = path.join(f.project, 'cross-runtime-dedup.mjs');
259
+ await writeFile(script, "import { appendFileSync } from 'node:fs'; appendFileSync('cross-runs.txt', process.pid+'\\n'); await new Promise(r=>setTimeout(r,500)); process.stdout.write('cross-ok');");
260
+ const second = createCodingRuntime({ policy:f.policy, signingKeyPath:f.keys.privateKeyPath, verifyKeyPath:f.keys.publicKeyPath });
261
+ const args={rootId:'project',commandId:'node_script',scriptPath:'cross-runtime-dedup.mjs',scriptSha256:await sha256File(script),timeoutMs:5000};
262
+ const [a,b]=await Promise.all([f.runtime.commandRun(args),second.commandRun(args)]);
263
+ assert.equal(a.status,'passed',a.stderr);assert.equal(b.status,'passed',b.stderr);
264
+ assert.equal(a.request_sha256,b.request_sha256);
265
+ assert.equal(a.receipt_id,b.receipt_id,'shared evidence state must converge on one signed execution receipt');
266
+ const runs=(await readFile(path.join(f.project,'cross-runs.txt'),'utf8')).trim().split(/\\r?\\n/).filter(Boolean);
267
+ assert.equal(runs.length,1,'independent runtime instances spawned duplicate child processes');
268
+ } finally { await rm(f.root,{recursive:true,force:true}); }
269
+ });
@@ -42,3 +42,9 @@ test('publish boundary excludes live state, private keys, grants and non-example
42
42
  const forbidden=files.filter(rel=>rel.startsWith('tmp/')||rel.startsWith('.deadbyte-machine-fs-recovery/')||/(^|\/)(active-release\.json|runtime\/|audit\/|evidence\/)|\.pem$|(^|\/)deadbyte-controller\.config\.psd1$|(^|\/)deadbyte-host-policy\.json$|(^|\/)[^/]*(?:grant|arm)\.json$/i.test(rel));
43
43
  assert.deepEqual(forbidden,[]);
44
44
  });
45
+
46
+ test('publish boundary includes only the canonical top-level Windows launcher',()=>{
47
+ const files=packFiles();
48
+ const launchers=files.filter(rel=>/^DEADBYTE-MCP.*\.cmd$/i.test(rel));
49
+ assert.deepEqual(launchers,['DEADBYTE-MCP.cmd']);
50
+ });
@@ -3,15 +3,17 @@ import assert from 'node:assert/strict';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { DEADBYTE_VERSION } from '../src/version.mjs';
6
7
 
7
8
  const root=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
8
9
  const readme=()=>readFile(path.join(root,'README.txt'),'utf8');
10
+ const versionPattern=DEADBYTE_VERSION.replace(/[.*+?^$()|[\]\\]/g,'\\$&');
9
11
 
10
12
  test('production README documents one-command stdio configs for major MCP clients',async()=>{
11
13
  const text=await readme();
12
- assert.match(text,/npx -y deadbyte-mcp@0\.15\.5 mcp/);
14
+ assert.match(text,new RegExp(`npx -y deadbyte-mcp@${versionPattern} mcp`));
13
15
  assert.match(text,/CLAUDE DESKTOP/);
14
- assert.match(text,/"mcpServers"[\s\S]*?"command"\s*:\s*"npx"[\s\S]*?"-y"[\s\S]*?"deadbyte-mcp@0\.15\.5"[\s\S]*?"mcp"/);
16
+ assert.match(text,new RegExp(`"mcpServers"[\\s\\S]*?"command"\\s*:\\s*"npx"[\\s\\S]*?"-y"[\\s\\S]*?"deadbyte-mcp@${versionPattern}"[\\s\\S]*?"mcp"`));
15
17
  assert.match(text,/CURSOR/);
16
18
  assert.match(text,/\.cursor\/mcp\.json/);
17
19
  assert.match(text,/VS CODE/);
@@ -20,7 +22,7 @@ test('production README documents one-command stdio configs for major MCP client
20
22
  assert.match(text,/CODEX/);
21
23
  assert.match(text,/\[mcp_servers\.deadbyte\]/);
22
24
  assert.match(text,/command\s*=\s*"npx"/);
23
- assert.match(text,/args\s*=\s*\["-y",\s*"deadbyte-mcp@0\.15\.5",\s*"mcp"\]/);
25
+ assert.match(text,new RegExp(`args\\s*=\\s*\\["-y",\\s*"deadbyte-mcp@${versionPattern}",\\s*"mcp"\\]`));
24
26
  });
25
27
 
26
28
  test('production README records tracer bullet, semantic scope, remote UX, safety and document extension',async()=>{
@@ -3,40 +3,32 @@ import assert from 'node:assert/strict';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { DEADBYTE_VERSION } from '../src/version.mjs';
5
5
 
6
- const root=new URL('../',import.meta.url);
7
- const read=rel=>readFile(new URL(rel,root),'utf8');
6
+ const root = new URL('../', import.meta.url);
7
+ const read = rel => readFile(new URL(rel, root), 'utf8');
8
+ const json = rel => read(rel).then(JSON.parse);
8
9
 
9
- test('R49 0.15.26 successor binds exact published immutable 0.15.25 parent',async()=>{
10
- const [pkg,lock,release,provenance,matrix]=await Promise.all([
11
- read('package.json').then(JSON.parse),
12
- read('package-lock.json').then(JSON.parse),
13
- read('RELEASE.json').then(JSON.parse),
14
- read('PROVENANCE.json').then(JSON.parse),
15
- read('TEST-MATRIX.json').then(JSON.parse)
10
+ test('R48 compatibility release contract remains coherent in the current successor', async () => {
11
+ const [pkg, lock, release, provenance, matrix] = await Promise.all([
12
+ json('package.json'), json('package-lock.json'), json('RELEASE.json'),
13
+ json('PROVENANCE.json'), json('TEST-MATRIX.json')
16
14
  ]);
17
- for(const value of [pkg.version,lock.version,lock.packages[''].version,DEADBYTE_VERSION,release.version,provenance.version,matrix.version])assert.equal(value,'0.15.26');
18
- assert.equal(release.train,'R49');
19
- assert.equal(release.label,'BOUNDED SEMANTIC DESKTOP WAIT + REMOTE CONTROL HARDENING');
20
- assert.equal(release.parent.release_id,'v0.15.25-7ed657b1aa038ee6');
21
- assert.equal(release.parent.manifest_sha256,'7ed657b1aa038ee679ff081f1a83c421a5eeb5fc7ea6b746e0f661079b69b319');
22
- assert.equal(release.parent.generation_manifest_sha256,'c9763738e27ec39b1180473995f2af088d85293a94f5693abd6a843e09cecec9');
23
- assert.equal(release.source_predecessor.version,'0.15.25');
24
- assert.equal(release.source_predecessor.tarball_sha256,'0410b41b3c891210262a4db793ee3b339862472ef069f881c9e092c1083ba6d2');
25
- assert.equal(release.source_predecessor.manifest_file_sha256,'7ed657b1aa038ee679ff081f1a83c421a5eeb5fc7ea6b746e0f661079b69b319');
26
- assert.equal(release.source_predecessor.reference_server_sha256,'dfc303bb7dd2e8d01debac50fc43bb8644d00089bffdf2887e149497cff8b305');
27
- assert.equal(release.source_predecessor.reference_schemas_sha256,'f342345e34e48769dabaefe1b932f09d41e2e207b422f7794a15ee50ffa8f140');
28
- assert.equal(release.capabilities.full_tool_count,117);
29
- assert.equal(release.capabilities.desktop_bounded_semantic_wait,true);
30
- assert.equal(release.capabilities.commander_incremental_pdf_revisions,true);
31
- assert.equal(release.capabilities.commander_docx_header_footer_search,true);
32
- assert.equal(release.capabilities.commander_directory_read_fallback,true);
33
- assert.equal(release.capabilities.commander_binary_detection,true);
34
- assert.equal(release.capabilities.commander_protocol_adversarial,true);
35
- assert.equal(release.capabilities.atomic_mutation_unknown_effect,true);
36
- assert.equal(provenance.parent_release_id,release.parent.release_id);
37
- assert.equal(provenance.parent_manifest_sha256,release.parent.manifest_sha256);
38
- assert.equal(provenance.parent_generation_manifest_sha256,release.parent.generation_manifest_sha256);
39
- assert.equal(provenance.source_predecessor_tarball_sha256,release.source_predecessor.tarball_sha256);
40
- assert.equal(matrix.predecessor_r48_full_regression_partition_proof.files,211);
41
- assert.equal(matrix.predecessor_r48_full_regression_partition_proof.not_valid_as_r49_proof,true);
15
+
16
+ for (const value of [
17
+ pkg.version, lock.version, lock.packages[''].version, DEADBYTE_VERSION,
18
+ release.version, provenance.version, matrix.version
19
+ ]) assert.equal(value, DEADBYTE_VERSION);
20
+
21
+ assert.equal(release.capabilities.full_tool_count, 117);
22
+ assert.equal(release.capabilities.desktop_bounded_semantic_wait, true);
23
+ assert.equal(release.capabilities.commander_incremental_pdf_revisions, true);
24
+ assert.equal(release.capabilities.commander_docx_header_footer_search, true);
25
+ assert.equal(release.capabilities.commander_directory_read_fallback, true);
26
+ assert.equal(release.capabilities.commander_binary_detection, true);
27
+ assert.equal(release.capabilities.commander_protocol_adversarial, true);
28
+ assert.equal(release.capabilities.atomic_mutation_unknown_effect, true);
29
+
30
+ assert.equal(provenance.parent_release_id, release.parent.release_id);
31
+ assert.equal(provenance.parent_manifest_sha256, release.parent.manifest_sha256);
32
+ assert.equal(provenance.parent_generation_manifest_sha256, release.parent.generation_manifest_sha256);
33
+ assert.equal(provenance.source_predecessor_tarball_sha256, release.source_predecessor.tarball_sha256);
42
34
  });
@@ -1,27 +1,31 @@
1
1
  import assert from 'node:assert/strict';
2
- import {readFile} from 'node:fs/promises';
2
+ import { readFile } from 'node:fs/promises';
3
3
  import test from 'node:test';
4
4
 
5
5
  const read = path => readFile(new URL(`../${path}`, import.meta.url), 'utf8');
6
6
 
7
- test('R49 canonical Windows gate is successor-bound and preserves the R48 historical gate', async () => {
8
- const [pkgText, gate, evidence, historical, deferred] = await Promise.all([
7
+ test('R51 canonical Windows gate is successor-bound and preserves R50/R49 historical gates', async () => {
8
+ const [pkgText, gate, evidence, historicalR50, historicalR49, deferred] = await Promise.all([
9
9
  read('package.json'),
10
+ read('scripts/gate-windows-r51.ps1'),
11
+ read('scripts/windows-gate-evidence-r51.mjs'),
12
+ read('scripts/gate-windows-r50.ps1'),
10
13
  read('scripts/gate-windows-r49.ps1'),
11
- read('scripts/windows-gate-evidence-r49.mjs'),
12
- read('scripts/gate-windows-r48.ps1'),
13
14
  read('scripts/deferred-slot-operation-r46.mjs')
14
15
  ]);
15
16
  const pkg = JSON.parse(pkgText);
16
- assert.match(pkg.scripts['gate:windows'], /gate-windows-r49\.ps1$/);
17
- assert.match(gate, /DEADBYTE 0\.15\.26 \/ R49 WINDOWS GATE: PASS/);
17
+ assert.match(pkg.scripts['gate:windows'], /gate-windows-r51\.ps1$/);
18
+ assert.match(gate, /DEADBYTE 0\.15\.28 \/ R51 WINDOWS GATE: PASS/);
19
+ assert.match(gate, /r51-package-boundary/);
20
+ assert.match(gate, /r51-focused-contracts/);
18
21
  assert.match(gate, /r49-remote-control-donors\.test\.mjs/);
19
22
  assert.match(gate, /desktop-runtime-r40\.test\.mjs/);
20
23
  assert.match(gate, /manifest-final-verify/);
21
- assert.match(evidence, /deadbyte\.r49-windows-gate\.v1/);
22
- assert.match(evidence, /pkg\.version==='0\.15\.26'/);
23
- assert.match(evidence, /release\.train==='R49'/);
24
- assert.match(historical, /DEADBYTE 0\.15\.25 \/ R48 WINDOWS GATE: PASS/);
24
+ assert.match(evidence, /deadbyte\.r51-windows-gate\.v1/);
25
+ assert.match(evidence, /pkg\.version === '0\.15\.28'/);
26
+ assert.match(evidence, /release\.train === 'R51'/);
27
+ assert.match(historicalR50, /DEADBYTE 0\.15\.27 \/ R50 WINDOWS GATE: PASS/);
28
+ assert.match(historicalR49, /DEADBYTE 0\.15\.26 \/ R49 WINDOWS GATE: PASS/);
25
29
  assert.match(deferred, /const expectedVersion=packageIdentity\.version/);
26
30
  assert.match(deferred, /'--expected-version',expectedVersion/);
27
31
  assert.match(deferred, /async function awaitHandoffCompletion/);
@@ -0,0 +1,28 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { selectLiveLogNames } from '../src/remote-live-log.mjs';
4
+ import { readFile } from 'node:fs/promises';
5
+
6
+ test('R51 live log discovery tails only current and previous audit segments plus runtime logs',()=>{
7
+ const selected=selectLiveLogNames({
8
+ auditNames:['segment-00000001.jsonl','junk.txt','segment-00000003.jsonl','segment-00000002.jsonl'],
9
+ runtimeNames:['bridge.stdout.log','bridge.stderr.log','note.txt']
10
+ });
11
+ assert.deepEqual(selected.audit,['segment-00000002.jsonl','segment-00000003.jsonl']);
12
+ assert.deepEqual(selected.runtime,['bridge.stderr.log','bridge.stdout.log']);
13
+ });
14
+
15
+ test('R51 live tail caches directory discovery instead of rescanning every 250ms poll',async()=>{
16
+ const cli=await readFile(new URL('../src/deadbyte-cli.mjs',import.meta.url),'utf8');
17
+ assert.match(cli,/LIVE_LOG_DISCOVERY_INTERVAL_MS\s*=\s*1000/);
18
+ assert.match(cli,/nextDiscoveryAt/);
19
+ assert.doesNotMatch(cli,/for\(const file of await listLogFiles\(root\)\)/);
20
+ });
21
+
22
+ test('R51 live tail parses each audit line once and reuses the decoded event',async()=>{
23
+ const cli=await readFile(new URL('../src/deadbyte-cli.mjs',import.meta.url),'utf8');
24
+ assert.match(cli,/parseAuditLogLine/);
25
+ assert.match(cli,/auditEvent/);
26
+ assert.match(cli,/auditTimelineRecord\(file,line,auditEvent\)/);
27
+ assert.match(cli,/formatLogLine\(file,line,\{auditEvent,/);
28
+ });