@yunhozz/arc 0.5.0 → 0.5.1

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 (57) hide show
  1. package/MANIFEST.sha256 +45 -51
  2. package/README.md +99 -33
  3. package/claude/agents/arc-implementer.md +1 -1
  4. package/claude/skill/SKILL.md +1 -1
  5. package/claude/skill/models.toml +6 -6
  6. package/claude/skill/references/coordination.md +0 -4
  7. package/claude/skill/references/handoff-prep.md +1 -1
  8. package/claude/skill/references/verification.md +4 -9
  9. package/codex/skill/SKILL.md +1 -1
  10. package/codex/skill/models.toml +6 -6
  11. package/codex/skill/references/coordination.md +0 -4
  12. package/codex/skill/references/handoff-prep.md +1 -1
  13. package/codex/skill/references/verification.md +4 -9
  14. package/gemini/agents/arc-implementer.md +2 -2
  15. package/gemini/agents/arc-planner.md +1 -1
  16. package/gemini/agents/arc-qa.md +1 -1
  17. package/gemini/agents/arc-scouter.md +1 -1
  18. package/gemini/skill/SKILL.md +1 -1
  19. package/gemini/skill/models.toml +5 -5
  20. package/gemini/skill/references/coordination.md +0 -4
  21. package/gemini/skill/references/handoff-prep.md +1 -1
  22. package/gemini/skill/references/verification.md +4 -9
  23. package/grok/agents/arc-implementer.md +1 -1
  24. package/grok/skill/SKILL.md +1 -1
  25. package/grok/skill/references/coordination.md +0 -4
  26. package/grok/skill/references/handoff-prep.md +1 -1
  27. package/grok/skill/references/verification.md +4 -9
  28. package/lib/installer/runtime-assets.mjs +1 -5
  29. package/lib/installer/targets.mjs +3 -1
  30. package/lib/management/operations.mjs +4 -4
  31. package/lib/prompts/agent-fragments.json +3 -3
  32. package/lib/runtime/local-cli.mjs +9 -2
  33. package/lib/runtime/role-dispatch-policy.mjs +5 -2
  34. package/lib/tui/app.mjs +36 -11
  35. package/lib/tui/interface.mjs +2 -2
  36. package/lib/tui/render.mjs +4 -2
  37. package/lib/tui/terminal.mjs +5 -3
  38. package/lib/watch/brief.mjs +44 -0
  39. package/lib/watch/dispatch.mjs +44 -6
  40. package/lib/watch/index.mjs +107 -22
  41. package/lib/watch/markdown.mjs +42 -9
  42. package/lib/watch/model.mjs +1 -0
  43. package/lib/watch/render.mjs +3 -2
  44. package/lib/watch/scope.mjs +125 -0
  45. package/lib/watch/watcher.mjs +149 -82
  46. package/lib/watch/worktree-menu.mjs +64 -0
  47. package/package.json +1 -1
  48. package/shared/skill/runtime/local-cli.mjs +9 -2
  49. package/shared/skill/runtime/role-dispatch-policy.mjs +5 -2
  50. package/lib/runtime/final-verify.mjs +0 -2158
  51. package/lib/runtime/node-test-reporter.mjs +0 -81
  52. package/lib/runtime/test-results.mjs +0 -736
  53. package/lib/runtime/verify-cli.mjs +0 -60
  54. package/shared/skill/runtime/final-verify.mjs +0 -2158
  55. package/shared/skill/runtime/node-test-reporter.mjs +0 -81
  56. package/shared/skill/runtime/test-results.mjs +0 -736
  57. package/shared/skill/runtime/verify-cli.mjs +0 -60
@@ -51,7 +51,7 @@
51
51
  },
52
52
  {
53
53
  "id": "planner.task-shape",
54
- "text": "Return one complete plan draft covering all top-level tasks and dependencies; DO NOT split it into a Planner call per implementation task. For each top-level task, include ID/title, implementation goal/scope/files, predecessors/dependencies and criteria. For that task, also include required QA/focused checks/evidence before acceptance and holds. List each task's related tests with reasons. In final verification list the union, all contract tests and check scripts, and a provisional full-regression trigger judgment with reason. Put inseparable changes in one task from the outset. DO NOT merge distinct approved tasks during execution. Substeps/checkboxes track progress, not commit units."
54
+ "text": "Return one complete plan draft covering all top-level tasks and dependencies; DO NOT split it into a Planner call per implementation task. For each top-level task, include ID/title, implementation goal/scope/files, predecessors/dependencies and criteria. For that task, also include required QA/focused checks/evidence before acceptance and holds. List each task's related tests with reasons. In final verification list all contract tests and check scripts, expected cross-task file overlap that may need recheck, and a provisional full-regression trigger judgment with reason. Put inseparable changes in one task from the outset. DO NOT merge distinct approved tasks during execution. Substeps/checkboxes track progress, not commit units."
55
55
  },
56
56
  {
57
57
  "id": "planner.commit-boundary",
@@ -79,7 +79,7 @@
79
79
  },
80
80
  {
81
81
  "id": "qa.verification-steps",
82
- "text": "1. Use the shared brief, criteria, Implementer summary and relevant prior findings. Independently verify assigned behavior with related tests only: test files directly exercising changed modules, contract tests the change requires updating and matching check scripts; additions within these categories with reasons are authorized; report each selection and reason. Final verification is run by Orchestrator, not QA. Use approved structural/consistency checks for policy/configuration.\n2. Run authorized tests and inspect output, but DO NOT edit source, documents, tests or configuration. DO NOT repair failures or broaden verification without authorization.\n3. Report every brief criterion by ID or original wording. Record method/scope, run status, accessible evidence, criterion verdict, unverified reason and remaining scope.\n4. Run status is passed, failed, not run or environment blocked. Verdict is proven, unmet or unverified. Passing alone proves no criterion; connect conditions/expected results to observations. Keep partial checks, out-of-scope criteria, missing checks and environment blocks unverified. Omit no criterion. PASS means run status only.\n5. Structural checks prove structural criteria only, not behavior, installation or live agent compliance. After a fix, rerun reproduction and invalidated checks; report the prior finding resolved, unresolved or unverified with evidence. Compare failures with the brief's baseline by test name; only new failures are findings. Rerun a suspected intermittent test alone, up to the brief's limit (default three), as diagnosis rather than retry; report passes-in-isolation and rerun count.\n6. Only with assigned UI criteria and a brief citation to installed ARC `references/verification.md`'s `UI browser acceptance checks`, read/follow that section before launching apps or using browser tools. Otherwise DO NOT launch apps/browsers for UI acceptance. Report missing citations/prerequisites and leave criteria unverified.\n7. Report exact commands, results, evidence, unresolved issues and limits. Separate failures from environment problems. Run approved checks and report only; DO NOT edit, repair, plan or decide acceptance."
82
+ "text": "1. Use the shared brief, criteria, Implementer summary and relevant prior findings. Independently verify assigned behavior with related tests only: test files directly exercising changed modules, contract tests the change requires updating and matching check scripts; additions within these categories with reasons are authorized; report each selection and reason. When assigned final verification, run all contract tests, all check scripts and the brief's re-changed-file tests at the verified HEAD, plus full regression once when the brief's provisional judgment or your own check of triggers (1), (3) and (4) finds one applies or cannot decide. Use approved structural/consistency checks for policy/configuration.\n2. Run authorized tests and inspect output, but DO NOT edit source, documents, tests or configuration. DO NOT repair failures or broaden verification without authorization.\n3. Report every brief criterion by ID or original wording. Record method/scope, run status, accessible evidence, criterion verdict, unverified reason and remaining scope.\n4. Run status is passed, failed, not run or environment blocked. Verdict is proven, unmet or unverified. Passing alone proves no criterion; connect conditions/expected results to observations. Keep partial checks, out-of-scope criteria, missing checks and environment blocks unverified. Omit no criterion. PASS means run status only.\n5. Structural checks prove structural criteria only, not behavior, installation or live agent compliance. After a fix, rerun reproduction and invalidated checks; report the prior finding resolved, unresolved or unverified with evidence. Classify each HEAD failure first by read-only diff against the approved base (unrelated when its test, direct imports, fixtures and test configuration are unchanged), and report the rest as needing a base run; when Orchestrator supplies a base worktree, rerun only those by test name and classify them as baseline, new or new-failure candidate. Only new failures are findings; unrelated failures and candidates need Orchestrator disposition. Rerun a suspected intermittent test alone, up to the brief's limit (default three), as diagnosis rather than retry; report passes-in-isolation and rerun count.\n6. Only with assigned UI criteria and a brief citation to installed ARC `references/verification.md`'s `UI browser acceptance checks`, read/follow that section before launching apps or using browser tools. Otherwise DO NOT launch apps/browsers for UI acceptance. Report missing citations/prerequisites and leave criteria unverified.\n7. Report exact commands, results, evidence, unresolved issues and limits. Separate failures from environment problems. Run approved checks and report only; DO NOT edit, repair, plan or decide acceptance."
83
83
  },
84
84
  {
85
85
  "id": "reviewer.contract-intro",
@@ -87,7 +87,7 @@
87
87
  },
88
88
  {
89
89
  "id": "reviewer.review-steps",
90
- "text": "- Use goal, criteria, assigned diff/source scope and relevant QA evidence. Independently review only that scope for substantive correctness, factual accuracy and security.\n- Return actionable findings, relevant questions, next actions and workspace/path issues with file/page/source references. State when no substantive findings exist.\n- For acceptance-linked behavior findings, report criterion, expected behavior, observed problem, source, reproduction conditions/steps and evidence. Separate source inference from execution observation. DO NOT run QA tests to obtain observations.\n- Outside the final plan Reviewer exception, Orchestrator routes corrections to Implementer and post-fix QA. Continue reviewing structure/design/factual/security issues execution cannot settle.\n- For significant/high-risk work, review the final full change after required QA/focused checks and QA rechecks. QA owns task functional/test verification; Orchestrator runs final verification and owns overall completion and acceptance.\n- DO NOT run QA, plan or decide acceptance. "
90
+ "text": "- Use goal, criteria, assigned diff/source scope and relevant QA evidence. Independently review only that scope for substantive correctness, factual accuracy and security.\n- Return actionable findings, relevant questions, next actions and workspace/path issues with file/page/source references. State when no substantive findings exist.\n- For acceptance-linked behavior findings, report criterion, expected behavior, observed problem, source, reproduction conditions/steps and evidence. Separate source inference from execution observation. DO NOT run QA tests to obtain observations.\n- Outside the final plan Reviewer exception, Orchestrator routes corrections to Implementer and post-fix QA. Continue reviewing structure/design/factual/security issues execution cannot settle.\n- For significant/high-risk work, review the final full change after required QA/focused checks and QA rechecks. QA owns task and final functional/test verification; Orchestrator owns overall completion and acceptance.\n- DO NOT run QA, plan or decide acceptance. "
91
91
  },
92
92
  {
93
93
  "id": "reviewer.final-plan-findings",
@@ -6,9 +6,16 @@ import {runtimeRegistryOf} from './platform-registry.mjs';
6
6
 
7
7
  const environments = new WeakMap();
8
8
  const authKinds = new WeakMap();
9
+ export function unknownPlatformMessage(platform, knownIds) {
10
+ const id = typeof platform === 'string'
11
+ ? [...platform.replace(/[\p{Cc}\u2028\u2029]/gu, '')].slice(0, 256).join('')
12
+ : '(invalid)';
13
+ return `Unknown platform: ${id}. Known platforms: ${knownIds.join(', ')}`;
14
+ }
9
15
  export function resolveConfigHome(platform, context = {}) {
10
- const descriptor = runtimeRegistryOf(context).getPlatform(platform);
11
- if (!descriptor) throw Error('Target must be codex or claude');
16
+ const registry = runtimeRegistryOf(context);
17
+ const descriptor = registry.getPlatform(platform);
18
+ if (!descriptor) throw Error(unknownPlatformMessage(platform, registry.byDisplayOrder().map(({id}) => id)));
12
19
  return descriptor.home.resolve(context);
13
20
  }
14
21
  export function resolveLocalCli(platform, { cwd, userHome, env = process.env, runtimePlatforms } = {}) {
@@ -1,4 +1,4 @@
1
- import {runtimeRegistryOf} from './platform-registry.mjs';
1
+ import {byDisplayOrder, runtimeRegistryOf} from './platform-registry.mjs';
2
2
  // Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
3
3
  // GK2/GG2 'approval' means a Grok/Gemini host keeps its platform-default sandbox (off), runs in ask mode, and obtains user approval for each runtime command; it is not a verified pass.
4
4
  // GK2 evidence: Grok 1.0.89, 2026-11-19, ask mode with the sandbox off.
@@ -65,6 +65,9 @@ export const DEFAULT_POLICY = Object.freeze({
65
65
  probeTimeoutMs: PROBE_TIMEOUT_MS
66
66
  });
67
67
 
68
+ const cliEnvironments = byDisplayOrder().flatMap(({executionEnvironments}) => executionEnvironments)
69
+ .filter(environment => environment.endsWith('-cli')).join(' or ');
70
+
68
71
  export const RELEASE_CONDITIONS = Object.freeze({
69
72
  activation_unverified: 'Verify the active configuration, all prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <anchor home>/arc-role-dispatch for unreadable or corrupted files.',
70
73
  resume_unverified: 'Update ARC after verifying platform session resume against the recorded session UUID.',
@@ -72,7 +75,7 @@ export const RELEASE_CONDITIONS = Object.freeze({
72
75
  'Not Available': 'Install the target platform CLI so that it is found on PATH.',
73
76
  Unauthorized: 'Authenticate the target platform CLI.',
74
77
  Incomplete: 'Make the target platform CLI authentication status check complete successfully.',
75
- environment_unverified: 'Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare codex-cli or claude-cli instead; otherwise use a CLI host or a later ARC update that changes the support status.',
78
+ environment_unverified: `Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare a CLI environment (${cliEnvironments}) instead; otherwise use a CLI host or a later ARC update that changes the support status.`,
76
79
  host_sandbox_blocked: 'Allow the host to write the anchor home and keep a detached supervisor alive, with explicit user approval.',
77
80
  capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
78
81
  permission_scope_unverified: 'Update ARC and verify enforcement of the role permissions and approved scope before starting.',
package/lib/tui/app.mjs CHANGED
@@ -8,17 +8,41 @@ import {collectStatus} from '../management/status.mjs';
8
8
  import {runInstallFlow,loadRoleDefaults,roleDisplayName} from './setup.mjs';
9
9
  import {loadStaticModelCatalog} from '../models/static-catalog.mjs';
10
10
  import {statusInfo,statusVersion} from './mode.mjs';
11
- import {installerRegistryOf,platformLabel} from '../platforms/index.mjs';
11
+ import {installerRegistryOf,platformLabel,sortByDisplay} from '../platforms/index.mjs';
12
12
  const packageVersion=JSON.parse(readFileSync(new URL('../../package.json',import.meta.url),'utf8')).version;
13
13
  const home=[{id:'install',label:'Configure'},{id:'status',label:'Status'},{id:'uninstall',label:'Uninstall'},{id:'exit',label:'Exit'}];
14
- export function resultRows(result,registry=installerRegistryOf(),{version}={}){
14
+ export function resultRows(result,registry=installerRegistryOf(),{version,kind,latestVersion,previousStates}={}){
15
15
  version=result.version??version;
16
16
  const clean=text=>text.replace(/; rollback: [^\r\n]*/g,''),label=platform=>platformLabel(platform,registry),errorLine=error=>clean(error.message.split(/[\r\n]/)[0]);
17
- const residualRows=new Set();
18
- const removed=result.code===0&&['removed','absent'].includes(result.cli?.status);
19
- const platformOf=item=>item.platform??item.target?.platform??'Target',installed=result.code===0?(result.results??[]).filter(item=>item.status==='installed'&&!item.error):[];
20
- const applied=installed.length?['🎉 Setup ran successfully! Please restart ARC to check.','Apply to: '+installed.map(item=>label(platformOf(item))).join(', ')]:[];
21
- return[...(result.messages??[]).map(s=>clean(s.trim())),...[result.stdout,result.stderr].flatMap(text=>text?text.trimEnd().split(/\r?\n/).map(clean):[]),...(result.results??[]).flatMap(item=>{const platform=platformOf(item);return[...(removed&&item.status==='uninstalled'?[]:installed.includes(item)?(item===installed[0]?applied:[]):[item.status==='installed'?`ARC${version==null?'':' '+version} installed for ${label(platform)}.`:item.status==='uninstalled'?`Removed from ${label(platform)}.`:`${platform}: ${item.status}`]),...(item.residualPaths??[]).map(p=>'Residual path: '+p),...(item.error?['Error: '+errorLine(item.error)]:[])];}),...(removed?[result.cli.status==='removed'?'Removed ARC and CLI.':'Removed ARC.']:result.cli?['CLI: '+result.cli.status,...(result.cli.error?['CLI error: '+errorLine(result.cli.error)]:[])]:[]),...(result.error?['Error: '+errorLine(result.error)]:[]),...(result.code!==0?['Exit code: '+result.code]:[]),...(result.exitSession?[result.cli?'CLI removal ended this session.':'CLI replacement ended this session.']:[])].filter(row=>{if(!row.startsWith('Residual path: '))return true;if(residualRows.has(row))return false;residualRows.add(row);return true;});
17
+ const items=result.results??[],platformOf=item=>item.platform??item.target?.platform??'Target';
18
+ const messages=(result.messages??[]).map(s=>clean(s.trim())),residualPaths=item=>(item.residualPaths??[]).map(p=>'Residual path: '+p);
19
+ const isResidual=row=>row.startsWith('Residual path: '),residualRows=new Set();
20
+ const uniqueResiduals=rows=>rows.filter(row=>{if(!isResidual(row))return true;if(residualRows.has(row))return false;residualRows.add(row);return true;});
21
+ const cliRemoved=result.cli?.status==='removed',cliAbsent=result.cli?.status==='absent';
22
+ if(result.code===0&&kind==='update'){
23
+ const residuals=(result.stdout??'').split(/\r?\n/).filter(isResidual);
24
+ return uniqueResiduals([`🚀 Upgraded to ARC ${latestVersion}.`,'Restart ARC to check.',...residuals]);
25
+ }
26
+ if(result.code===0&&!result.error&&!result.cli?.error&&(!result.cli||cliRemoved||cliAbsent)&&items.every(item=>['installed','uninstalled'].includes(item.status)&&!item.error)){
27
+ const rows=[];
28
+ if(cliRemoved){
29
+ rows.push('👋 ARC and the arc CLI removed.');
30
+ if(result.exitSession)rows.push('CLI removal ended this session.');
31
+ }else if(cliAbsent){
32
+ rows.push('👋 ARC removed.');
33
+ }else{
34
+ const displayOrder=ids=>[...sortByDisplay(ids.filter(id=>registry.getPlatform(id)),registry),...ids.filter(id=>!registry.getPlatform(id))];
35
+ const installed=displayOrder(items.filter(item=>item.status==='installed').map(platformOf));
36
+ const existing=platform=>['installed','incomplete'].includes(previousStates?.[platform]);
37
+ const newPlatforms=installed.filter(platform=>!existing(platform)),existingPlatforms=installed.filter(existing);
38
+ if(newPlatforms.length)rows.push(`✨ ARC installed for ${newPlatforms.map(label).join(', ')}.`);
39
+ if(existingPlatforms.length)rows.push(`🔧 Settings applied to ${existingPlatforms.map(label).join(', ')}.`);
40
+ if(installed.length)rows.push('Restart ARC to check.');
41
+ for(const platform of displayOrder(items.filter(item=>item.status==='uninstalled').map(platformOf)))rows.push(`🧹 Removed ARC from ${label(platform)}.`);
42
+ }
43
+ return uniqueResiduals([...rows,...messages,...items.flatMap(residualPaths)]);
44
+ }
45
+ return uniqueResiduals([...messages,...[result.stdout,result.stderr].flatMap(text=>text?text.trimEnd().split(/\r?\n/).map(clean):[]),...items.flatMap(item=>{const platform=platformOf(item);return[item.status==='installed'?`ARC${version==null?'':' '+version} installed for ${label(platform)}.`:item.status==='uninstalled'?`Removed from ${label(platform)}.`:`${platform}: ${item.status}`,...residualPaths(item),...(item.error?['Error: '+errorLine(item.error)]:[])];}),...(result.cli?['CLI: '+result.cli.status,...(result.cli.error?['CLI error: '+errorLine(result.cli.error)]:[])]:[]),...(result.error?['Error: '+errorLine(result.error)]:[]),...(result.code!==0?['Exit code: '+result.code]:[]),...(result.exitSession?[result.cli?'CLI removal ended this session.':'CLI replacement ended this session.']:[])]);
22
46
  }
23
47
  function formatElapsed(ms){
24
48
  const minutes=Math.floor(ms/60000),hours=Math.floor(minutes/60),days=Math.floor(hours/24);
@@ -58,7 +82,7 @@ export async function runTui(options={}){
58
82
  try{return typeof api.currentInstallState==='function'?await api.currentInstallState(context):{mode:'unverified',platforms:[]};}
59
83
  catch{return {mode:'unverified',platforms:[]};}
60
84
  }
61
- async function execute(prepared,{retried=false,request}={}){
85
+ async function execute(prepared,{retried=false,request,statuses=[]}={}){
62
86
  if(!prepared)return;const result=await ui.busy(()=>api.executeOperation(context,prepared));code=result.code;
63
87
  if(code!==130&&!result.exitSession&&!retried&&['composite','switch'].includes(prepared.kind)&&result.error?.blockingDispatches?.length){
64
88
  const entries=result.error.blockingDispatches,eligible=entries.some(entry=>entry.forceFinishable);
@@ -71,11 +95,12 @@ export async function runTui(options={}){
71
95
  let next;
72
96
  try{next=await ui.busy(()=>api.prepareOperation(context,request));}
73
97
  catch(error){if(['ARC_CANCELLED','ARC_TUI_EOF','ARC_TUI_HOME'].includes(error.code))throw error;await ui.page('Force finish',[error.message,notRetried]);return false;}
74
- return execute(next,{retried:true,request});
98
+ return execute(next,{retried:true,request,statuses});
75
99
  }
76
100
  }
77
101
  if(code===0&&['install','preset','switch','composite'].includes(prepared.kind))for(const key of Object.keys(draft))delete draft[key];
78
- const rows=prepared.kind==='update'&&code===0?['🎉 Update ran successfully! Please restart ARC to check.']:resultRows(result,registry,{version:packageVersion});
102
+ const previousStates=Object.fromEntries(statuses.map(status=>[status.platform,status.state]));
103
+ const rows=resultRows(result,registry,{version:packageVersion,kind:prepared.kind,latestVersion:prepared.latestVersion,previousStates});
79
104
  if(code===130||result.exitSession){finalReport=rows;if(result.exitSession)session.render({title:'Result',rows:finalReport,hint:'Session ended'});return true;}
80
105
  await ui.page('Result',rows);return false;
81
106
  }
@@ -103,7 +128,7 @@ export async function runTui(options={}){
103
128
  if(choice!==0||!showUpgrade)prepared=null;
104
129
  }
105
130
  else if(action==='uninstall')prepared=await uninstall(statuses);
106
- if(await execute(prepared,{request:lastRequest}))return code;
131
+ if(await execute(prepared,{request:lastRequest,statuses}))return code;
107
132
  }catch(error){if(error.code==='ARC_TUI_HOME')continue;if(['ARC_CANCELLED','ARC_TUI_EOF'].includes(error.code))throw error;code=error.code==='ARC_CLI_INPUT'?2:1;try{await ui.page('Operation unavailable',[error.message,...(error.residualPaths??[]).map(p=>'Residual path: '+p),'No changes were applied.']);}catch(navigation){if(navigation.code!=='ARC_TUI_HOME')throw navigation;}}
108
133
  }
109
134
 
@@ -4,7 +4,7 @@ function goHome(){throw Object.assign(Error('Return home'),{code:'ARC_TUI_HOME'}
4
4
  function interrupted(){return Object.assign(Error('Session interrupted'),{code:'ARC_CANCELLED'});}
5
5
  export function createTuiInterface(session,{input,controller}={}){
6
6
  async function event(){const e=await session.nextEvent();if(e.name==='interrupt')throw interrupted();if(e.name==='eof')throw Object.assign(Error('Session closed'),{code:'ARC_TUI_EOF'});if(e.name==='error')throw e.error;return e;}
7
- async function menu(title,rows,{selected=0,info=[],infoTones,notice=[],fitRows=false,backRow=false,actionKinds,backLabel='back',wordmark=false,version,renderBody,onHorizontal,refreshMs,hint='menu'}={}){
7
+ async function menu(title,rows,{selected=0,info=[],infoTones,rowTones,notice=[],fitRows=false,backRow=false,actionKinds,backLabel='back',wordmark=false,version,renderBody,onHorizontal,refreshMs,hint='menu'}={}){
8
8
  const actions=backRow?[...rows,'Back']:rows,kinds=rows.map((_,index)=>actionKinds?.[index]);if(backRow)kinds.push('cancel');
9
9
  selected=actions.length?Math.max(0,Math.min(selected,actions.length-1)):0;
10
10
  const animate=wordmark&&session.frameMs>0,pulse=typeof onHorizontal==='function'&&session.motion===true,tickMs=animate||pulse?session.frameMs:refreshMs;
@@ -17,7 +17,7 @@ export function createTuiInterface(session,{input,controller}={}){
17
17
  const notices=typeof notice==='function'?notice({selected,...viewport}):notice,noticeRows=wrapDetailRows(notices,viewport.columns);while(noticeRows.at(-1)==='')noticeRows.pop();
18
18
  const capacity=Math.max(1,viewport.rows-(wordmark?wordmarkRows(viewport):1)-information.length-noticeRows.length-4),offset=Math.max(0,Math.min(displayIndex-capacity+1,display.length-capacity)),visible=display.slice(offset,offset+capacity).map(row=>fitRows?fitChoiceRow(row,viewport.columns):row);
19
19
  const screen={title,wordmark,version,frame,notices,rows:[...information,...visible],selected:actions.length?information.length+displayIndex-offset:undefined,hint:navigationHint(hint,{backLabel,horizontal:typeof onHorizontal==='function'}),...(display.length>capacity?{position:(offset+1)+'-'+Math.min(offset+capacity,display.length)+'/'+display.length}:{})};
20
- if(infoTones){screen.rowTones=[...tones,...visible.map(()=>undefined)];screen.rowStatusSpans=spans;}
20
+ if(infoTones||rowTones){screen.rowTones=[...tones,...visible.map((_,index)=>rowTones?.[offset+index])];screen.rowStatusSpans=spans;}
21
21
  if(backRow||actionKinds)screen.rowKinds=[...information.map(()=>undefined),...kinds.slice(offset,offset+capacity)];
22
22
  const body=renderBody?.({selected,blink,frame,...viewport});if(body){delete screen.rowTones;delete screen.rowStatusSpans;delete screen.rowKinds;if(body.rowKinds)screen.rowKinds=body.rowKinds;screen.rows=body.rows;screen.selected=body.selected;screen.showSelection=body.showSelection;screen.compactFooter=body.compactFooter;if(Object.hasOwn(body,'notices'))screen.notices=body.notices;if(Object.hasOwn(body,'position'))screen.position=body.position;}
23
23
  const rendered=(repainting?(session.repaint??session.render):session.render).call(session,screen);pending??=event().then(e=>{settled={e};wake?.();},error=>{settled={error};wake?.();});
@@ -81,9 +81,10 @@ export function renderScreen(screen={}, {columns=80,rows=24}={}){
81
81
  const selectedLine=heading.length+selected;
82
82
  for(let line=0;line<visible.length;line++){
83
83
  const source=indices[line],runs=[];
84
+ const dim=source>=heading.length&&source<heading.length+entries.length&&rowTones[source-heading.length]==='dim';
84
85
  function add(from,to,role,fg,bg,bold){
85
86
  to=Math.min(to,[...visible[line]].length);if(from>=to)return;
86
- const run={from,to,role,...(fg?{fg}:{}),...(bg?{bg}:{}),...(bold?{bold}: {})},last=runs.at(-1);
87
+ const run={from,to,role,...(fg?{fg}:{}),...(bg?{bg}:{}),...(bold?{bold}: {}),...(dim?{dim:true}:{})},last=runs.at(-1);
87
88
  if(last&&last.to===from&&last.role===role&&JSON.stringify(last.fg)===JSON.stringify(fg)&&JSON.stringify(last.bg)===JSON.stringify(bg)&&last.bold===run.bold)last.to=to;else runs.push(run);
88
89
  }
89
90
  const length=[...visible[line]].length;
@@ -107,7 +108,8 @@ export function renderScreen(screen={}, {columns=80,rows=24}={}){
107
108
  }
108
109
  else if(source>=heading.length&&source<heading.length+entries.length&&rowTones[source-heading.length]){
109
110
  const tone=rowTones[source-heading.length],text=visible[line].slice(2);
110
- if(tone==='status'||tone==='platform-status')for(const {from,to,role} of rowStatusSpans[source-heading.length]??(tone==='status'?statusSpans:platformStatusSpans)(entries[source-heading.length]))add(from+2,to+2,role,TONE_FG[role]);
111
+ if(tone==='dim')add(0,length,'dim');
112
+ else if(tone==='status'||tone==='platform-status')for(const {from,to,role} of rowStatusSpans[source-heading.length]??(tone==='status'?statusSpans:platformStatusSpans)(entries[source-heading.length]))add(from+2,to+2,role,TONE_FG[role]);
111
113
  else if(tone==='diagnostic'){const separator=text.indexOf(': ');if(separator>=0)add(2+[...text.slice(0,separator+2)].length,length,'warn',TONE_FG.warn);}
112
114
  else if(tone==='diagnostic-cont'||tone==='note')add(2,length,'warn',TONE_FG.warn);
113
115
  }
@@ -9,11 +9,13 @@ export function formatLine(line,style,depth){
9
9
  if(depth==='none'||!style?.runs?.length)return line;
10
10
  const characters=[...line];let result='',end=0,painted=false;
11
11
  for(const run of style.runs){
12
- if(!Object.hasOwn(BASIC,run.role))continue;
12
+ if(run.role!=='dim'&&!Object.hasOwn(BASIC,run.role))continue;
13
13
  const from=Math.max(end,Math.min(characters.length,run.from)),to=Math.min(characters.length,run.to);if(from>=to)continue;
14
14
  if(from>end){if(painted){result+='\x1b[0m';painted=false;}result+=characters.slice(end,from).join('');}
15
- let params=BASIC[run.role];if(depth!=='16'){const values=run.bold?['1']:[];for(const [key,code] of [['fg',38],['bg',48]])if(run[key])values.push(depth==='truecolor'?code+';2;'+rgb(run[key]).join(';'):code+';5;'+toAnsi256(run[key]));params=values.join(';');}
16
- if(params){if(painted!==params)result+='\x1b[0;'+params+'m';painted=params;}else if(painted){result+='\x1b[0m';painted=false;}
15
+ let params=BASIC[run.role]??'';if(depth!=='16'){const values=run.bold?['1']:[];for(const [key,code] of [['fg',38],['bg',48]])if(run[key])values.push(depth==='truecolor'?code+';2;'+rgb(run[key]).join(';'):code+';5;'+toAnsi256(run[key]));params=values.join(';');}
16
+ const dim=run.dim||run.role==='dim';
17
+ const escape=(params?'\x1b[0;'+params+'m':'')+(dim?'\x1b[2m':'');
18
+ if(escape){if(painted!==escape)result+=(!params&&painted?'\x1b[0m':'')+escape;painted=escape;}else if(painted){result+='\x1b[0m';painted=false;}
17
19
  result+=characters.slice(from,to).join('');end=to;
18
20
  }
19
21
  if(painted)result+='\x1b[0m';return result+characters.slice(end).join('');
@@ -0,0 +1,44 @@
1
+ import {renderBox} from './markdown.mjs';
2
+ import {sanitizeText} from './policy.mjs';
3
+ import {displayWidth, wrapLineRanges} from './text-width.mjs';
4
+
5
+ function wrapPlain(text, width) {
6
+ return wrapLineRanges(text, width).map(({from,to,overflows}) => overflows ? '�' : text.slice(from,to));
7
+ }
8
+
9
+ export function briefLines(brief, {version, keys}) {
10
+ const scope = sanitizeText(brief.scope + (brief.branch ? ` (${brief.branch})` : ''));
11
+ return [
12
+ `arc watch ${version}`,
13
+ `**Scope** ${scope.replace(/[\\*`\[]/g, '\\$&')}`,
14
+ `**Platforms** ${brief.platforms.map(platform => platform.toUpperCase()).join(' · ')}`,
15
+ `**Keys** ${keys.join(' · ')}`,
16
+ ];
17
+ }
18
+
19
+ export function earlierPageLines({shown, remaining}) {
20
+ if (!shown) return {start:'── no earlier events in loaded history ──'};
21
+ const position = remaining ? `${remaining} more` : 'start of loaded history';
22
+ return {start:`── earlier ${shown} events · ${position} ──`,end:'── back to live ──'};
23
+ }
24
+
25
+ export function renderBrief(brief, {version, keys, width, color}) {
26
+ const columns = width - 1;
27
+ if (columns < 1) return [];
28
+ const lines = briefLines(brief, {version, keys});
29
+ if (width >= 24) return renderBox(lines, {width:columns, baseCode:color ? '2' : undefined});
30
+ return lines.flatMap(markdown => {
31
+ const label = /^\*\*([^*]+)\*\* /.exec(markdown);
32
+ const value = markdown.slice(label?.[0].length ?? 0).replace(/\\([\\*`\[])/g, '$1');
33
+ if (!label) return wrapPlain(value, columns);
34
+
35
+ const prefix = `${label[1]} `;
36
+ const available = columns - displayWidth(prefix);
37
+ if (available < 1 || !value) return wrapPlain(prefix + value, columns);
38
+ const [first] = wrapLineRanges(value, available);
39
+ if (first.overflows) return wrapPlain(prefix + value, columns);
40
+
41
+ const rest = value.slice(first.to).trimStart();
42
+ return [prefix + value.slice(first.from, first.to), ...(rest ? wrapPlain(rest, columns) : [])];
43
+ });
44
+ }
@@ -3,6 +3,17 @@ import path from 'node:path';
3
3
  import {createTail} from './tail.mjs';
4
4
  import {roleFromName} from './labels.mjs';
5
5
 
6
+ const HEARTBEAT_SUFFIX = '.heartbeat.json';
7
+
8
+ function parseHeartbeat(text) {
9
+ try {
10
+ const {at} = JSON.parse(text) ?? {};
11
+ return Number.isFinite(at) ? at : null;
12
+ } catch {
13
+ return null;
14
+ }
15
+ }
16
+
6
17
  export function parseLeaseLenient(text) {
7
18
  let value;
8
19
  try { value = JSON.parse(text); } catch { return null; }
@@ -11,6 +22,8 @@ export function parseLeaseLenient(text) {
11
22
  for (const key of ['dispatchId', 'workflowId', 'role', 'route', 'hostPlatform', 'state', 'sessionId', 'nativeAgentId', 'createdAt', 'updatedAt']) {
12
23
  if (typeof value[key] === 'string') lease[key] = value[key];
13
24
  }
25
+ if (typeof value.version === 'number') lease.version = value.version;
26
+ if (value.version === 2 && typeof value.targetPlatform === 'string') lease.targetPlatform = value.targetPlatform;
14
27
  lease.reasons = Array.isArray(value.reasons) ? value.reasons.filter(reason => typeof reason === 'string') : [];
15
28
  return lease;
16
29
  }
@@ -25,13 +38,27 @@ async function entries(dir) {
25
38
 
26
39
  export function createDispatchIndex({storeDir} = {}) {
27
40
  const refs = new Map(), leases = new Map(), tails = new Map(), records = new Map(), signatures = new Map();
41
+ const sessionEventKinds = new Map();
42
+ const heartbeats = new Map();
28
43
 
29
- async function readLeases() {
44
+ async function readStore() {
30
45
  const dir = storeDir, seen = new Set();
31
- for (const entry of await entries(dir)) {
32
- if (!entry.isFile() || entry.name.startsWith('.') || !entry.name.endsWith('.json') || entry.name.endsWith('.heartbeat.json')) continue;
46
+ for (const entry of dir ? await entries(dir) : []) {
47
+ if (!entry.isFile() || entry.name.startsWith('.') || !entry.name.endsWith('.json')) continue;
33
48
  const file = path.join(dir, entry.name);
34
49
  seen.add(file);
50
+ if (entry.name.endsWith(HEARTBEAT_SUFFIX)) {
51
+ try {
52
+ const {mtimeMs} = await fsp.stat(file);
53
+ if (heartbeats.get(file)?.mtimeMs === mtimeMs) continue;
54
+ const at = parseHeartbeat(await fsp.readFile(file, 'utf8'));
55
+ heartbeats.set(file, {mtimeMs, at});
56
+ } catch (error) {
57
+ if (error.code === 'ENOENT') heartbeats.delete(file);
58
+ else heartbeats.set(file, {at:null});
59
+ }
60
+ continue;
61
+ }
35
62
  try {
36
63
  const {mtimeMs} = await fsp.stat(file);
37
64
  if (leases.get(file)?.mtimeMs === mtimeMs) continue;
@@ -42,7 +69,11 @@ export function createDispatchIndex({storeDir} = {}) {
42
69
  }
43
70
  }
44
71
  for (const file of leases.keys()) if (!seen.has(file)) leases.delete(file);
45
- return new Map([...leases.values()].map(({value}) => [value.dispatchId, value]));
72
+ for (const file of heartbeats.keys()) if (!seen.has(file)) heartbeats.delete(file);
73
+ return {
74
+ currentLeases: new Map([...leases.values()].map(({value}) => [value.dispatchId, value])),
75
+ heartbeatTimes: new Map([...heartbeats].map(([file,{at}]) => [path.basename(file,HEARTBEAT_SUFFIX), at])),
76
+ };
46
77
  }
47
78
 
48
79
  async function readRecord(dir) {
@@ -69,7 +100,7 @@ export function createDispatchIndex({storeDir} = {}) {
69
100
  const sessionId = event?.kind === 'thread' ? event.threadId : event?.kind === 'init' ? event.sessionId : null;
70
101
  if (typeof sessionId !== 'string') continue;
71
102
  if (!ref.sessionIds.includes(sessionId)) ref.sessionIds.push(sessionId);
72
- ref.childPlatform = event.kind === 'thread' ? 'codex' : 'claude';
103
+ sessionEventKinds.set(ref.dispatchId, event.kind);
73
104
  }
74
105
  }
75
106
 
@@ -80,7 +111,8 @@ export function createDispatchIndex({storeDir} = {}) {
80
111
 
81
112
  return {
82
113
  async scan({gitCommonDirs}) {
83
- const currentLeases = storeDir ? await readLeases() : new Map(), artifacts = new Map();
114
+ const {currentLeases,heartbeatTimes} = await readStore();
115
+ const artifacts = new Map();
84
116
  for (const gcd of gitCommonDirs) {
85
117
  const workflows = path.join(gcd, 'arc', 'workflows');
86
118
  for (const workflow of await entries(workflows)) {
@@ -116,6 +148,12 @@ export function createDispatchIndex({storeDir} = {}) {
116
148
  ref.inScope = Boolean(artifact);
117
149
  ref.artifactDir = artifact?.dir ?? null;
118
150
  ref.cwd = artifact?.cwd ?? null;
151
+ ref.heartbeatAt = lease ? heartbeatTimes.get(id) : undefined;
152
+ const sessionEvent = sessionEventKinds.get(id);
153
+ ref.childPlatform = (lease?.version ?? 1) === 1 && sessionEvent
154
+ ? (sessionEvent === 'thread' ? 'codex' : 'claude') : null;
155
+ if (lease?.targetPlatform !== undefined) ref.targetPlatform = lease.targetPlatform;
156
+ else delete ref.targetPlatform;
119
157
  if (!lease && !artifact) continue;
120
158
  for (const key of ['workflowId', 'rawRole', 'route', 'hostPlatform', 'state', 'updatedAt']) delete ref[key];
121
159
  if (artifact) ref.workflowId = artifact.workflowId;
@@ -1,13 +1,17 @@
1
1
  import os from 'node:os';
2
+ import {readFileSync} from 'node:fs';
2
3
  import {parseWatchArgs} from './args.mjs';
3
4
  import {resolveConfigHome} from '../runtime/local-cli.mjs';
4
5
  import {DEFAULT_PLATFORM_REGISTRY} from '../runtime/platform-registry.mjs';
5
6
  import {createWatcher} from './watcher.mjs';
6
- import {resolveScope} from './scope.mjs';
7
- import {createGitRunner} from './git.mjs';
7
+ import {groupActivity, parseWorktreeList, resolveScope, scopeForWorktree, selectableWorktrees} from './scope.mjs';
8
+ import {createGitRunner, GIT_ALLOWED} from './git.mjs';
8
9
  import {renderHuman, renderJson} from './render.mjs';
9
10
  import {watchLocationLabel, statusBlockLines} from './status-line.mjs';
10
11
  import {WATCH_LIMITS as L} from './model.mjs';
12
+ import {earlierPageLines, renderBrief} from './brief.mjs';
13
+
14
+ const packageVersion = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
11
15
 
12
16
  export {parseWatchArgs};
13
17
  export const WATCH_HELP = `Usage: arc watch [options]
@@ -15,7 +19,7 @@ export const WATCH_HELP = `Usage: arc watch [options]
15
19
  Follow session activity of supported platforms in one read-only stream.
16
20
 
17
21
  Scope:
18
- Check the platforms to watch in the menu; all supported platforms are checked by default. Every selection watches the current Git worktree, or the current directory outside Git. Requires an interactive terminal.
22
+ In a Git repository, first choose the worktree to watch from git worktree list, wherever it was created; the current worktree is selected, recent session activity is shown, and worktrees without recent activity are dimmed. Outside Git the current directory is watched. Then check the platforms to watch; all supported platforms are checked by default. Requires an interactive terminal.
19
23
 
20
24
  Output:
21
25
  --tail <n> First show the last <n> events from recently active sessions (default 20, 0 = new only)
@@ -30,8 +34,34 @@ User messages, agent messages, prompts and file paths are shown in full; other e
30
34
  PROMPT is an agent-generated prompt sent to a child session (kind "prompt" in JSON).
31
35
  Color TTY output renders Markdown in AGENT and PROMPT messages. NO_COLOR, piped output and --json keep the Markdown source text.
32
36
  Tool and command outputs are never shown; common secret patterns are masked.
37
+ A summary box at the start shows the scope, platforms and keys (TTY only).
33
38
  A status block on the last lines shows the watched path and, while a turn is in progress, a spinner (TTY only).
34
- Press Ctrl-L to clear the screen (TTY only) and Ctrl-C to stop.`;
39
+ Press Ctrl-H to show earlier events from the history loaded at start, 20 at a time, Ctrl-L to clear the screen and Ctrl-C to stop. Ctrl-H and Ctrl-L work in a TTY only.
40
+ Terminals that send ^H for Backspace also show earlier events on Backspace.`;
41
+
42
+ function resolveWatchHomes({registry,userHome,env,cwd}) {
43
+ const homes = {}, homeErrors = {};
44
+ for (const {id} of registry.byAnchorOrder()) {
45
+ try { homes[id] = resolveConfigHome(id,{userHome,env,cwd,runtimePlatforms:registry}); }
46
+ catch (cause) { homes[id] = null; homeErrors[id] = cause.message; }
47
+ }
48
+ return {homes,homeErrors};
49
+ }
50
+
51
+ async function probeWorktrees({worktrees,scope,homes,userHome,git,now,registry}) {
52
+ const platforms = registry.byDisplayOrder().filter(row=>row.capabilities.watch.state==='verified').map(row=>row.id);
53
+ const probe = createWatcher({
54
+ options:{probe:true,platforms,tail:0},homes:{...homes,user:userHome},git,now,registry,
55
+ scope:{kind:'repo',roots:worktrees.map(tree=>tree.root),excludedRoots:[],gitCommonDir:scope.gitCommonDir},
56
+ });
57
+ try {
58
+ await probe.start();
59
+ const time = now();
60
+ return {groups:groupActivity(worktrees,probe.listActivity(),{now:time}),now:time};
61
+ } finally {
62
+ await probe.close();
63
+ }
64
+ }
35
65
 
36
66
  export async function runWatch(argv, io = {}) {
37
67
  const input = io.input ?? process.stdin;
@@ -46,16 +76,52 @@ export async function runWatch(argv, io = {}) {
46
76
  return 2;
47
77
  }
48
78
  const registry = io.registry ?? DEFAULT_PLATFORM_REGISTRY;
79
+ const cwd = io.cwd ?? process.cwd(), env = io.env ?? process.env, userHome = io.userHome ?? os.homedir();
80
+ const git = io.git ?? createGitRunner({env}), now = io.now ?? Date.now;
81
+ const {homes,homeErrors} = resolveWatchHomes({registry,userHome,env,cwd});
82
+ let porcelain, scope;
83
+ try {
84
+ scope = await resolveScope({dir:cwd,git:async (dir,args)=>{
85
+ if (args!==GIT_ALLOWED[2]) return git(dir,args);
86
+ try { porcelain = await git(dir,args); } catch { porcelain = null; }
87
+ // A missing list should not turn a confirmed Git worktree into a directory scope.
88
+ return porcelain ?? '';
89
+ }});
90
+ } catch (cause) {
91
+ error.write(`Error: ${String(cause.message ?? cause).replace(/[\r\n]+/g,' ')}\n`);
92
+ return 1;
93
+ }
94
+ if (io.signal?.aborted) return 0;
49
95
  const choose = io.choosePlatforms ?? (await import('./menu.mjs')).chooseWatchPlatforms;
50
96
  let platforms;
51
97
  try {
52
- platforms = await choose({input,output,env:io.env,signals:io.process,registry});
98
+ if (scope.kind==='repo' && porcelain) {
99
+ const currentRoot = scope.roots[0];
100
+ let picker;
101
+ try {
102
+ const {worktrees,mainRoot} = selectableWorktrees(parseWorktreeList(porcelain));
103
+ if (worktrees.some(tree=>tree.root===currentRoot)) {
104
+ scope = scopeForWorktree(scope,worktrees,currentRoot,{home:userHome});
105
+ picker = {worktrees,mainRoot,...await probeWorktrees({worktrees,scope,homes,userHome,git,now,registry})};
106
+ }
107
+ } catch {
108
+ // A corrupt list or unreadable probe leaves the current worktree selected.
109
+ }
110
+ if (io.signal?.aborted) return 0;
111
+ if (picker) {
112
+ const {chooseWatchWorktree} = await import('./worktree-menu.mjs');
113
+ const root = await chooseWatchWorktree({input,output,env,signals:io.process,registry,currentRoot,home:userHome,...picker});
114
+ if (root===null) return 0;
115
+ scope = scopeForWorktree(scope,picker.worktrees,root,{home:userHome});
116
+ }
117
+ }
118
+ platforms = await choose({input,output,env,signals:io.process,registry});
53
119
  } catch (cause) {
54
120
  if (cause.code === 'ARC_CANCELLED') return 130;
55
121
  throw cause;
56
122
  }
57
123
  if (platforms === null) return 0;
58
- return followWatch(options,{...io,input,output,error,registry,platforms});
124
+ return followWatch(options,{...io,input,output,error,registry,platforms,scope,homes,homeErrors,git});
59
125
  }
60
126
 
61
127
  export async function followWatch(options, io = {}) {
@@ -64,12 +130,11 @@ export async function followWatch(options, io = {}) {
64
130
  const output = io.output ?? process.stdout, error = io.error ?? process.stderr;
65
131
  const cwd = io.cwd ?? process.cwd(), env = io.env ?? process.env;
66
132
  const registry = io.registry ?? DEFAULT_PLATFORM_REGISTRY;
67
- const userHome = io.userHome ?? os.homedir(), disabled = [];
68
- const homes = Object.fromEntries(registry.byAnchorOrder().map(({id}) => [id,null]));
69
- for (const {id:platform} of registry.byAnchorOrder()) {
70
- try { homes[platform] = resolveConfigHome(platform, {userHome,env,cwd,runtimePlatforms:registry}); }
71
- catch (cause) { if (io.platforms.includes(platform)) disabled.push(`${platform} disabled: ${cause.message}`); }
72
- }
133
+ const userHome = io.userHome ?? os.homedir();
134
+ const {homes,homeErrors} = io.homes ? {homes:io.homes,homeErrors:io.homeErrors ?? {}}
135
+ : resolveWatchHomes({registry,userHome,env,cwd});
136
+ const disabled = Object.entries(homeErrors).filter(([platform])=>io.platforms.includes(platform))
137
+ .map(([platform,message])=>`${platform} disabled: ${message}`);
73
138
  const platforms = io.platforms.filter(platform => homes[platform] !== null);
74
139
  if (!platforms.length) { error.write('Error: no usable watch source.\n'); return 1; }
75
140
  const now = io.now ?? Date.now, git = io.git ?? createGitRunner({env});
@@ -79,7 +144,7 @@ export async function followWatch(options, io = {}) {
79
144
  const color = Boolean(output.isTTY && !options.json && !env.NO_COLOR);
80
145
  const blockEnabled = Boolean(output.isTTY && !options.json);
81
146
  const fancy = color && env.TERM !== 'dumb';
82
- const label = watchLocationLabel({dir:cwd,home:userHome});
147
+ const label = io.scope?.display ?? watchLocationLabel({dir:cwd,home:userHome});
83
148
  const keysEnabled = Boolean(input.isTTY && output.isTTY && !options.json && typeof input.setRawMode === 'function');
84
149
  const frames = ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'];
85
150
  let drawnLines = 0, frame = 0, tick = 0;
@@ -90,10 +155,11 @@ export async function followWatch(options, io = {}) {
90
155
  output.write(erase);
91
156
  };
92
157
  const resize = () => { width = options.width ?? (output.isTTY ? Math.max(L.ttyWidthMin, output.columns || L.ttyWidthMin) : L.nonTtyWidth); };
158
+ const blockWidth = () => Math.min(width, output.columns || width);
93
159
  resize();
94
160
  return new Promise(resolve => {
95
161
  const signals = ['SIGINT','SIGTERM','SIGHUP'];
96
- let rawModeEnabled = false;
162
+ let rawModeEnabled = false, startupComplete = false;
97
163
  const stop = (code = 0, cause) => {
98
164
  if (stopped) return;
99
165
  stopped = true;
@@ -122,8 +188,7 @@ export async function followWatch(options, io = {}) {
122
188
  const drawBlock = () => {
123
189
  if (!stopped && blockEnabled) {
124
190
  const busy = Boolean(watcher?.busy?.());
125
- const blockWidth = Math.min(width, output.columns || width);
126
- const lines = statusBlockLines({label,busy,glyph:frames[frame],tick,color,fancy,width:blockWidth});
191
+ const lines = statusBlockLines({label,busy,glyph:frames[frame],tick,color,fancy,width:blockWidth()});
127
192
  if (busy) frame = (frame + 1) % frames.length;
128
193
  drawnLines = lines.length;
129
194
  output.write(lines.join('\n'));
@@ -133,20 +198,30 @@ export async function followWatch(options, io = {}) {
133
198
  for (const byte of Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) {
134
199
  if (stopped) break;
135
200
  if (byte === 0x03) stop();
136
- else if (byte === 0x0c) {
201
+ else if (byte === 0x08 && startupComplete) {
202
+ const {events,remaining} = watcher.earlier(L.earlierPage);
203
+ const {start,end} = earlierPageLines({shown:events.length,remaining});
204
+ const separator = line => {
205
+ const clipped = line.slice(0, Math.max(0, blockWidth() - 1));
206
+ return color ? `\x1b[2m${clipped}\x1b[0m` : clipped;
207
+ };
208
+ write(events,[separator(start)],end === undefined ? undefined : separator(end));
209
+ } else if (byte === 0x0c) {
137
210
  output.write('\x1b[H\x1b[2J\x1b[3J');
138
211
  drawnLines = 0;
139
212
  drawBlock();
140
213
  }
141
214
  }
142
215
  };
143
- const write = events => {
216
+ const write = (events, leadingLines, trailingLine) => {
144
217
  if (stopped) return;
145
218
  eraseBlock();
219
+ if (leadingLines?.length) output.write(leadingLines.join('\n') + '\n');
146
220
  for (const event of events) {
147
221
  if (stopped) break;
148
222
  output.write((options.json ? renderJson(event) : renderHuman(event,{width,color,verbose:options.verbose,wrap})) + '\n');
149
223
  }
224
+ if (!stopped && trailingLine !== undefined) output.write(trailingLine + '\n');
150
225
  drawBlock();
151
226
  };
152
227
  for (const signal of signals) proc.on(signal, onSignal);
@@ -161,14 +236,24 @@ export async function followWatch(options, io = {}) {
161
236
  input.resume();
162
237
  input.on('data', onKey);
163
238
  }
164
- const scope = await resolveScope({dir:cwd,git});
239
+ const scope = io.scope ?? await resolveScope({dir:cwd,git});
165
240
  if (stopped) return;
166
- watcher = createWatcher({options:{...options,platforms},homes:{...homes,user:userHome},scope,git,now,registry});
241
+ watcher = createWatcher({options:{...options,platforms,earlier:keysEnabled},homes:{...homes,user:userHome},scope,git,now,registry});
242
+ const disabledEvents = [];
167
243
  for (const text of disabled) {
168
244
  const ts = new Date(now()).toISOString();
169
- write([{v:1,ts,observedAt:ts,source:'watch',kind:'notice',label:'watch',text}]);
245
+ const event = {v:1,ts,observedAt:ts,source:'watch',kind:'notice',label:'watch',text};
246
+ if (blockEnabled) disabledEvents.push(event);
247
+ else write([event]);
170
248
  }
171
- write(await watcher.start());
249
+ const startup = await watcher.start();
250
+ if (blockEnabled) {
251
+ const [header, ...events] = startup;
252
+ const keys = keysEnabled ? ['Ctrl-C stop','Ctrl-H earlier','Ctrl-L clear'] : ['Ctrl-C stop'];
253
+ const lines = renderBrief(header.brief, {version:packageVersion,keys,width:blockWidth(),color});
254
+ write([...disabledEvents,...events.filter(event => event.startup !== 'live')], lines);
255
+ } else write(startup);
256
+ startupComplete = true;
172
257
  if (stopped) return;
173
258
  nextPollAt = now() + L.filePollMs;
174
259
  timer = schedule(() => {