mlai-code 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) 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 +153 -26
  5. package/src/cloud.mjs +2 -0
  6. package/src/engine.mjs +1 -1
  7. package/src/headless.mjs +39 -11
  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 +17 -0
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +16 -5
  16. package/src/runtime.mjs +2 -0
  17. package/src/server.mjs +46 -7
  18. package/src/session.mjs +31 -8
  19. package/src/tui/acp.mjs +121 -19
  20. package/src/tui/app.mjs +2 -1
  21. package/src/tui/chat.mjs +35 -10
  22. package/src/tui/cmd-config.mjs +3 -1
  23. package/src/tui/cmd-core.mjs +9 -5
  24. package/src/tui/cmd-extensibility.mjs +5 -0
  25. package/src/tui/extensions-local.mjs +2 -0
  26. package/src/tui/mcp-config.mjs +22 -4
  27. package/src/tui/review-cli.mjs +15 -4
  28. package/src/tui/snapshots.mjs +57 -16
  29. package/src/tui/transcript.mjs +13 -2
  30. package/src/two-words.mjs +14 -8
  31. package/src/view-sync.mjs +48 -0
  32. package/src/winenv.mjs +1 -1
  33. package/src/workspace-api.mjs +21 -4
  34. package/vendor/client-sdk/index.cjs +2 -1
  35. package/vendor/cloud-cli/mlai.mjs +23 -11
  36. package/worker/architecture_worker.py +33 -4
  37. package/worker/browser_tool.py +19 -1
  38. package/worker/chat_fork.py +4 -1
  39. package/worker/checkpoints.py +71 -8
  40. package/worker/command_safety.py +56 -3
  41. package/worker/connected_turn.py +30 -0
  42. package/worker/conversation.py +125 -13
  43. package/worker/git_sync.py +4 -4
  44. package/worker/image_generation.py +2 -2
  45. package/worker/kimi_bridge.py +251 -31
  46. package/worker/kimi_gates.py +25 -6
  47. package/worker/kimi_hook.py +154 -13
  48. package/worker/media_tools.py +4 -1
  49. package/worker/mlai_hooks.py +222 -3
  50. package/worker/mlai_mcp.py +26 -6
  51. package/worker/mlai_review/README.md +35 -0
  52. package/worker/mlai_review/__init__.py +1 -0
  53. package/worker/mlai_review/__main__.py +261 -0
  54. package/worker/mlai_review/_compat.py +29 -0
  55. package/worker/mlai_review/analysis/__init__.py +3 -0
  56. package/worker/mlai_review/analysis/detect.py +50 -0
  57. package/worker/mlai_review/analysis/main.py +128 -0
  58. package/worker/mlai_review/analysis/messages.py +8 -0
  59. package/worker/mlai_review/analysis/tools.py +194 -0
  60. package/worker/mlai_review/application/__init__.py +1 -0
  61. package/worker/mlai_review/application/asking.py +53 -0
  62. package/worker/mlai_review/application/challengers.py +142 -0
  63. package/worker/mlai_review/application/context_builder.py +194 -0
  64. package/worker/mlai_review/application/errors.py +17 -0
  65. package/worker/mlai_review/application/feedback.py +52 -0
  66. package/worker/mlai_review/application/matching.py +46 -0
  67. package/worker/mlai_review/application/messages.py +41 -0
  68. package/worker/mlai_review/application/ports.py +222 -0
  69. package/worker/mlai_review/application/prompts.py +342 -0
  70. package/worker/mlai_review/application/review_service.py +200 -0
  71. package/worker/mlai_review/application/reviewers.py +438 -0
  72. package/worker/mlai_review/application/streaming.py +91 -0
  73. package/worker/mlai_review/application/tools.py +138 -0
  74. package/worker/mlai_review/application/usage.py +145 -0
  75. package/worker/mlai_review/application/write_check.py +46 -0
  76. package/worker/mlai_review/contracts/__init__.py +5 -0
  77. package/worker/mlai_review/contracts/analysis.py +57 -0
  78. package/worker/mlai_review/contracts/review.py +42 -0
  79. package/worker/mlai_review/domain/__init__.py +4 -0
  80. package/worker/mlai_review/domain/changes.py +77 -0
  81. package/worker/mlai_review/domain/context.py +147 -0
  82. package/worker/mlai_review/domain/diagnostics.py +239 -0
  83. package/worker/mlai_review/domain/feedback.py +216 -0
  84. package/worker/mlai_review/domain/findings.py +505 -0
  85. package/worker/mlai_review/domain/lifecycle.py +85 -0
  86. package/worker/mlai_review/domain/partition.py +42 -0
  87. package/worker/mlai_review/domain/relations.py +166 -0
  88. package/worker/mlai_review/domain/relevance.py +202 -0
  89. package/worker/mlai_review/domain/report.py +99 -0
  90. package/worker/mlai_review/domain/structure.py +56 -0
  91. package/worker/mlai_review/domain/writes.py +86 -0
  92. package/worker/mlai_review/eval.py +221 -0
  93. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  94. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  95. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  96. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  97. package/worker/mlai_review/feedback_report.py +60 -0
  98. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  99. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  100. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  101. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  102. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  103. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  104. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  105. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  106. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  107. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  108. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  109. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  110. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  111. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  112. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  113. package/worker/mlai_review/infrastructure/messages.py +54 -0
  114. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  115. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  116. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  117. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  118. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  119. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  120. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  121. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  122. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  123. package/worker/mlai_review/pipeline.py +89 -0
  124. package/worker/mlai_review/runtime.py +194 -0
  125. package/worker/mlai_review/settings.py +139 -0
  126. package/worker/preview.py +15 -0
  127. package/worker/product_facts.py +3 -1
  128. package/worker/repo_policy.py +5 -0
  129. package/worker/roles.py +29 -2
  130. package/worker/runner.py +164 -23
  131. package/worker/runtime_control.py +95 -9
  132. package/worker/secret_scan.py +3 -2
  133. package/worker/server_memory.py +122 -0
  134. package/worker/subagents.py +6 -2
  135. package/worker/tool_catalog.py +5 -2
  136. package/worker/verification.py +113 -8
@@ -192,6 +192,127 @@ def outside_repo(p, repo=None):
192
192
  return not (full == base or full.startswith(base.rstrip(os.sep) + os.sep))
193
193
 
194
194
 
195
+ # BUG-0499: on This Mac/CLI, reading outside the project asks first unless the path is under a folder the person added
196
+ # with --add-dir (request.json `readDirs`). A yes covers that folder for the rest of the run.
197
+ OUTSIDE_READ_PROGRAMS = frozenset(('cat', 'head', 'tail', 'less', 'more', 'nl', 'tac', 'grep', 'rg', 'egrep', 'fgrep', 'ag', 'ack', 'ls', 'tree', 'wc',
198
+ 'stat', 'file', 'xxd', 'od', 'strings', 'diff', 'cmp', 'awk', 'sed', 'sort', 'uniq', 'cut', 'jq', 'yq', 'find', 'fd',
199
+ 'md5sum', 'sha256sum', 'sha1sum', 'shasum', 'base64', 'zcat', 'du', 'cp', 'tar', 'zip', 'rsync'))
200
+ _OUTSIDE_OK = set()
201
+ # Installed software and system settings a shell command may inspect (which, ls /usr/local/bin, cat /etc/os-release).
202
+ SYSTEM_READ = ('/usr', '/bin', '/sbin', '/lib', '/opt', '/etc', '/nix', '/snap', '/System', '/Library', '/Applications', '/private/etc')
203
+
204
+
205
+ def _read_roots(cfg, root=None):
206
+ import tempfile
207
+ out = [os.path.realpath(str(root or ROOT)), os.path.realpath(os.path.dirname(os.path.abspath(__file__))), os.path.realpath(tempfile.gettempdir()), '/tmp', '/private/tmp', '/dev']
208
+ out += [os.path.realpath(os.path.expanduser(d)) for d in (cfg.get('readDirs') or []) if isinstance(d, str) and d]
209
+ return out + sorted(_OUTSIDE_OK)
210
+
211
+
212
+ def _under(full, roots):
213
+ return any(full == r or full.startswith(r.rstrip(os.sep) + os.sep) for r in roots)
214
+
215
+
216
+ def _command_read_paths(command):
217
+ """Path-looking arguments of read programs in a shell command (absolute, ~, $HOME or ../ paths only)."""
218
+ out = []
219
+ try:
220
+ import command_safety as cs
221
+ for st in cs.split_statements(str(command or ''))[:40]:
222
+ try: words, redirects = cs._words(st); words, _f = cs._strip_wrappers(words)
223
+ except Exception: continue
224
+ targets = [t for kind, t in redirects if kind == 'read']
225
+ if words and words[0].rsplit('/', 1)[-1] in OUTSIDE_READ_PROGRAMS: targets += [w for w in words[1:] if not w.startswith('-')]
226
+ for w in targets:
227
+ w = w.replace('$HOME', '~').replace('${HOME}', '~')
228
+ if w.startswith(('/', '~', '../')) or w == '..': out.append(w)
229
+ except Exception: return []
230
+ return out[:20]
231
+
232
+
233
+ def outside_read_paths(tool, command, path, cfg, root=None, repo=None):
234
+ """Paths this call would read outside the project and outside every allowed folder."""
235
+ if command: paths = _command_read_paths(command)
236
+ elif canonical(tool) == 'read': paths = [path] if isinstance(path, str) else list(path or [])
237
+ else: return []
238
+ base = os.path.realpath(str(repo or REPO)); roots = [base] + _read_roots(cfg, root) + (list(SYSTEM_READ) if command else [])
239
+ out = []
240
+ for p in paths:
241
+ if not p: continue
242
+ s = os.path.expanduser(str(p))
243
+ full = os.path.realpath(s if os.path.isabs(s) else os.path.join(base, s))
244
+ if not _under(full, roots): out.append(full)
245
+ return out
246
+
247
+
248
+ def read_allowed(full, cfg=None, root=None):
249
+ """True when an absolute path outside the project may be read (an --add-dir folder, or approved this run)."""
250
+ cfg = cfg if cfg is not None else settings(root)
251
+ dirs = [os.path.realpath(os.path.expanduser(d)) for d in (cfg.get('readDirs') or []) if isinstance(d, str) and d]
252
+ return _under(os.path.realpath(str(full)), dirs + sorted(_OUTSIDE_OK))
253
+
254
+
255
+ def outside_read_gate(tool, args, command, path, cfg, root=None, mode=None):
256
+ if not cfg.get('laptop') or cfg.get('restricted'): return None
257
+ if (cfg.get('perms') or {}).get('bypass') or (Path(root or ROOT) / 'kimi-approve-all').exists(): return None
258
+ outside = outside_read_paths(tool, command, path, cfg, root)
259
+ if not outside: return None
260
+ import mlai_permissions as mp
261
+ shown = ', '.join(clip(p, 200) for p in outside[:3])
262
+ if not mp.ask_user('Read outside the project: ' + shown, 'outside the project', root or ROOT,
263
+ reason='This reads a file outside the project folder. Start mlai with --add-dir <folder> to allow a folder without asking.'):
264
+ emit('policy', root, rule='outside the project', decision='deny', content='Not read: ' + shown, permission=True)
265
+ return ('The user did not approve reading outside the project (' + shown + '). Do not try another way to read it; '
266
+ 'tell the user they can allow the folder with --add-dir <folder>.')
267
+ for p in outside: _OUTSIDE_OK.add(p)
268
+ return None
269
+
270
+
271
+ # BUG-0531: asked to fix one function, the agent created tests/test_x.py and pip-installed pytest into a new .venv.
272
+ # Running the project's existing tests is fine; adding test files or installing tools needs the user's say-so.
273
+ _INSTALL = re.compile(r'(?:^|[;&|(]\s*|\s)(?:sudo\s+)?(?:(?:python3?|py)\s+-m\s+pip|pip3?|uv\s+pip|pipx|conda|mamba|poetry|brew|apt(?:-get)?|gem|cargo|go)\s+(?:install|add)\b'
274
+ r'|(?:^|[;&|(]\s*|\s)(?:npm|pnpm|yarn|bun)\s+(?:install|i|add)\s+(?:-\S+\s+)*[@\w]', re.I)
275
+ _TEST_FILE = re.compile(r'(?:^|/)(?:tests?|__tests__|spec|e2e)/|(?:^|/)test_[^/]+\.py$|_test\.(?:py|go)$|\.(?:test|spec)\.[cm]?[jt]sx?$', re.I)
276
+ _ASKED_INSTALL = re.compile(r'\b(?:install|installing|dependenc(?:y|ies)|packages?|set ?up|setup|venv|virtual ?env|requirements|pip|npm i|add (?:a |the )?(?:library|lib|package|dependency))\b', re.I)
277
+ _ASKED_TESTS = re.compile(r'\b(?:tests?|testing|unit ?tests?|spec|specs|coverage|pytest|jest|vitest|tdd)\b', re.I)
278
+ _SCOPE_OK = set()
279
+
280
+
281
+ def install_command(command):
282
+ return bool(command) and bool(_INSTALL.search(str(command)))
283
+
284
+
285
+ def new_test_file(tool, path, root=None):
286
+ if canonical(tool) != 'edit': return None
287
+ for p in ([path] if isinstance(path, str) else list(path or [])):
288
+ if not p or not _TEST_FILE.search(str(p).replace('\\', '/')): continue
289
+ full = Path(p) if os.path.isabs(str(p)) else Path(REPO) / str(p)
290
+ if not full.exists(): return str(p)
291
+ return None
292
+
293
+
294
+ def scope_gate(tool, command, path, cfg, run=None, root=None):
295
+ """Laptop runs: adding a new test file or installing packages the request did not ask for needs the user first.
296
+ Unattended runs (auto, approve all, bypass) cannot ask, so the agent is told to ask in its answer instead."""
297
+ if not cfg.get('laptop') or cfg.get('restricted'): return None
298
+ task = str((run or {}).get('task') or _request(root or ROOT).get('task') or '')
299
+ what = None
300
+ if command and install_command(command) and not _ASKED_INSTALL.search(task): what = ('install', 'Install packages: ' + clip(command, 300))
301
+ elif not command:
302
+ f = new_test_file(tool, path, root)
303
+ if f and not _ASKED_TESTS.search(task): what = ('test file', 'Add a new test file: ' + clip(f, 200))
304
+ if not what or what[1] in _SCOPE_OK: return None
305
+ unattended = (run or {}).get('mode') in ('auto', 'plan') or (cfg.get('perms') or {}).get('bypass') or (Path(root or ROOT) / 'kimi-approve-all').exists()
306
+ stop = ('Not done: ' + what[1] + '. The user did not ask for this. You may run the tests the project already has, but do not add new '
307
+ 'test files or install tools on your own. Finish what was asked and, in your answer, ask whether they want this.')
308
+ if unattended:
309
+ emit('policy', root, rule='not requested', decision='deny', content=what[1]); return stop
310
+ import mlai_permissions as mp
311
+ if not mp.ask_user(what[1], 'not requested', root or ROOT, reason='Not part of what you asked for. Allow the agent to do this?'):
312
+ emit('policy', root, rule='not requested', decision='deny', content=what[1], permission=True); return stop
313
+ _SCOPE_OK.add(what[1]); return None
314
+
315
+
195
316
  def restricted_block(tool, command, path, cfg, root=None):
196
317
  if not cfg.get('restricted'): return None
197
318
  if command or canonical(tool) in ('shell', 'agent'):
@@ -245,7 +366,8 @@ def settings(root=None, repo=None, config=None):
245
366
  'vault': {}, 'plugins': {p['id']: p for p in (ext.get('plugins') or []) if isinstance(p, dict) and isinstance(p.get('id'), str)},
246
367
  'files': ext.get('files') if isinstance(ext.get('files'), dict) else {}, 'perms': _perms_config(ext.get('permissions')),
247
368
  'offline': isinstance(ext.get('network'), dict) and ext['network'].get('enabled') is False,
248
- 'restricted': isinstance(ext.get('restricted'), dict) and ext['restricted'].get('enabled') is True}
369
+ 'restricted': isinstance(ext.get('restricted'), dict) and ext['restricted'].get('enabled') is True,
370
+ 'readDirs': [d for d in (config.get('readDirs') or []) if isinstance(d, str)][:20] if isinstance(config.get('readDirs'), list) else []}
249
371
  _CACHE.clear(); _CACHE[key] = out
250
372
  return out
251
373
 
@@ -341,11 +463,33 @@ def _glob_hit(c, q):
341
463
 
342
464
 
343
465
  def path_match(path, patterns, repo=None):
344
- """Glob match for repo-relative patterns (src/**, **/*.pem) and absolute or ~ patterns (~/.aws/**)."""
466
+ """Glob match for repo-relative patterns (src/**, **/*.pem) and absolute or ~ patterns (~/.aws/**).
467
+ BUG-0526: a symlink alias (docs -> secret, cfg -> ~/.aws) is matched by the real path it points to as well."""
345
468
  repo = os.path.normpath(str(repo or REPO))
346
469
  raw = _expand(str(path or '').strip().strip('"\''))
347
470
  if not raw: return None
348
471
  absolute = os.path.normpath(raw if os.path.isabs(raw) else os.path.join(repo, raw))
472
+ hit = _path_match(absolute, patterns, repo)
473
+ if hit or not patterns: return hit
474
+ try:
475
+ real, real_repo = os.path.realpath(absolute), os.path.realpath(repo)
476
+ except (OSError, ValueError):
477
+ return None
478
+ if real == absolute and real_repo == repo: return None
479
+ hit = _path_match(real, patterns, real_repo)
480
+ if hit: return hit
481
+ # Expanded pattern roots can themselves be symlinks (macOS /tmp -> /private/tmp): compare against the real ones too.
482
+ for pat in patterns:
483
+ e = _expand(pat)
484
+ if not os.path.isabs(e): continue
485
+ parts = e.split('/'); i = next((k for k, x in enumerate(parts) if re.search(r'[*?\[]', x)), len(parts))
486
+ fixed = '/'.join(parts[:i]) or '/'
487
+ moved = os.path.realpath(fixed)
488
+ if moved != os.path.normpath(fixed) and _path_match(real, [moved + ('/' + '/'.join(parts[i:]) if i < len(parts) else '')], real_repo): return pat
489
+ return None
490
+
491
+
492
+ def _path_match(absolute, patterns, repo):
349
493
  rel = os.path.relpath(absolute, repo) if absolute == repo or absolute.startswith(repo + os.sep) else None
350
494
  for pat in patterns:
351
495
  q = os.path.normpath(_expand(pat)) + ('/**' if str(pat).endswith('/**') and not os.path.normpath(_expand(pat)).endswith('**') else '')
@@ -448,7 +592,7 @@ def _run_stamp(root=None):
448
592
 
449
593
 
450
594
  def remember_denied(command, pat, root=None, repo=None):
451
- if pat in ('credentials', 'network'): return
595
+ if pat in ('credentials', 'network', 'git-hooks'): return
452
596
  targets = _deny_targets(command, pat, repo)
453
597
  if not targets: return
454
598
  f = Path(root or ROOT) / DENIED_FILE
@@ -496,11 +640,36 @@ def denied_again(tool, command=None, paths=(), root=None, repo=None):
496
640
  return None, None
497
641
 
498
642
 
643
+ # BUG-0551: the project's git hooks (pre-commit lint, pre-push tests) are the team's rules. The agent never skips them
644
+ # (--no-verify, -n, core.hooksPath) or rewrites them; when a hook blocks, it reports that and asks the user.
645
+ GIT_HOOK_REASON = ('Refused: this would skip or change the project\'s git hooks (for example a pre-commit lint check). Agents never use '
646
+ '--no-verify or edit .git/hooks. Do not get the same result another way. Tell the user what the hook reported and ask how '
647
+ 'they want to proceed (fix the problem, or they can commit themselves).')
648
+
649
+
650
+ def git_hook_reason(command):
651
+ for seg in segments(command):
652
+ try: words = shlex.split(seg)
653
+ except ValueError: words = seg.split()
654
+ if not words: continue
655
+ if any(re.search(r'(^|/)\.git/hooks(/|$)', w) for w in words) and (re.search(r'(^|\s)(>|>>|tee|cp|mv|rm|ln|chmod|sed\s+-i|truncate|install)\b', seg) or '>' in seg):
656
+ return GIT_HOOK_REASON
657
+ if os.path.basename(words[0]) != 'git': continue
658
+ if any(re.match(r'core\.hookspath\s*=', w, re.I) for w in words): return GIT_HOOK_REASON
659
+ sub = next((w for w in words[1:] if not w.startswith('-') and '=' not in w), '')
660
+ if sub in ('commit', 'push', 'merge', 'am', 'rebase', 'cherry-pick', 'revert') and '--no-verify' in words: return GIT_HOOK_REASON
661
+ if sub == 'commit' and any(re.fullmatch(r'-[A-Za-z]*n[A-Za-z]*', w) for w in words[words.index('commit') + 1:]): return GIT_HOOK_REASON
662
+ if sub == 'config' and any(w.lower() == 'core.hookspath' for w in words): return GIT_HOOK_REASON
663
+ return None
664
+
665
+
499
666
  def deny_command(command, cfg=None, repo=None):
500
667
  """(rule, reason) when the command may never run, else (None, None)."""
501
668
  cfg = cfg or settings(repo=repo)
502
669
  reason = credential_reason(command, repo)
503
670
  if reason: return 'credentials', reason
671
+ reason = git_hook_reason(command)
672
+ if reason: return 'git-hooks', reason
504
673
  d = cfg['deny']
505
674
  pat = match_command(command, d['commands'])
506
675
  if pat: return pat, HARD_DENY_COMMAND.format(pat=pat)
@@ -525,6 +694,26 @@ def deny_path(path, cfg=None, repo=None):
525
694
  return None, None
526
695
 
527
696
 
697
+ _LISTED_PATH = re.compile(r'^(?:\./)?([^\s:][^:\n]*?)(?::\d+)?(?::|$)')
698
+
699
+
700
+ def filter_denied_lines(text, cfg=None, repo=None):
701
+ """BUG-0527: drops search/list output lines that name a hard-denied or credential file (path:line: text, or a bare
702
+ path), so protected text never reaches the model. Returns (text, removed_count)."""
703
+ if not isinstance(text, str) or not text: return text, 0
704
+ cfg = cfg or settings(repo=repo)
705
+ pats = list(cfg['deny']['paths'])
706
+ if not pats: return text, 0
707
+ keep, removed = [], 0
708
+ for line in text.split('\n'):
709
+ m = _LISTED_PATH.match(line)
710
+ if m and ('/' in m.group(1) or '.' in m.group(1)) and path_match(m.group(1), pats, repo):
711
+ removed += 1; continue
712
+ keep.append(line)
713
+ if removed: keep.append('(%d result%s from protected paths left out by a hard-deny rule.)' % (removed, '' if removed == 1 else 's'))
714
+ return '\n'.join(keep), removed
715
+
716
+
528
717
  def deny_url(url, cfg=None):
529
718
  cfg = cfg or settings()
530
719
  try: host = urllib.parse.urlparse(str(url)).hostname or ''
@@ -781,6 +970,8 @@ def before(tool, args, run=None, command=None, path=None, cfg=None, root=None):
781
970
  r = dispatch('before_command', payload('before_command', run, tool={'name': tool, 'canonical': name}, command=command), command, (), cfg, root)
782
971
  if r['decision'] == 'block': return block_text(r, 'before')
783
972
  blocked = permission(tool, args, command, path, cfg, root, mode=(run or {}).get('mode'))
973
+ if not blocked and _PERM.get('grant') not in ('allow', 'asked', 'bypass'): blocked = outside_read_gate(tool, args, command, path, cfg, root)
974
+ if not blocked and _PERM.get('grant') not in ('allow', 'asked', 'bypass'): blocked = scope_gate(tool, command, path, cfg, run, root)
784
975
  if blocked or (run or {}).get('mode') != 'auto' or _PERM.get('grant') in ('allow', 'bypass'): return blocked
785
976
  try: import mlai_auto_review
786
977
  except ImportError: return None
@@ -861,6 +1052,34 @@ def tool_paths(args):
861
1052
  return out[:20]
862
1053
 
863
1054
 
1055
+ # ------------------------------------------------------------------ structured "cannot complete" outcome (BUG-0523)
1056
+ # The agent reports a request it decided cannot be done (no git remote, an unsupported feature, a refused action) with
1057
+ # the cannot_complete tool. The CLI reads cannot-complete.json after the run and exits with its own code (6).
1058
+ CANNOT_COMPLETE_FILE = 'cannot-complete.json'
1059
+ CANNOT_COMPLETE_TOOL = {'name': 'cannot_complete', 'description': (
1060
+ 'Report that the request cannot be done as asked (for example: pushing with no git remote configured, a feature this '
1061
+ 'product does not have, an action the user denied). Call it once, before your final answer, with a short reason the user '
1062
+ 'can act on. Do not call it when the work is done or only partly verified.'),
1063
+ 'inputSchema': {'type': 'object', 'properties': {'reason': {'type': 'string', 'minLength': 1, 'maxLength': 600}}, 'required': ['reason']}}
1064
+
1065
+
1066
+ def record_cannot_complete(args, root=None):
1067
+ reason = ' '.join(str((args or {}).get('reason') or '').split())[:600] if isinstance(args, dict) else ''
1068
+ if not reason: raise ValueError('Give a short reason')
1069
+ root = Path(root or ROOT)
1070
+ tmp = root / (CANNOT_COMPLETE_FILE + '.tmp'); tmp.write_text(json.dumps({'reason': reason, 'time': time.time()})); tmp.replace(root / CANNOT_COMPLETE_FILE)
1071
+ emit('cannot_complete', root, content=reason)
1072
+ return {'recorded': True, 'note': 'Recorded. Now finish with a short answer that says what could not be done and why, and what the user can do instead.'}
1073
+
1074
+
1075
+ # BUG-0523/BUG-0529/BUG-0531: rules for runs on the person's own computer (CLI and Mac app), both engines.
1076
+ LAPTOP_RULES = (
1077
+ 'Outcome rules: (1) If the request cannot be done as asked, call cannot_complete {reason} once and then answer; never report it as done. '
1078
+ '(2) When the user denies an action, stop that line of work: do not retry it another way and do not start other work they did not ask '
1079
+ 'for. Say what was not done and ask what they want next. (3) Do only what was asked. You may run the project\'s existing tests, but '
1080
+ 'ask the user before adding new test files or installing packages or test tools (pip install, npm install, a new virtualenv) just to verify a change.')
1081
+
1082
+
864
1083
  # ------------------------------------------------------------------ built-in runner (worker/runner.py)
865
1084
  class _Globals:
866
1085
  """Attribute access over a module's globals() dict."""
@@ -34,7 +34,7 @@ from repo_memory import TOOL as MEMORY_PROPOSE_TOOL
34
34
  import computer_use
35
35
 
36
36
  WRITE_TOOLS = [IMAGE_TOOL, STOCK_TOOL, BRAND_TOOL, *deck_tools.TOOLS, MEMORY_PROPOSE_TOOL,
37
- {'name': 'browser', 'description': 'Open the local app (http://127.0.0.1:3000 by default, start it with preview first; it is browsed under a preview-style *.vercel.run host, the way the user reaches it, so dev-server host and origin blocks show up here) in headless Chromium at a given viewport, run up to 12 steps and take a screenshot. Reports page errors, console errors, failed requests, horizontal overflow, visible text and whether the page became interactive (hydrated). For UI work check a phone width (<=480) and a desktop width (>=1024) with at least one click/fill/press and an assert_text. Each call starts a fresh browser profile: localStorage, cookies and sessions from an earlier call are gone, so do every step that depends on saved state (sign in, add items, then a goto step to the same URL to reload, then assert_text) inside one call.',
37
+ {'name': 'browser', 'description': 'Built-in Playwright browser checks (BUG-0202: this is the browser tool; no Playwright install is needed). Open the local app (http://127.0.0.1:3000 by default, start it with preview first; it is browsed under a preview-style *.vercel.run host, the way the user reaches it, so dev-server host and origin blocks show up here) in headless Chromium at a given viewport, run up to 12 steps and take a screenshot. Reports page errors, console errors, failed requests, horizontal overflow, visible text and whether the page became interactive (hydrated). For UI work check a phone width (<=480) and a desktop width (>=1024) with at least one click/fill/press and an assert_text. Each call starts a fresh browser profile: localStorage, cookies and sessions from an earlier call are gone, so do every step that depends on saved state (sign in, add items, then a goto step to the same URL to reload, then assert_text) inside one call.',
38
38
  'inputSchema': {'type': 'object', 'properties': {'url': {'type': 'string'}, 'width': {'type': 'integer', 'minimum': 320, 'maximum': 1920}, 'height': {'type': 'integer', 'minimum': 400, 'maximum': 1200},
39
39
  'steps': {'type': 'array', 'maxItems': 12, 'items': {'type': 'object', 'properties': {'action': {'type': 'string', 'enum': ['goto', 'click', 'fill', 'press', 'assert_text']}, 'role': {'type': 'string'}, 'name': {'type': 'string'}, 'selector': {'type': 'string'}, 'value': {'type': 'string'}, 'key': {'type': 'string'}, 'text': {'type': 'string'}, 'url': {'type': 'string'}}, 'required': ['action']}}}}},
40
40
  {'name': 'preview', 'description': 'Start (or check) the managed preview of this project on port 3000: Next.js and Vite dev/start scripts, or a static index.html. Installs missing packages first and runs the dev server (hot reload) during the task; after the task it is swapped for the production build the user opens and shares. Servers started with Bash in the background stop when the task ends.',
@@ -161,8 +161,13 @@ def ask(request, always=False):
161
161
  """Wait for the user's verdict on one request (one at a time, shared with the hook). Returns the verdict."""
162
162
  if not always and auto_mode(): return 'approve'
163
163
  import fcntl
164
+ queued = time.time()
164
165
  with (ROOT / 'approval.lock').open('a') as lock:
165
166
  fcntl.flock(lock, fcntl.LOCK_EX)
167
+ # BUG-0251: queued behind an approval the user rejected in the same step: rejected too, never shown later.
168
+ try:
169
+ if float((ROOT / 'last-reject').read_text().strip() or 0) >= queued: return None
170
+ except (OSError, ValueError): pass
166
171
  request = {'id': os.urandom(8).hex(), **request}
167
172
  tmp = ROOT / 'pending.json.tmp'; tmp.write_text(json.dumps(request)); tmp.replace(ROOT / 'pending.json'); emit('approval', **request)
168
173
  decision = ROOT / ('decision-' + request['id']); deadline = time.time() + 540
@@ -172,6 +177,7 @@ def ask(request, always=False):
172
177
  raise ValueError('Task stopped' if (ROOT / 'cancel').exists() else 'The user did not approve this call in time. Do not retry it; report what is waiting.')
173
178
  time.sleep(0.4)
174
179
  verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (ROOT / 'pending.json').unlink(missing_ok=True)
180
+ if verdict not in ('approve', 'approve_all'): (ROOT / 'last-reject').write_text(str(time.time()))
175
181
  if verdict == 'approve_all' and not always:
176
182
  (ROOT / 'kimi-approve-all').write_text('1'); emit('mode', mode='auto', content='Approved all remaining steps for this task.')
177
183
  return request['id'] if verdict in ('approve', 'approve_all') else None
@@ -183,9 +189,9 @@ def integration(args):
183
189
  if not match: raise ValueError('This tool is not enabled for this task. Use integration_search to find enabled tools.')
184
190
  if os.getenv('MINI_READONLY') == '1' and match.get('write') is not False:
185
191
  raise ValueError('This turn is read-only, so tools that change data in a connected app cannot run now. Tell the user what you would do and ask them to confirm.')
186
- req = {'kind': 'integration', 'connection': connection, 'name': name, 'arguments': args.get('arguments') or {}, 'command': 'Connected tool: ' + name}
187
- # The app runs the call with the user's sign-in, so the request still goes through the app. In Auto mode it runs without a prompt.
188
- if auto_mode(): req['autoAllowed'] = True
192
+ req = {'kind': 'integration', 'connection': connection, 'name': name, 'arguments': args.get('arguments') or {}, 'command': 'Connected tool: ' + name, 'write': match.get('write') is not False} # BUG-0457
193
+ # The app runs the call with the user's sign-in, so the request goes through the app. Connected-app calls ask even in
194
+ # Auto mode, as Connectors and the docs promise (BUG-0485); "Allow for this task" on the card covers that app afterwards.
189
195
  ident = ask(req, always=True)
190
196
  if not ident: raise ValueError('The user rejected this integration call.')
191
197
  result = ROOT / ('result-' + ident)
@@ -224,6 +230,12 @@ def fingerprint_now():
224
230
  from quality import fingerprint
225
231
  return fingerprint(REPO, run_state().get('base') or 'HEAD')
226
232
 
233
+ def readonly_browser():
234
+ """BUG-0202: the Browser panel says Playwright can open the local app, so the agent must have the tool in question and
235
+ no-change turns too. A browser check only looks at the running app (each scenario still asks first); it never edits files."""
236
+ if os.getenv('MINI_SUBAGENT') == '1': return []
237
+ return [t for t in WRITE_TOOLS if t.get('name') == 'browser']
238
+
227
239
  def browser(args):
228
240
  args = {k: v for k, v in args.items() if k in ('url', 'width', 'height', 'steps')}
229
241
  installed = False
@@ -337,7 +349,15 @@ def simulator(args):
337
349
  if not seen: return text
338
350
  return {'_mcp_content': [{'type': 'text', 'text': text}, {'type': 'image', 'mimeType': 'image/jpeg', 'data': base64.b64encode(Path(seen['path']).read_bytes()).decode()}]}
339
351
 
352
+ try: # BUG-0523: structured "cannot complete" outcome
353
+ from mlai_hooks import CANNOT_COMPLETE_TOOL as _CC_TOOL
354
+ TOOLS.append(_CC_TOOL)
355
+ except Exception: pass
356
+
340
357
  def call(name, args):
358
+ if name == 'cannot_complete':
359
+ from mlai_hooks import record_cannot_complete
360
+ return record_cannot_complete(args, ROOT)
341
361
  if name == 'schedule_wakeup':
342
362
  import wakeups
343
363
  return wakeups.tool(ROOT, args, emit)
@@ -404,7 +424,7 @@ def call(name, args):
404
424
  return web('web_fetch', {'urls': [str(u) for u in urls]})
405
425
  if name == 'evidence': return ledger().run({'claims': args['claims']} if args.get('claims') else {})
406
426
  if name in ('browser', 'preview', 'job', 'network'):
407
- if os.getenv('MINI_READONLY') == '1': raise ValueError('Not available in read-only mode')
427
+ if os.getenv('MINI_READONLY') == '1' and name != 'browser': raise ValueError('Not available in read-only mode')
408
428
  return {'browser': browser, 'preview': preview, 'job': job, 'network': network}[name](args)
409
429
  if name in ('list_sessions', 'read_messages', 'send_message'): return hub(name, args)
410
430
  if name in ('repo_map', 'symbols'):
@@ -441,7 +461,7 @@ def main():
441
461
  if msg_id is None: continue # notifications
442
462
  if method == 'initialize':
443
463
  reply(msg_id, {'protocolVersion': (msg.get('params') or {}).get('protocolVersion') or '2025-06-18', 'capabilities': {'tools': {}}, 'serverInfo': {'name': 'mlai', 'version': '1.0'}})
444
- elif method == 'tools/list': reply(msg_id, {'tools': TOOLS + ([] if os.getenv('MINI_READONLY') == '1' else WRITE_TOOLS + (INTEGRATION_TOOLS if enabled_tools() else []) + ([DEPLOY_TOOL] if deploy_info() else []) + ([computer_use.TOOL] if computer_use.available() else []) + sim_tools()) + hub_tools()})
464
+ elif method == 'tools/list': reply(msg_id, {'tools': TOOLS + (readonly_browser() if os.getenv('MINI_READONLY') == '1' else WRITE_TOOLS + (INTEGRATION_TOOLS if enabled_tools() else []) + ([DEPLOY_TOOL] if deploy_info() else []) + ([computer_use.TOOL] if computer_use.available() else []) + sim_tools()) + hub_tools()})
445
465
  elif method == 'tools/call':
446
466
  p = msg.get('params') or {}
447
467
  try:
@@ -0,0 +1,35 @@
1
+ # ML AI Review
2
+
3
+ The verified reviewer (relevance filter, outline context and related code, linter diagnostics, three
4
+ independent readings, grouping and matching, refuter, noise budget, streaming inline comments,
5
+ "looks resolved" lifecycle, feedback from dismissed comments, security specialist, eval harness),
6
+ running inside our worker instead of Temporal and Azure.
7
+
8
+ python -m mlai_review run REQUEST.json # one review; events to request.out (JSONL)
9
+ python -m mlai_review analyse --root DIR --out FILE [--no-eslint] [--no-install]
10
+ python -m mlai_review feedback owner/repo --days 30
11
+ python -m mlai_review eval [--cases DIR] [--mode deep] [--record --request REQUEST.json]
12
+
13
+ The model key comes from `MODEL_API_KEY` (our model route or a run token for the gateway) and,
14
+ for pull requests, `GITHUB_TOKEN`; both are removed from the environment before anything else runs.
15
+
16
+ Where it runs:
17
+
18
+ - Chat in the cloud: `lib/code-review.ts` (actions `review_start`, `review_status`, `review_dismiss`).
19
+ - Chat on This Mac: `apps/laptop/src/review.mjs`, same actions, run token from `/api/laptop`.
20
+ - Pull requests: `lib/code-review-run.ts`, started by the "Review pull requests" routine
21
+ (`lib/code-review-routine.ts`). Linters run first with no secrets present; the review then posts
22
+ inline comments and an "ML AI Review" check run, or a commit status when the token cannot
23
+ create check runs. `workflows/watch-pr-review.ts` stops the computer as soon as the review ends
24
+ (or the reviewer exits); its 40-minute lifetime is only a ceiling.
25
+
26
+ Metering: cloud chat reviews are runs in the ledger (`lib/code-review-billing.ts`): gated like a task
27
+ start, capped by the request's `budget` (billable tokens left) and weighted by `creditRates`, exactly
28
+ as the task worker and model gateway weigh tokens. The final `usage` event carries `billable`; past
29
+ the cap no model call starts and a `limited` event explains why the review is partial.
30
+
31
+ Modes (`settings.for_mode`): `standard` (3 readings), `deep` (5 readings, refuter with more effort
32
+ and lookups, write-path check), `security` (security specialist, refuter). Scope `repo` reviews
33
+ the source files of the whole repository, sensitive paths first.
34
+
35
+ Without the tree-sitter wheel, outlines fall back to `infrastructure/structure/heuristic.py`.
@@ -0,0 +1 @@
1
+ """ML AI orchestrator: runs each pull request review as a durable workflow."""