@yunhozz/arc 0.3.3 → 0.3.5

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 (126) hide show
  1. package/MANIFEST.sha256 +80 -122
  2. package/README.md +3 -3
  3. package/claude/skill/SKILL.md +1 -0
  4. package/claude/skill/references/coordination.md +5 -3
  5. package/claude/skill/references/git-recovery.md +5 -0
  6. package/claude/skill/references/handoff-prep.md +6 -8
  7. package/claude/skill/references/handoff.md +4 -4
  8. package/claude/skill/references/planning.md +5 -0
  9. package/claude/skill/references/worktree-creation.md +14 -0
  10. package/codex/skill/references/coordination.md +5 -3
  11. package/codex/skill/references/git-recovery.md +1 -5
  12. package/codex/skill/references/worktree-creation.md +20 -0
  13. package/lib/installer/manifest.mjs +10 -9
  14. package/lib/installer/package-references.mjs +2 -2
  15. package/lib/installer/plan.mjs +3 -1
  16. package/lib/installer/skill-sources.mjs +23 -0
  17. package/lib/installer/superpowers.mjs +5 -5
  18. package/lib/runtime/bootstrap.mjs +1 -1
  19. package/lib/runtime/local-cli.mjs +10 -20
  20. package/lib/runtime/role-bridge.mjs +2 -4
  21. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  22. package/lib/runtime/role-routing.mjs +1 -2
  23. package/lib/watch/dispatch.mjs +10 -2
  24. package/lib/watch/git.mjs +4 -2
  25. package/lib/watch/index.mjs +16 -8
  26. package/lib/watch/model.mjs +8 -4
  27. package/lib/watch/normalize-claude.mjs +83 -6
  28. package/lib/watch/normalize-codex.mjs +15 -11
  29. package/lib/watch/render.mjs +73 -19
  30. package/lib/watch/scope.mjs +5 -5
  31. package/lib/watch/watcher.mjs +110 -10
  32. package/package.json +2 -1
  33. package/scripts/check-installer-parity.mjs +3 -1
  34. package/scripts/update-manifest.mjs +1 -1
  35. package/scripts/update-runtime-assets.mjs +1 -1
  36. package/{codex → shared}/skill/references/handoff-worktree.md +17 -16
  37. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  38. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  39. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  40. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  41. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  42. package/claude/skill/runtime/bootstrap.mjs +0 -38
  43. package/claude/skill/runtime/local-cli.mjs +0 -248
  44. package/claude/skill/runtime/role-bridge.mjs +0 -227
  45. package/codex/skill/references/brainstorming.md +0 -316
  46. package/codex/skill/references/builder-check-prompt.md +0 -23
  47. package/codex/skill/references/scripts/frame-template.html +0 -213
  48. package/codex/skill/references/scripts/helper.js +0 -167
  49. package/codex/skill/references/scripts/server.cjs +0 -723
  50. package/codex/skill/references/scripts/start-server.sh +0 -216
  51. package/codex/skill/references/scripts/stop-server.sh +0 -120
  52. package/codex/skill/references/superpowers-LICENSE +0 -21
  53. package/codex/skill/references/superpowers-provenance.json +0 -26
  54. package/codex/skill/references/test-driven-development.md +0 -330
  55. package/codex/skill/references/visual-companion.md +0 -299
  56. package/codex/skill/references/writing-good-tests.md +0 -198
  57. package/codex/skill/references/writing-plans.md +0 -204
  58. package/codex/skill/runtime/acceptance.mjs +0 -68
  59. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  60. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  61. package/codex/skill/runtime/assignment.mjs +0 -42
  62. package/codex/skill/runtime/capabilities.mjs +0 -44
  63. package/codex/skill/runtime/cli.mjs +0 -8
  64. package/codex/skill/runtime/command.mjs +0 -38
  65. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  66. package/codex/skill/runtime/cooperative.mjs +0 -239
  67. package/codex/skill/runtime/evaluate.mjs +0 -331
  68. package/codex/skill/runtime/external.mjs +0 -51
  69. package/codex/skill/runtime/gate.mjs +0 -71
  70. package/codex/skill/runtime/git-evidence.mjs +0 -258
  71. package/codex/skill/runtime/git-query.mjs +0 -88
  72. package/codex/skill/runtime/identity.mjs +0 -49
  73. package/codex/skill/runtime/operations.mjs +0 -6
  74. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  75. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  76. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  77. package/codex/skill/runtime/role-observe.mjs +0 -299
  78. package/codex/skill/runtime/role-policy.json +0 -654
  79. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  80. package/codex/skill/runtime/role-routing.mjs +0 -233
  81. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  82. package/codex/skill/runtime/schema.mjs +0 -98
  83. package/codex/skill/runtime/scope.mjs +0 -36
  84. package/codex/skill/runtime/store.mjs +0 -94
  85. package/codex/skill/runtime/target-preparation.mjs +0 -110
  86. package/codex/skill/runtime/verification.mjs +0 -125
  87. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  88. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  89. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  90. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  91. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  92. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  93. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  94. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  95. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  96. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  97. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  98. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  99. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  100. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  101. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  102. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  103. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  104. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  105. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  106. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  107. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  108. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  109. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  110. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  111. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  112. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  113. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  114. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  115. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  116. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  117. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  118. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  119. /package/{claude → shared}/skill/runtime/role-policy.json +0 -0
  120. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  121. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  122. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  123. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  124. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  125. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  126. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -1,5 +1,3 @@
1
- import {WATCH_LIMITS} from './model.mjs';
2
-
3
1
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
2
  const string = value => typeof value === 'string';
5
3
  const strings = values => values.filter(string);
@@ -39,25 +37,27 @@ function changePaths(changes) {
39
37
  } else if (object(changes)) {
40
38
  for (const [path, change] of Object.entries(changes)) paths.push(path, change?.move_path);
41
39
  }
42
- return [...new Set(strings(paths))].slice(0, WATCH_LIMITS.pathsMax);
40
+ return [...new Set(strings(paths))];
43
41
  }
44
42
 
45
43
  function splitChangePaths(changes) {
46
- const added = [], changed = [];
44
+ const added = [], changed = [], deleted = [];
47
45
  const isAdd = change => object(change) && (change.type === 'add' || change.kind?.type === 'add' || Object.hasOwn(change,'add'));
46
+ const isDelete = change => object(change) && (change.type === 'delete' || change.kind?.type === 'delete' || Object.hasOwn(change,'delete'));
47
+ const group = change => isAdd(change) ? added : isDelete(change) ? deleted : changed;
48
48
  if (Array.isArray(changes)) {
49
49
  for (const change of changes) {
50
- (isAdd(change) ? added : changed).push(change?.path, change?.file);
50
+ group(change).push(change?.path, change?.file);
51
51
  changed.push(change?.move_path);
52
52
  }
53
53
  } else if (object(changes)) {
54
54
  for (const [path, change] of Object.entries(changes)) {
55
- (isAdd(change) ? added : changed).push(path);
55
+ group(change).push(path);
56
56
  changed.push(change?.move_path);
57
57
  }
58
58
  }
59
- const unique = paths => [...new Set(strings(paths))].slice(0,WATCH_LIMITS.pathsMax);
60
- return {added:unique(added),changed:unique(changed)};
59
+ const unique = paths => [...new Set(strings(paths))];
60
+ return {added:unique(added),changed:unique(changed),deleted:unique(deleted)};
61
61
  }
62
62
 
63
63
  /** Normalize one parsed rollout line; no I/O or transcript state. */
@@ -105,9 +105,13 @@ export function normalizeCodexLine(obj) {
105
105
  case 'CommandExecution': return emit('command', {text:commandText(item.command), exitCode:Number.isFinite(item.exit_code) ? item.exit_code : undefined});
106
106
  case 'FileChange':
107
107
  case 'PatchApply': {
108
- const {added,changed} = splitChangePaths(item.changes);
109
- if (!added.length) return emit('file_change', {paths:changePaths(item.changes)});
110
- return [...emit('file_create', {paths:added}), ...(changed.length ? emit('file_change', {paths:changed}) : [])];
108
+ const {added,changed,deleted} = splitChangePaths(item.changes);
109
+ if (!added.length && !deleted.length) return emit('file_change', {paths:changePaths(item.changes)});
110
+ return [
111
+ ...(added.length ? emit('file_create', {paths:added}) : []),
112
+ ...(changed.length ? emit('file_change', {paths:changed}) : []),
113
+ ...(deleted.length ? emit('file_delete', {paths:deleted}) : []),
114
+ ];
111
115
  }
112
116
  case 'McpToolCall': return emit('tool', {tool:strings([item.server,item.tool]).join('.')});
113
117
  case 'Extension':
@@ -3,6 +3,59 @@ import {WATCH_LIMITS, MESSAGE_KINDS} from './model.mjs';
3
3
  import {sanitizeText, sanitizeMessage, clipCodePoints} from './policy.mjs';
4
4
  import {realPath} from './scope.mjs';
5
5
 
6
+ const graphemes = new Intl.Segmenter(undefined, {granularity:'grapheme'});
7
+ const roleLabels = new Map([
8
+ ['scouter','Scouter'], ['planner','Planner'], ['implementer','Implementer'],
9
+ ['qa','QA'], ['reviewer','Reviewer'], ['orchestrator','Orchestrator'],
10
+ ]);
11
+ const zeroWidth = /^[\u0300-\u036f\u200b-\u200f\ufe00-\ufe0f]+$/u;
12
+ const wide = /[\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua000-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{1f300}-\u{1f64f}\u{1f900}-\u{1f9ff}\u{20000}-\u{3fffd}]/u;
13
+ function graphemeWidth(text) {
14
+ if (zeroWidth.test(text)) return 0;
15
+ if (wide.test(text) || /\p{Emoji_Presentation}/u.test(text) || (/[\u200d\ufe0f]/u.test(text) && /\p{Extended_Pictographic}/u.test(text))) return 2;
16
+ return 1;
17
+ }
18
+
19
+ export function displayWidth(text) {
20
+ let width = 0;
21
+ for (const {segment} of graphemes.segment(text)) width += graphemeWidth(segment);
22
+ return width;
23
+ }
24
+
25
+ export function wrapLine(text, avail) {
26
+ if (avail <= 0) return [text];
27
+ const parts = [...graphemes.segment(text)].map(({segment}) => segment);
28
+ const widths = parts.map(graphemeWidth);
29
+ const lines = [];
30
+ let start = 0;
31
+ while (start < parts.length) {
32
+ let end = start, cols = 0, space = -1, hasContent = false;
33
+ while (end < parts.length && cols + widths[end] <= avail) {
34
+ if (parts[end] === ' ') { if (hasContent) space = end; }
35
+ else hasContent = true;
36
+ cols += widths[end++];
37
+ }
38
+ if (end === parts.length) {
39
+ const piece = parts.slice(start).join('');
40
+ if (piece.trim()) lines.push(piece);
41
+ break;
42
+ }
43
+ // A space immediately after a full line can be discarded as the boundary.
44
+ if (parts[end] === ' ' && hasContent) space = end;
45
+ let piece;
46
+ if (space >= 0) {
47
+ piece = parts.slice(start,space).join('');
48
+ start = space + 1;
49
+ } else {
50
+ end = Math.max(start + 1,end);
51
+ piece = parts.slice(start,end).join('');
52
+ start = end;
53
+ }
54
+ if (piece.trim()) lines.push(piece);
55
+ }
56
+ return lines.length ? lines : [''];
57
+ }
58
+
6
59
  export const PLATFORM_COLORS = Object.freeze({codex:'36', claude:'38;5;208', other:'2'});
7
60
 
8
61
  // Compare both the lexical root and its real path (e.g. /tmp and /private/tmp).
@@ -19,7 +72,7 @@ export function displayPath(file, root) {
19
72
 
20
73
  export function tagColor(event) {
21
74
  if (event.kind === 'command') return event.exitCode == null || event.exitCode === 0 ? '38;5;242' : '31';
22
- return ({user:'1;35', agent:'32', file_change:'33', file_create:'38;5;69', tool:'2', spawn:'38;5;141',
75
+ return ({user:'1;35', agent:'32', file_change:'33', file_create:'38;5;69', file_delete:'31', tool:'2', spawn:'38;5;141',
23
76
  dispatch:'38;5;137', approval:'1;4', turn_failed:'31', error:'31', tool_failed:'31'})[event.kind] ?? '2';
24
77
  }
25
78
 
@@ -29,15 +82,10 @@ export function bodyColor(event) {
29
82
  }
30
83
 
31
84
  export function kindTag(event) {
32
- if (event.kind === 'agent') {
33
- const name = event.role || (event.source === 'subagent' && event.label?.includes('/') ? event.label.split('/').at(-1) : '');
34
- const safeName = clipCodePoints(sanitizeText(name), WATCH_LIMITS.agentNameMax).text;
35
- return safeName ? `AGENT(${safeName})` : 'AGENT';
36
- }
37
85
  if (event.kind === 'command') return event.exitCode == null ? 'CMD' : `CMD(${event.exitCode})`;
38
86
  return ({session:'SESSION', settings:'SETTINGS', turn_start:'TURN', turn_end:'END',
39
87
  turn_failed:'FAIL', user:'USER', agent:'AGENT', reasoning:'THINK', tool:'TOOL',
40
- tool_failed:'TOOL!', file_change:'EDIT', file_create:'CREATE', spawn:'SPAWN', approval:'APPROVE',
88
+ tool_failed:'TOOL!', file_change:'EDIT', file_create:'CREATE', file_delete:'DELETE', spawn:'SPAWN', approval:'APPROVE',
41
89
  dispatch:'DISPATCH', error:'ERROR', other:'ITEM', notice:'NOTICE'})[event.kind] ?? 'ITEM';
42
90
  }
43
91
 
@@ -45,16 +93,13 @@ function eventText(event, verbose) {
45
93
  if (event.kind === 'tool' || event.kind === 'tool_failed') {
46
94
  return [event.tool, event.text].map(sanitizeText).filter(Boolean).join(' ');
47
95
  }
48
- if (event.kind === 'file_change' || event.kind === 'file_create') {
49
- return [event.text, ...(event.paths ?? []).map(file => displayPath(file,event.root))].map(sanitizeText).filter(Boolean).join(' ');
50
- }
51
96
  if (event.kind !== 'dispatch') return sanitizeText(event.text);
52
97
  return sanitizeText([event.state, event.route, event.workflowId,
53
98
  event.reasons?.join(','), verbose && event.hostPlatform ? `host=${event.hostPlatform}` : undefined,
54
99
  ].filter(Boolean).join(' '));
55
100
  }
56
101
 
57
- export function renderHuman(event, {width, color, verbose}) {
102
+ export function renderHuman(event, {width, color, verbose, wrap = false}) {
58
103
  let date = new Date(event.ts);
59
104
  if (Number.isNaN(date.getTime())) date = new Date(event.observedAt);
60
105
  const time = Number.isNaN(date.getTime()) ? '00:00:00' : date.toLocaleTimeString('en-GB', {hour12:false});
@@ -62,26 +107,36 @@ export function renderHuman(event, {width, color, verbose}) {
62
107
  const tag = sanitizeText(kindTag(event)).padEnd(8);
63
108
  const prefix = `${time} ${platform} ${tag} `;
64
109
  const message = MESSAGE_KINDS.includes(event.kind);
65
- const fullLine = message || event.kind === 'file_change' || event.kind === 'file_create';
110
+ const fullLine = message || event.kind === 'file_change' || event.kind === 'file_create' || event.kind === 'file_delete';
66
111
  const text = message ? sanitizeMessage(event.text) : eventText(event, verbose);
67
- const messageBody = text.split('\n').map((line, i) => !line ? '' : (i ? ' '.repeat([...prefix].length) : '') + line).join('\n');
68
- const plain = message ? (text ? prefix + messageBody : prefix.trimEnd()) : fullLine ? prefix + text : clipCodePoints(prefix + text, width).text;
112
+ const bodyLines = message ? (text ? text.split('\n') : []) : fullLine
113
+ ? [event.text, ...(event.paths ?? []).map(file => displayPath(file,event.root))].map(sanitizeText).filter(Boolean) : [];
114
+ const roleName = event.kind === 'agent' ? roleLabels.get(event.role) : undefined;
115
+ if (roleName && bodyLines.length) bodyLines[0] = `[${roleName}] ${bodyLines[0]}`;
116
+ const indent = ' '.repeat([...prefix].length);
117
+ const avail = width - Math.max([...prefix].length, displayWidth(prefix));
118
+ const lines = wrap && avail >= WATCH_LIMITS.wrapMinBody ? bodyLines.flatMap(line => wrapLine(line,avail)) : bodyLines;
119
+ const bodyText = paintLine => lines.map((line,i) => !line ? '' : (i ? indent : '') + paintLine(line,i)).join('\n');
120
+ const plain = fullLine ? (message && !lines.length ? prefix.trimEnd() : prefix + bodyText(line => line)) : clipCodePoints(prefix + text, width).text;
69
121
  if (!color || (!fullLine && [...prefix].length > width)) return plain;
70
122
  const code = bodyColor(event);
71
123
  const paint = (value, code) => `\x1b[${code}m${value}\x1b[0m`;
72
124
  const platformColor = event.source === 'watch' ? PLATFORM_COLORS.other : PLATFORM_COLORS[event.platform] ?? PLATFORM_COLORS.other;
73
125
  const paintedTag = paint(tag.trimEnd(), tagColor(event));
74
126
  const padding = tag.slice(tag.trimEnd().length);
75
- const clippedText = message ? messageBody : [...plain].slice([...prefix].length).join('');
127
+ const clippedText = [...plain].slice([...prefix].length).join('');
76
128
  if (message && !text) return `${time} ${paint(platform, platformColor)} ${paintedTag}`;
77
- const body = message ? text.split('\n').map((line, i) => !line ? '' : (i ? ' '.repeat([...prefix].length) : '') + (code ? paint(line, code) : line)).join('\n')
129
+ const body = fullLine ? bodyText((line,i) => {
130
+ if (roleName && i === 0) line = line.replace(`[${roleName}]`, `[\x1b[1m${roleName}\x1b[22m]`);
131
+ return code ? paint(line,code) : line;
132
+ })
78
133
  : code && clippedText ? paint(clippedText, code) : clippedText;
79
134
  return `${time} ${paint(platform, platformColor)} ${paintedTag}${padding} ${body}`;
80
135
  }
81
136
 
82
137
  export function renderJson(event) {
83
138
  const fields = ['ts','observedAt','platform','source','origin','sessionId','parentId','depth',
84
- 'label','role','dispatchId','workflowId','kind','text','truncated','exitCode','tool','paths',
139
+ 'label','role','dispatchId','workflowId','kind','text','truncated','exitCode','tool','paths','inferred',
85
140
  'model','effort','approval','state','reasons','route','hostPlatform','cwd'];
86
141
  const output = {v:1};
87
142
  for (const key of fields) {
@@ -98,8 +153,7 @@ export function renderJson(event) {
98
153
  } else if (key === 'truncated') {
99
154
  if (value || output.truncated) output.truncated = true;
100
155
  } else if (Array.isArray(value)) {
101
- output[key] = (key === 'paths' ? value.slice(0, WATCH_LIMITS.pathsMax) : value)
102
- .filter(item => item != null).map(item => sanitizeText(item));
156
+ output[key] = value.filter(item => item != null).map(item => sanitizeText(item));
103
157
  } else {
104
158
  output[key] = typeof value === 'string' ? sanitizeText(value) : value;
105
159
  }
@@ -30,8 +30,8 @@ export async function resolveScope({mode, dir, session, git}) {
30
30
  if (top !== null) {
31
31
  const common = await git(root, GIT_ALLOWED[1]), trees = await git(root, GIT_ALLOWED[2]);
32
32
  if (common !== null && trees !== null) {
33
- const roots = worktreeRoots(trees);
34
- return {kind:'repo', roots:roots.length ? roots : [realPath(top.trim())], gitCommonDir:realPath(common.trim()), description:`Repository ${top.trim()}`};
33
+ const selected = realPath(top.trim());
34
+ return {kind:'repo', roots:[selected], excludedRoots:worktreeRoots(trees).filter(root=>root!==selected), gitCommonDir:realPath(common.trim()), description:`Worktree ${selected}`};
35
35
  }
36
36
  }
37
37
  return {kind:'dir', roots:[root], gitCommonDir:null, description:`Directory ${root}`};
@@ -41,8 +41,7 @@ export async function refreshScope(scope, git) {
41
41
  if (scope.kind !== 'repo') return scope;
42
42
  const output = await git(scope.roots[0], GIT_ALLOWED[2]);
43
43
  if (output === null) return scope;
44
- const roots = worktreeRoots(output);
45
- return roots.length ? {...scope, roots} : scope;
44
+ return {...scope, excludedRoots:worktreeRoots(output).filter(root=>!scope.roots.includes(root))};
46
45
  }
47
46
 
48
47
  export function inScope(scope, cwd) {
@@ -51,7 +50,8 @@ export function inScope(scope, cwd) {
51
50
  if (!cache) { cache = new Map(); scopeCaches.set(scope, cache); }
52
51
  if (cache.has(cwd)) return cache.get(cwd);
53
52
  const candidates = [path.resolve(cwd), realPath(cwd)];
54
- const inside = scope.roots.some(root => [path.resolve(root), realPath(root)].some(base => candidates.some(candidate => candidate === base || candidate.startsWith(base.endsWith(path.sep) ? base : base + path.sep))));
53
+ const contains = root => [path.resolve(root), realPath(root)].some(base => candidates.some(candidate => candidate === base || candidate.startsWith(base.endsWith(path.sep) ? base : base + path.sep)));
54
+ const inside = scope.roots.some(contains) && !(scope.excludedRoots ?? []).some(root=>scope.roots.some(base=>root.startsWith(base+path.sep)) && contains(root));
55
55
  cache.set(cwd, inside);
56
56
  return inside;
57
57
  }
@@ -15,7 +15,7 @@ import {GIT_ALLOWED} from './git.mjs';
15
15
  /** Read-only, timer-free merger. The caller owns scheduling and output. */
16
16
  export function createWatcher({options, homes, scope: initialScope, git, now, dependencies = {}}) {
17
17
  const {readClaudeHead: claudeHead = readClaudeHead, readCodexMeta: codexMeta = readCodexMeta,
18
- createClaudeDiscovery: claudeDiscovery = createClaudeDiscovery, createDispatchIndex: dispatchIndex = createDispatchIndex} = dependencies;
18
+ lstat = fsp.lstat, createClaudeDiscovery: claudeDiscovery = createClaudeDiscovery, createDispatchIndex: dispatchIndex = createDispatchIndex} = dependencies;
19
19
  const platforms = options.platforms ?? ['codex','claude'];
20
20
  const session = options.session ?? null, verbose = Boolean(options.verbose);
21
21
  const tailCount = options.tail ?? L.defaultTail;
@@ -24,7 +24,8 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
24
24
  const followed = new Map(), pending = new Map(), ignored = new Map(), detached = new Map();
25
25
  const seenAtStart = new Map(), heads = new Map(), metas = new Map(), agentMetas = new Map(), childLists = new Map();
26
26
  const compressed = new Set(), missingDispatch = new Set(), repos = new Map();
27
- const rootsByCwd = new Map();
27
+ const rootsByCwd = new Map(), gitTopByCwd = new Map(), shellRoots = new Map();
28
+ let shellCursor = 0;
28
29
  const dispatch = dispatchIndex({codexHome:homes.codex});
29
30
  const claude = homes.claude ? claudeDiscovery({claudeHome:homes.claude}) : null;
30
31
  const stamp = () => new Date(now()).toISOString();
@@ -39,10 +40,13 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
39
40
  return e;
40
41
  };
41
42
  const selectedDispatch = ref => !session || ref.dispatchId === session || ref.sessionIds.includes(session);
42
- const allowedDispatch = ref => ref.inScope && selectedDispatch(ref);
43
+ const dispatchInScope = ref => ref.inScope && (scope.kind==='all' || scope.kind==='session'
44
+ || (ref.cwd ? inScope(scope,ref.cwd) : [...followed.values()].some(row=>ref.sessionIds.includes(row.id))));
45
+ const allowedDispatch = ref => dispatchInScope(ref) && selectedDispatch(ref);
43
46
  function mapped(row) {
44
47
  const ref = dispatch.bySession(row.id);
45
- return ref && ref.inScope ? ref : null;
48
+ return ref && ref.inScope && (scope.kind==='all' || scope.kind==='session'
49
+ || (ref.cwd ? inScope(scope,ref.cwd) : row.cwd && inScope(scope,row.cwd))) ? ref : null;
46
50
  }
47
51
  function label(row, seen = new Set()) {
48
52
  if (seen.has(row.id)) return topLabel(row);
@@ -69,13 +73,20 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
69
73
  return [row.id.slice(0,8),row.origin,row.version,row.cwd ? `cwd=${row.cwd}` : '',
70
74
  ...(ref ? ['dispatch',ref.dispatchId,ref.workflowId] : [])].filter(Boolean).join(' ');
71
75
  }
72
- function normalize(row, lines) {
76
+ function normalize(row, lines, live = false) {
73
77
  const out = [];
74
78
  for (const line of lines) {
75
79
  const events = row.platform === 'codex' ? normalizeCodexLine(line) : normalizeClaudeLine(line,row.state);
76
80
  for (const e of events) {
81
+ const shell = shellRoots.get(row.gitTop);
82
+ if (live && shell && !shell.off && ['file_change','file_create','file_delete'].includes(e.kind)) {
83
+ for (const file of e.paths ?? []) {
84
+ const absolute=path.resolve(row.cwd,file);
85
+ shell.claims.set(path.join(realPath(path.dirname(absolute)),path.basename(absolute)),now());
86
+ }
87
+ }
77
88
  if (['turn_end','turn_failed'].includes(e.kind)) row.active = false;
78
- else if (['turn_start','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','spawn','approval'].includes(e.kind)) row.active = true;
89
+ else if (['turn_start','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','file_delete','spawn','approval'].includes(e.kind)) row.active = true;
79
90
  if (!isVisible(e.kind,verbose) || (e.kind === 'notice' && !verbose)) continue;
80
91
  out.push(clean({...identity(row),...e,ts:e.ts ?? stamp(),...(e.kind === 'session' ? {text:sessionText(row)} : {})}));
81
92
  }
@@ -127,7 +138,14 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
127
138
  let history;
128
139
  try { history = previous ? {endOffset:previous.offset} : await readTail(row.file); }
129
140
  catch (error) { debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code ?? 'error'})`); ignored.set(row.file,row.size); return; }
141
+ row.gitTop = await gitTop(row.cwd);
130
142
  row.root = await sessionRoot(row.cwd);
143
+ if (row.gitTop && !shellRoots.has(row.gitTop) && shellRoots.size < L.maxRepos) {
144
+ const state = {snapshot:null,pending:false,pendingSince:undefined,lastTriggerAt:-Infinity,
145
+ lastScanAt:-Infinity,prevScanAt:-Infinity,claims:new Map(),candidates:new Map(),failures:0,off:false};
146
+ shellRoots.set(row.gitTop,state);
147
+ await scanRoot(row.gitTop,state,out);
148
+ }
131
149
  row.tail=createTail(row.file,{offset:previous?.offset ?? history.endOffset});
132
150
  row.state=createClaudeState(); row.active=false; row.held=[]; row.lastActivity=row.mtimeMs;
133
151
  followed.set(row.id,row); pending.delete(row.file); detached.delete(row.file);
@@ -139,15 +157,26 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
139
157
  emit(row,events,out);
140
158
  }
141
159
  }
160
+ async function gitTop(cwd) {
161
+ if (!cwd) return undefined;
162
+ if (gitTopByCwd.has(cwd)) return gitTopByCwd.get(cwd);
163
+ let top;
164
+ try {
165
+ const result = (await git(cwd,GIT_ALLOWED[0]))?.trim();
166
+ if (result) top = realPath(result);
167
+ }
168
+ catch { /* Missing Git is equivalent to a non-repository session. */ }
169
+ if (gitTopByCwd.size >= L.maxRepos) gitTopByCwd.delete(gitTopByCwd.keys().next().value);
170
+ gitTopByCwd.set(cwd,top);
171
+ return top;
172
+ }
142
173
  async function sessionRoot(cwd) {
143
174
  if (!cwd) return undefined;
144
175
  try {
145
176
  const matches = (scope.roots ?? []).filter(root => inScope({kind:'dir',roots:[root]},cwd));
146
177
  if (matches.length) return matches.sort((a,b) => Math.max(path.resolve(b).length,realPath(b).length) - Math.max(path.resolve(a).length,realPath(a).length))[0];
147
178
  if (rootsByCwd.has(cwd)) return rootsByCwd.get(cwd);
148
- let root = cwd;
149
- try { root = (await git(cwd,GIT_ALLOWED[0]))?.trim() || cwd; }
150
- catch { /* A missing repository still has a useful cwd root. */ }
179
+ const root = await gitTop(cwd) || cwd;
151
180
  if (rootsByCwd.size >= L.maxRepos) rootsByCwd.delete(rootsByCwd.keys().next().value);
152
181
  rootsByCwd.set(cwd,root);
153
182
  return root;
@@ -323,12 +352,82 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
323
352
  row.overflowed=result.overflowed;
324
353
  if (row.tail.offset!==row.size) row.lastActivity=now();
325
354
  row.size=row.tail.offset;
326
- emit(row,normalize(row,result.lines),out);
355
+ const shell = shellRoots.get(row.gitTop);
356
+ if (result.lines.length && shell && !shell.off) {
357
+ shell.pending=true; shell.pendingSince ??= now(); shell.lastTriggerAt=now();
358
+ shell.candidates.set(row.id,now());
359
+ }
360
+ emit(row,normalize(row,result.lines,true),out);
327
361
  if (now()-row.lastActivity>=L.idleDetachMs && !row.held.length) {
328
362
  followed.delete(id);detached.set(row.file,{file:row.file,platform:row.platform,offset:row.tail.offset,size:row.size});debug(out,`detached idle session ${row.id.slice(0,8)}`);
329
363
  }
330
364
  }
331
365
  }
366
+ async function scanRoot(top, state, out) {
367
+ const scanStart = now();
368
+ for (const [file,ts] of state.claims) if (scanStart - ts > L.shellClaimTtlMs) state.claims.delete(file);
369
+ const disable = reason => {
370
+ state.off=true;
371
+ out.push(notice(`shell change detection off for ${top}: ${reason}`));
372
+ };
373
+ const listing = await git(top,GIT_ALLOWED[3]);
374
+ if (listing === null) {
375
+ state.failures++;
376
+ if (state.failures >= L.shellScanFailureMax) disable(`git ls-files failed ${L.shellScanFailureMax} times`);
377
+ } else {
378
+ state.failures=0;
379
+ const files=listing.split('\0').filter(Boolean);
380
+ if (files.length > L.shellScanMaxFiles) disable(`more than ${L.shellScanMaxFiles} files`);
381
+ else {
382
+ const previous=state.snapshot, snapshot=new Map();
383
+ const paths=[...new Set([...files.map(file=>path.join(top,file)),...(previous?.keys() ?? [])])];
384
+ for (let i=0;i<paths.length;i+=L.shellLstatBatch) {
385
+ await Promise.all(paths.slice(i,i+L.shellLstatBatch).map(async file=>{
386
+ try {
387
+ const stat=await lstat(file);
388
+ if (!stat.isDirectory()) snapshot.set(file,`${stat.mtimeMs}:${stat.size}:${stat.ino}:${stat.mode}`);
389
+ } catch (error) {
390
+ if (!['ENOENT','ENOTDIR'].includes(error.code) && previous?.has(file)) snapshot.set(file,previous.get(file));
391
+ }
392
+ }));
393
+ }
394
+ const changes={file_create:[],file_change:[],file_delete:[]};
395
+ if (previous) {
396
+ for (const file of paths) {
397
+ let kind;
398
+ if (!previous.has(file) && snapshot.has(file)) kind='file_create';
399
+ else if (previous.has(file) && !snapshot.has(file)) kind='file_delete';
400
+ else if (previous.get(file) !== snapshot.get(file)) kind='file_change';
401
+ if (!kind) continue;
402
+ const claim=state.claims.get(file);
403
+ if (claim !== undefined && claim <= scanStart) { state.claims.delete(file); continue; }
404
+ changes[kind].push(file);
405
+ }
406
+ }
407
+ state.snapshot=snapshot;
408
+ const candidate=[...state.candidates].filter(([id])=>followed.has(id)).sort((a,b)=>b[1]-a[1])[0];
409
+ if (candidate) {
410
+ const row=followed.get(candidate[0]);
411
+ const events=Object.entries(changes).filter(([,files])=>files.length).map(([kind,files])=>
412
+ clean({...identity(row),ts:stamp(),kind,paths:files.sort(),inferred:true}));
413
+ emit(row,events,out);
414
+ }
415
+ }
416
+ }
417
+ state.prevScanAt=state.lastScanAt; state.lastScanAt=now();
418
+ state.pending=false; state.pendingSince=undefined; state.candidates.clear();
419
+ }
420
+ async function scanShell(out) {
421
+ const roots=[...shellRoots];
422
+ let scans=0;
423
+ for (let visited=0;visited<roots.length && scans<L.shellScansPerTick;visited++) {
424
+ const [top,state]=roots[shellCursor % roots.length];
425
+ shellCursor=(shellCursor+1) % roots.length;
426
+ if (!state.pending || state.off || now()-state.lastScanAt<L.shellScanMinIntervalMs
427
+ || (now()-state.lastTriggerAt<L.shellScanDelayMs && now()-state.pendingSince<L.shellScanMinIntervalMs)) continue;
428
+ await scanRoot(top,state,out);scans++;
429
+ }
430
+ }
332
431
  function markEmitted(events) {
333
432
  for (const e of events) if (e.sessionId && followed.has(e.sessionId)) followed.get(e.sessionId).emitted=true;
334
433
  return events.map(clean);
@@ -349,6 +448,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
349
448
  if (now()-lastRefresh>=L.worktreeRefreshMs) {scope=await refreshScope(scope,git);lastRefresh=now();}
350
449
  if (now()-lastDiscovery>=L.discoveryMs||pending.size||[...followed.values()].some(row=>row.holdUntil!==undefined)) await discover(false,out);
351
450
  await poll(out);
451
+ await scanShell(out);
352
452
  return markEmitted(sort(out));
353
453
  },
354
454
  busy() {return [...followed.values()].some(row=>row.active && now()-row.lastActivity<=L.spinnerIdleMs);},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunhozz/arc",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -42,6 +42,7 @@
42
42
  "prebuilds/",
43
43
  "native/binding.c",
44
44
  "native/binding.gyp",
45
+ "shared/skill/",
45
46
  "codex/skill/",
46
47
  "codex/agents/",
47
48
  "claude/skill/",
@@ -8,7 +8,9 @@ const root=path.resolve(arg('--root',fileURLToPath(new URL('../',import.meta.url
8
8
  const complete=process.argv.includes('--complete');
9
9
  // Frozen before the legacy files were removed: test bodies, assertion expressions,
10
10
  // and helper assertion sites. Coverage mappings may change; this inventory may not.
11
- const inventorySha='b21f21cb1786d8400914f6f1837e8c3dddc51e4629fbdc4e091567a99f3825de';
11
+ // Re-pinned after d98d7c7 translated seven assertion expressions to English (line IDs
12
+ // and sourceSha256 still refer to the recorded source revision).
13
+ const inventorySha='586d1055494a0d62ae726f67de43384ea210dbcf7b66403eef7ed8fa7af165dd';
12
14
  try{
13
15
  const ledger=JSON.parse(fs.readFileSync(path.join(root,'tests/installer-parity.json'),'utf8'));
14
16
  const inventory={tests:ledger.legacyInventory,helpers:ledger.legacyHelpers?.map(({id,assertions})=>({id,assertions}))};
@@ -17,7 +17,7 @@ function visit(relative) {
17
17
  } else if (stat.isFile() && !mutable.has(relative)) files.set(relative,fs.readFileSync(filename));
18
18
  else if (!stat.isFile()) throw new Error(`Protected payload is not regular: ${relative}`);
19
19
  }
20
- for (const entry of ['README.md', 'install.command', 'package.json', 'bin', 'lib', 'native/binding.c', 'native/binding.gyp', 'scripts', 'vendor', 'prebuilds', 'codex/skill', 'codex/agents', 'claude/skill', 'claude/agents']) visit(entry);
20
+ for (const entry of ['README.md', 'install.command', 'package.json', 'bin', 'lib', 'native/binding.c', 'native/binding.gyp', 'scripts', 'vendor', 'prebuilds', 'shared/skill', 'codex/skill', 'codex/agents', 'claude/skill', 'claude/agents']) visit(entry);
21
21
  const content = renderManifest(files);
22
22
  const manifest = path.join(root, 'MANIFEST.sha256');
23
23
  if (process.argv.includes('--check')) {
@@ -18,7 +18,7 @@ try{
18
18
  if(modules.length!==RUNTIME_MODULE_PATHS.length||modules.some((name,index)=>name!==RUNTIME_MODULE_PATHS[index]))throw Error('Runtime asset inventory does not match canonical modules');
19
19
  const entries=modules.map(name=>[name.slice('lib/runtime/'.length),fs.readFileSync(path.join(root,name))]);
20
20
  const policy=path.join(root,'lib/policy/role-policy.json');safe(policy);entries.push(['role-policy.json',fs.readFileSync(policy)]);
21
- const outputs=[];for(const platform of ['codex','claude'])for(const [name,bytes]of entries){const filename=path.join(root,platform,'skill/runtime',name);safe(filename);outputs.push({filename,bytes});}
21
+ const outputs=[];for(const [name,bytes]of entries){const filename=path.join(root,'shared/skill/runtime',name);safe(filename);outputs.push({filename,bytes});}
22
22
  let drift=false;for(const {filename,bytes}of outputs){if(!fs.existsSync(filename)||!fs.readFileSync(filename).equals(bytes)){drift=true;if(!check){fs.mkdirSync(path.dirname(filename),{recursive:true});fs.writeFileSync(filename,bytes);}}}
23
23
  if(check&&drift){console.error('Runtime payload drift');process.exitCode=1;}else console.log(`Runtime payload ${check?'verified':'generated'} (${outputs.length} files)`);
24
24
  }catch(error){console.error(error.message);process.exitCode=1;}
@@ -9,32 +9,24 @@ After explicit new-managed-worktree selection, Orchestrator reads this before cr
9
9
  <a id="new-managed-worktree"></a>
10
10
  ### New managed worktree
11
11
 
12
- After the first required chat draft and focused preparation gate, verify actual creation, managed registration, current-chat attachment, repository, common directory, base, approved branch and source preservation below. Review and save new documents directly in the verified target. Planned paths prove no preparation; initial preparation authorizes neither Implementer nor document commits.
12
+ After the first required chat draft and focused preparation gate, verify actual creation, managed registration, platform attachment evidence defined in worktree-creation, repository, common directory, base, approved branch and source preservation below. Review and save new documents directly in the verified target. Planned paths prove no preparation; initial preparation authorizes neither Implementer nor document commits.
13
13
 
14
- 1. Only explicit selection of this third path authorizes preparation. Use the selection target verified under handoff-prep's request gate. The app chooses the actual path; DO NOT propose siblings or require user-specified paths. Use verified full source HEAD SHA as base, never remote HEAD/default branch or automatic fetch.
14
+ 1. Only explicit selection of this third path authorizes preparation. Use the selection target verified under handoff-prep's request gate. Use verified full source HEAD SHA as base, never remote HEAD/default branch or automatic fetch.
15
15
  2. After choice and immediately before the call, recheck source state, base SHA, approved candidate/collision, name and document scope. Changed pre-creation inputs require fresh explicit choice. After successful creation/verification, handoff lifetime/restart rules apply.
16
- 3. Before `mcp__codex_app__create_worktree`, validate candidate/collision under handoff-prep. Collisions require new explicit choice, never automatic suffixes. Existing-branch reuse is forbidden by default. Only this managed path permits an approved existing branch at the same base and not checked out in any worktree, after both checks. Unexpected branch, different base or uncertain lookup stops work.
17
- 4. Use only the app tool:
16
+ 3. Before creation through [worktree-creation](worktree-creation.md), validate candidate/collision under handoff-prep. Collisions require new explicit choice, never automatic suffixes. Existing-branch reuse is forbidden by default. Only this managed path permits an approved existing branch at the same base and not checked out in any worktree, after both checks. Unexpected branch, different base or uncertain lookup stops work.
17
+ 4. Creation uses only [worktree-creation](worktree-creation.md).
18
18
 
19
- mcp__codex_app__create_worktree({
20
- allowAsync: true,
21
- name: "<approved-descriptive-name>",
22
- ref: "<verified-source-head-full-sha>"
23
- })
24
-
25
- The descriptive name does not guarantee a path or branch. There are no destination-path/branch arguments. Pass full SHA `ref` explicitly; NEVER omit or rely on remote defaults. For `operationId`, use `mcp__codex_app__get_worktree_creation_status` until completed. Preparing/creating/registering is not success.
26
-
27
- Only registration failure permits reattachment of the returned workspace with `mcp__codex_app__attach_worktree`. No saving/transfer/staging/commit/Implementer before completed registration, current-chat attachment and branch verification. Missing tools, failed reattachment or mismatched results stop with actual-state reporting. No raw Git worktree fallback, alternate name/ref/path/branch retries or automatic cleanup/deletion/prune/archive. Read git-recovery before dependent recovery.
19
+ No saving/transfer/staging/commit/Implementer before completed registration, platform attachment evidence defined in worktree-creation and branch verification. Read git-recovery before dependent recovery.
28
20
 
29
21
  Verify creation in order:
30
22
 
31
- 1. Verify returned absolute path and app-artifact management/current-chat attachment.
23
+ 1. Verify returned absolute path and platform attachment evidence defined in [worktree-creation](worktree-creation.md).
32
24
  2. Record initial branch or detached HEAD, approved candidate, final branch and target HEAD equal to approved ref.
33
25
  3. Verify linked registration, source/target common-directory identity, registered path and target dirty state. Verify source branch/HEAD/index/files preservation. Approved-target shared metadata additions are authorized. Linked `.git` may be a file; repository identity requires neither identical top-level path nor a `.git` directory.
34
- 4. After registration/attachment/base checks, create/check out the approved branch: `git switch -c <approved-branch> <ref>` if detached, or `git switch <approved-branch>` under the existing-branch exception. No pointer moves, alternate branches, `--force` or `-B`. If the app already returned the approved branch, verify without repeating completed work.
26
+ 4. After registration/attachment/base checks, create/check out the approved branch: `git switch -c <approved-branch> <ref>` if detached, or `git switch <approved-branch>` under the existing-branch exception. No pointer moves, alternate branches, `--force` or `-B`. If creation already returned the approved branch, verify without repeating completed work.
35
27
  5. Unexpected branch/HEAD mismatch stops work. Verify final branch/HEAD before formal drafting, saving, transfer, batch docs commit, final Git checks and handoff.
36
28
 
37
- The tool copies no uncommitted changes. Transfer rules below apply only to existing approved documents in legacy/restart/explicit-target-change cases, not normal new documents.
29
+ Transfer rules below apply only to existing approved documents in legacy/restart/explicit-target-change cases, not normal new documents.
38
30
 
39
31
  - Untracked approved documents MUST be absent from source HEAD/index, with working-tree bytes matching latest approval.
40
32
  - Tracked documents require source index blob/mode equal to HEAD and working-tree bytes equal to latest approval. Approved working revisions may differ from HEAD/index. DO NOT stage source documents to repair or verify them.
@@ -51,3 +43,12 @@ Only for existing approved documents in legacy/pre-existing-document, restart, o
51
43
  3. Before replacing a destination, prove clean base state: no staged/unstaged changes, index/working bytes equal base. Documents absent from base MUST also be absent at destination. NEVER overwrite unexpected changes.
52
44
  4. Verify approved bytes before reusing identical content; verify approved bytes after transfer.
53
45
  5. Record approvals, versions, evidence, absolute source and target paths, common relative paths and content checks. Changed content/approval scope needs revised approval. Transfer nothing else. Failure/partial transfer blocks dependent staging, commits and Implementer handoff.
46
+
47
+ <a id="worktree-failures-and-partial-completion"></a>
48
+ ### Worktree failures and partial completion
49
+
50
+ Managed-worktree creation/registration/attachment/identity/base/checkout/transfer/stage/commit failures stop dependent work/handoff. Branch-only or partial-path creation, registration/path mismatch, wrong base/branch and partial transfer count as partial completion.
51
+
52
+ Record source/target commands/errors/branch/HEAD/common directory/registration/index/files, target dirty state and source preservation. Include platform attachment evidence defined in worktree-creation, initial/final branch, base/ref SHA and ownership. Inspect actual state/completed work before authorized retry.
53
+
54
+ No automatic alternate path/branch, deletion, `git worktree prune`, `--force`/`-B`, cleanup or archive. Normal preparation after explicit managed selection is allowed; arbitrary recovery workspace moves are not. Resolve and revalidate the full gate; renewed choice follows handoff lifetime rules. Preserve completion and platform recovery/no-fallback limits defined in [worktree-creation](worktree-creation.md).
@@ -18,7 +18,7 @@ export async function cooperativeVersions(){
18
18
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
19
19
  let policy;try{policy=await fs.readFile(new URL('../policy/role-policy.json',import.meta.url));}catch(error){if(error.code!=='ENOENT')throw error;policy=await fs.readFile(new URL('./role-policy.json',import.meta.url));}
20
20
  const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
21
- return {policy:'1',runtime:'cooperative-8',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
21
+ return {policy:'1',runtime:'cooperative-9',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
22
22
  }
23
23
  export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
24
24
  validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
@@ -2,7 +2,6 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { StringDecoder } from 'node:string_decoder';
4
4
  import { spawn } from 'node:child_process';
5
- import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
6
5
 
7
6
  const environments = new WeakMap();
8
7
  export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
@@ -215,34 +214,25 @@ export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } =
215
214
  if (signal?.aborted) abort();
216
215
  });
217
216
  }
218
- export function compareVersions(a, b) {
219
- const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
220
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
221
- return 0;
222
- }
223
- /** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
224
- export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
225
- const platform = context?.platform;
226
- const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
227
- if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
217
+ /** Runs `<cli> --version` for reporting only; keeps only the parsed version, never the raw output. */
218
+ export async function probeCliVersion(context, { signal, timeoutMs = 10000 } = {}) {
219
+ const result = (version, reason) => ({ version, ...(reason ? { reason } : {}) });
220
+ if (!environments.has(context) || signal?.aborted) return result(null, 'cli_execution_error');
228
221
  return new Promise(resolve => {
229
222
  let child, output = '', overflow = false, done = false;
230
223
  const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
231
- const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
232
- const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
224
+ const abort = () => { child?.kill(); finish(result(null, 'cli_execution_error')); };
225
+ const timer = setTimeout(() => { child?.kill(); finish(result(null, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
233
226
  signal?.addEventListener('abort', abort, { once: true });
234
227
  try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
235
- catch { finish(result(null, false, 'cli_execution_error')); return; }
228
+ catch { finish(result(null, 'cli_execution_error')); return; }
236
229
  child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
237
230
  child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
238
- child.on('error', () => finish(result(null, false, 'cli_execution_error')));
231
+ child.on('error', () => finish(result(null, 'cli_execution_error')));
239
232
  child.on('close', (code, exitSignal) => {
240
- if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
233
+ if (exitSignal || code !== 0 || overflow) return finish(result(null, 'cli_execution_error'));
241
234
  const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
242
- if (!version) return finish(result(null, false, 'version_unparsed'));
243
- const range = policy?.supportedVersions?.[platform];
244
- const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
245
- finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
235
+ finish(version ? result(version) : result(null, 'version_unparsed'));
246
236
  });
247
237
  });
248
238
  }