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
@@ -10,7 +10,7 @@ really done also run here, after the engine exits, and a failed check resumes th
10
10
  and the bridge runs them. Only assertion failures count; a broken test file is treated as the tester's fault.
11
11
 
12
12
  Also: deterministic trimming of oversized tool output in model requests (cache-friendly, saves tokens)."""
13
- import json, os, re, subprocess, sys, time
13
+ import json, os, re, shutil, subprocess, sys, time
14
14
  from pathlib import Path
15
15
 
16
16
  ACCEPTANCE_DIR = 'acceptance'
@@ -71,6 +71,8 @@ Rules:
71
71
  - 3 to 8 focused test cases. No network, no sleeping, no servers, no new dependencies, no file writes outside a temporary directory.
72
72
  - Python: a unittest module. The repository root is on sys.path, so import modules as the repository does (e.g. `from shop.cart import total`).
73
73
  - JavaScript: an ES module using node:test and node:assert/strict. Import repository files with absolute file URLs built from REPO_ROOT, e.g. `const m = await import(REPO_ROOT + '/calc.js')` where `const REPO_ROOT = 'file://' + process.env.ACCEPTANCE_REPO;`. If the module is CommonJS, use createRequire.
74
+ - To read a repository file, use a path, not a URL: `fs.readFileSync(path.join(process.env.ACCEPTANCE_REPO, 'src/styles.css'), 'utf8')`. ACCEPTANCE_REPO is a plain folder path; for URLs use process.env.ACCEPTANCE_REPO_URL (a file:// URL ending in /) or pathToFileURL from node:url. Never pass the plain path to new URL().
75
+ - Colours, sizes and other CSS values have many equal spellings (#141, #141210, #141210ff, rgb(20 18 16), a named colour). Never match a colour or CSS value with one spelling; if the task says "near-black", parse the colour and check its lightness.
74
76
  - Prefer expected values stated in the task or in the existing tests. When you compute one, write the arithmetic in a comment and check it twice.
75
77
  - If the task is not testable this way (UI-only, docs, config, research, or behaviour you cannot pin down from the task), say so.
76
78
 
@@ -113,9 +115,17 @@ def tester_invalid(language, output):
113
115
  if re.search(r'^FAIL: ', output, re.M): return False
114
116
  return bool(re.search(r'(ImportError|ModuleNotFoundError|SyntaxError|IndentationError|NameError)', output)) or not re.search(r'^ERROR: ', output, re.M)
115
117
  if re.search(r'AssertionError|ERR_ASSERTION', output): return False
116
- return bool(re.search(r'ERR_MODULE_NOT_FOUND|SyntaxError|Cannot find module|ReferenceError|does not provide an export', output)) or '# fail 0' in output
118
+ # ERR_INVALID_URL: new URL('./src/styles.css', ACCEPTANCE_REPO + '/') with a plain folder path (CLI bug list, 0.3.3).
119
+ return bool(re.search(r'ERR_MODULE_NOT_FOUND|SyntaxError|Cannot find module|ReferenceError|does not provide an export|ERR_INVALID_URL|TypeError: Invalid URL|ERR_INVALID_FILE_URL_PATH|ENOENT: no such file', output)) or '# fail 0' in output
117
120
 
118
- REVIEW_SYSTEM = '''You check failing acceptance tests before they are reported to a builder. For each failing test, decide whether the test itself is right: does the task text really require this behaviour, and is the expected value correct? Recompute every expected number step by step from the task. A test is wrong if it asserts something the task does not require, or if its expected value is miscalculated.
121
+ TESTER_RETRY = '''
122
+
123
+ This is a second try. Your previous test could not run; the error is in `error`. Fix the test itself (imports, paths,
124
+ module format, a missing loader) and return the same JSON shape. Test through files and commands that run in plain
125
+ Node or Python here: for a React or other bundled UI, test the server, data and pure modules, or read the built output,
126
+ instead of importing JSX. If no test can run in this repository, return {"applicable": false, "reason": "..."}.'''
127
+
128
+ REVIEW_SYSTEM = '''You check failing acceptance tests before they are reported to a builder. For each failing test, decide whether the test itself is right: does the task text really require this behaviour, and is the expected value correct? Recompute every expected number step by step from the task. A test is wrong if it matches a colour or CSS value by one spelling (a 3-digit hex pattern that rejects #141210), or if it fails while loading a file (Invalid URL, ENOENT) instead of on the behaviour. A test is wrong if it asserts something the task does not require, or if its expected value is miscalculated.
119
129
 
120
130
  Reply with JSON only: {"genuine": ["test_name", ...], "wrong": [{"test": "test_name", "why": "..."}]}'''
121
131
 
@@ -141,14 +151,26 @@ def run_acceptance(root, repo, language, code, timeout=180):
141
151
  name = 'test_acceptance.py' if language == 'python' else 'acceptance.test.mjs'
142
152
  path = d / name; path.write_text(code)
143
153
  env = {k: v for k, v in os.environ.items() if k not in ('MODEL_API_KEY', 'MINI_VAULT', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'VERCEL_OIDC_TOKEN')}
144
- env.update({'PYTHONPATH': str(repo), 'ACCEPTANCE_REPO': str(repo), 'PYTHONDONTWRITEBYTECODE': '1'})
145
- cmd = [sys.executable, str(path), '-v'] if language == 'python' else ['node', '--test', str(path)]
154
+ env.update({'PYTHONPATH': str(repo), 'ACCEPTANCE_REPO': str(repo), 'ACCEPTANCE_REPO_URL': Path(repo).resolve().as_uri().rstrip('/') + '/', 'PYTHONDONTWRITEBYTECODE': '1'})
146
155
  if language == 'python': path.write_text(code if 'unittest.main' in code else code + '\n\nif __name__ == "__main__":\n import unittest; unittest.main()\n')
156
+ # BUG-0221: run the test from a scratch folder inside the project, so relative imports, package imports and
157
+ # __file__-based paths resolve against the project, not the engine's own folder. The copy in root stays for the log.
158
+ scratch = Path(repo) / ('.mlai-acceptance-' + os.urandom(4).hex())
159
+ try:
160
+ scratch.mkdir()
161
+ run_path = scratch / name; run_path.write_text(path.read_text())
162
+ except OSError:
163
+ scratch, run_path = None, path
164
+ cmd = [sys.executable, str(run_path), '-v'] if language == 'python' else ['node', '--test', str(run_path)]
147
165
  try:
148
166
  r = subprocess.run(cmd, cwd=repo, env=env, capture_output=True, text=True, timeout=timeout)
149
- return r.returncode, (r.stdout + '\n' + r.stderr)[-6000:]
167
+ out = (r.stdout + '\n' + r.stderr)
168
+ if scratch is not None: out = out.replace(str(scratch) + '/', '').replace(str(scratch), '.')
169
+ return r.returncode, out[-6000:]
150
170
  except subprocess.TimeoutExpired:
151
171
  return 124, 'Acceptance check timed out after %ds' % timeout
172
+ finally:
173
+ if scratch is not None: shutil.rmtree(scratch, ignore_errors=True)
152
174
 
153
175
  def acceptance(config, st, model, root, repo, changed, event):
154
176
  """Write and run the hidden acceptance test once. Returns {status, ...}: passed | failed | skipped | invalid."""
@@ -172,6 +194,24 @@ def acceptance(config, st, model, root, repo, changed, event):
172
194
  event('acceptance', status='skipped', content='Acceptance check not applicable: ' + str(reason)[:300])
173
195
  return {'status': 'skipped', 'reason': str(reason)[:300]}
174
196
  code, output = run_acceptance(root, repo, spec['language'], spec['code'])
197
+ if code not in (0, 124) and tester_invalid(spec['language'], output):
198
+ # Web bug list Bug-017 and Bug-021: a test that cannot even load (JSX imported into plain Node, a wrong path)
199
+ # says nothing about the build. Give the tester its own error once and run the corrected test.
200
+ retry = json.dumps({'task': str(config.get('task', ''))[:12000], 'languages_changed': sorted(langs), 'repository_files': files,
201
+ 'previous_test': spec['code'][:20000], 'error': output[-3000:]})
202
+ try:
203
+ fixed_text, _ = model.request([{'role': 'system', 'content': TESTER_SYSTEM + TESTER_RETRY},
204
+ {'role': 'user', 'content': retry}], max_tokens=12000, allow_tools=False)
205
+ fixed = _parse(fixed_text)
206
+ except Exception:
207
+ fixed = None
208
+ if fixed and fixed.get('applicable') and fixed.get('language') == spec['language'] and isinstance(fixed.get('code'), str) and len(fixed['code']) <= 40000:
209
+ spec = {**spec, **fixed}
210
+ code, output = run_acceptance(root, repo, spec['language'], spec['code'])
211
+ elif isinstance(fixed, dict) and fixed.get('applicable') is False:
212
+ reason = str(fixed.get('reason') or 'the tester could not write a test that runs here')[:300]
213
+ event('acceptance', status='skipped', content='Acceptance check not applicable: ' + reason)
214
+ return {'status': 'skipped', 'reason': reason}
175
215
  covers = [str(c)[:200] for c in spec.get('covers') or []][:8]
176
216
  if code == 0: status = 'passed'
177
217
  elif code != 124 and tester_invalid(spec['language'], output): status = 'invalid'
@@ -250,6 +290,10 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
250
290
  issues = []
251
291
  try: changed = role_engine.changed_files(repo, st.get('base'))
252
292
  except Exception: changed = []
293
+ try:
294
+ from runtime_control import turn_changes
295
+ changed = turn_changes(root, repo, changed) # BUG-0495: not files that were already untracked or changed at the start
296
+ except Exception: pass
253
297
  code_changed = [p for p in changed if role_engine.CODE_EXT.search(p)]
254
298
  progress = {}
255
299
  try: progress = json.loads((Path(root) / 'kimi-progress.json').read_text())
@@ -291,6 +335,30 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
291
335
  except Exception as exc:
292
336
  issue = 'Verification report could not complete: ' + str(exc)[:200]
293
337
  event('note', content=issue); issues.append(issue)
338
+ if allow_acceptance and changed and not st.get('inspect'):
339
+ # The running preview is the user's view of the work: a page that answers 500, or a linked page that 404s, is not
340
+ # done, whatever the final message says. Nothing listening on the preview port means there is nothing to judge.
341
+ try:
342
+ import site_check
343
+ routes = sorted(site_check.internal_links(repo, changed))
344
+ bad = site_check.live_routes(routes)
345
+ found = site_check.live_findings(bad)
346
+ if found:
347
+ event('verification_report', status='failed', reasons=[found[0]['message'].split('.')[0]], findings=found, checks=0, passed=0)
348
+ issues += [f['message'] for f in found if f['message'] not in issues]
349
+ except Exception as exc:
350
+ event('note', content='Could not check the preview routes: ' + str(exc)[:200])
351
+ if allow_acceptance and config.get('conversation_route') in (None, 'build'):
352
+ # A run must not end on "I'll now make the slides", and a presentation or PDF request must leave a file behind.
353
+ # Each note is sent once; if the agent still cannot do it, its own explanation stands.
354
+ try:
355
+ from conversation import deliverable_issue, stalled_promise, STALLED_NOTE
356
+ if 'stalled' not in done and not changed and stalled_promise(answer):
357
+ done.add('stalled'); issues.append(STALLED_NOTE)
358
+ elif 'deliverable' not in done:
359
+ note = deliverable_issue(config.get('task', ''), changed, repo)
360
+ if note: done.add('deliverable'); issues.append(note)
361
+ except Exception: pass # these hints never block a run
294
362
  if config.get('selected_design'):
295
363
  from design_director import browser_review
296
364
  from quality import fingerprint
@@ -30,7 +30,7 @@ def save(name, data):
30
30
  def event(event_type, **data):
31
31
  with (ROOT / 'events.jsonl').open('a') as f: f.write(json.dumps({'type': event_type, 'time': time.time(), **data}) + '\n')
32
32
 
33
- HOOK_KEYS = ('recent', 'landed', 'stuck_warned', 'gates_done', 'planned', 'plan_reviewed', 'plan_dismissed', 'brief_ok', 'brief_rounds', 'brief_nudged', 'mode', 'nudged', 'diagnosed_for', 'scope', 'scope_ok', 'approved_kinds', 'calls', 'agents', 'budget_warned', 'touched', 'policy_noted', 'policy_ok_paths', 'token_stage', 'account_stop', 'account_stop_at', 'helpers', 'budget_next', 'budget_declined')
33
+ HOOK_KEYS = ('steps_used', 'step_limit_noted', 'recent', 'landed', 'stuck_warned', 'gates_done', 'planned', 'plan_reviewed', 'plan_dismissed', 'brief_ok', 'brief_rounds', 'brief_nudged', 'mode', 'nudged', 'diagnosed_for', 'scope', 'scope_ok', 'approved_kinds', 'calls', 'agents', 'budget_warned', 'touched', 'policy_noted', 'policy_ok_paths', 'token_stage', 'account_stop', 'account_stop_at', 'helpers', 'budget_next', 'budget_declined', 'plan_items', 'brief_q_nudged', 'plan_nudged', 'question_changes')
34
34
  def save_state(st):
35
35
  """The hook owns only these keys; the bridge owns kimi-state.json (static) and kimi-progress.json."""
36
36
  save('kimi-hook.json', {k: st[k] for k in HOOK_KEYS if k in st})
@@ -38,6 +38,22 @@ def save_state(st):
38
38
  def state():
39
39
  return {**load('kimi-state.json', {}), **load('kimi-progress.json', {}), **load('kimi-hook.json', {})}
40
40
 
41
+ # Tools that change the project, run code or reach outside it. Before a Brief task list is approved, and after the user
42
+ # dismissed a plan (Not now), none of them run: the agent reads, answers and waits (BUG-0102).
43
+ WORK_TOOLS = frozenset(('Write', 'Edit', 'Bash', 'Agent', 'AgentSwarm'))
44
+ WORK_MCP = frozenset(('scope', 'preview', 'browser', 'job', 'deploy', 'integration_call', 'network', 'schedule_wakeup', 'send_message', 'ios_simulator', 'generate_image', 'stock_photo', 'brand_lookup', 'deck_check', 'deck_import', 'find_image', 'find_icon', 'image_prep'))
45
+ DISMISSED_BLOCK = ('The user dismissed the plan (Not now). Do not start the work in this task: no edits, commands, images, scope '
46
+ 'requests or helper agents, and do not look for another way to start. In one or two sentences, say the plan is on hold and ask '
47
+ 'what they would like changed, then finish. The user starts the work again from the chat.')
48
+
49
+ def is_work_tool(name):
50
+ name = str(name or '')
51
+ if name in WORK_TOOLS: return True
52
+ m = re.match(r'^mcp__(\w+?)__(\w+)$', name)
53
+ if not m: return False
54
+ if m.group(1) != 'mlai': return True # connected-app and other MCP tools can change outside data
55
+ return m.group(2) in WORK_MCP
56
+
41
57
  def block(reason):
42
58
  sys.stderr.write(reason); sys.stderr.flush(); sys.exit(2)
43
59
 
@@ -45,13 +61,16 @@ def steering():
45
61
  """Consume queued user instructions (oldest first)."""
46
62
  d = ROOT / 'steering'
47
63
  if not d.is_dir(): return []
48
- out = []
64
+ out, notes = [], []
49
65
  for f in sorted(d.glob('*.json')):
50
- try: msg = json.loads(f.read_text()).get('message', '')
51
- except (OSError, ValueError): msg = ''
66
+ try: note = json.loads(f.read_text())
67
+ except (OSError, ValueError): note = {}
68
+ msg = note.get('message', '') if isinstance(note, dict) else ''
52
69
  f.unlink(missing_ok=True)
53
- if isinstance(msg, str) and msg.strip(): out.append(msg.strip()[:5000])
54
- for m in out: event('steering', content=m)
70
+ if isinstance(msg, str) and msg.strip():
71
+ out.append(msg.strip()[:5000]); notes.append({'note': f.stem, **({'source': str(note['source'])} if note.get('source') else {})})
72
+ # The note id lets the app match a delivered instruction to the message it sent.
73
+ for m, n in zip(out, notes): event('steering', content=m, **n)
55
74
  return out
56
75
 
57
76
  def platform_notes():
@@ -73,11 +92,19 @@ def steer_block(messages, stopping=False):
73
92
  def wait_decision(request, seconds=540, strict=False):
74
93
  """One approval at a time even when Kimi runs tool calls in parallel. Strict (repository policy) reviews ignore "Approve all"."""
75
94
  import fcntl
95
+ queued = time.time()
76
96
  with (ROOT / 'approval.lock').open('a') as lock:
77
97
  fcntl.flock(lock, fcntl.LOCK_EX)
98
+ # BUG-0251: a call that queued behind an approval the user then rejected (parallel tool calls of one step)
99
+ # is rejected too, so a leftover card can never run a change the user just said no to.
100
+ if rejected_since(queued): block('The user rejected a related action in this step, so this call was not run. Do not retry it; explain what you would change and ask.')
78
101
  if not strict and (ROOT / 'kimi-approve-all').exists(): return
79
102
  _wait(request, seconds)
80
103
 
104
+ def rejected_since(t):
105
+ try: return float((ROOT / 'last-reject').read_text().strip() or 0) >= t
106
+ except (OSError, ValueError): return False
107
+
81
108
  def user_hooks(fn, *args):
82
109
  """Project hooks and hard-deny rules (mlai_hooks). They fail open on an internal error, like the rest of this hook."""
83
110
  try:
@@ -88,6 +115,9 @@ def user_hooks(fn, *args):
88
115
  def mlai_run(st):
89
116
  return user_hooks('kimi_run', st) or {}
90
117
 
118
+ REJECTED = ('The user rejected this action. Do not make the same change another way (another tool, a shell command or a retry) '
119
+ 'and do not claim the permission mode changed. Stop now, say plainly what was not done, and ask the user how to proceed.')
120
+
91
121
  def _wait(request, seconds):
92
122
  ident = request['id']
93
123
  if request.get('kind') not in ('plan', 'brief'):
@@ -106,8 +136,21 @@ def _wait(request, seconds):
106
136
  verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (ROOT / 'pending.json').unlink(missing_ok=True)
107
137
  if verdict == 'approve_all':
108
138
  (ROOT / 'kimi-approve-all').write_text('1'); event('mode', mode='auto', content='Approved all remaining steps for this task.')
139
+ if verdict == 'approve_chat':
140
+ # BUG-0594: remember this exact command for the chat, only when it is a safe kind; otherwise it is a one-time approval.
141
+ try:
142
+ from command_safety import chat_allow_ok, chat_allow_key
143
+ if request.get('kind') == 'command' and not request.get('strict') and chat_allow_ok(request.get('effect'), request.get('command'), REPO):
144
+ allowed = [c for c in load('chat-allow.json', []) if isinstance(c, str)]
145
+ key = chat_allow_key(request.get('command'))
146
+ if key not in allowed: save('chat-allow.json', (allowed + [key])[-50:])
147
+ event('note', content='Always allowed in this chat: ' + key[:200])
148
+ except Exception: pass
149
+ verdict = 'approve'
109
150
  if verdict not in ('approve', 'approve_all'):
110
- block('The user rejected this action. Choose another approach or explain what you need.')
151
+ (ROOT / 'last-reject').write_text(str(time.time()))
152
+ # BUG-0491: "Choose another approach" made the agent retry the same write with Write, printf and touch.
153
+ block(REJECTED)
111
154
 
112
155
  def wait_plan(request, seconds=540):
113
156
  """Plan review: returns the raw verdict (approve | approve:0,2 | reject), or None on timeout."""
@@ -127,11 +170,29 @@ def briefing(st):
127
170
  """Brief mode before the user has approved a task list: read-only, every TodoList opens a review."""
128
171
  return bool(st.get('brief')) and not st.get('brief_ok') and not st.get('plan_dismissed')
129
172
 
173
+ def brief_label(st):
174
+ """BUG-0591: an ask-first brief in an Auto or Guided chat is not "Brief mode" (the composer still says Auto), so the
175
+ agent is not told, and does not tell the user, that the workspace is in Brief mode."""
176
+ back = st.get('brief_return')
177
+ if back in ('auto', 'approve'): return 'Ask first (the chat stays in %s)' % ('Auto' if back == 'auto' else 'Guided')
178
+ return 'Brief mode'
179
+
130
180
  def brief_unlock(st):
131
181
  back = st.get('brief_return') if st.get('brief_return') in ('approve', 'auto') else 'approve'
132
182
  st['brief_ok'] = True; st['mode'] = back; st['scope_ok'] = True; save_state(st)
133
183
  event('mode', mode=back, content='Plan agreed. Building the approved list in %s mode.' % ('Auto' if back == 'auto' else 'Guided'))
134
184
 
185
+ def plan_key(text):
186
+ return ' '.join(str(text).lower().split())[:300]
187
+
188
+ def plan_added(items, st):
189
+ """Items in this task list that the user has not approved yet. Status updates of the same list add nothing."""
190
+ known = set(st.get('plan_items') or [])
191
+ return [i for i in items if plan_key(i) not in known]
192
+
193
+ def remember_plan(items, st):
194
+ st['plan_items'] = sorted(set(st.get('plan_items') or []) | {plan_key(i) for i in items})[:200]
195
+
135
196
  def plan_gate(args, st):
136
197
  """First task list of a run: optional user review (Guided mode by default, or always when the user asked).
137
198
  Brief mode: every task list is reviewed until the user approves; replies come back to the agent as feedback."""
@@ -142,9 +203,24 @@ def plan_gate(args, st):
142
203
  st['planned'] = True; save_state(st)
143
204
  policy = st.get('plan_approval') or 'guided'
144
205
  wants = brief or policy == 'always' or (policy == 'guided' and st.get('mode') == 'approve')
206
+ if wants and not brief and question_only(st):
207
+ # BUG-0345: a task list for answering a question needs no review. It does not count as the plan, so a later
208
+ # edit in this turn still asks for the plan first.
209
+ st['planned'] = False; save_state(st); return
145
210
  if brief:
146
- if len(items) < 2: block('Brief mode: the task list needs at least two concrete items before the user can review it. Call TodoList again with the full plan.')
147
- elif not first or st.get('readonly') or st.get('plan_reviewed') or len(items) < 2 or not wants or (ROOT / 'kimi-approve-all').exists(): return
211
+ if len(items) < 2: block(brief_label(st) + ': the task list needs at least two concrete items before the user can review it. Call TodoList again with the full plan.')
212
+ if st.get('mode') == 'brief' and not int(st.get('brief_rounds') or 0) and not st.get('brief_q_nudged') and not load('kimi-brief-questions.json', []):
213
+ # BUG-0124: Brief mode promises to clarify requirements before the task list. Ask once for the open questions.
214
+ st['brief_q_nudged'] = True; st['planned'] = False; save_state(st)
215
+ event('note', content='Brief mode: asked for clarifying questions before the task list')
216
+ block('Brief mode clarifies requirements first. Before this task list goes to the user, record one to three short questions about '
217
+ 'what is still open in the request (for example style, content, images or scope) with mcp__mlai__brief_questions '
218
+ '{"questions": [{"question": "...", "options": [{"label": "...", "detail": "..."}], "recommended": 0}]}, each with your '
219
+ 'recommended answer. Then call TodoList again with the same list. If the request truly leaves nothing open, call TodoList again unchanged.')
220
+ elif st.get('readonly') or len(items) < 2 or not wants or (ROOT / 'kimi-approve-all').exists(): return
221
+ elif not first or st.get('plan_reviewed'):
222
+ # Guided: an approved list is not asked again, but a later list that adds work asks again (BUG-0039).
223
+ if not st.get('plan_reviewed') or not plan_added(items, st): return
148
224
  st['plan_reviewed'] = True
149
225
  rounds = int(st.get('brief_rounds') or 0) + 1
150
226
  if brief: st['brief_rounds'] = rounds
@@ -173,17 +249,19 @@ def plan_gate(args, st):
173
249
  block('The user replied to your plan: "' + reply + '"\nAnswer briefly if they asked something, then call TodoList again with the revised task list (3 to 10 items) and, if anything is still open, record your questions with mcp__mlai__brief_questions {"questions": [...]} before the TodoList. Nothing is built until they approve.')
174
250
  if verdict in ('approve', 'approve_all'):
175
251
  if brief: brief_unlock(st)
252
+ remember_plan(items, st)
176
253
  st['scope_ok'] = True; save_state(st); event('plan_review', content='Plan approved'); return
177
254
  if verdict.startswith('approve:'):
178
255
  keep = {int(x) for x in verdict[8:].split(',') if x.strip().isdigit()}
179
256
  kept = [t for i, t in enumerate(items) if i in keep]; removed = [t for i, t in enumerate(items) if i not in keep]
180
257
  if kept:
181
258
  if brief: brief_unlock(st)
259
+ remember_plan(kept, st); save_state(st)
182
260
  event('plan_review', content='%d of %d tasks approved' % (len(kept), len(items)))
183
261
  block('The user approved only part of the task list.\nApproved: ' + '; '.join(kept) + '\nRemoved (keep these out of scope; do not do them): ' + '; '.join(removed) + '\nCall TodoList again with only the approved items, then build.')
184
262
  event('plan_review', content='Plan dismissed')
185
263
  st['plan_dismissed'] = True; save_state(st)
186
- block('The user dismissed this task list. Do not start the work. Briefly ask what they want changed, then finish.')
264
+ block(DISMISSED_BLOCK)
187
265
 
188
266
  def resolve(path):
189
267
  p = Path(path)
@@ -291,6 +369,19 @@ def secret_gate(name, args, rel, pol):
291
369
  'Read it from an environment variable instead (for example process.env.' + f['name'] + ' or os.environ["' + f['name'] + '"]), '
292
370
  'add the name to .env.example with an empty value, and tell the user to store the real value in the Vault as ' + f['name'] + '. Re-issue the edit without the literal value.')
293
371
 
372
+ # BUG-0224: installed dependencies are not the project's code. Editing them in place (often to get past a check) is
373
+ # refused unless the task itself asks for it; the change would also vanish on the next install.
374
+ DEP_DIRS = ('node_modules', 'site-packages', 'dist-packages', 'bower_components')
375
+ DEP_WRITE = re.compile(r'(?:\bsed\s+(?:-\w+\s+)*-i|\bperl\s+-\w*i|>>?|\btee\b|\bpatch\b|write_text|writeFileSync)[^|;&\n]*\b(?:node_modules|site-packages)/')
376
+ def dependency_gate(what, rel, st):
377
+ parts = rel.replace('\\', '/').split('/')
378
+ if not any(p in DEP_DIRS for p in parts): return
379
+ if re.search(r'node_modules|site-packages|patch-package|vendored? (?:dependency|library)', str(st.get('task', '')), re.I): return
380
+ event('safety', effect='write', decision='deny', command=what[:300], content='Refused: installed dependencies are not edited in place')
381
+ block('Refused: this changes an installed dependency (' + rel[:120] + '), which is outside the project and is lost on the next install. '
382
+ 'Do not edit dependencies to get past a check. Fix the project code or its configuration, or explain the problem and ask the user. '
383
+ 'This step was not run.')
384
+
294
385
  def protected_path_gate(name, args, rel, pol, st):
295
386
  """Paths the policy marks for review always ask, even in Auto mode (once per file per task)."""
296
387
  if pol is None or rel.startswith('..'): return
@@ -324,11 +415,73 @@ def command_policy_gate(command, pol, st, mode, auto):
324
415
  policy_event(pat, 'allow', 'Allowed by policy: ' + command[:300], command=command[:300]); return True
325
416
  return False
326
417
 
418
+ BOM = b'\xef\xbb\xbf'
419
+
420
+ def remember_bom(name, args):
421
+ """BUG-0546: the file tools drop a UTF-8 byte order mark; note which edited files had one so PostToolUse puts it back."""
422
+ if name not in ('Write', 'Edit') or not args.get('path'): return
423
+ try:
424
+ target = resolve(str(args['path']))
425
+ with open(target, 'rb') as f: had = f.read(3) == BOM
426
+ except OSError: return
427
+ if had:
428
+ known = load('kimi-bom.json', [])
429
+ if str(target) not in known: save('kimi-bom.json', (known + [str(target)])[-200:])
430
+
431
+ def restore_bom():
432
+ """Runs before the next tool call and at Stop (PostToolUse is only registered for project hooks), so it never races an edit."""
433
+ for path in load('kimi-bom.json', []):
434
+ try:
435
+ target = Path(path)
436
+ data = target.read_bytes()
437
+ if data and not data.startswith(BOM): target.write_bytes(BOM + data)
438
+ except OSError: pass
439
+
440
+ def step_limit_gate(st):
441
+ """BUG-0589: Settings > Agent > Maximum steps per task. Each command, edit or app call is one step; at the limit
442
+ the agent stops working and reports instead of running more (the model loop alone never went below 10)."""
443
+ try: limit = int(st.get('step_limit') or 0)
444
+ except (TypeError, ValueError): limit = 0
445
+ if limit <= 0: return
446
+ used = int(st.get('steps_used') or 0)
447
+ if used >= limit:
448
+ if not st.get('step_limit_noted'):
449
+ st['step_limit_noted'] = True; save_state(st)
450
+ event('note', content='Step limit reached (%d). Asked the agent to wrap up' % limit)
451
+ block('Step limit reached: the user allows %d step%s per task (Settings > Agent > Maximum steps per task), and all are used. '
452
+ 'This call was not run. Do not call more tools: reply now with what is done, what is left, and that they can raise the limit or send a follow-up.' % (limit, '' if limit == 1 else 's'))
453
+ st['steps_used'] = used + 1; save_state(st)
454
+
455
+ def question_only(st):
456
+ """BUG-0345: this turn answers a question and has not tried to change anything yet."""
457
+ return bool(st.get('question_turn') and not st.get('question_changes'))
458
+
459
+ def plan_first_due(st):
460
+ """The task list must be approved before the first change: Guided (plan_first), or Always in Auto too (BUG-0590)."""
461
+ mode = st.get('mode', 'approve')
462
+ return bool(st.get('plan_first') and (mode == 'approve' or (mode == 'auto' and st.get('plan_approval') == 'always'))
463
+ and not st.get('planned') and not st.get('plan_reviewed') and not st.get('readonly') and not (ROOT / 'kimi-approve-all').exists())
464
+
465
+ def always_plan_gate(command, st):
466
+ """With "Approve the task list first: Always", a command that changes files waits for the plan in Auto, like Write and Edit
467
+ (in Guided the command approval already asks). Reads and checks still run (BUG-0590)."""
468
+ if st.get('mode') != 'auto' or st.get('plan_approval') != 'always' or not plan_first_due(st): return
469
+ from command_safety import classify
470
+ if classify(command, REPO, cwd=REPO, home=os.path.dirname(REPO)).get('effect') in ('read', 'check'): return
471
+ event('note', content='Approve the task list first: asked for the plan before the first change')
472
+ block('The user approves your task list before any change, even in Auto. Call TodoList with 2 to 6 short, concrete items '
473
+ '(what you will change and how you will check it), then wait for the review. This command was not run; re-issue it after the plan is approved.')
474
+
327
475
  def pre(payload, st):
328
476
  name = str(payload.get('tool_name') or '')
329
477
  args = payload.get('tool_input') or {}
330
478
  if not isinstance(args, dict): args = {}
479
+ try: restore_bom(); remember_bom(name, args)
480
+ except Exception: pass
331
481
  if (ROOT / 'cancel').exists(): block('Task stopped by user.')
482
+ if st.get('plan_dismissed') and is_work_tool(name): # before any approval card: Not now means nothing else asks or runs
483
+ event('plan_review', content='Plan on hold: ' + re.sub(r'^mcp__\w+?__', '', name) + ' was not run')
484
+ block(DISMISSED_BLOCK)
332
485
  hooked = user_hooks('kimi_pre', name, args, st) # hard-deny, credential block, before_tool / before_command hooks
333
486
  if hooked: block(hooked)
334
487
  queued = steering()
@@ -350,16 +503,20 @@ def pre(payload, st):
350
503
  block('You have made this exact call three times recently. Repeating it will not give new information. Step back: re-read the latest error, form one hypothesis about the root cause, and take a different action.')
351
504
  save_state(st)
352
505
  if ACCEPTANCE in json.dumps(args) or HIDDEN.search(json.dumps(args)): block('That path holds the independent acceptance check, which is hidden from the builder by design. Work from the task and the failure output instead.')
506
+ if is_work_tool(name): step_limit_gate(st)
353
507
  if name == 'TodoList': return plan_gate(args, st)
354
- writes = name in ('Write', 'Edit', 'Bash', 'Agent', 'AgentSwarm')
355
- if writes and st.get('plan_dismissed'): block('The user dismissed the task list, so no work may start. Ask what they want changed and finish.')
356
- if briefing(st) and name in ('Write', 'Edit', 'Agent', 'AgentSwarm'):
357
- block('Brief mode: nothing is built until the user approves your task list. Read the repository, then call TodoList with the proposed items and state your open questions. This call was not run.')
508
+ if briefing(st) and (name in ('Write', 'Edit', 'Agent', 'AgentSwarm') or (name.startswith('mcp__') and is_work_tool(name))):
509
+ block(brief_label(st) + ': nothing is built until the user approves your task list. Read the repository, then call TodoList with the proposed items and state your open questions. This call was not run.')
358
510
  if st.get('inspect') and name in ('Write', 'Edit', 'Agent', 'AgentSwarm'):
359
511
  event('safety', effect='write', decision='deny', command=name + ' ' + str(args.get('path', ''))[:300], content='Refused: the user asked for no changes in this turn')
360
512
  block(INSPECT_BLOCK)
361
513
  if name in ('Write', 'Edit') and not st.get('readonly'):
362
514
  nudged = set(st.get('nudged') or [])
515
+ if (plan_first_due(st) and ('guided_plan' not in nudged or st.get('plan_approval') == 'always')):
516
+ nudged.add('guided_plan'); st['nudged'] = sorted(nudged); st['question_changes'] = True; save_state(st)
517
+ event('note', content='Guided mode: asked for the plan before the first edit')
518
+ block(('The user approves your task list before any change, even in Auto.' if st.get('mode') == 'auto' else 'Guided mode: the user approves your plan before any file changes.') + ' Call TodoList with 2 to 6 short, concrete items '
519
+ '(what you will change and how you will check it), then wait for the review. This edit was not applied; re-issue it after the plan is approved.')
363
520
  if st.get('large') and not st.get('planned') and 'plan' not in nudged:
364
521
  nudged.add('plan'); st['nudged'] = sorted(nudged); save_state(st)
365
522
  event('note', content='Large task: asked for a plan before editing')
@@ -386,6 +543,7 @@ def pre(payload, st):
386
543
  helper_gate(name, args, st)
387
544
  if name == 'Bash':
388
545
  command = str(args.get('command', ''))
546
+ always_plan_gate(command, st)
389
547
  try:
390
548
  from command_policy import offline_network_wait_reason
391
549
  reason = offline_network_wait_reason(command, st.get('task', ''))
@@ -393,6 +551,7 @@ def pre(payload, st):
393
551
  if reason: event('retry', content=reason); block(reason)
394
552
  masked = pipe_gate(command)
395
553
  if masked: event('note', content='Check would report a later command\'s exit status; asked for pipefail'); block(masked)
554
+ if DEP_WRITE.search(command): dependency_gate(command, 'node_modules', st)
396
555
  if command_policy_gate(command, pol, st, mode, auto): return
397
556
  return command_gate(command, st, mode, auto)
398
557
  if name in ('Write', 'Edit'):
@@ -406,6 +565,10 @@ def pre(payload, st):
406
565
  old, new = str(args.get('old_string', '')), str(args.get('new_string', ''))
407
566
  if old and old in original: after = original.replace(old, new) if args.get('replace_all') else original.replace(old, new, 1)
408
567
  rel = os.path.relpath(str(target), REPO)
568
+ if re.search(r'(^|/)\.git/hooks(/|$)', rel.replace(os.sep, '/')): # BUG-0551: the team's git hooks are not the agent's to change
569
+ from mlai_hooks import GIT_HOOK_REASON
570
+ event('safety', effect='write', decision='deny', command=name + ' ' + rel[:300], content='Refused: editing a git hook')
571
+ block(GIT_HOOK_REASON)
409
572
  if not rel.startswith('..'): secret_gate(name, args, rel, pol)
410
573
  if after is not None:
411
574
  try:
@@ -413,6 +576,7 @@ def pre(payload, st):
413
576
  problem = gate(rel, original, after, REPO) if not rel.startswith('..') else None
414
577
  except Exception: problem = None
415
578
  if problem: event('edit_guard', path=str(args.get('path', ''))[:200], content=problem[:600]); block(problem)
579
+ dependency_gate(name + ' ' + rel, rel, st)
416
580
  protected_path_gate(name, args, rel, pol, st)
417
581
  return edit_gate(name, args, rel, str(target), st, auto)
418
582
  if name in ('Agent', 'AgentSwarm') and not auto:
@@ -491,6 +655,13 @@ def edit_gate(name, args, rel, target, st, auto):
491
655
  wait_decision({'id': os.urandom(8).hex(), 'kind': 'scope', 'area': area(rel), 'command': summary})
492
656
  grant_area(st, rel)
493
657
 
658
+ def chat_allowed(command, effect):
659
+ """BUG-0594: the person chose "Always allow in this chat" for this exact command (safe kinds only, re-checked)."""
660
+ try:
661
+ from command_safety import chat_allow_ok, chat_allow_key
662
+ return chat_allow_key(command) in load('chat-allow.json', []) and chat_allow_ok(effect, command, REPO)
663
+ except Exception: return False
664
+
494
665
  def command_gate(command, st, mode, auto):
495
666
  """Classify the command; allow, ask or refuse according to the mode budget and the approved scope."""
496
667
  from command_safety import classify, decide, describe, relative
@@ -504,15 +675,20 @@ def command_gate(command, st, mode, auto):
504
675
  if decision['decision'] == 'deny':
505
676
  event('safety', effect=effect, decision='deny', command=command[:2000], content='Refused. ' + (decision.get('reason') or describe(decision)))
506
677
  if effect == 'catastrophic': block('Refused: ' + (decision.get('reason') or describe(decision)) + '. This command is never run, in any mode. Choose a contained alternative (delete specific files inside the project, keep the harness state alone, never touch devices or system directories).')
507
- if briefing(st): block('Brief mode: only read-only commands run before the user approves the task list. ' + describe(decision) + ' was not run; put it in the plan instead.')
678
+ if briefing(st): block(brief_label(st) + ': only read-only commands run before the user approves the task list. ' + describe(decision) + ' was not run; put it in the plan instead.')
508
679
  if st.get('inspect'): block('Not allowed: ' + describe(decision) + '. ' + INSPECT_BLOCK)
509
680
  block('Not allowed in this mode: ' + describe(decision) + '. Plan mode only reads; propose the command in your answer instead.')
510
681
  if decision['decision'] == 'allow':
511
682
  if effect not in ('read', 'check'): event('safety', effect=effect, decision='allow', command=command[:300], content=describe(decision))
512
683
  return
684
+ if effect not in ('destructive', 'privilege') and chat_allowed(command, effect):
685
+ event('safety', effect=effect, decision='allow', command=command[:300], content='Always allowed in this chat')
686
+ return
513
687
  request = {'id': os.urandom(8).hex(), 'kind': 'command', 'effect': effect, 'reason': decision.get('reason') or '', 'command': command[:20000]}
688
+ # Deletes and sudo ask every time, even after Approve all (BUG-0101). The card says so and offers no Approve all for them.
689
+ if effect in ('destructive', 'privilege'): request['strict'] = True
514
690
  event('safety', effect=effect, decision='ask', command=command[:300], content=describe(decision))
515
- wait_decision(request)
691
+ wait_decision(request, strict=effect in ('destructive', 'privilege')) # "Approve all" never covers deletes or sudo (BUG-0101)
516
692
  if effect in ('install', 'service'):
517
693
  kinds = sorted(set(st.get('approved_kinds') or []) | {effect}); st['approved_kinds'] = kinds; save_state(st)
518
694
  elif effect in ('write', 'exec') and not st.get('readonly'):
@@ -574,16 +750,23 @@ def readonly_stop(st):
574
750
  event('done_gate', content='Research claims not recorded yet')
575
751
  block('Before answering, record the material claims with mcp__mlai__evidence {claims:[{claim, kind, source_ids, quote, uncertainty}]}. Facts need an exact quote from a retrieved source; label inferences and assumptions. Link the source URLs in the answer.')
576
752
 
753
+ def _laptop_run():
754
+ """BUG-0531: the run is on the person's own computer (CLI or Mac app)."""
755
+ if os.getenv('MINI_LAPTOP') == '1': return True
756
+ try: return json.loads((ROOT / 'request.json').read_text()).get('laptop') is True
757
+ except (OSError, ValueError, AttributeError): return False
758
+
577
759
  def stop(payload, st):
578
760
  if (ROOT / 'cancel').exists(): return
579
761
  if st.get('account_stop'): return # out of credits: the summary is the last turn, no more gates
580
762
  queued = steering()
581
763
  if queued: steer_block(queued, stopping=True)
582
764
  if st.get('readonly') or st.get('inspect'): return readonly_stop(st)
765
+ if st.get('plan_dismissed'): return # Not now: the run ends here; no done gate may send the agent back to work (BUG-0102)
583
766
  if briefing(st) and not st.get('planned') and not st.get('brief_nudged'):
584
767
  st['brief_nudged'] = True; save_state(st)
585
- event('done_gate', content='Brief mode: asked for the task list before finishing')
586
- block('Brief mode: the user is waiting to review a task list. Call TodoList with 3 to 10 concrete items (and mcp__mlai__brief_questions for anything open) before finishing. If the request is already answered and nothing needs building, say so plainly and finish.')
768
+ event('done_gate', content=brief_label(st) + ': asked for the task list before finishing')
769
+ block(brief_label(st) + ': the user is waiting to review a task list. Call TodoList with 3 to 10 concrete items (and mcp__mlai__brief_questions for anything open) before finishing. If the request is already answered and nothing needs building, say so plainly and finish.')
587
770
  if briefing(st): return
588
771
  count = int(load('kimi-stop-count', 0) or 0)
589
772
  if count >= 3 or time.time() > st.get('deadline', 1e18) - 90: return
@@ -592,6 +775,10 @@ def stop(payload, st):
592
775
  import roles as role_engine
593
776
  try: changed = role_engine.changed_files(REPO, st.get('base'))
594
777
  except Exception: changed = []
778
+ try:
779
+ from runtime_control import turn_changes
780
+ changed = turn_changes(ROOT, REPO, changed) # BUG-0495: not files that were already untracked or changed at the start
781
+ except Exception: pass
595
782
  code_changed = [p for p in changed if role_engine.CODE_EXT.search(p)]
596
783
  if st.get('require_changes') and not changed and 'patch' not in done:
597
784
  done.add('patch'); issues.append('This task requires a repository change, but the working tree is unchanged. Make the fix, or explain the blocker if it truly cannot be fixed.')
@@ -616,9 +803,12 @@ def stop(payload, st):
616
803
  if blocking: done.add('verification'); issues += blocking[:3]
617
804
  except Exception: pass
618
805
  role = st.get('role')
806
+ if role and 'role' not in done and (ROOT / 'last-reject').exists() and float((ROOT / 'last-reject').read_text().strip() or 0) >= float(st.get('started') or 0):
807
+ done.add('role') # BUG-0529: after a denial the done-check must not push unrequested work; the agent stops and asks
808
+ event('role_check', role=role['id'], title=role['title'], status='skipped', issues=[])
619
809
  if role and 'role' not in done:
620
810
  done.add('role')
621
- try: gaps = role_engine.gate(role, REPO, st.get('base'), changed, st.get('task', ''))
811
+ try: gaps = role_engine.gate(role, REPO, st.get('base'), changed, st.get('task', ''), laptop=_laptop_run())
622
812
  except Exception: gaps = []
623
813
  event('role_check', role=role['id'], title=role['title'], status='blocked' if gaps else 'passed', issues=[{'kind': i['kind'], 'label': i['label'], 'message': i['message'][:600]} for i in gaps])
624
814
  if gaps: issues.append('Role done-check (' + role['title'] + '): ' + ' '.join(i['message'] for i in gaps) + ' Fix these for real (real data paths, real artifacts, verified). If one truly cannot apply, say why in the final summary.')
@@ -654,9 +844,13 @@ def main():
654
844
  st = state()
655
845
  if kind == 'PreToolUse': pre(payload, st)
656
846
  elif kind == 'PostToolUse':
847
+ try: restore_bom()
848
+ except Exception: pass
657
849
  feedback = user_hooks('kimi_post', payload, st) # after_tool / after_edit hooks
658
850
  if feedback: block(feedback)
659
851
  elif kind == 'Stop':
852
+ try: restore_bom()
853
+ except Exception: pass
660
854
  stop(payload, st)
661
855
  # Turn accepted: tell the bridge, which ends the engine if it lingers waiting on background processes (preview servers).
662
856
  save('kimi-stopped', {'time': time.time()})