@aibyzero/cm-workflow 0.10.5 → 0.11.0

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 (48) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +51 -0
  4. package/CONTRIBUTING.md +12 -1
  5. package/README.md +21 -5
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +40 -1
  8. package/docs/installation.md +19 -9
  9. package/docs/user-guide.md +8 -1
  10. package/install-codex.sh +1 -1
  11. package/package.json +2 -1
  12. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  13. package/runtime/js/cm-ai/review-result.schema.json +0 -1
  14. package/runtime/js/cm-fix/execution.mjs +2 -2
  15. package/runtime/js/cm-fix/repair.mjs +6 -2
  16. package/runtime/js/cm-test/branch-impact.mjs +145 -0
  17. package/runtime/js/cm-test/host.mjs +28 -8
  18. package/runtime/js/cm-test/unit-coverage.mjs +206 -0
  19. package/runtime/project-context.md +6 -0
  20. package/scripts/cm-check-runtime.sh +18 -0
  21. package/scripts/cm-evolution-analyze.py +576 -0
  22. package/scripts/cm-fix-repair-owner.test.mjs +24 -6
  23. package/scripts/cm-fix-repair.test.mjs +9 -2
  24. package/scripts/cm-fix-review-baseline.test.mjs +19 -1
  25. package/scripts/cm-release-smoke.sh +76 -0
  26. package/scripts/cm-review-schema.test.mjs +15 -0
  27. package/scripts/cm-test-branch-impact.test.mjs +186 -0
  28. package/scripts/cm-test-entry.mjs +6 -1
  29. package/scripts/cm-test-host.mjs +2 -2
  30. package/scripts/cm-unit-coverage.mjs +16 -0
  31. package/scripts/cm-unit-coverage.test.mjs +126 -0
  32. package/scripts/scan-public-safety.py +5 -5
  33. package/scripts/test-cm-evolution-analyze.py +870 -0
  34. package/scripts/test-scan-public-safety.py +59 -1
  35. package/scripts/validate-public-repo.py +25 -0
  36. package/skills/cm-ai/references/N3-execute-task.md +12 -1
  37. package/skills/cm-ai/references/N8-finish.md +5 -4
  38. package/skills/cm-doc-syncer/SKILL.md +22 -3
  39. package/skills/cm-fix/SKILL.md +11 -2
  40. package/skills/cm-fix/references/js-host.md +4 -0
  41. package/skills/cm-prd/SKILL.md +3 -3
  42. package/skills/cm-prd/references/context-scope.md +17 -13
  43. package/skills/cm-test/SKILL.md +24 -7
  44. package/skills/cm-test/references/branch-impact.md +70 -0
  45. package/skills/cm-test/references/js-host.md +14 -2
  46. package/skills/cm-test/references/unit-coverage.md +97 -0
  47. package/skills/codebase-context/SKILL.md +11 -24
  48. package/skills/codebase-context/references/writeback.md +66 -0
@@ -0,0 +1,576 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only, deterministic analyzer for repeated CM Workflow failure signals."""
3
+
4
+ from collections import Counter, defaultdict
5
+ from datetime import datetime
6
+ import hashlib
7
+ import json
8
+ import math
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import stat
13
+ import sys
14
+
15
+
16
+ MAX_FILES = 32
17
+ MAX_TOTAL_BYTES = 64 * 1024 * 1024
18
+ MAX_LINES = 200_000
19
+ MAX_LINE_BYTES = 65_536
20
+ MAX_FINGERPRINTS = 1_000
21
+ MAX_RUN_REFS = 128
22
+
23
+ IDENTIFIER = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{0,63}$")
24
+ ENTITY_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
25
+ RUN_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{7,127}$")
26
+ SECRET_SHAPED = re.compile(
27
+ r"api[_-]?key|authorization|cookie|password|passwd|private[_-]?key|"
28
+ r"recovery[_-]?code|secret|token",
29
+ re.IGNORECASE,
30
+ )
31
+ CREDENTIAL_SHAPED = re.compile(
32
+ r"(?:AKIA|ASIA)[A-Z0-9]{16}|gh[pousr]_[A-Za-z0-9]{20,}|"
33
+ r"github_pat_[A-Za-z0-9_]{20,}|AIza[0-9A-Za-z_-]{20,}|"
34
+ r"xox[baprs]-[A-Za-z0-9-]{20,}"
35
+ )
36
+ HIGH_RISK_IMPACTS = {
37
+ "security",
38
+ "data_integrity",
39
+ "state_integrity",
40
+ "completion_integrity",
41
+ }
42
+ RESOURCE_PHASES = {"acquired", "released", "cleanup_failed"}
43
+
44
+
45
+ class InputBoundaryError(Exception):
46
+ def __init__(self, code, input_index=None):
47
+ super().__init__(code)
48
+ self.code = code
49
+ self.input_index = input_index
50
+
51
+
52
+ def hash_ref(value):
53
+ return "sha256:" + hashlib.sha256(value.encode("utf-8")).hexdigest()
54
+
55
+
56
+ def parse_cli(arguments):
57
+ if not arguments or len(arguments) % 2:
58
+ raise InputBoundaryError("invalid_arguments")
59
+ paths = []
60
+ for offset in range(0, len(arguments), 2):
61
+ if arguments[offset] != "--log" or not arguments[offset + 1]:
62
+ raise InputBoundaryError("invalid_arguments", offset // 2 + 1)
63
+ paths.append(Path(arguments[offset + 1]))
64
+ if len(paths) > MAX_FILES:
65
+ raise InputBoundaryError("too_many_files")
66
+ return paths
67
+
68
+
69
+ def open_regular_file(path, input_index):
70
+ try:
71
+ if path.is_symlink():
72
+ raise InputBoundaryError("invalid_input", input_index)
73
+ flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NONBLOCK", 0)
74
+ flags |= getattr(os, "O_NOFOLLOW", 0)
75
+ descriptor = os.open(str(path), flags)
76
+ except InputBoundaryError:
77
+ raise
78
+ except (OSError, ValueError):
79
+ raise InputBoundaryError("unreadable_input", input_index)
80
+ try:
81
+ metadata = os.fstat(descriptor)
82
+ if not stat.S_ISREG(metadata.st_mode):
83
+ raise InputBoundaryError("invalid_input", input_index)
84
+ return os.fdopen(descriptor, "rb"), metadata.st_size
85
+ except InputBoundaryError:
86
+ os.close(descriptor)
87
+ raise
88
+ except OSError:
89
+ os.close(descriptor)
90
+ raise InputBoundaryError("unreadable_input", input_index)
91
+
92
+
93
+ def reject_non_standard_constant(_value):
94
+ raise ValueError("non-standard JSON constant")
95
+
96
+
97
+ def parse_finite_float(value):
98
+ parsed = float(value)
99
+ if not math.isfinite(parsed):
100
+ raise ValueError("non-finite JSON number")
101
+ return parsed
102
+
103
+
104
+ class Analyzer:
105
+ def __init__(self):
106
+ self.summary = {
107
+ "files": 0,
108
+ "lines": 0,
109
+ "valid_events": 0,
110
+ "signal_events": 0,
111
+ "malformed_lines": 0,
112
+ }
113
+ self.diagnostics = Counter()
114
+ self.aggregates = {}
115
+ self.resource_events = defaultdict(list)
116
+ self.invalid_resource_groups = set()
117
+ self.unknown_resource_runs = 0
118
+ self.total_bytes = 0
119
+
120
+ def diagnose(self, code, malformed=False):
121
+ self.diagnostics[code] += 1
122
+ if malformed:
123
+ self.summary["malformed_lines"] += 1
124
+
125
+ def read(self, paths):
126
+ self.summary["files"] = len(paths)
127
+ declared_size = 0
128
+ for input_index, path in enumerate(paths, start=1):
129
+ handle, file_size = open_regular_file(path, input_index)
130
+ declared_size += file_size
131
+ if declared_size > MAX_TOTAL_BYTES:
132
+ handle.close()
133
+ raise InputBoundaryError("input_too_large", input_index)
134
+ try:
135
+ with handle:
136
+ while True:
137
+ try:
138
+ raw_line = handle.readline(MAX_LINE_BYTES + 1)
139
+ except OSError:
140
+ raise InputBoundaryError("unreadable_input", input_index)
141
+ if not raw_line:
142
+ break
143
+ if len(raw_line) > MAX_LINE_BYTES:
144
+ raise InputBoundaryError("line_too_long", input_index)
145
+ self.total_bytes += len(raw_line)
146
+ if self.total_bytes > MAX_TOTAL_BYTES:
147
+ raise InputBoundaryError("input_too_large", input_index)
148
+ self.summary["lines"] += 1
149
+ if self.summary["lines"] > MAX_LINES:
150
+ raise InputBoundaryError("too_many_lines", input_index)
151
+ self.process_line(raw_line)
152
+ except InputBoundaryError:
153
+ raise
154
+ except OSError:
155
+ raise InputBoundaryError("unreadable_input", input_index)
156
+ self.finish_resources()
157
+
158
+ def process_line(self, raw_line):
159
+ try:
160
+ text = raw_line.decode("utf-8")
161
+ except UnicodeDecodeError:
162
+ self.diagnose("invalid_utf8", malformed=True)
163
+ return
164
+ try:
165
+ row = json.loads(
166
+ text,
167
+ parse_constant=reject_non_standard_constant,
168
+ parse_float=parse_finite_float,
169
+ )
170
+ except (json.JSONDecodeError, RecursionError, ValueError):
171
+ self.diagnose("malformed_json", malformed=True)
172
+ return
173
+ if not isinstance(row, dict):
174
+ self.diagnose("non_object", malformed=True)
175
+ return
176
+ self.summary["valid_events"] += 1
177
+ self.process_event(row)
178
+
179
+ def process_event(self, row):
180
+ event_name = row.get("event")
181
+ if not isinstance(event_name, str):
182
+ if "event" in row:
183
+ self.diagnose("invalid_field_type")
184
+ return
185
+
186
+ if event_name == "resource":
187
+ self.collect_resource(row)
188
+ return
189
+ if event_name == "error":
190
+ signal_kind = self.error_signal_kind(row)
191
+ if signal_kind is not None:
192
+ self.summary["signal_events"] += 1
193
+ self.add_event_signal(signal_kind, row)
194
+ return
195
+ if event_name == "degrade":
196
+ self.summary["signal_events"] += 1
197
+ self.add_event_signal("degrade", row)
198
+ return
199
+ if event_name == "warning":
200
+ recovered = row.get("recovered")
201
+ if not isinstance(recovered, bool):
202
+ self.diagnose("invalid_field_type")
203
+ return
204
+ if recovered is False:
205
+ self.summary["signal_events"] += 1
206
+ self.add_event_signal("unrecovered_warning", row)
207
+ return
208
+ if event_name in {"review", "task_review"}:
209
+ state = self.normalized_state(
210
+ row, {"retry": "retry", "changes_requested": "changes_requested"}
211
+ )
212
+ if state is not None:
213
+ self.summary["signal_events"] += 1
214
+ if state:
215
+ self.add_event_signal("review_retry", row, normalized_state=state)
216
+ return
217
+ if event_name in {"qa", "test_run"}:
218
+ state = self.normalized_state(
219
+ row, {"blocked": "blocked", "case_blocked": "case_blocked"}
220
+ )
221
+ if state is not None:
222
+ self.summary["signal_events"] += 1
223
+ if state:
224
+ self.add_event_signal("qa_blocked", row, normalized_state=state)
225
+
226
+ def normalized_state(self, row, allowed):
227
+ found = []
228
+ saw_relevant_field = False
229
+ for name in ("phase", "outcome"):
230
+ if name not in row:
231
+ continue
232
+ saw_relevant_field = True
233
+ value = row[name]
234
+ if not isinstance(value, str):
235
+ self.diagnose("invalid_field_type")
236
+ return ""
237
+ if value in allowed:
238
+ found.append(allowed[value])
239
+ if not found:
240
+ return None if saw_relevant_field else None
241
+ if len(set(found)) > 1:
242
+ self.diagnose("conflicting_signal_state")
243
+ return ""
244
+ return found[0]
245
+
246
+ def error_signal_kind(self, row):
247
+ recovered = row.get("recovered")
248
+ if "recovered" in row and not isinstance(recovered, bool):
249
+ self.diagnose("invalid_field_type")
250
+ return None
251
+ for name in ("outcome", "impact"):
252
+ if name in row and not isinstance(row[name], str):
253
+ self.diagnose("invalid_field_type")
254
+ return None
255
+ high_risk = (
256
+ recovered is False
257
+ and row.get("outcome") == "blocked"
258
+ and row.get("impact") in HIGH_RISK_IMPACTS
259
+ )
260
+ return "high_risk_error" if high_risk else "error"
261
+
262
+ def common_signature(self, row, signal_kind):
263
+ schema_version = row.get("schema_version")
264
+ if isinstance(schema_version, bool) or not isinstance(schema_version, int):
265
+ self.diagnose(
266
+ "invalid_field_type" if "schema_version" in row else "insufficient_signature"
267
+ )
268
+ return None
269
+ if schema_version != 1:
270
+ self.diagnose("unsupported_schema_version")
271
+ return None
272
+ workflow = self.identifier(row, "workflow")
273
+ if workflow is None:
274
+ return None
275
+ return {
276
+ "fingerprint_version": 1,
277
+ "schema_version": 1,
278
+ "workflow": workflow,
279
+ "signal_kind": signal_kind,
280
+ }
281
+
282
+ def identifier(self, row, name, pattern=IDENTIFIER):
283
+ if name not in row:
284
+ self.diagnose("insufficient_signature")
285
+ return None
286
+ value = row[name]
287
+ if not isinstance(value, str):
288
+ self.diagnose("invalid_field_type")
289
+ return None
290
+ if SECRET_SHAPED.search(value) or CREDENTIAL_SHAPED.search(value):
291
+ self.diagnose("secret_shaped_token")
292
+ return None
293
+ if not pattern.fullmatch(value):
294
+ self.diagnose("invalid_identifier")
295
+ return None
296
+ return value
297
+
298
+ def scope_ref(self, row, preferred, fallback):
299
+ name = preferred if preferred in row else fallback
300
+ pattern = IDENTIFIER if name == "node" else ENTITY_ID
301
+ value = self.identifier(row, name, pattern)
302
+ return None if value is None else hash_ref(value)
303
+
304
+ def valid_run_id(self, row):
305
+ if "run_id" not in row:
306
+ self.diagnose("invalid_run_id")
307
+ return None
308
+ value = row["run_id"]
309
+ if not isinstance(value, str):
310
+ self.diagnose("invalid_field_type")
311
+ return None
312
+ if SECRET_SHAPED.search(value) or CREDENTIAL_SHAPED.search(value):
313
+ self.diagnose("secret_shaped_token")
314
+ return None
315
+ if not RUN_ID.fullmatch(value):
316
+ self.diagnose("invalid_run_id")
317
+ return None
318
+ return value
319
+
320
+ def resource_run_identity(self, row):
321
+ if "run_id" not in row:
322
+ self.diagnose("invalid_run_id")
323
+ self.unknown_resource_runs += 1
324
+ return f"unknown:{self.unknown_resource_runs}", None
325
+ value = row["run_id"]
326
+ if not isinstance(value, str):
327
+ self.diagnose("invalid_field_type")
328
+ self.unknown_resource_runs += 1
329
+ return f"unknown:{self.unknown_resource_runs}", None
330
+ if SECRET_SHAPED.search(value) or CREDENTIAL_SHAPED.search(value):
331
+ self.diagnose("secret_shaped_token")
332
+ return None, None
333
+ if not RUN_ID.fullmatch(value):
334
+ self.diagnose("invalid_run_id")
335
+ try:
336
+ return "invalid:" + hash_ref(value), None
337
+ except UnicodeEncodeError:
338
+ return None, None
339
+ return "valid:" + value, value
340
+
341
+ def add_event_signal(self, signal_kind, row, normalized_state=None):
342
+ raw_run_id = row.get("run_id")
343
+ if isinstance(raw_run_id, str) and (
344
+ SECRET_SHAPED.search(raw_run_id) or CREDENTIAL_SHAPED.search(raw_run_id)
345
+ ):
346
+ self.diagnose("secret_shaped_token")
347
+ return
348
+ signature = self.common_signature(row, signal_kind)
349
+ if signature is None:
350
+ return
351
+
352
+ if signal_kind == "error":
353
+ scope_ref = self.scope_ref(row, "node", "task")
354
+ phase = self.identifier(row, "phase")
355
+ error_type = self.identifier(row, "error_type")
356
+ if None in (scope_ref, phase, error_type):
357
+ return
358
+ signature.update(
359
+ {"scope_ref": scope_ref, "phase": phase, "error_type": error_type}
360
+ )
361
+ elif signal_kind == "high_risk_error":
362
+ scope_ref = self.scope_ref(row, "node", "task")
363
+ phase = self.identifier(row, "phase")
364
+ outcome = self.identifier(row, "outcome")
365
+ error_type = self.identifier(row, "error_type")
366
+ impact = self.identifier(row, "impact")
367
+ if None in (scope_ref, phase, outcome, error_type, impact):
368
+ return
369
+ signature.update(
370
+ {
371
+ "scope_ref": scope_ref,
372
+ "phase": phase,
373
+ "outcome": outcome,
374
+ "error_type": error_type,
375
+ "impact": impact,
376
+ }
377
+ )
378
+ elif signal_kind == "degrade":
379
+ phase = self.identifier(row, "phase")
380
+ error_type = self.identifier(row, "error_type")
381
+ if None in (phase, error_type):
382
+ return
383
+ signature.update({"phase": phase, "error_type": error_type})
384
+ elif signal_kind == "unrecovered_warning":
385
+ scope_ref = self.scope_ref(row, "node", "task")
386
+ phase = self.identifier(row, "phase")
387
+ error_type = self.identifier(row, "error_type")
388
+ if None in (scope_ref, phase, error_type):
389
+ return
390
+ signature.update(
391
+ {"scope_ref": scope_ref, "phase": phase, "error_type": error_type}
392
+ )
393
+ elif signal_kind == "review_retry":
394
+ scope_ref = self.scope_ref(row, "task", "node")
395
+ if scope_ref is None:
396
+ return
397
+ signature.update(
398
+ {"scope_ref": scope_ref, "review_state": normalized_state}
399
+ )
400
+ elif signal_kind == "qa_blocked":
401
+ case_id = self.identifier(row, "case_id", ENTITY_ID)
402
+ if case_id is None:
403
+ return
404
+ signature.update(
405
+ {"case_ref": hash_ref(case_id), "qa_state": normalized_state}
406
+ )
407
+ run_id = self.valid_run_id(row)
408
+ self.aggregate(signature, run_id, signal_kind == "high_risk_error")
409
+
410
+ def collect_resource(self, row):
411
+ phase = row.get("phase")
412
+ if not isinstance(phase, str):
413
+ self.diagnose("invalid_field_type")
414
+ return
415
+ if phase not in RESOURCE_PHASES:
416
+ return
417
+ run_key, run_id = self.resource_run_identity(row)
418
+ resource_id = self.identifier(row, "resource_id", ENTITY_ID)
419
+ resource_kind = self.identifier(row, "resource_kind")
420
+ if None in (run_key, resource_id, resource_kind):
421
+ return
422
+ key = (run_key, resource_id, resource_kind)
423
+ at_value = row.get("at")
424
+ if not isinstance(at_value, str) or SECRET_SHAPED.search(at_value) or CREDENTIAL_SHAPED.search(at_value):
425
+ self.diagnose(
426
+ "invalid_field_type" if not isinstance(at_value, str) else "secret_shaped_token"
427
+ )
428
+ self.diagnose("ambiguous_resource_terminal")
429
+ self.invalid_resource_groups.add(key)
430
+ return
431
+ try:
432
+ parsed_at = datetime.fromisoformat(at_value.replace("Z", "+00:00"))
433
+ if parsed_at.tzinfo is None:
434
+ raise ValueError
435
+ except (ValueError, OverflowError):
436
+ self.diagnose("ambiguous_resource_terminal")
437
+ self.invalid_resource_groups.add(key)
438
+ return
439
+ common = self.common_signature(row, "resource_cleanup_failed")
440
+ self.resource_events[key].append((parsed_at, phase, common, run_id))
441
+
442
+ def finish_resources(self):
443
+ for key in sorted(self.resource_events):
444
+ if key in self.invalid_resource_groups:
445
+ continue
446
+ rows = self.resource_events[key]
447
+ by_time = defaultdict(set)
448
+ for at_value, phase, _, _ in rows:
449
+ by_time[at_value].add(phase)
450
+ if any(len(states) > 1 for states in by_time.values()):
451
+ self.diagnose("ambiguous_resource_terminal")
452
+ continue
453
+ final_at = max(by_time)
454
+ final_phase = next(iter(by_time[final_at]))
455
+ if final_phase != "cleanup_failed":
456
+ continue
457
+ _, _, resource_kind = key
458
+ final_common = [
459
+ common
460
+ for at_value, _, common, _ in rows
461
+ if at_value == final_at and common is not None
462
+ ]
463
+ if not final_common:
464
+ continue
465
+ common = min(final_common, key=lambda value: value["workflow"])
466
+ run_id = next(
467
+ (
468
+ candidate
469
+ for at_value, _, _, candidate in rows
470
+ if at_value == final_at and candidate is not None
471
+ ),
472
+ None,
473
+ )
474
+ signature = dict(common)
475
+ signature.update(
476
+ {
477
+ "resource_kind": resource_kind,
478
+ "resource_state": "cleanup_failed_unreleased",
479
+ }
480
+ )
481
+ self.summary["signal_events"] += 1
482
+ self.aggregate(signature, run_id, True)
483
+
484
+ def aggregate(self, signature, run_id, high_risk):
485
+ canonical = json.dumps(
486
+ signature, ensure_ascii=True, separators=(",", ":"), sort_keys=False
487
+ ).encode("utf-8")
488
+ fingerprint = "sha256:" + hashlib.sha256(canonical).hexdigest()
489
+ if fingerprint not in self.aggregates:
490
+ if len(self.aggregates) >= MAX_FINGERPRINTS:
491
+ raise InputBoundaryError("too_many_fingerprints")
492
+ self.aggregates[fingerprint] = {
493
+ "signal_kind": signature["signal_kind"],
494
+ "signature": signature,
495
+ "occurrences": 0,
496
+ "run_ids": set(),
497
+ "high_risk": high_risk,
498
+ }
499
+ aggregate = self.aggregates[fingerprint]
500
+ aggregate["occurrences"] += 1
501
+ if run_id is not None:
502
+ aggregate["run_ids"].add(run_id)
503
+
504
+ def output(self):
505
+ signals = []
506
+ for fingerprint in sorted(self.aggregates):
507
+ aggregate = self.aggregates[fingerprint]
508
+ run_ids = aggregate["run_ids"]
509
+ if aggregate["high_risk"]:
510
+ classification = "candidate"
511
+ reason = "high_risk_invariant"
512
+ elif len(run_ids) >= 2:
513
+ classification = "candidate"
514
+ reason = "repeated_across_runs"
515
+ else:
516
+ classification = "observe"
517
+ reason = "single_run"
518
+ run_refs = sorted(hash_ref(run_id) for run_id in run_ids)
519
+ signals.append(
520
+ {
521
+ "fingerprint": fingerprint,
522
+ "classification": classification,
523
+ "reason": reason,
524
+ "signal_kind": aggregate["signal_kind"],
525
+ "occurrences": aggregate["occurrences"],
526
+ "distinct_runs": len(run_ids),
527
+ "run_refs": run_refs[:MAX_RUN_REFS],
528
+ "run_refs_truncated": len(run_refs) > MAX_RUN_REFS,
529
+ "signature": aggregate["signature"],
530
+ }
531
+ )
532
+ if any(item["classification"] == "candidate" for item in signals):
533
+ status_value = "candidate"
534
+ elif signals or self.diagnostics:
535
+ status_value = "observe"
536
+ else:
537
+ status_value = "no_signal"
538
+ diagnostics = [
539
+ {"code": code, "count": self.diagnostics[code]}
540
+ for code in sorted(self.diagnostics)
541
+ ]
542
+ return {
543
+ "schema_version": 1,
544
+ "status": status_value,
545
+ "summary": self.summary,
546
+ "signals": signals,
547
+ "diagnostics": diagnostics,
548
+ }
549
+
550
+
551
+ def run(arguments):
552
+ paths = parse_cli(arguments)
553
+ analyzer = Analyzer()
554
+ analyzer.read(paths)
555
+ payload = analyzer.output()
556
+ sys.stdout.write(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
557
+ sys.stdout.write("\n")
558
+ return 0
559
+
560
+
561
+ def main():
562
+ try:
563
+ return run(sys.argv[1:])
564
+ except InputBoundaryError as error:
565
+ message = "cm-evolution-analyze:error=" + error.code
566
+ if error.input_index is not None:
567
+ message += " input=" + str(error.input_index)
568
+ sys.stderr.write(message + "\n")
569
+ return 2
570
+ except (MemoryError, RecursionError):
571
+ sys.stderr.write("cm-evolution-analyze:error=resource_limit\n")
572
+ return 2
573
+
574
+
575
+ if __name__ == "__main__":
576
+ raise SystemExit(main())
@@ -19,7 +19,7 @@ import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
19
19
  import {readProjectInstructionContext} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
20
20
 
21
21
  test('durable repair registers before write, preserves cause approval history and never redispatches lost results',async()=>{
22
- for(const mode of ['revision','revision-approved','revision-lost','normal','lost','cause','unfixed','regression-intent','lesson','retrospective-lost','lesson-intent','lesson-pending','handoff-forged','handoff-legacy','handoff-large']){
22
+ for(const mode of ['revision','revision-approved','revision-lost','normal','lost','cause','cause-map','unfixed','regression-intent','lesson','retrospective-lost','lesson-intent','lesson-pending','handoff-forged','handoff-legacy','handoff-large']){
23
23
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-repair-owner-')));
24
24
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
25
25
  fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
@@ -27,12 +27,14 @@ test('durable repair registers before write, preserves cause approval history an
27
27
  fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
28
28
  if(mode==='revision-approved')fs.writeFileSync(path.join(cwd,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
29
29
  const identity={repositoryId:'fixture',runId:'repair-owner',taskId:'T-FIX-owner',attempt:1};
30
+ const mapPaths=mode==='cause-map'?['docs/codebase-context/00-index.md','docs/codebase-context/07-business-logic.md','docs/codebase-context/09-changelog.md']:[];
31
+ const mapPlan='Create partial value map; cover value.mjs only; other modules unverified.';
30
32
  const reviewer={reviewerId:'cause-reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',contextId:'review-context',excludedThreadIds:mode==='cause'?Array.from({length:32},(_,index)=>`excluded-${index}`):[]};
31
33
  const options={identity,specsRoot,create:true,configuration:{hostContextId:'fixture-host',defect:'Wrong constant',
32
34
  reproduction:{cwd,command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
33
35
  redTest:{cwd,testFiles:['red.mjs'],command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
34
36
  baseline:{cwd,testFiles:['existing.mjs'],commands:[{id:mode==='normal'?'x'.repeat(128):'existing',command:[process.execPath,'existing.mjs']}],timeoutMs:2000},
35
- repair:{scope:['value.mjs'],requirements:['value.mjs']},...(mode==='cause'||mode.startsWith('revision')?{causeReview:reviewer}:{})}};
37
+ repair:{scope:['value.mjs',...mapPaths],requirements:['value.mjs']},...(mode.startsWith('cause')||mode.startsWith('revision')?{causeReview:reviewer}:{})}};
36
38
  if(mode==='handoff-large')options.configuration.redTest.command=[process.execPath,'-e',
37
39
  "import('./value.mjs').then(({value})=>{if(value!==2){process.stderr.write('BUG'+'x'.repeat(128*1024-3));process.exitCode=1;}});//"+'x'.repeat(31*1024)];
38
40
  if(mode==='revision-approved')options.configuration.walkthrough={timeoutMs:2000,flows:[{id:'value-flow',modules:['one'],steps:['Read corrected value'],expected:['Value is 2'],kind:'commands',command:[process.execPath,'red.mjs']}]};
@@ -52,7 +54,7 @@ test('durable repair registers before write, preserves cause approval history an
52
54
  const bridge=createHostToolBridge();let writes=0,retrospectives=0;
53
55
  bridge.attach(row=>{
54
56
  if(row.type!=='host_request')return;
55
- let result={status:'diagnosed',rootCause:'Wrong constant',affectedPaths:['value.mjs'],affectedModules:['one'],crossLayer:mode==='cause',plan:'Correct constant'};
57
+ let result={status:'diagnosed',rootCause:'Wrong constant',affectedPaths:['value.mjs'],affectedModules:['one'],crossLayer:mode.startsWith('cause'),plan:mode==='cause-map'?mapPlan:'Correct constant'};
56
58
  if(mode==='revision-approved')result.investigation={discardedAlternatives:[],boundaryAnalysis:null};
57
59
  if(row.kind==='fix_retrospective'){
58
60
  const state=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json')));
@@ -67,6 +69,13 @@ test('durable repair registers before write, preserves cause approval history an
67
69
  assert.equal(state.records.at(-1).id,row.payload.identity.attempt===2?'fix-revision-repair-intent':'fix-repair-intent');writes++;
68
70
  if(row.payload.identity.attempt===2){assert.equal(row.payload.priorReview.review.findings[0].id,'F1');assert.deepEqual(row.payload.scope,['value.mjs']);}
69
71
  fs.writeFileSync(path.join(cwd,'value.mjs'),row.payload.identity.attempt===2?'export const value=2; // reviewed boundary repair':mode==='unfixed'?'export const value=3;':'export const value=2;');
72
+ if(mode==='cause-map'){
73
+ assert.deepEqual(row.payload.diagnosis.affectedPaths,['value.mjs']);
74
+ for(const file of mapPaths){
75
+ assert(row.payload.scope.includes(file));fs.mkdirSync(path.dirname(path.join(cwd,file)),{recursive:true});
76
+ fs.writeFileSync(path.join(cwd,file),'# Partial map\nvalue.mjs exports value=2; only this module verified.\n');
77
+ }
78
+ }
70
79
  if(mode==='revision-lost'&&row.payload.identity.attempt===2){bridge.close();return;}
71
80
  if(mode==='lost'){bridge.close();return;}result={outcome:'repaired'};
72
81
  }
@@ -79,7 +88,8 @@ test('durable repair registers before write, preserves cause approval history an
79
88
  try{
80
89
  if(mode==='revision-approved')startFixRun({specsRoot,identity,configuration:options.configuration});
81
90
  await owner.advance({authorized:true});
82
- if(mode==='cause'){
91
+ if(mode.startsWith('cause')){
92
+ if(mode==='cause-map')assert(!fs.existsSync(path.join(cwd,'docs')));
83
93
  const pkg=owner.causeReviewPackage();await authority.hostDecisionProvider.decide({identity,packageDigest:pkg.packageDigest},new AbortController().signal);
84
94
  await owner.reviewCause();
85
95
  }
@@ -101,7 +111,7 @@ test('durable repair registers before write, preserves cause approval history an
101
111
  owner=openFixExecution({...options,create:false},{bridge,prepare,causeReview,assertReviewReady(){}});
102
112
  result=owner.status();assert.equal(result.stage,'regression_required');
103
113
  }
104
- assert.equal(result.completionEligible,false);if(mode==='cause')assert.equal(result.causeReview.review.verdict,'approved');
114
+ assert.equal(result.completionEligible,false);if(mode.startsWith('cause'))assert.equal(result.causeReview.review.verdict,'approved');
105
115
  owner.close();
106
116
  assert.throws(()=>openFixExecution({...options,create:false,configuration:{...options.configuration,
107
117
  repair:{...options.configuration.repair,scope:['AGENTS.md']}}}),{code:'protected_scope'});
@@ -125,7 +135,7 @@ test('durable repair registers before write, preserves cause approval history an
125
135
  if(mode==='unfixed')assert.throws(()=>owner.implementationPackage(),{code:'fix_not_ready_for_handoff'});
126
136
  else{
127
137
  const pkg=owner.implementationPackage();
128
- assert.deepEqual(pkg.changes.map(change=>change.path),['value.mjs']);
138
+ assert.deepEqual(pkg.changes.map(change=>change.path),[...mapPaths,'value.mjs']);
129
139
  assert.deepEqual(pkg.checks.map(check=>check.id),['red-test','baseline.1']);
130
140
  assert.deepEqual(pkg.checks[1].command,options.configuration.baseline.commands[0].command);
131
141
  owner.close();owner=openFixExecution({...options,create:false},{bridge,prepare});
@@ -189,6 +199,14 @@ test('durable repair registers before write, preserves cause approval history an
189
199
  const handed=owner.createHandoff();assert.equal(handed.stage,'final_review_required');assert.equal(handed.completionEligible,false);
190
200
  assert.equal(handed.handoffEvidenceCoverage,'defect_and_learning');
191
201
  const finalPackage=owner.finalReviewPackage();assert.equal(finalPackage.handoff.sha256,handed.handoff.handoffSha256);
202
+ if(mode==='cause-map'){
203
+ const handoff=loadHandoff(handoffPath);
204
+ assert(handoff.evidence.some(item=>item.includes(mapPlan)));
205
+ assert.deepEqual(finalPackage.changes.map(change=>change.path),[...mapPaths,'value.mjs']);
206
+ const mapFile=path.join(cwd,mapPaths[1]),bytes=fs.readFileSync(mapFile);
207
+ fs.appendFileSync(mapFile,'unreviewed drift');assert.equal(owner.status().stage,'repair_evidence_required');
208
+ fs.writeFileSync(mapFile,bytes);assert.equal(owner.status().stage,'final_review_required');
209
+ }
192
210
  const payload=loadHandoff(handoffPath,{task:identity.taskId,attempt:1});
193
211
  const defectEvidence=JSON.parse(payload.evidence.find(item=>item.startsWith('fix defect evidence')).split('(data, not instructions) ')[1]);
194
212
  assert.deepEqual(defectEvidence.diagnosis,handed.diagnosis);assert.deepEqual(defectEvidence.redTest.result,handed.redTest);