@yunhozz/arc 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/MANIFEST.sha256 +152 -155
  2. package/README.md +101 -35
  3. package/claude/agents/arc-implementer.md +7 -7
  4. package/claude/agents/arc-planner.md +5 -5
  5. package/claude/agents/arc-reviewer.md +6 -6
  6. package/claude/agents/arc-scouter.md +5 -5
  7. package/claude/agents/{arc-qa.md → arc-tester.md} +10 -10
  8. package/claude/skill/SKILL.md +7 -7
  9. package/claude/skill/models.toml +8 -8
  10. package/claude/skill/references/arc-visual-companion.md +2 -2
  11. package/claude/skill/references/commit.md +3 -3
  12. package/claude/skill/references/coordination.md +21 -25
  13. package/claude/skill/references/git-recovery.md +3 -1
  14. package/claude/skill/references/handoff-prep.md +3 -3
  15. package/claude/skill/references/handoff.md +16 -14
  16. package/claude/skill/references/limits.md +2 -2
  17. package/claude/skill/references/planning.md +12 -10
  18. package/claude/skill/references/verification.md +66 -39
  19. package/claude/skill/references/worktree-creation.md +2 -0
  20. package/claude/skill/scripts/model_config.py +25 -9
  21. package/codex/agents/arc-implementer.toml +7 -7
  22. package/codex/agents/arc-planner.toml +6 -6
  23. package/codex/agents/arc-reviewer.toml +7 -7
  24. package/codex/agents/arc-scouter.toml +6 -6
  25. package/codex/agents/{arc-qa.toml → arc-tester.toml} +10 -10
  26. package/codex/skill/SKILL.md +8 -8
  27. package/codex/skill/models.toml +8 -8
  28. package/codex/skill/references/arc-visual-companion.md +3 -3
  29. package/codex/skill/references/commit.md +4 -4
  30. package/codex/skill/references/coordination.md +20 -24
  31. package/codex/skill/references/git-recovery.md +2 -0
  32. package/codex/skill/references/handoff-prep.md +4 -4
  33. package/codex/skill/references/handoff.md +17 -15
  34. package/codex/skill/references/limits.md +2 -2
  35. package/codex/skill/references/planning.md +13 -11
  36. package/codex/skill/references/verification.md +67 -40
  37. package/codex/skill/references/worktree-creation.md +2 -0
  38. package/codex/skill/scripts/model_config.py +28 -15
  39. package/gemini/agents/arc-implementer.md +8 -8
  40. package/gemini/agents/arc-planner.md +6 -6
  41. package/gemini/agents/arc-reviewer.md +6 -6
  42. package/gemini/agents/arc-scouter.md +6 -6
  43. package/gemini/agents/{arc-qa.md → arc-tester.md} +11 -11
  44. package/gemini/skill/SKILL.md +7 -7
  45. package/gemini/skill/models.toml +7 -7
  46. package/gemini/skill/references/arc-visual-companion.md +2 -2
  47. package/gemini/skill/references/commit.md +3 -3
  48. package/gemini/skill/references/coordination.md +21 -25
  49. package/gemini/skill/references/git-recovery.md +3 -1
  50. package/gemini/skill/references/handoff-prep.md +3 -3
  51. package/gemini/skill/references/handoff.md +16 -14
  52. package/gemini/skill/references/limits.md +2 -2
  53. package/gemini/skill/references/planning.md +12 -10
  54. package/gemini/skill/references/verification.md +66 -39
  55. package/gemini/skill/references/worktree-creation.md +2 -0
  56. package/grok/agents/arc-implementer.md +7 -7
  57. package/grok/agents/arc-planner.md +5 -5
  58. package/grok/agents/arc-reviewer.md +6 -6
  59. package/grok/agents/arc-scouter.md +5 -5
  60. package/grok/agents/{arc-qa.md → arc-tester.md} +10 -10
  61. package/grok/skill/SKILL.md +7 -7
  62. package/grok/skill/models.toml +2 -2
  63. package/grok/skill/references/arc-visual-companion.md +2 -2
  64. package/grok/skill/references/commit.md +3 -3
  65. package/grok/skill/references/coordination.md +21 -25
  66. package/grok/skill/references/git-recovery.md +3 -1
  67. package/grok/skill/references/handoff-prep.md +3 -3
  68. package/grok/skill/references/handoff.md +16 -14
  69. package/grok/skill/references/limits.md +2 -2
  70. package/grok/skill/references/planning.md +12 -10
  71. package/grok/skill/references/verification.md +66 -39
  72. package/grok/skill/references/worktree-creation.md +2 -0
  73. package/lib/installer/install-mode.mjs +4 -2
  74. package/lib/installer/install.mjs +4 -3
  75. package/lib/installer/language.mjs +1 -1
  76. package/lib/installer/legacy-profiles.mjs +51 -0
  77. package/lib/installer/manifest.mjs +1 -1
  78. package/lib/installer/plan.mjs +5 -3
  79. package/lib/installer/preset.mjs +2 -2
  80. package/lib/installer/role-routing.mjs +49 -18
  81. package/lib/installer/runtime-assets.mjs +2 -5
  82. package/lib/installer/targets.mjs +4 -2
  83. package/lib/installer/transaction.mjs +35 -4
  84. package/lib/installer/uninstall.mjs +13 -10
  85. package/lib/installer/upgrade-state.mjs +13 -1
  86. package/lib/management/operations.mjs +13 -13
  87. package/lib/management/reapply.mjs +5 -3
  88. package/lib/models/config.mjs +25 -7
  89. package/lib/models/profiles.mjs +1 -1
  90. package/lib/platforms/formats/gemini-markdown.mjs +3 -3
  91. package/lib/platforms/formats/grok-markdown.mjs +3 -3
  92. package/lib/platforms/formats/markdown.mjs +2 -2
  93. package/lib/platforms/formats/toml.mjs +2 -2
  94. package/lib/policy/placement.mjs +1 -1
  95. package/lib/policy/render.mjs +3 -3
  96. package/lib/policy/role-policy.json +28 -28
  97. package/lib/prompts/agent-fragments.json +24 -24
  98. package/lib/prompts/render.mjs +9 -9
  99. package/lib/runtime/acceptance.mjs +4 -3
  100. package/lib/runtime/bootstrap.mjs +3 -1
  101. package/lib/runtime/command.mjs +27 -1
  102. package/lib/runtime/cooperative-schema.mjs +16 -5
  103. package/lib/runtime/cooperative.mjs +6 -3
  104. package/lib/runtime/evaluate.mjs +10 -7
  105. package/lib/runtime/handoff-record.mjs +58 -0
  106. package/lib/runtime/identity.mjs +10 -7
  107. package/lib/runtime/local-cli.mjs +9 -2
  108. package/lib/runtime/operations.mjs +41 -3
  109. package/lib/runtime/role-bridge-args.mjs +5 -5
  110. package/lib/runtime/role-bridge.mjs +10 -2
  111. package/lib/runtime/role-dispatch-policy.mjs +11 -6
  112. package/lib/runtime/role-dispatch-store.mjs +3 -0
  113. package/lib/runtime/role-observe.mjs +5 -5
  114. package/lib/runtime/role-routing-config.mjs +20 -6
  115. package/lib/runtime/role-routing.mjs +4 -3
  116. package/lib/runtime/schema.mjs +8 -5
  117. package/lib/runtime/scope.mjs +1 -1
  118. package/lib/runtime/store.mjs +2 -2
  119. package/lib/runtime/verification.mjs +15 -7
  120. package/lib/tui/app.mjs +36 -11
  121. package/lib/tui/interface.mjs +2 -2
  122. package/lib/tui/render.mjs +4 -2
  123. package/lib/tui/setup.mjs +1 -1
  124. package/lib/tui/terminal.mjs +5 -3
  125. package/lib/watch/brief.mjs +44 -0
  126. package/lib/watch/dispatch.mjs +44 -6
  127. package/lib/watch/index.mjs +107 -22
  128. package/lib/watch/labels.mjs +2 -1
  129. package/lib/watch/markdown.mjs +42 -9
  130. package/lib/watch/model.mjs +3 -2
  131. package/lib/watch/render.mjs +5 -4
  132. package/lib/watch/scope.mjs +125 -0
  133. package/lib/watch/watcher.mjs +149 -82
  134. package/lib/watch/worktree-menu.mjs +64 -0
  135. package/package.json +1 -1
  136. package/shared/skill/runtime/acceptance.mjs +4 -3
  137. package/shared/skill/runtime/bootstrap.mjs +3 -1
  138. package/shared/skill/runtime/command.mjs +27 -1
  139. package/shared/skill/runtime/cooperative-schema.mjs +16 -5
  140. package/shared/skill/runtime/cooperative.mjs +6 -3
  141. package/shared/skill/runtime/evaluate.mjs +10 -7
  142. package/shared/skill/runtime/handoff-record.mjs +58 -0
  143. package/shared/skill/runtime/identity.mjs +10 -7
  144. package/shared/skill/runtime/local-cli.mjs +9 -2
  145. package/shared/skill/runtime/operations.mjs +41 -3
  146. package/shared/skill/runtime/role-bridge-args.mjs +5 -5
  147. package/shared/skill/runtime/role-bridge.mjs +10 -2
  148. package/shared/skill/runtime/role-dispatch-policy.mjs +11 -6
  149. package/shared/skill/runtime/role-dispatch-store.mjs +3 -0
  150. package/shared/skill/runtime/role-observe.mjs +5 -5
  151. package/shared/skill/runtime/role-policy.json +28 -28
  152. package/shared/skill/runtime/role-routing-config.mjs +20 -6
  153. package/shared/skill/runtime/role-routing.mjs +4 -3
  154. package/shared/skill/runtime/schema.mjs +8 -5
  155. package/shared/skill/runtime/scope.mjs +1 -1
  156. package/shared/skill/runtime/store.mjs +2 -2
  157. package/shared/skill/runtime/verification.mjs +15 -7
  158. package/lib/runtime/final-verify.mjs +0 -2158
  159. package/lib/runtime/node-test-reporter.mjs +0 -81
  160. package/lib/runtime/test-results.mjs +0 -736
  161. package/lib/runtime/verify-cli.mjs +0 -60
  162. package/shared/skill/runtime/final-verify.mjs +0 -2158
  163. package/shared/skill/runtime/node-test-reporter.mjs +0 -81
  164. package/shared/skill/runtime/test-results.mjs +0 -736
  165. package/shared/skill/runtime/verify-cli.mjs +0 -60
@@ -1,736 +0,0 @@
1
- import {posix} from 'node:path';
2
-
3
- export const PARSER_SCHEMA_VERSION = 3;
4
- export const REPORT_SCHEMA_VERSION = 1;
5
-
6
- export function normalizeTestFile(raw, worktreeRealpath) {
7
- if (typeof raw !== 'string' || !raw || raw.includes('\0')) return '-';
8
- let value = raw;
9
- if (/^file:\/\//i.test(value)) {
10
- try {
11
- const url = new URL(value);
12
- value = (url.hostname ? '//' + url.hostname : '') + decodeURIComponent(url.pathname);
13
- } catch {
14
- return '-';
15
- }
16
- }
17
- if (value.includes('\0')) return '-';
18
-
19
- const posixPath = value => posix.normalize(value.replaceAll('\\', '/').replace(/^\/(?=[a-z]:\/)/i, ''));
20
- let file = posixPath(value);
21
- if (posix.isAbsolute(file) || /^[a-z]:\//i.test(file)) {
22
- const root = posixPath(worktreeRealpath).replace(/\/?$/, '/');
23
- if (!file.startsWith(root)) return '-';
24
- file = file.slice(root.length);
25
- }
26
- return !file || file === '.' || file === '..' || file.startsWith('../') ? '-' : file;
27
- }
28
-
29
- function worktreeNamePattern(paths) {
30
- const alternatives = [...new Set(paths.filter(Boolean))]
31
- .sort((a, b) => b.length - a.length)
32
- .map(path => path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
33
- if (!alternatives.length) return null;
34
- const before = "(?:^|(?<=[\\s\"'`=(:,\\[{])|(?<=\\bfile://))";
35
- return new RegExp(before + '(?:' + alternatives.join('|') + ')', 'g');
36
- }
37
-
38
- const pathClosingDelimiters = {'(': ')', '[': ']', '{': '}'};
39
-
40
- function isWorktreePathEnd(value, start, end) {
41
- const next = value[end];
42
- if (next === '/' || next === '\\') return true;
43
-
44
- const prefix = value.slice(0, start).replace(/file:\/\/$/, '');
45
- const preceding = prefix.at(-1);
46
- if (preceding && "\"'`".includes(preceding)) return next === preceding;
47
- if (next === undefined || /\s/.test(next)) return true;
48
-
49
- const opening = /([([{])[^()[\]{}]*$/.exec(prefix)?.[1];
50
- return opening !== undefined && (next === pathClosingDelimiters[opening] || next === ',');
51
- }
52
-
53
- function worktreeNameParts(value, pattern, paths) {
54
- if (!pattern) return null;
55
- const parts = [];
56
- let offset = 0;
57
- for (const match of value.matchAll(pattern)) {
58
- const start = match.index;
59
- const end = start + match[0].length;
60
- if (!isWorktreePathEnd(value, start, end)) continue;
61
- parts.push(value.slice(offset, start), paths.indexOf(match[0]));
62
- offset = end;
63
- }
64
- if (!parts.length) return null;
65
- parts.push(value.slice(offset));
66
- return parts;
67
- }
68
-
69
- function normalizedWorktreeName(value, parts) {
70
- return parts?.map(part => typeof part === 'number' ? '{worktree}' : part).join('') ?? value;
71
- }
72
-
73
- const testNameKey = (file, suite, name) => JSON.stringify([file, suite, name]);
74
- const suiteElements = suite => Array.isArray(suite) ? suite : suite ? [suite] : [];
75
-
76
- export function assignTestIds(tests, ctx) {
77
- const worktreePaths = [ctx?.worktree, ctx?.worktreeAlias];
78
- const pattern = worktreeNamePattern(worktreePaths);
79
- const getParts = value => worktreeNameParts(value, pattern, worktreePaths);
80
- const ordinals = new Map();
81
- return tests.map(({file, suite, name, status, durationMs, originalSuiteParts, isolationNameParts}) => {
82
- const suiteParts = originalSuiteParts ?? suiteElements(suite).map(value => getParts(value) ?? value);
83
- suite = suiteParts.map(part => Array.isArray(part) ? normalizedWorktreeName('', part) : part).join('/');
84
- // Preserve element boundaries and path spellings that the flattened suite cannot represent.
85
- const preserveSuiteParts = suiteParts.length > 1 || Array.isArray(suiteParts[0]);
86
- // Keep each original path spelling available to isolate selectors without storing run-specific paths.
87
- const parts = getParts(name);
88
- name = normalizedWorktreeName(name, parts);
89
- isolationNameParts = parts ?? isolationNameParts;
90
- const key = testNameKey(file, suite, name);
91
- const k = (ordinals.get(key) ?? 0) + 1;
92
- ordinals.set(key, k);
93
- return {testId: file + '::' + suite + '::' + name + '#' + k, file, suite, name, k, status, durationMs,
94
- ...(preserveSuiteParts ? {originalSuiteParts: suiteParts} : {}),
95
- ...(isolationNameParts ? {isolationNameParts} : {})};
96
- });
97
- }
98
-
99
- export function originalTestSpelling({suite, name, originalSuiteParts, isolationNameParts}) {
100
- // The parts record the original spelling without keeping absolute worktree paths.
101
- return JSON.stringify([originalSuiteParts ?? suiteElements(suite), isolationNameParts ?? name]);
102
- }
103
-
104
- function findNormalizedNameCollisions(tests) {
105
- const originalSpellings = new Map();
106
- const collisions = new Map();
107
- for (const test of tests) {
108
- const {file, suite, name} = test;
109
- const key = testNameKey(file, suite, name);
110
- const spelling = originalTestSpelling(test);
111
- if (!originalSpellings.has(key)) originalSpellings.set(key, spelling);
112
- else if (originalSpellings.get(key) !== spelling) collisions.set(key, {file, suite, name});
113
- }
114
- return [...collisions.values()];
115
- }
116
-
117
- function fileFromName(name, ctx) {
118
- if (typeof name !== 'string' || !/[\\/]|[^.]\.[^./\\]+$/.test(name)) return '-';
119
- return existingTestFile(name, ctx);
120
- }
121
-
122
- function existingTestFile(raw, ctx) {
123
- const file = normalizeTestFile(raw, ctx.worktree);
124
- return file !== '-' && ctx.fileExists(file) ? file : '-';
125
- }
126
-
127
- function symlinkedTestFile(raw, ctx) {
128
- const file = normalizeTestFile(raw, ctx.worktree);
129
- return file !== '-' && ctx.fileIsSymlink?.(file);
130
- }
131
-
132
- function duration(value, multiplier = 1) {
133
- if (value == null || !String(value).trim()) return null;
134
- const ms = Number(value) * multiplier;
135
- return Number.isFinite(ms) && ms >= 0 ? ms : null;
136
- }
137
-
138
- const commandIssue = reason => ({scope: 'command', reason});
139
- const fileIssue = path => ({scope: 'file', path, reason: 'file_error'});
140
-
141
- const xmlEntities = Object.freeze({amp: '&', lt: '<', gt: '>', quot: '"', apos: "'"});
142
- const invalidXmlChar = /[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u;
143
-
144
- function malformedXml() {
145
- throw new SyntaxError('Malformed JUnit XML');
146
- }
147
-
148
- function decodeXml(value) {
149
- if (invalidXmlChar.test(value)) malformedXml();
150
- return value.replace(/&(?:([^&<;\s]+);)?/g, (_, entity) => {
151
- if (Object.hasOwn(xmlEntities, entity)) return xmlEntities[entity];
152
- const numeric = /^#(?:(\d+)|x([\da-fA-F]+))$/.exec(entity ?? '');
153
- if (!numeric) malformedXml();
154
- const point = numeric[1] ? Number(numeric[1]) : Number.parseInt(numeric[2], 16);
155
- if (point > 0x10ffff) malformedXml();
156
- const decoded = String.fromCodePoint(point);
157
- if (invalidXmlChar.test(decoded)) malformedXml();
158
- return decoded;
159
- });
160
- }
161
-
162
- function xmlAttributes(text) {
163
- const attrs = Object.create(null);
164
- const attrPattern = /\s+([A-Za-z_:][\w.:-]*)\s*=\s*(?:"([^"<]*)"|'([^'<]*)')/y;
165
- while (attrPattern.lastIndex < text.length) {
166
- const start = attrPattern.lastIndex;
167
- const attr = attrPattern.exec(text);
168
- if (!attr) {
169
- if (text.slice(start).trim()) malformedXml();
170
- break;
171
- }
172
- if (Object.hasOwn(attrs, attr[1])) malformedXml();
173
- attrs[attr[1]] = decodeXml((attr[2] ?? attr[3]).replace(/\r\n|[\t\r\n]/g, ' '));
174
- }
175
- return attrs;
176
- }
177
-
178
- export function parseJunitXml(text, ctx) {
179
- const tests = [];
180
- const incomplete = [];
181
- const stack = [];
182
- let rootSeen = false;
183
- let cursor = text.charCodeAt(0) === 0xfeff ? 1 : 0;
184
- const tagPattern = /<(\/?)([A-Za-z_:][\w.:-]*)((?:"[^"]*"|'[^']*'|[^<>"'])*)>/y;
185
-
186
- function closeElement() {
187
- const node = stack.pop();
188
- if (node.tag === 'testsuite' && !node.hasTestcase && node.hasError) incomplete.push(fileIssue(node.file));
189
- }
190
-
191
- try {
192
- while (cursor < text.length) {
193
- if (text[cursor] !== '<') {
194
- const next = text.indexOf('<', cursor);
195
- const content = text.slice(cursor, next === -1 ? text.length : next);
196
- if ((!stack.length && content.trim()) || content.includes(']]>')) malformedXml();
197
- decodeXml(content);
198
- cursor += content.length;
199
- continue;
200
- }
201
-
202
- const opener = ['<!--', '<?', '<![CDATA['].find(prefix => text.startsWith(prefix, cursor));
203
- if (opener) {
204
- const closer = {'<!--': '-->', '<?': '?>', '<![CDATA[': ']]>'}[opener];
205
- const start = cursor + opener.length;
206
- const end = text.indexOf(closer, start);
207
- if (end === -1 || (opener === '<![CDATA[' && !stack.length) ||
208
- (opener === '<!--' && text.slice(start, end).includes('--'))) malformedXml();
209
- if (invalidXmlChar.test(text.slice(start, end))) malformedXml();
210
- cursor = end + closer.length;
211
- continue;
212
- }
213
-
214
- // Declarations other than comments and CDATA (including DOCTYPE) have no valid tag token.
215
- tagPattern.lastIndex = cursor;
216
- const token = tagPattern.exec(text);
217
- if (!token) malformedXml();
218
- cursor = tagPattern.lastIndex;
219
- const [, closing, tag, rawAttrs] = token;
220
- const parent = stack.at(-1);
221
- if (closing) {
222
- if (tag !== parent?.tag || rawAttrs.trim()) malformedXml();
223
- closeElement();
224
- continue;
225
- }
226
- if (!parent) {
227
- if (rootSeen || !['testsuites', 'testsuite'].includes(tag)) malformedXml();
228
- rootSeen = true;
229
- }
230
-
231
- const selfClosing = rawAttrs.endsWith('/');
232
- const attrs = xmlAttributes(selfClosing ? rawAttrs.slice(0, -1) : rawAttrs);
233
- const node = {tag, suite: parent?.suite};
234
- if (tag === 'testsuite') {
235
- const inferred = fileFromName(attrs.name, ctx);
236
- node.parentSuite = node.suite;
237
- node.suite = node;
238
- node.names = [...(node.parentSuite?.names ?? []), ...(attrs.name ? [attrs.name] : [])];
239
- node.explicitFile = attrs.file || node.parentSuite?.explicitFile;
240
- node.inferredFile = inferred === '-' ? node.parentSuite?.inferredFile : inferred;
241
- node.file = node.explicitFile
242
- ? normalizeTestFile(node.explicitFile, ctx.worktree) : node.inferredFile ?? '-';
243
- node.hasError = Number(attrs.errors) > 0;
244
- } else if (tag === 'testcase' && ['testsuite', 'testsuites'].includes(parent?.tag)) {
245
- const {suite} = node;
246
- const explicitFile = attrs.file || suite?.explicitFile;
247
- node.test = {
248
- file: explicitFile ? normalizeTestFile(explicitFile, ctx.worktree) : suite?.inferredFile ?? '-',
249
- suite: [...(suite?.names ?? []), ...(attrs.classname ? [attrs.classname] : [])],
250
- name: attrs.name ?? '',
251
- status: 'passed',
252
- durationMs: duration(attrs.time, 1000)
253
- };
254
- tests.push(node.test);
255
- for (let ancestor = suite; ancestor; ancestor = ancestor.parentSuite) ancestor.hasTestcase = true;
256
- } else if (tag === 'error' && parent?.tag === 'testsuite') {
257
- parent.hasError = true;
258
- } else if (parent?.test) {
259
- if (tag === 'failure' || tag === 'error') parent.test.status = 'failed';
260
- if (tag === 'skipped' && parent.test.status !== 'failed') parent.test.status = 'skipped';
261
- }
262
- stack.push(node);
263
- if (selfClosing) closeElement();
264
- }
265
- if (stack.length || !rootSeen) malformedXml();
266
- } catch (error) {
267
- if (!(error instanceof SyntaxError)) throw error;
268
- return {tests: [], incomplete: [commandIssue('parse_error')], unmappedStatusCount: 0};
269
- }
270
- return {tests: assignTestIds(tests, ctx), incomplete, unmappedStatusCount: 0};
271
- }
272
-
273
- function tapLocation(raw) {
274
- const quoted = /^(['"])(.*)\1$/.exec(raw);
275
- let value = raw;
276
- if (quoted?.[1] === "'") value = quoted[2].replaceAll("''", "'");
277
- if (quoted?.[1] === '"') {
278
- try {
279
- value = JSON.parse(raw);
280
- } catch {
281
- value = quoted[2];
282
- }
283
- }
284
- const location = /^(.*):(\d+):(\d+)$/.exec(value);
285
- if (!location) return null;
286
- return {path: location[1], atFileStart: location[2] === '1' && location[3] === '1'};
287
- }
288
-
289
- const tapLevel = () => ({points: [], plan: null, child: null});
290
-
291
- export function parseTap(text, ctx) {
292
- const root = tapLevel();
293
- const levels = [root];
294
- let invalid = false;
295
- let diagnostic = null;
296
-
297
- for (const line of text.split(/\r?\n/)) {
298
- const content = line.trimStart();
299
- if (diagnostic) {
300
- if (content === '...') diagnostic = null;
301
- else if (content.startsWith('duration_ms:')) diagnostic.durationMs = duration(content.slice(12).trim());
302
- else if (content.startsWith('location:')) diagnostic.location = tapLocation(content.slice(9).trim());
303
- else if (/^type:\s*(?:suite|'suite'|"suite")\s*$/.test(content)) diagnostic.isSuite = true;
304
- continue;
305
- }
306
-
307
- if (!content || /^TAP version (?:13|14)\s*$/.test(content)) continue;
308
- if (/^Bail out!/i.test(content)) {
309
- invalid = true;
310
- break;
311
- }
312
- const indent = line.length - content.length;
313
- const depth = Math.floor(indent / 4);
314
- if (depth > levels.length) {
315
- invalid = true;
316
- continue;
317
- }
318
- if (depth === levels.length) {
319
- const parent = levels.at(-1);
320
- parent.child ??= tapLevel();
321
- levels.push(parent.child);
322
- } else {
323
- levels.length = depth + 1;
324
- }
325
- const level = levels[depth];
326
-
327
- if (content === '---') {
328
- diagnostic = level.points.at(-1) ?? null;
329
- continue;
330
- }
331
- const subtest = /^# Subtest:\s*(.*)$/.exec(content);
332
- if (subtest) {
333
- level.child ??= tapLevel();
334
- level.child.name = subtest[1];
335
- continue;
336
- }
337
- const plan = /^1\.\.(\d+)(?:\s+.*)?$/.exec(content);
338
- if (plan) {
339
- if (level.plan !== null) invalid = true;
340
- level.plan = Number(plan[1]);
341
- continue;
342
- }
343
- const point = /^(not ok|ok)(?=\s|$)(?:[ \t]+(\d+)(?=[ \t]|$))?[ \t]*(?:-[ \t]+)?(.*)$/.exec(content);
344
- if (!point) continue;
345
-
346
- const description = point[3].trim();
347
- const directive = /(?:^|\s+)#\s*(?:skip|todo)(?=\s|$)/i.exec(description);
348
- const name = (directive ? description.slice(0, directive.index) : description).trim();
349
- level.points.push({
350
- name: name || level.child?.name || '',
351
- status: directive ? 'skipped' : point[1] === 'ok' ? 'passed' : 'failed',
352
- durationMs: null,
353
- child: level.child
354
- });
355
- level.child = null;
356
- }
357
-
358
- const tests = [];
359
- const incomplete = [];
360
- function visit(level, inheritedFile, suite, topLevel) {
361
- if ((level.plan !== null && level.plan !== level.points.length) ||
362
- (level.child && (level.child.points.length || level.child.plan !== null))) invalid = true;
363
-
364
- for (const point of level.points) {
365
- const headerFile = topLevel ? fileFromName(point.name, ctx) : '-';
366
- const located = existingTestFile(point.location?.path, ctx);
367
- const file = located !== '-' ? located : headerFile !== '-' ? headerFile : inheritedFile;
368
- const hasChildren = Boolean(point.child?.points.length);
369
- if (hasChildren) {
370
- const childSuite = headerFile === '-' && point.name ? [...suite, point.name] : suite;
371
- visit(point.child, file, childSuite, false);
372
- } else if (point.child) {
373
- visit(point.child, file, suite, false);
374
- }
375
- if (hasChildren) continue;
376
-
377
- if (point.status === 'failed') {
378
- const namedFile = existingTestFile(point.name, ctx);
379
- if ((namedFile === '-' && symlinkedTestFile(point.name, ctx)) ||
380
- (located === '-' && symlinkedTestFile(point.location?.path, ctx))) {
381
- incomplete.push(commandIssue('symlinked_test_file'));
382
- continue;
383
- }
384
- if (namedFile !== '-') {
385
- incomplete.push(fileIssue(namedFile));
386
- continue;
387
- }
388
- // Node attaches source locations to ordinary failures too. Its top-level file point starts at 1:1.
389
- if (!point.isSuite && topLevel && point.location?.atFileStart && located !== '-') {
390
- incomplete.push(fileIssue(located));
391
- continue;
392
- }
393
- }
394
- if (!point.isSuite) tests.push({file, suite, name: point.name, status: point.status, durationMs: point.durationMs});
395
- }
396
- }
397
-
398
- visit(root, '-', [], true);
399
- if (invalid || diagnostic) incomplete.push(commandIssue('parse_error'));
400
- if (root.plan === null) incomplete.push(commandIssue('plan_missing'));
401
- return {tests: assignTestIds(tests, ctx), incomplete, unmappedStatusCount: 0};
402
- }
403
-
404
- export function validateRegexSpec(results) {
405
- try {
406
- if (typeof results?.pattern !== 'string') throw new TypeError('pattern must be a string');
407
- const pattern = new RegExp(results.pattern);
408
- // The empty alternative exposes the capture names even when the supplied pattern never matches "".
409
- const groups = new RegExp('(?:' + results.pattern + ')|').exec('').groups;
410
- if (!groups || !Object.hasOwn(groups, 'status') || !Object.hasOwn(groups, 'name')) {
411
- throw new SyntaxError('pattern requires named groups status and name');
412
- }
413
- return pattern;
414
- } catch (error) {
415
- throw Object.assign(new Error('Invalid regex results pattern: ' + error.message), {code: 'invalid_request'});
416
- }
417
- }
418
-
419
- export function parseRegex(text, ctx, results) {
420
- const pattern = validateRegexSpec(results);
421
- const statuses = new Map();
422
- for (const [field, status] of [['pass', 'passed'], ['fail', 'failed'], ['skip', 'skipped'], ['fileError', 'file_error']]) {
423
- for (const value of results.statusMap[field] ?? []) statuses.set(value, status);
424
- }
425
- const tests = [];
426
- const incomplete = [];
427
- let unmappedStatusCount = 0;
428
- for (const line of text.split(/\r?\n/)) {
429
- const match = pattern.exec(line);
430
- if (!match) continue;
431
- const group = match.groups;
432
- const status = statuses.get(group.status);
433
- if (!status) {
434
- unmappedStatusCount++;
435
- continue;
436
- }
437
- const file = normalizeTestFile(group.file, ctx.worktree);
438
- if (status === 'file_error') incomplete.push(fileIssue(file));
439
- else tests.push({file, suite: group.suite ?? '', name: group.name ?? '', status, durationMs: duration(group.duration)});
440
- }
441
- return {tests: assignTestIds(tests, ctx), incomplete, unmappedStatusCount};
442
- }
443
-
444
- function countTests(tests) {
445
- const counts = {total: tests.length, passed: 0, failed: 0, skipped: 0};
446
- for (const {status} of tests) counts[status]++;
447
- return counts;
448
- }
449
-
450
- export function summarizeCommand({format, results, streams, resultFiles, exit, truncated, ctx, allowEmpty = false}) {
451
- const {code: exitCode, signal = null, timedOut = false} = exit;
452
- const badExit = exitCode !== 0 || Boolean(signal) || timedOut;
453
- const tests = [];
454
- const incomplete = [];
455
- let unmappedStatusCount = 0;
456
- const summary = {format, exitCode, signal, timedOut};
457
-
458
- if (format === 'none') {
459
- return {...summary, tests, counts: countTests(tests), incomplete, unmappedStatusCount,
460
- status: badExit ? 'fail' : 'pass'};
461
- }
462
-
463
- let texts;
464
- if (results.stream === 'both') texts = [(streams.stdout ?? '') + '\n' + (streams.stderr ?? '')];
465
- else if (results.stream) texts = [streams[results.stream] ?? ''];
466
- else {
467
- texts = (resultFiles ?? []).map(({text}) => text);
468
- if (!texts.length) incomplete.push(commandIssue('results_missing'));
469
- }
470
-
471
- const parse = {'junit-xml': parseJunitXml, tap: parseTap, regex: parseRegex}[format];
472
- for (const text of texts) {
473
- let parsed;
474
- try {
475
- parsed = parse(text, ctx, results);
476
- } catch {
477
- incomplete.push(commandIssue('parse_error'));
478
- continue;
479
- }
480
- for (const item of parsed.tests) tests.push(item);
481
- for (const issue of parsed.incomplete) incomplete.push(issue);
482
- unmappedStatusCount += parsed.unmappedStatusCount;
483
- }
484
- const counts = countTests(tests);
485
- if (timedOut) incomplete.push(commandIssue('timeout'));
486
- else if (signal) incomplete.push(commandIssue('signal'));
487
- if (badExit && !counts.failed) incomplete.push(commandIssue('unattributed'));
488
- if (!counts.total && !allowEmpty) incomplete.push(commandIssue('no_results'));
489
- if (truncated) incomplete.push(commandIssue('output_truncated'));
490
-
491
- const uniqueIssues = new Map(incomplete.map(issue => [JSON.stringify([issue.scope, issue.path, issue.reason]), issue]));
492
- const identifiedTests = assignTestIds(tests);
493
- return {...summary, tests: identifiedTests, counts, incomplete: [...uniqueIssues.values()], unmappedStatusCount,
494
- normalizedNameCollisions: findNormalizedNameCollisions(identifiedTests)};
495
- }
496
-
497
- export function isolationPasses(attempts) {
498
- if (attempts.some(({status}) => status === 'passed')) return 'yes';
499
- return attempts.some(({status}) => status === 'failed') ? 'no' : null;
500
- }
501
-
502
- function incompleteFor(summary, file) {
503
- return summary.incomplete.find(issue => issue.scope === 'command' || issue.path === file);
504
- }
505
-
506
- function testKey(commandId, testId) {
507
- return JSON.stringify([commandId, testId]);
508
- }
509
-
510
- function intermittentTests(base, head, history, reruns) {
511
- const evidence = new Map();
512
- const failures = new Map([base, head].map(run => [run.runId, new Set(run.commands.flatMap(({id, summary}) =>
513
- summary.tests.filter(test => test.status === 'failed').map(test => testKey(id, test.testId))))]));
514
-
515
- function evidenceFor(commandId, testId) {
516
- const key = testKey(commandId, testId);
517
- if (!evidence.has(key)) evidence.set(key, {commandId, testId, byCacheKey: new Map(), byRun: new Map()});
518
- return evidence.get(key);
519
- }
520
-
521
- for (const {runId, loadClass, commands, cacheKey} of history) {
522
- for (const {id, summary} of commands) {
523
- for (const {testId, status} of summary.tests) {
524
- const {byCacheKey} = evidenceFor(id, testId);
525
- if (!byCacheKey.has(cacheKey)) byCacheKey.set(cacheKey, []);
526
- byCacheKey.get(cacheKey).push({runId, loadClass, status});
527
- }
528
- }
529
- }
530
- for (const {runId = head.runId, commandId, testId, attempts} of reruns) {
531
- const {byRun} = evidenceFor(commandId, testId);
532
- if (!byRun.has(runId)) byRun.set(runId, []);
533
- for (const attempt of attempts) byRun.get(runId).push(attempt);
534
- }
535
-
536
- const candidates = [];
537
- for (const [key, {commandId, testId, byCacheKey, byRun}] of evidence) {
538
- const varyingHistory = [...byCacheKey.values()].filter(rows => new Set(rows.map(row => row.status)).size > 1).flat();
539
- const varyingReruns = [...byRun].some(([runId, attempts]) => {
540
- const statuses = new Set(attempts.map(({status}) => status).filter(status => status === 'passed' || status === 'failed'));
541
- return statuses.size > 1 || failures.get(runId)?.has(key) && statuses.has('passed');
542
- });
543
- if (varyingHistory.length || varyingReruns) {
544
- const attempts = [...byRun.values()].flat();
545
- candidates.push({commandId, testId, history: varyingHistory, reruns: attempts, passesInIsolation: isolationPasses(attempts)});
546
- }
547
- }
548
- return candidates;
549
- }
550
-
551
- export function compareRuns({base, head, history = [], reruns = []}) {
552
- const comparison = {
553
- newFailures: [],
554
- baselineReproduced: [],
555
- baselineNotReproduced: [],
556
- newFailureCandidates: [],
557
- intermittentCandidates: intermittentTests(base, head, history, reruns),
558
- disappearedTests: [],
559
- addedTests: [],
560
- addedFiles: [],
561
- removedFiles: []
562
- };
563
- const baseCommands = new Map(base.commands.map(command => [command.id, command]));
564
- for (const current of head.commands) {
565
- const {id: commandId, summary} = current;
566
- const prior = baseCommands.get(commandId);
567
- const baseFiles = new Set(prior.expandedFiles);
568
- const headFiles = new Set(current.expandedFiles);
569
- for (const path of headFiles) {
570
- if (!baseFiles.has(path)) comparison.addedFiles.push({commandId, path});
571
- }
572
- for (const path of baseFiles) {
573
- if (!headFiles.has(path)) comparison.removedFiles.push({commandId, path});
574
- }
575
-
576
- for (const issue of summary.incomplete) {
577
- comparison.newFailureCandidates.push({commandId, testId: null, reason: issue.reason});
578
- }
579
- if (current.format === 'none') {
580
- if (summary.status === 'fail') comparison.newFailureCandidates.push({commandId, testId: null, reason: 'none_failed'});
581
- continue;
582
- }
583
-
584
- const baseTests = new Map(prior.summary.tests.map(test => [test.testId, test]));
585
- const headTests = new Map(summary.tests.map(test => [test.testId, test]));
586
- const collisionKeys = new Set([prior.summary, summary].flatMap(({normalizedNameCollisions, tests}) =>
587
- (normalizedNameCollisions ?? findNormalizedNameCollisions(tests)).map(({file, suite, name}) =>
588
- testNameKey(file, suite, name))));
589
- for (const [testId, test] of headTests) {
590
- const before = baseTests.get(testId);
591
- const related = {commandId, testId};
592
- const baseIssue = incompleteFor(prior.summary, test.file);
593
- if (baseIssue) {
594
- if (test.status === 'failed') comparison.newFailureCandidates.push({...related, reason: baseIssue.reason});
595
- continue;
596
- }
597
- if (incompleteFor(summary, test.file)) continue;
598
-
599
- if (!before) comparison.addedTests.push(related);
600
- if (test.status === 'failed') {
601
- if (before?.status !== 'failed') comparison.newFailures.push(related);
602
- else if (collisionKeys.has(testNameKey(test.file, test.suite, test.name))) {
603
- comparison.newFailureCandidates.push({...related, reason: 'normalized_name_collision'});
604
- } else comparison.baselineReproduced.push(related);
605
- } else if (test.status === 'passed' && before?.status === 'failed') {
606
- comparison.baselineNotReproduced.push(related);
607
- }
608
- }
609
-
610
- for (const [testId, {file}] of baseTests) {
611
- if (!headTests.has(testId) && !incompleteFor(prior.summary, file) && !incompleteFor(summary, file)) {
612
- comparison.disappearedTests.push({commandId, testId});
613
- }
614
- }
615
- }
616
-
617
- const hasCandidates = comparison.newFailureCandidates.length || comparison.intermittentCandidates.length;
618
- const verdict = comparison.newFailures.length ? 'new-failures' : hasCandidates ? 'candidates' : 'no-new-failures';
619
- return {...comparison, verdict};
620
- }
621
-
622
- function rankTimings(commands, phases, topN) {
623
- const files = [];
624
- const tests = [];
625
- for (const {id: commandId, summary} of commands) {
626
- const fileTimes = new Map();
627
- for (const {file, testId, durationMs} of summary.tests) {
628
- if (!Number.isFinite(durationMs) || durationMs < 0) continue;
629
- tests.push({commandId, testId, durationMs});
630
- if (file !== '-') fileTimes.set(file, (fileTimes.get(file) ?? 0) + durationMs);
631
- }
632
- for (const [file, durationMs] of fileTimes) files.push({commandId, file, durationMs});
633
- }
634
- const timeOrder = (a, b) => b.durationMs - a.durationMs;
635
- return {
636
- files: files.sort(timeOrder).slice(0, topN),
637
- tests: tests.sort(timeOrder).slice(0, topN),
638
- phases: phases.filter(phase => Number.isFinite(phase.ms) && phase.ms >= 0)
639
- .sort((a, b) => b.ms - a.ms).slice(0, topN)
640
- };
641
- }
642
-
643
- function runMetadata({runId, commit, tree, load, cacheHit, reusedFrom = null}) {
644
- return {runId, commit, tree, load, cacheHit, reusedFrom};
645
- }
646
-
647
- function commandReport({expandedFiles, summary}) {
648
- return {
649
- exitCode: summary.exitCode,
650
- wallMs: summary.wallMs ?? null,
651
- tests: summary.counts ?? countTests(summary.tests),
652
- incomplete: summary.incomplete,
653
- expandedFiles
654
- };
655
- }
656
-
657
- function mdValue(value) {
658
- const text = String(value ?? '-').replace(/\r\n|\n|\r/g, ' ');
659
- let fence = String.fromCharCode(96);
660
- for (const match of text.matchAll(/\x60+/g)) {
661
- if (match[0].length >= fence.length) fence = String.fromCharCode(96).repeat(match[0].length + 1);
662
- }
663
- return fence + ' ' + text + ' ' + fence;
664
- }
665
-
666
- function renderReportMd(json, topN) {
667
- const lines = ['# 최종 검증 보고서', '', '판정 ' + mdValue(json.verdict)];
668
- function section(title, rows) {
669
- lines.push('', '## ' + title, '');
670
- if (!rows.length) lines.push('- 없음');
671
- for (const row of rows) lines.push('- ' + row);
672
- }
673
-
674
- const identify = entry => [entry.commandId, entry.testId].filter(Boolean).map(mdValue).join(' / ');
675
- const {tmpdir, envNames, ...conditions} = json.conditions;
676
- section('기록 조건', [
677
- '기준선 ' + mdValue(json.base.runId) + ' / ' + mdValue(json.base.commit),
678
- 'head ' + mdValue(json.head.runId) + ' / ' + mdValue(json.head.commit),
679
- ...Object.entries(conditions).map(([key, value]) => key + ' ' + mdValue(value)),
680
- 'tmpdir ' + mdValue(tmpdir.realpath) + ' / ' + mdValue(tmpdir.fsType),
681
- 'envNames ' + envNames.map(mdValue).join(', ')
682
- ]);
683
- const totals = ({tests, wallMs}) => {
684
- const wall = wallMs == null ? '-' : wallMs + ' ms';
685
- return '총 ' + tests.total + '건, 통과 ' + tests.passed + ', 실패 ' + tests.failed +
686
- ', 건너뜀 ' + tests.skipped + ', 실행 시간 ' + wall;
687
- };
688
- section('명령별 합계 및 실행 시간', json.commands.map(({id, base, head}) =>
689
- mdValue(id) + ' / 기준선 ' + totals(base) + ' / head ' + totals(head)));
690
- section('새 실패', json.newFailures.map(identify));
691
- section('기준선 재현', json.baselineReproduced.map(identify));
692
- section('기준선 미재현', json.baselineNotReproduced.map(identify));
693
- section('간헐 후보', json.intermittentCandidates.map(entry => {
694
- const runs = entry.history.map(({runId, loadClass, status}) => [runId, loadClass, status].map(mdValue).join(' / '));
695
- const attempts = entry.reruns.map(({attempt, status}) => attempt + '회 ' + mdValue(status));
696
- return [
697
- identify(entry),
698
- '단독 통과 ' + mdValue(entry.passesInIsolation),
699
- '시도 ' + entry.reruns.length + '회' + (attempts.length ? ' (' + attempts.join(', ') + ')' : ''),
700
- ...(runs.length ? ['이력 ' + runs.join(', ')] : [])
701
- ].join(' · ');
702
- }));
703
- section('새 실패 후보', json.newFailureCandidates.map(entry =>
704
- identify(entry) + ' / ' + mdValue(entry.reason)));
705
- section('사라진 테스트 및 새 테스트', [
706
- ...json.disappearedTests.map(entry => '사라진 테스트 ' + identify(entry)),
707
- ...json.addedTests.map(entry => '새 테스트 ' + identify(entry)),
708
- ...json.removedFiles.map(({commandId, path}) => '제외된 파일 ' + mdValue(commandId) + ' / ' + mdValue(path)),
709
- ...json.addedFiles.map(({commandId, path}) => '추가된 파일 ' + mdValue(commandId) + ' / ' + mdValue(path))
710
- ]);
711
- section('느린 상위 ' + topN + '개', [
712
- ...json.slowest.files.map(entry => '파일 ' + identify({...entry, testId: entry.file}) + ' / ' + entry.durationMs + ' ms'),
713
- ...json.slowest.tests.map(entry => '테스트 ' + identify(entry) + ' / ' + entry.durationMs + ' ms'),
714
- ...json.slowest.phases.map(({name, ms}) => 'prepare 단계 ' + mdValue(name) + ' / ' + ms + ' ms')
715
- ]);
716
- return lines.join('\n') + '\n';
717
- }
718
-
719
- export function buildReport({base, head, comparison, conditions, phases = [], topN = 10, generatedAt}) {
720
- const baseCommands = new Map(base.commands.map(command => [command.id, command]));
721
- const json = {
722
- schemaVersion: REPORT_SCHEMA_VERSION,
723
- base: runMetadata(base),
724
- head: runMetadata(head),
725
- conditions,
726
- commands: head.commands.map(command => ({
727
- id: command.id,
728
- base: commandReport(baseCommands.get(command.id)),
729
- head: commandReport(command)
730
- })),
731
- ...comparison,
732
- slowest: rankTimings(head.commands, phases, topN),
733
- generatedAt
734
- };
735
- return {json, md: renderReportMd(json, topN)};
736
- }