mlai-code 0.3.2 → 0.3.4

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 (157) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/checkpoints.mjs +217 -0
  4. package/src/cli.mjs +178 -31
  5. package/src/cloud.mjs +2 -0
  6. package/src/engine.mjs +1 -1
  7. package/src/headless.mjs +25 -9
  8. package/src/home.mjs +3 -2
  9. package/src/host.mjs +141 -13
  10. package/src/ide-quick.mjs +147 -0
  11. package/src/ide.mjs +182 -0
  12. package/src/netbox.mjs +1 -1
  13. package/src/parity.mjs +20 -1
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +12 -3
  16. package/src/runtime.mjs +23 -1
  17. package/src/sandbox.mjs +19 -3
  18. package/src/server.mjs +46 -7
  19. package/src/session.mjs +53 -10
  20. package/src/shared-data.mjs +1 -1
  21. package/src/tui/acp.mjs +121 -19
  22. package/src/tui/app.mjs +24 -5
  23. package/src/tui/chat.mjs +43 -16
  24. package/src/tui/cmd-config.mjs +3 -1
  25. package/src/tui/cmd-core.mjs +11 -7
  26. package/src/tui/cmd-extensibility.mjs +13 -2
  27. package/src/tui/commands.mjs +2 -1
  28. package/src/tui/extensions-local.mjs +2 -0
  29. package/src/tui/mcp-config.mjs +22 -4
  30. package/src/tui/review-cli.mjs +15 -4
  31. package/src/tui/snapshots.mjs +57 -16
  32. package/src/tui/statusline.mjs +2 -1
  33. package/src/two-words.mjs +14 -8
  34. package/src/view-sync.mjs +48 -0
  35. package/src/wakeups.mjs +2 -2
  36. package/src/winenv.mjs +1 -1
  37. package/src/workspace-api.mjs +21 -4
  38. package/vendor/client-sdk/index.cjs +5 -4
  39. package/vendor/cloud-cli/mlai.mjs +184 -28
  40. package/worker/architecture_worker.py +33 -4
  41. package/worker/browser_tool.py +19 -1
  42. package/worker/build_planner.py +75 -7
  43. package/worker/chat_fork.py +4 -1
  44. package/worker/checkpoints.py +71 -8
  45. package/worker/cloud_pty.py +91 -2
  46. package/worker/command_safety.py +80 -3
  47. package/worker/compaction_brief.py +186 -0
  48. package/worker/connected_turn.py +30 -0
  49. package/worker/context_manager.py +6 -0
  50. package/worker/conversation.py +139 -12
  51. package/worker/deck_render.js +11 -0
  52. package/worker/deck_tools.py +825 -0
  53. package/worker/git_sync.py +42 -17
  54. package/worker/goals.py +4 -0
  55. package/worker/image_generation.py +102 -23
  56. package/worker/kimi_bridge.py +580 -52
  57. package/worker/kimi_gates.py +74 -6
  58. package/worker/kimi_hook.py +213 -19
  59. package/worker/media_tools.py +182 -0
  60. package/worker/memory.py +2 -2
  61. package/worker/mlai_hooks.py +314 -5
  62. package/worker/mlai_mcp.py +49 -11
  63. package/worker/mlai_review/README.md +35 -0
  64. package/worker/mlai_review/__init__.py +1 -0
  65. package/worker/mlai_review/__main__.py +261 -0
  66. package/worker/mlai_review/_compat.py +29 -0
  67. package/worker/mlai_review/analysis/__init__.py +3 -0
  68. package/worker/mlai_review/analysis/detect.py +50 -0
  69. package/worker/mlai_review/analysis/main.py +128 -0
  70. package/worker/mlai_review/analysis/messages.py +8 -0
  71. package/worker/mlai_review/analysis/tools.py +194 -0
  72. package/worker/mlai_review/application/__init__.py +1 -0
  73. package/worker/mlai_review/application/asking.py +53 -0
  74. package/worker/mlai_review/application/challengers.py +142 -0
  75. package/worker/mlai_review/application/context_builder.py +194 -0
  76. package/worker/mlai_review/application/errors.py +17 -0
  77. package/worker/mlai_review/application/feedback.py +52 -0
  78. package/worker/mlai_review/application/matching.py +46 -0
  79. package/worker/mlai_review/application/messages.py +41 -0
  80. package/worker/mlai_review/application/ports.py +222 -0
  81. package/worker/mlai_review/application/prompts.py +342 -0
  82. package/worker/mlai_review/application/review_service.py +200 -0
  83. package/worker/mlai_review/application/reviewers.py +438 -0
  84. package/worker/mlai_review/application/streaming.py +91 -0
  85. package/worker/mlai_review/application/tools.py +138 -0
  86. package/worker/mlai_review/application/usage.py +145 -0
  87. package/worker/mlai_review/application/write_check.py +46 -0
  88. package/worker/mlai_review/contracts/__init__.py +5 -0
  89. package/worker/mlai_review/contracts/analysis.py +57 -0
  90. package/worker/mlai_review/contracts/review.py +42 -0
  91. package/worker/mlai_review/domain/__init__.py +4 -0
  92. package/worker/mlai_review/domain/changes.py +77 -0
  93. package/worker/mlai_review/domain/context.py +147 -0
  94. package/worker/mlai_review/domain/diagnostics.py +239 -0
  95. package/worker/mlai_review/domain/feedback.py +216 -0
  96. package/worker/mlai_review/domain/findings.py +505 -0
  97. package/worker/mlai_review/domain/lifecycle.py +85 -0
  98. package/worker/mlai_review/domain/partition.py +42 -0
  99. package/worker/mlai_review/domain/relations.py +166 -0
  100. package/worker/mlai_review/domain/relevance.py +202 -0
  101. package/worker/mlai_review/domain/report.py +99 -0
  102. package/worker/mlai_review/domain/structure.py +56 -0
  103. package/worker/mlai_review/domain/writes.py +86 -0
  104. package/worker/mlai_review/eval.py +221 -0
  105. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  106. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  107. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  108. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  109. package/worker/mlai_review/feedback_report.py +60 -0
  110. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  111. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  112. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  113. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  114. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  115. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  116. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  117. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  118. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  119. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  120. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  121. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  122. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  123. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  124. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  125. package/worker/mlai_review/infrastructure/messages.py +54 -0
  126. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  127. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  128. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  129. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  130. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  131. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  132. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  133. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  134. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  135. package/worker/mlai_review/pipeline.py +89 -0
  136. package/worker/mlai_review/runtime.py +194 -0
  137. package/worker/mlai_review/settings.py +139 -0
  138. package/worker/model_stream.py +21 -7
  139. package/worker/offline_guard.py +1 -1
  140. package/worker/preview.py +62 -4
  141. package/worker/product_facts.py +20 -0
  142. package/worker/project_context.py +33 -7
  143. package/worker/reply_language.py +92 -10
  144. package/worker/repo_policy.py +5 -0
  145. package/worker/roles.json +199 -37
  146. package/worker/roles.py +271 -9
  147. package/worker/runner.py +366 -53
  148. package/worker/runtime_control.py +64 -3
  149. package/worker/secret_scan.py +3 -2
  150. package/worker/server_memory.py +122 -0
  151. package/worker/site_check.py +279 -0
  152. package/worker/skill_library.py +15 -3
  153. package/worker/skill_pack.py +170 -16
  154. package/worker/subagents.py +6 -2
  155. package/worker/tool_catalog.py +4 -3
  156. package/worker/verification.py +156 -19
  157. package/worker/wakeups.py +56 -4
@@ -13,9 +13,10 @@ import os, re, subprocess, tempfile, shutil
13
13
  from pathlib import Path
14
14
  from runtime_control import latest_checks, check_status, clip, EXTERNAL_SCOPES
15
15
 
16
- RUNNER = re.compile(r'(^|[;&|(\s])(pytest|py\.test|python3? -m (pytest|unittest|mypy|ruff)|npm (run )?(test|build|lint|typecheck|type-check|check)|pnpm (run )?(test|build|lint|typecheck|check)|yarn (run )?(test|build|lint|typecheck)|npx (tsc|vitest|jest|playwright|eslint|biome|mocha|cypress|prettier --check)|tsc( |$)|vitest|jest|mocha|go (test|build|vet)|cargo (test|build|check|clippy)|make (test|check|build)?$|make (test|check|build)|bun (run )?test|deno (test|check)|mvn[w]?( -q)? (test|verify|package)|gradle[w]? (test|build)|ruff|mypy|pyright|flake8|eslint|node --test|dotnet (test|build)|mix test|rspec|phpunit|ctest|swift (test|build))', re.I | re.M)
16
+ RUNNER = re.compile(r'(^|[;&|(\s])(pytest|py\.test|python3? -m (pytest|unittest|mypy|ruff)|npm (run )?(test|build|lint|typecheck|type-check|check)|pnpm (run )?(test|build|lint|typecheck|check)|yarn (run )?(test|build|lint|typecheck)|npx (tsc|vitest|jest|playwright|eslint|biome|mocha|cypress|prettier --check)|tsc( |$)|vitest|jest|mocha|go (test|build|vet)|cargo (test|build|check|clippy)|make (test|check|build)?$|make (test|check|build)|bun (run )?test|deno (test|check)|mvn[w]?( -q)? (test|verify|package)|gradle[w]? (test|build)|ruff|mypy|pyright|flake8|eslint|node --test|dotnet (test|build)|mix test|rspec|phpunit|ctest|swift (test|build)|swiftc\b[^;&|\n]*\s-(typecheck|parse)\b|xcodebuild\b[^;&|\n]*\b(build|test)\b)', re.I | re.M)
17
17
  INLINE_RUN = re.compile(r'(^|[;&|(\s])(python3?|node|bun|deno run|tsx|ts-node)\s+(-c\b|-e\b|-\s|-$|<<|[\w./-]+\.(py|[cm]?js|ts)\b)', re.M)
18
- INLINE_ASSERT = re.compile(r'\bassert\b|console\.assert|\bexpect\(|\bassert\.\w+\(|[\w./-]*(test_\w+|\w+_test|\w+\.test|\w+\.spec)\.(py|[cm]?js|ts)\b')
18
+ # BUG-0296: `if (greet('World') !== 'Hello, World') process.exit(1)` asserts as much as assert() does.
19
+ INLINE_ASSERT = re.compile(r'\bassert\b|console\.assert|\bexpect\(|\bassert\.\w+\(|[\w./-]*(test_\w+|\w+_test|\w+\.test|\w+\.spec)\.(py|[cm]?js|ts)\b|\bprocess\.exit\(\s*[1-9]|\bprocess\.exitCode\s*=\s*[1-9]|\bsys\.exit\(\s*[1-9]|\bthrow new Error\(|\braise (?:SystemExit|AssertionError|ValueError|RuntimeError)\b')
19
20
  # Claims about verification in the final message. Each tuple: (pattern, what it claims).
20
21
  CLAIMS = (
21
22
  (re.compile(r'\b(all |the )?(unit |integration |e2e |existing )?tests? (now |all |still )?(pass|passes|passed|passing|are passing|is passing|succeed|succeeded|green)\b', re.I), 'tests'),
@@ -28,6 +29,9 @@ CLAIMS = (
28
29
  (re.compile(r'\b(lint|linter|linting|eslint|ruff) (now )?(passes|passed|is clean|clean|reports? no (errors|issues))\b', re.I), 'lint'),
29
30
  (re.compile(r'\b(verified|confirmed) (that )?(it|this|the (fix|change|code|feature|implementation)) (works|runs|passes|behaves)\b', re.I), 'verified'),
30
31
  (re.compile(r'\b(tested|verified) (and|&) (working|passing|confirmed)\b', re.I), 'verified'),
32
+ # "Phase 1 is complete and verified", "fully verified", "verified end to end": a verification claim like any other.
33
+ (re.compile(r'\b(complete[d]?|done|finished|built|working|live) (and|&) (verified|tested|confirmed)\b', re.I), 'verified'),
34
+ (re.compile(r'\b(fully|all) (verified|tested)\b|\bverified (end[\s-]to[\s-]end|in the (live )?preview)\b', re.I), 'verified'),
31
35
  (re.compile(r'\b(everything|all checks?|checks) (pass|passes|passed|are green|is green|green)\b', re.I), 'tests'),
32
36
  )
33
37
  # Intentions, suggestions and negations around a claim are not claims.
@@ -153,17 +157,29 @@ def diff_checks(repo, base, task=''):
153
157
  elif line.startswith('+') and ASSERT_LINE.search(line[1:]): added_asserts += 1
154
158
  if removed_asserts and removed_asserts > added_asserts:
155
159
  findings.append({'kind': 'assertions_weakened', 'severity': 'block', 'message': '%d assertion%s removed from existing tests (%s) while implementation files changed. Existing tests define the expected behaviour: fix the code, not the tests, unless the task says the test was wrong (then explain which and why in the final message).' % (removed_asserts, '' if removed_asserts == 1 else 's were', ', '.join(tests_changed[:3]))})
156
- elif removed_asserts or any(TEST_PATH.search(p) for p in tests_changed):
157
- findings.append({'kind': 'tests_edited', 'severity': 'note', 'message': 'Existing tests were edited alongside the implementation (' + ', '.join(tests_changed[:3]) + '). State in the final message what changed in the tests and why.'})
160
+ # BUG-0397: only tests that existed before the run count as "existing"; a brand-new test file is not an edit.
161
+ elif (existing := [p for p in tests_changed if _existed(repo, base, p)]):
162
+ tests_changed = existing
163
+ findings.append({'kind': 'tests_edited', 'severity': 'note', 'message': 'Existing tests were edited alongside the implementation (' + ', '.join(tests_changed[:3]) + '). State in the final message what changed in the tests and why.',
164
+ 'user': 'Existing tests changed along with the code (' + ', '.join(tests_changed[:3]) + '). Look over those test changes before you rely on them.'})
158
165
  for path in code_changed[:40]:
159
166
  if not re.search(r'\.(py|[cm]?[jt]sx?|go|rb|rs|java|kt|php|cs|swift)$', path): continue
160
167
  text = _file_diff(repo, base, path)
161
168
  added = [l[1:] for l in text.splitlines() if l.startswith('+') and not l.startswith('+++')]
162
169
  if 3 <= len(added) <= 12 and sum(1 for l in added if re.fullmatch(r'\s*(return\s+)?(\[[\d,\s]*\]|\{[^}]{0,80}\}|"[^"]{0,60}"|\'[^\']{0,60}\'|-?\d+(\.\d+)?|true|false|True|False|None|null)\s*;?\s*', l)) >= max(2, len(added) // 2):
163
- findings.append({'kind': 'hardcoded_output', 'severity': 'note', 'message': 'The change to ' + path + ' mostly returns literal values. Make sure it implements the behaviour rather than the expected test outputs.'})
170
+ findings.append({'kind': 'hardcoded_output', 'severity': 'note', 'message': 'The change to ' + path + ' mostly returns literal values. Make sure it implements the behaviour rather than the expected test outputs.',
171
+ 'user': 'The change to ' + path + ' mostly returns fixed values. Check that it computes the result rather than matching test outputs.'})
164
172
  return findings
165
173
 
166
174
 
175
+ def _existed(repo, base, path):
176
+ """True when path is in the base commit (it existed before the run)."""
177
+ try:
178
+ r = subprocess.run(['git', 'cat-file', '-e', (base or 'HEAD') + ':' + path], cwd=repo, capture_output=True, timeout=20)
179
+ return r.returncode == 0
180
+ except (OSError, subprocess.SubprocessError): return False
181
+
182
+
167
183
  def _file_diff(repo, base, path):
168
184
  text = _git(repo, 'diff', '--unified=0', base or 'HEAD', '--', path)
169
185
  if text: return text
@@ -374,12 +390,37 @@ def out_of_scope(files, scope):
374
390
  e = re.sub(r'\*.*$', '', re.sub(r'^\./', '', raw)).rstrip('/')
375
391
  if e == '' or path == e or path.startswith(e + '/'): return True
376
392
  return False
377
- outside = [f['path'] for f in files if not LOCKFILE.search(f['path']) and not f['path'].startswith('.mini/') and not inside(f['path'])]
393
+ # BUG-0580: PLAN.md is the project plan the harness keeps (build_planner ticks its boxes after a phase), not a change to approve.
394
+ outside = [f['path'] for f in files if not LOCKFILE.search(f['path']) and not f['path'].startswith('.mini/') and f['path'] != 'PLAN.md' and not inside(f['path'])]
378
395
  if not outside: return []
379
396
  return [{'kind': 'out_of_scope', 'severity': 'note', 'file': outside[0], 'line': 1,
380
397
  'message': '%d file%s changed outside the areas approved for this task (%s). Check that these changes are wanted.' % (len(outside), '' if len(outside) == 1 else 's', ', '.join(outside[:5]))}]
381
398
 
382
399
 
400
+ NO_TEST_SCRIPT = re.compile(r"\b(?:do not|don't|never|without)\s+(?:add(?:ing)?|creat(?:e|ing)|writ(?:e|ing)|introduc(?:e|ing))\s+(?:a\s+|any\s+|new\s+)*(?:\"?test\"?\s+scripts?|tests?(?:\s+files?)?)\b", re.I)
401
+ def forbidden_test_script(files, task=''):
402
+ """CLI bug list: "Keep running npm test until it passes. Do not add a test script." The agent decided the first
403
+ sentence overrode the second, added "test": "node --test" and a test file, and closed Done. A "do not add" stays."""
404
+ if not NO_TEST_SCRIPT.search(str(task or '')): return []
405
+ added = []
406
+ for f in files:
407
+ path = f.get('path') or ''
408
+ if f.get('deleted'): continue
409
+ if path.split('/')[-1] == 'package.json' and any(re.search(r'^\s*"test"\s*:', str(text)) for _, text in f.get('added') or []):
410
+ added.append(path + ' ("test" script)')
411
+ elif TEST_PATH.search(path) and f.get('added'):
412
+ added.append(path)
413
+ if not added: return []
414
+ return [{'kind': 'forbidden_change', 'severity': 'block', 'file': added[0].split(' ')[0], 'line': 1,
415
+ 'message': 'The request says not to add a test script or tests, but this change adds ' + ', '.join(added[:4]) + '. Undo that and report the real result instead (for example: npm test fails because the project has no test script).',
416
+ 'user': 'The request said not to add a test script, but the change added ' + ', '.join(added[:4]) + '.'}]
417
+
418
+
419
+ def in_git(repo):
420
+ """Outside a git work tree there is no diff, so an empty one says nothing about the edits (BUG-0508)."""
421
+ return _git(repo, 'rev-parse', '--is-inside-work-tree').strip() == 'true'
422
+
423
+
383
424
  def empty_change(edits, files, task=''):
384
425
  """Files were edited during the task but nothing is left behind: the edits cancelled out. An unchanged repository is
385
426
  the correct outcome when the user asked for no changes (an assessment or review), so it is not flagged then."""
@@ -418,6 +459,8 @@ RETRACTS = re.compile(r"\b(earlier|previously|before|correction|i was wrong|was
418
459
  DENIAL = re.compile(r"\b(never|at no point|did(?: not|n't)|have(?: not|n't)|had(?: not|n't)|was(?: not|n't)|were(?: not|n't)|no)\b[^.!?\n]{0,70}?\b(browser|playwright|viewport|run|ran|tests?|tested|testing|verif(?:y|ied|ication)|check(?:ed|s)?)\b", re.I)
419
460
  WHOLE_PAST = re.compile(r"\b(never|at no point|at all|actually|earlier|previous(ly)?|before|prior|so far|in this (session|conversation|project|thread)|to date|any (browser|real|actual))\b", re.I)
420
461
  THIS_TURN = re.compile(r"\b(this (turn|time|step|change|round)|just now|since (the|my) (last|latest)|after (the|my) (last|latest)|yet for|again|re-?r[au]n)\b", re.I)
462
+ ABSENT_THING = re.compile(r"\b(no|without( a| any)?|missing|lacks?( a| any)?|has(?: not|n't)( got)?( a| any)?|does(?: not|n't) have( a| any)?)\s+(\"?test\"?|tests?|testing|build|lint|check)\s+(script|scripts|file|files|suite|runner|framework|command|setup|configured|defined)\b|\bmissing script\b", re.I)
463
+ TEST_TOPIC = re.compile(r'\b(test|tests|jest|vitest|pytest|mocha|spec|unittest|playwright test)\b', re.I)
421
464
  BROWSER_WORDS = re.compile(r'\b(browser|playwright|viewport|\d{3,4} ?px|mobile width|desktop width|screenshot)\b', re.I)
422
465
  ALL_PASSED = re.compile(r"\b(all|every|everything)\b[^.!?\n]{0,50}?\b(pass(?:ed|es|ing)?|green|succe(?:ss|ed|eded|ssful))\b|\b(\d+)\s*(?:/|of|out of)\s*(\d+)\b[^.!?\n]{0,30}\b(pass(?:ed|es|ing)?)\b", re.I)
423
466
  REMOTE_OPEN = re.compile(r"\b(ci|remote|github actions?|pipeline|workflow|deploy(?:ment)? check)\b[^.!?\n]{0,90}\b(pending|not (?:yet )?(?:run|finished|complete[d]?|verified|checked|confirmed|observed)|still running|in progress|unverified|queued|waiting|has(?: not|n't)|have(?: not|n't)|did(?: not|n't))\b|\b(pending|waiting on|not (?:yet )?(?:verified|checked|confirmed|observed)|unverified)\b[^.!?\n]{0,90}\b(ci|remote|github actions?|pipeline|workflow)\b", re.I)
@@ -526,14 +569,16 @@ def behaviour_check(text, earlier=()):
526
569
  if not now: return []
527
570
  findings = []
528
571
  if not CITATION.search(str(text or '')):
529
- findings.append({'kind': 'uncited_behaviour', 'severity': 'block', 'message': 'The final message states how the code behaves ("' + quote(now[0]['text']) + '") without pointing at the code. Open the file that sets it, read the exact value and whether it renews, and cite path:line next to the statement. If you cannot find it, say it is unverified instead of stating it as fact.'})
572
+ findings.append({'kind': 'uncited_behaviour', 'severity': 'block', 'message': 'The final message states how the code behaves ("' + quote(now[0]['text']) + '") without pointing at the code. Open the file that sets it, read the exact value and whether it renews, and cite path:line next to the statement. If you cannot find it, say it is unverified instead of stating it as fact.',
573
+ 'user': 'The reply states how the code behaves ("' + quote(now[0]['text']) + '") without pointing at the code. Treat it as unverified until it is checked.'})
530
574
  if not RETRACTS.search(str(text or '')):
531
575
  for s in now:
532
576
  for old in earlier or ():
533
577
  if not isinstance(old, dict) or old.get('topic') != s['topic']: continue
534
578
  differs = (old.get('amounts') and s['amounts'] and not set(old['amounts']) & set(s['amounts'])) or (old.get('mode') and s['mode'] and old['mode'] != s['mode'])
535
579
  if differs:
536
- findings.append({'kind': 'unacknowledged_change', 'severity': 'block', 'message': 'An earlier answer in this project said: "' + quote(old.get('text')) + '". This answer says something different about the same thing ("' + quote(s['text']) + '") without saying so. Re-read the code, cite path:line, and tell the user plainly which statement is right and that the other was wrong.'})
580
+ findings.append({'kind': 'unacknowledged_change', 'severity': 'block', 'message': 'An earlier answer in this project said: "' + quote(old.get('text')) + '". This answer says something different about the same thing ("' + quote(s['text']) + '") without saying so. Re-read the code, cite path:line, and tell the user plainly which statement is right and that the other was wrong.',
581
+ 'user': 'An earlier answer in this project said: "' + quote(old.get('text')) + '". This answer says something different ("' + quote(s['text']) + '"). Check which one is right.'})
537
582
  return findings
538
583
  return findings
539
584
 
@@ -544,18 +589,25 @@ def denial_check(text, record):
544
589
  import time as _time
545
590
  for s in _sentences(text):
546
591
  if not DENIAL.search(s) or not WHOLE_PAST.search(s) or THIS_TURN.search(s) or s.endswith('?'): continue
592
+ # "There is no test script in this project" says what the project lacks, not that nothing was checked (CLI bug list:
593
+ # a true "npm test fails" answer was blocked against an older, passing npm run build).
594
+ if ABSENT_THING.search(s): continue
547
595
  browser = bool(BROWSER_WORDS.search(s))
596
+ topic = TEST_TOPIC if re.search(r'\btest', s, re.I) and not re.search(r'\b(check|verif)', s, re.I) else None
548
597
  for run in reversed(list(record or [])):
549
598
  if not isinstance(run, dict): continue
550
599
  when = _time.strftime('%Y-%m-%d %H:%M UTC', _time.gmtime(float(run.get('time') or 0)))
551
600
  if browser:
552
601
  widths = sorted({int(b.get('width') or 0) for b in run.get('browser') or [] if isinstance(b, dict) and b.get('ok')})
553
602
  if widths:
554
- return [{'kind': 'contradicted_denial', 'severity': 'block', 'message': 'The final message says "' + quote(s) + '", but the run record shows passing browser checks on ' + when + ' at ' + ', '.join('%dpx' % w for w in widths) + '. Correct the statement: say what was tested and when, and whether the code has changed since.'}]
603
+ return [{'kind': 'contradicted_denial', 'severity': 'block', 'message': 'The final message says "' + quote(s) + '", but the run record shows passing browser checks on ' + when + ' at ' + ', '.join('%dpx' % w for w in widths) + '. Correct the statement: say what was tested and when, and whether the code has changed since.',
604
+ 'user': 'The reply says "' + quote(s) + '", but the run record shows passing browser checks on ' + when + ' at ' + ', '.join('%dpx' % w for w in widths) + '.'}]
555
605
  else:
556
- passed = [clip(c.get('command') or '', 160) for c in run.get('checks') or [] if isinstance(c, dict) and c.get('status') == 'passed']
606
+ passed = [clip(c.get('command') or '', 160) for c in run.get('checks') or [] if isinstance(c, dict) and c.get('status') == 'passed'
607
+ and (topic is None or topic.search(str(c.get('command') or c.get('label') or '')))]
557
608
  if passed:
558
- return [{'kind': 'contradicted_denial', 'severity': 'block', 'message': 'The final message says "' + quote(s) + '", but the run record shows passing checks on ' + when + ' (' + '; '.join(passed[:3]) + '). Correct the statement: say what was run and when, and whether the code has changed since.'}]
609
+ return [{'kind': 'contradicted_denial', 'severity': 'block', 'message': 'The final message says "' + quote(s) + '", but the run record shows passing checks on ' + when + ' (' + '; '.join(passed[:3]) + '). Correct the statement: say what was run and when, and whether the code has changed since.',
610
+ 'user': 'The reply says "' + quote(s) + '", but the run record shows passing checks on ' + when + ' (' + '; '.join(passed[:3]) + ').'}]
559
611
  return []
560
612
 
561
613
 
@@ -570,7 +622,8 @@ def remote_claim_check(text, checks):
570
622
  if m.group(3) and m.group(3) != m.group(4): continue # "10 of 11 passed" already admits a gap
571
623
  if re.search(r'\b(local(ly)?|unit)\b', s, re.I) and not re.search(r'\b(ci|remote|github actions?|pipeline|checks)\b', s, re.I): continue # scoped to local results
572
624
  n = len(pending)
573
- return [{'kind': 'remote_pending_claim', 'severity': 'block', 'message': 'The final message says "' + quote(s) + '", but %d remote/CI check%s no result yet (%s). Report local and remote results separately: what passed locally, and that the remote check is pending or was not observed.' % (n, ' has' if n == 1 else 's have', quote(pending[0].get('label') or pending[0].get('command')))}]
625
+ return [{'kind': 'remote_pending_claim', 'severity': 'block', 'message': 'The final message says "' + quote(s) + '", but %d remote/CI check%s no result yet (%s). Report local and remote results separately: what passed locally, and that the remote check is pending or was not observed.' % (n, ' has' if n == 1 else 's have', quote(pending[0].get('label') or pending[0].get('command'))),
626
+ 'user': 'The reply says "%s", but %d remote/CI check%s no result yet (%s).' % (quote(s), n, ' has' if n == 1 else 's have', quote(pending[0].get('label') or pending[0].get('command')))}]
574
627
  return []
575
628
 
576
629
 
@@ -604,10 +657,21 @@ def repair_note(issues, limit=MAX_NOTE):
604
657
  return text if len(text) <= limit else text[:limit] + '\n…(%d more characters)' % (len(text) - limit)
605
658
 
606
659
 
660
+ # Wording meant for the agent ("State in the final message ...") never reaches the person (web bug list, Bug-022).
661
+ _AGENT_DIRECTED = re.compile(r'\b(?:final message|your (?:final )?(?:reply|answer|message)|in the summary|tell the user|before finishing)\b', re.I)
662
+
663
+
607
664
  def notice(report):
608
- """The lines the harness tells the user itself when verification ends with points the agent was not sent back to fix."""
609
- items = [bounded(f.get('message'), 320, 320) for f in notes((report or {}).get('findings'))][:4]
610
- return ('Points to check (from the harness, not the agent):\n- ' + '\n- '.join(items)) if items else ''
665
+ """The lines shown to the person when verification ends with points the agent was not sent back to fix. Each uses the
666
+ finding's user-facing text; a finding written only as an instruction to the agent is left out."""
667
+ items = []
668
+ for f in notes((report or {}).get('findings')):
669
+ text = str(f.get('user') or '').strip() or str(f.get('message') or '').strip()
670
+ if not text or (not f.get('user') and _AGENT_DIRECTED.search(text)):
671
+ continue
672
+ items.append(bounded(text, 320, 320))
673
+ items = items[:4]
674
+ return ('Worth checking:\n- ' + '\n- '.join(items)) if items else ''
611
675
 
612
676
 
613
677
  # Checks that read the agent's wording are heuristics. Each is asked once; if the agent keeps the statement, the user is told
@@ -638,9 +702,16 @@ def report(repo, base, final_text, commands, checks, task='', last_edit=None, ed
638
702
  try: files = file_diffs(repo, base)
639
703
  except Exception: pass
640
704
  if files is not None:
641
- for check in (lambda: line_rules(files, task), lambda: check_weakening(files, task), lambda: invalid_json(repo, files), lambda: out_of_scope(files, scope), lambda: empty_change(edits, files, task)):
705
+ for check in (lambda: line_rules(files, task), lambda: check_weakening(files, task), lambda: invalid_json(repo, files), lambda: out_of_scope(files, scope), lambda: empty_change(edits, files, task) if in_git(repo) else [], lambda: forbidden_test_script(files, task)):
642
706
  try: findings += check()
643
707
  except Exception: pass
708
+ # Build integrity: navigation into pages that were never built, and a message that admits an open error yet says done.
709
+ try:
710
+ import site_check
711
+ changed = changed_paths(repo, base)[0] if base else []
712
+ if changed: findings += site_check.dead_links(repo, changed)
713
+ findings += site_check.open_error_claim(final_text)
714
+ except Exception: pass
644
715
  for check in (lambda: citation_check(final_text, repo, task), lambda: behaviour_check(final_text, earlier), lambda: denial_check(final_text, record), lambda: remote_claim_check(final_text, checks)):
645
716
  try: findings += check()
646
717
  except Exception: pass
@@ -652,12 +723,18 @@ def report(repo, base, final_text, commands, checks, task='', last_edit=None, ed
652
723
 
653
724
 
654
725
  # Shell commands that count as checks (shared by the bridge and the PreToolUse hook).
655
- TEST_COMMAND = re.compile(r'(^|[;&|(\s])(pytest|python3? -m (pytest|unittest)|npm (run )?(test|build|lint|typecheck)|pnpm (run )?(test|build|lint)|yarn (run )?(test|build|lint)|npx (tsc|vitest|jest|playwright|eslint)|tsc( |$)|vitest|jest|go (test|build|vet)|cargo (test|build|check)|make (test|check)|bun (run )?test|deno test|mvn( -q)? test|gradle test|ruff|mypy|node --test)', re.I)
726
+ # BUG-0350: `swiftc -typecheck *.swift` and `xcodebuild ... build` are the type check and build of a Swift project.
727
+ TEST_COMMAND = re.compile(r'(^|[;&|(\s])(pytest|python3? -m (pytest|unittest)|npm (run )?(test|build|lint|typecheck)|pnpm (run )?(test|build|lint)|yarn (run )?(test|build|lint)|npx (tsc|vitest|jest|playwright|eslint)|tsc( |$)|vitest|jest|go (test|build|vet)|cargo (test|build|check)|make (test|check)|bun (run )?test|deno test|mvn( -q)? test|gradle test|ruff|mypy|node --test|swift (test|build)|swiftc\b[^;&|\n]*\s-(typecheck|parse)\b|xcrun swiftc\b[^;&|\n]*\s-typecheck\b|xcodebuild\b[^;&|\n]*\b(build|test)\b)', re.I)
656
728
  # Inline checks: an interpreter run (heredoc, -c/-e or a script) that asserts on behaviour, or runs a test-named file.
657
729
  INLINE_RUN = re.compile(r'(^|[;&|(\s])(python3?|node|bun|deno run|tsx|ts-node)\s+(-c\b|-e\b|-\s|-$|<<|[\w./-]+\.(py|[cm]?js|ts)\b)', re.M)
658
- INLINE_ASSERT = re.compile(r'\bassert\b|console\.assert|\bexpect\(|\bassert\.\w+\(|[\w./-]*(test_\w+|\w+_test|\w+\.test|\w+\.spec)\.(py|[cm]?js|ts)\b')
730
+ # BUG-0296: `if (greet('World') !== 'Hello, World') process.exit(1)` asserts as much as assert() does.
731
+ INLINE_ASSERT = re.compile(r'\bassert\b|console\.assert|\bexpect\(|\bassert\.\w+\(|[\w./-]*(test_\w+|\w+_test|\w+\.test|\w+\.spec)\.(py|[cm]?js|ts)\b|\bprocess\.exit\(\s*[1-9]|\bprocess\.exitCode\s*=\s*[1-9]|\bsys\.exit\(\s*[1-9]|\bthrow new Error\(|\braise (?:SystemExit|AssertionError|ValueError|RuntimeError)\b')
732
+ # An inline script that rewrites files is an edit, not a check, even when it asserts that its search text was found
733
+ # (Windows bug list, item 7: python3 heredoc edits to .tsx files showed up as failed checks).
734
+ EDIT_SCRIPT = re.compile(r'\.write_text\(|\.write_bytes\(|writeFileSync\(|open\([^)]*,\s*[\'"][wa]\+?[\'"]|\bsed\s+-i')
659
735
  def looks_like_check(command):
660
- return bool(TEST_COMMAND.search(command) or (INLINE_RUN.search(command) and INLINE_ASSERT.search(command)))
736
+ if TEST_COMMAND.search(command): return True
737
+ return bool(INLINE_RUN.search(command) and INLINE_ASSERT.search(command) and not EDIT_SCRIPT.search(command))
661
738
 
662
739
 
663
740
  # ---------------------------------------------------------------- exit-status integrity (EXEC-001)
@@ -723,3 +800,63 @@ def unverified_banner(report):
723
800
  detail = ('; '.join(parts) + '. ') if parts else ''
724
801
  return ('> **Not verified.** The final checks did not confirm this work (' + detail.rstrip('. ') + ').' if parts else '> **Not verified.** The final checks did not confirm this work.') + \
725
802
  ' Any "verified" or "working" claims below are unconfirmed until the checks are rerun and pass.\n\n'
803
+
804
+
805
+ # ---------------------------------------------------------------- BUG-0542: projects with no test suite
806
+ # A project with no tests, build or type check cannot be "verified" by one. Running the changed program itself
807
+ # (node app.js, python3 tool.py, ./run.sh) and seeing it exit 0 is the best check there is, so it counts as one.
808
+ RUN_FILE = re.compile(r'^\s*(?:(?:node|python3?|bash|sh|bun|deno run|tsx|ts-node)\s+(?:-[\w-]+\s+)*)?(\.{0,2}/?[\w./-]+\.(?:py|[cm]?js|ts|sh)|\./[\w./-]+)(?:\s+[^;&|<>`$]*)?$')
809
+ SUITE_FILES = re.compile(r'(^|/)(pytest\.ini|tox\.ini|conftest\.py|noxfile\.py|Cargo\.toml|go\.mod|pom\.xml|build\.gradle(\.kts)?|tsconfig\.json|jest\.config\.[cm]?[jt]s|vitest\.config\.[cm]?[jt]s|test_[^/]+\.py|[^/]+_test\.(py|go)|[^/]+\.(test|spec)\.[cm]?[jt]sx?)$|(^|/)(tests?|__tests__|spec)/', re.I)
810
+
811
+ def has_test_suite(repo):
812
+ """True when the project has something a check can run: test files, a test/build/lint script, or a build config."""
813
+ import subprocess, json
814
+ root = Path(repo)
815
+ try:
816
+ pkg = json.loads((root / 'package.json').read_text())
817
+ scripts = pkg.get('scripts') if isinstance(pkg.get('scripts'), dict) else {}
818
+ for k in ('test', 'build', 'lint', 'typecheck', 'check'):
819
+ v = str(scripts.get(k) or '')
820
+ if v and 'no test specified' not in v: return True
821
+ except (OSError, ValueError, AttributeError): pass
822
+ try:
823
+ if re.search(r'^\s*(test|check)\s*:', (root / 'Makefile').read_text(errors='replace'), re.M): return True
824
+ except OSError: pass
825
+ try:
826
+ if '[tool.pytest' in (root / 'pyproject.toml').read_text(errors='replace'): return True
827
+ except OSError: pass
828
+ try:
829
+ out = subprocess.run(['git', 'ls-files', '-co', '--exclude-standard'], cwd=root, capture_output=True, text=True, timeout=10)
830
+ names = out.stdout.splitlines() if out.returncode == 0 else [str(p.relative_to(root)) for p in list(root.rglob('*'))[:5000] if '/node_modules/' not in str(p)]
831
+ except (OSError, subprocess.SubprocessError, ValueError): names = []
832
+ return any(SUITE_FILES.search(n.replace('\\', '/')) for n in names[:20000] if not n.startswith('node_modules/'))
833
+
834
+ INLINE_MODULE = re.compile(r"""\brequire\(\s*['"](\.{1,2}/[\w./-]+)['"]\s*\)|\bimport\(\s*['"](\.{1,2}/[\w./-]+)['"]\s*\)|\bfrom\s+['"](\.{1,2}/[\w./-]+)['"]|(?:^|[;"'])\s*from\s+([\w.]+)\s+import\b|(?:^|[;"'])\s*import\s+([\w.]+)""", re.M)
835
+
836
+ def inline_module_check(command, repo):
837
+ """BUG-0296: `node -e "const {greet} = require('./greet'); console.log(greet('World'))"` loads the changed file and runs
838
+ it. In a project with no test suite that is the check the agent can run, like `node greet.js`. Returns the file, or ''."""
839
+ command = str(command or '')
840
+ if not re.search(r'(^|[;&|(\s])(python3?|node|bun|tsx|ts-node)\s+(-c\b|-e\b|-p\b|-\s|-$|<<)', command, re.M) or EDIT_SCRIPT.search(command): return ''
841
+ root = Path(repo).resolve()
842
+ for m in INLINE_MODULE.finditer(command):
843
+ rel = next(g for g in m.groups() if g)
844
+ candidates = [rel] if rel.startswith('.') else [rel.replace('.', '/')]
845
+ for base in candidates:
846
+ for ext in ('', '.js', '.mjs', '.cjs', '.ts', '.py', '/index.js', '/__init__.py'):
847
+ try:
848
+ target = (root / (base + ext)).resolve()
849
+ if target.is_file() and root in target.parents: return str(target.relative_to(root))
850
+ except (OSError, ValueError): pass
851
+ return ''
852
+
853
+
854
+ def program_run_check(command, repo):
855
+ """The repository file a command runs directly (node a.js, ./run.sh), when that file exists; else ''."""
856
+ m = RUN_FILE.match(str(command or ''))
857
+ if not m: return inline_module_check(command, repo)
858
+ target = (Path(repo) / m.group(1)).resolve()
859
+ try:
860
+ if target.is_file() and Path(repo).resolve() in target.parents: return m.group(1)
861
+ except OSError: pass
862
+ return ''
package/worker/wakeups.py CHANGED
@@ -3,7 +3,7 @@
3
3
  The run writes ROOT/wakeup.json; whoever owns the session schedules it: the cloud picks it up when the run ends
4
4
  (workflows/wake-job.ts sleeps until the time, then starts a run with this note), the Mac engine's scheduler checks
5
5
  every minute and on wake (apps/laptop/src/wakeups.mjs). One pending wakeup per session; a new one replaces it."""
6
- import json, secrets, time
6
+ import json, os, secrets, time
7
7
  from datetime import datetime, timezone
8
8
 
9
9
  MIN_MINUTES, MAX_MINUTES, GOAL_MIN_MINUTES = 5, 30*24*60, 1
@@ -27,17 +27,17 @@ def read(root):
27
27
  def schedule(root,at=None,in_minutes=None,note='',kind='agent',run_id=None,now=None):
28
28
  """Validate and record one pending wakeup. Returns the record; raises ValueError with a message the agent can act on."""
29
29
  now=time.time() if now is None else now
30
- if kind not in ('agent','goal'):raise ValueError('Unknown wakeup kind')
30
+ if kind not in ('agent','goal','verify'):raise ValueError('Unknown wakeup kind')
31
31
  if (at is None)==(in_minutes is None):raise ValueError('Give exactly one of in_minutes or at')
32
32
  if in_minutes is not None:
33
33
  if isinstance(in_minutes,bool) or not isinstance(in_minutes,(int,float)):raise ValueError('in_minutes must be a number')
34
34
  when=now+float(in_minutes)*60
35
35
  else:when=_parse(at)
36
- low=GOAL_MIN_MINUTES if kind=='goal' else MIN_MINUTES
36
+ low=GOAL_MIN_MINUTES if kind in ('goal','verify') else MIN_MINUTES
37
37
  if when<now+low*60-1:raise ValueError('Schedule the wakeup at least %d minutes ahead'%low)
38
38
  if when>now+MAX_MINUTES*60:raise ValueError('Schedule the wakeup within 30 days')
39
39
  note=' '.join(str(note or '').split())[:1000]
40
- if kind=='agent' and not note:raise ValueError('Add a note saying what to check when the session resumes')
40
+ if kind in ('agent','verify') and not note:raise ValueError('Add a note saying what to check when the session resumes')
41
41
  record={'id':secrets.token_hex(8),'at':_iso(when),'note':note,'kind':kind,'state':'pending','created':_iso(now),**({'runId':run_id} if run_id else {})}
42
42
  (root/'wakeup.json').write_text(json.dumps(record))
43
43
  return record
@@ -61,3 +61,55 @@ def tool(root,args,event=None,run_id=None):
61
61
  record=schedule(root,at=args.get('at'),in_minutes=args.get('in_minutes'),note=args.get('note',''),run_id=run_id)
62
62
  if event:event('wakeup',state='pending',id=record['id'],at=record['at'],note=record['note'],kind='agent')
63
63
  return json.dumps({'scheduled':record['at'],'id':record['id'],'note':'This session resumes then. Finish this turn now with a short summary of what is pending.'})
64
+
65
+
66
+ # ---------------------------------------------------------------- automatic continue after failed verification
67
+ # A run whose final checks still fail after its repair rounds (or that hit the time limit mid-build) continues by itself:
68
+ # it schedules a 'verify' wakeup a minute out, and the next run starts with the open problems. Bounded per request so a
69
+ # problem the agent cannot fix never loops; any run the person starts cancels the pending continue and resets the count.
70
+ VERIFY_FILE='verify-resume.json'
71
+ def verify_limit():
72
+ try:return max(0,min(5,int(os.getenv('MINI_VERIFY_RESUMES','2') or 2)))
73
+ except ValueError:return 2
74
+ def _verify_state(root):
75
+ try:value=json.loads((root/VERIFY_FILE).read_text())
76
+ except (OSError,ValueError):return {}
77
+ return value if isinstance(value,dict) else {}
78
+
79
+ def verify_resume(root,issues,wake=None,task='',reason='checks',event=None,in_minutes=1,now=None):
80
+ """Schedule the automatic continue. Returns the wakeup record, or None when the limit is reached or another wakeup
81
+ (the agent's own check-in or a goal) is already pending."""
82
+ resumed=isinstance(wake,dict) and wake.get('kind')=='verify'
83
+ prev=_verify_state(root) if resumed else {}
84
+ count=int(prev.get('count') or 0)+1
85
+ task=prev.get('task') or task # a continue run's own prompt is the wakeup note; keep the person's request
86
+ if count>verify_limit():
87
+ (root/VERIFY_FILE).write_text(json.dumps({'count':count-1,'exhausted':True,'task':str(task or '')[:600]}))
88
+ if event:event('auto_continue',state='exhausted',attempts=count-1,content='Stopped continuing automatically after %d attempts; the open problems are listed below'%(count-1))
89
+ return None
90
+ current=read(root)
91
+ if current and current.get('state')=='pending' and current.get('kind')!='verify':return None
92
+ head=('The run reached its time limit before the work was finished and checked.' if reason=='time'
93
+ else 'The model connection dropped before the run finished.' if reason=='stall'
94
+ else 'The final checks still failed when the run ended.')
95
+ problems=' '.join(' '.join(str(i).split()) for i in (issues or [])[:4])[:700]
96
+ asked=' '.join(str(task or '').split())[:240]
97
+ note=(head+(' Open problems: '+problems if problems else '')+(' Original request: '+asked if asked else ''))[:1000]
98
+ record=schedule(root,in_minutes=in_minutes,note=note,kind='verify',now=now)
99
+ (root/VERIFY_FILE).write_text(json.dumps({'count':count,'id':record['id'],'task':str(task or '')[:600]}))
100
+ if event:
101
+ event('wakeup',state='pending',id=record['id'],at=record['at'],note=record['note'],kind='verify')
102
+ event('auto_continue',state='scheduled',attempt=count,limit=verify_limit(),at=record['at'],content='Continuing automatically to fix what is still open (attempt %d of %d)'%(count,verify_limit()))
103
+ return record
104
+
105
+ def verify_settled(root,event=None):
106
+ """The checks passed: clear the count (and any stale automatic continue)."""
107
+ (root/VERIFY_FILE).unlink(missing_ok=True)
108
+ current=read(root)
109
+ if current and current.get('state')=='pending' and current.get('kind')=='verify':
110
+ gone=cancel(root)
111
+ if event and gone:event('wakeup',state='cancelled',id=gone['id'])
112
+
113
+ def person_started(root,event=None):
114
+ """A run the person started (not a wakeup): it replaces any pending automatic continue and resets the count."""
115
+ verify_settled(root,event)