mlai-code 0.0.0-stage → 0.3.1

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 (182) hide show
  1. package/README.md +12 -2
  2. package/bin/mlai.mjs +3 -0
  3. package/package.json +18 -3
  4. package/src/browser-setup.mjs +77 -0
  5. package/src/cli-ext.mjs +146 -0
  6. package/src/cli.mjs +534 -0
  7. package/src/cloud.mjs +29 -0
  8. package/src/completion.mjs +159 -0
  9. package/src/credentials.mjs +54 -0
  10. package/src/deploy.mjs +134 -0
  11. package/src/distribution.mjs +373 -0
  12. package/src/engine-key.mjs +4 -0
  13. package/src/engine.mjs +167 -0
  14. package/src/headless.mjs +196 -0
  15. package/src/home.mjs +22 -0
  16. package/src/host.mjs +123 -0
  17. package/src/local-models.mjs +64 -0
  18. package/src/modes.mjs +38 -0
  19. package/src/netbox.mjs +97 -0
  20. package/src/netjail.py +59 -0
  21. package/src/offline.mjs +98 -0
  22. package/src/parity.mjs +86 -0
  23. package/src/project.mjs +68 -0
  24. package/src/relay.mjs +140 -0
  25. package/src/render.mjs +73 -0
  26. package/src/restricted.mjs +47 -0
  27. package/src/review.mjs +70 -0
  28. package/src/runner.mjs +127 -0
  29. package/src/runtime.mjs +75 -0
  30. package/src/sandbox.mjs +135 -0
  31. package/src/sdk.mjs +11 -0
  32. package/src/server.mjs +110 -0
  33. package/src/session.mjs +290 -0
  34. package/src/settings.mjs +135 -0
  35. package/src/shared-data.mjs +3 -0
  36. package/src/tui/acp.mjs +145 -0
  37. package/src/tui/agents-cli.mjs +114 -0
  38. package/src/tui/agents-local.mjs +65 -0
  39. package/src/tui/ansi.mjs +123 -0
  40. package/src/tui/app.mjs +710 -0
  41. package/src/tui/approval.mjs +88 -0
  42. package/src/tui/bg.mjs +172 -0
  43. package/src/tui/bgterm.mjs +79 -0
  44. package/src/tui/chat.mjs +230 -0
  45. package/src/tui/clipboard.mjs +74 -0
  46. package/src/tui/cloud-cli.mjs +57 -0
  47. package/src/tui/cloud-run.mjs +123 -0
  48. package/src/tui/cmd-agents.mjs +130 -0
  49. package/src/tui/cmd-auto-review.mjs +94 -0
  50. package/src/tui/cmd-cloud.mjs +17 -0
  51. package/src/tui/cmd-config.mjs +104 -0
  52. package/src/tui/cmd-core.mjs +160 -0
  53. package/src/tui/cmd-distribution.mjs +15 -0
  54. package/src/tui/cmd-ecosystem.mjs +169 -0
  55. package/src/tui/cmd-extensibility.mjs +333 -0
  56. package/src/tui/cmd-remote.mjs +18 -0
  57. package/src/tui/cmd-review.mjs +58 -0
  58. package/src/tui/cmd-session-extra.mjs +152 -0
  59. package/src/tui/cmd-tui.mjs +200 -0
  60. package/src/tui/commands.mjs +160 -0
  61. package/src/tui/custom-commands.mjs +98 -0
  62. package/src/tui/diff.mjs +60 -0
  63. package/src/tui/editor.mjs +190 -0
  64. package/src/tui/ext-state.mjs +16 -0
  65. package/src/tui/extensions-local.mjs +140 -0
  66. package/src/tui/files.mjs +72 -0
  67. package/src/tui/handoff.mjs +110 -0
  68. package/src/tui/import-setups.mjs +151 -0
  69. package/src/tui/init.mjs +104 -0
  70. package/src/tui/keymap.mjs +70 -0
  71. package/src/tui/keys.mjs +101 -0
  72. package/src/tui/loop.mjs +75 -0
  73. package/src/tui/markdown.mjs +118 -0
  74. package/src/tui/mcp-config.mjs +225 -0
  75. package/src/tui/mcp-oauth.mjs +162 -0
  76. package/src/tui/permissions.mjs +189 -0
  77. package/src/tui/plain.mjs +32 -0
  78. package/src/tui/plugins-local.mjs +103 -0
  79. package/src/tui/remote.mjs +125 -0
  80. package/src/tui/review-cli.mjs +332 -0
  81. package/src/tui/review-github.mjs +59 -0
  82. package/src/tui/screen.mjs +60 -0
  83. package/src/tui/session-ops.mjs +104 -0
  84. package/src/tui/skills-local.mjs +92 -0
  85. package/src/tui/snapshots.mjs +87 -0
  86. package/src/tui/statusline.mjs +98 -0
  87. package/src/tui/transcript.mjs +116 -0
  88. package/src/two-words.mjs +36 -0
  89. package/src/wakeups.mjs +53 -0
  90. package/src/winenv.mjs +94 -0
  91. package/src/winsandbox.py +351 -0
  92. package/src/workspace-api.mjs +621 -0
  93. package/src/worktree.mjs +128 -0
  94. package/vendor/client-sdk/controller.cjs +115 -0
  95. package/vendor/client-sdk/files.cjs +38 -0
  96. package/vendor/client-sdk/index.cjs +133 -0
  97. package/vendor/client-sdk/login.cjs +52 -0
  98. package/vendor/client-sdk/updates.cjs +41 -0
  99. package/vendor/cloud-cli/mlai.mjs +394 -0
  100. package/worker/architecture_parse.cjs +23 -0
  101. package/worker/architecture_worker.py +394 -0
  102. package/worker/ask_first.py +96 -0
  103. package/worker/attachment_reader.py +66 -0
  104. package/worker/background_jobs.py +111 -0
  105. package/worker/brief_questions.py +56 -0
  106. package/worker/browser_local.py +49 -0
  107. package/worker/browser_pane.py +89 -0
  108. package/worker/browser_tool.py +101 -0
  109. package/worker/build_planner.py +187 -0
  110. package/worker/chat_fork.py +277 -0
  111. package/worker/checkpoints.py +133 -0
  112. package/worker/cloud_pty.py +351 -0
  113. package/worker/command_policy.py +39 -0
  114. package/worker/command_safety.py +717 -0
  115. package/worker/computer_card.sh +23 -0
  116. package/worker/computer_setup.sh +86 -0
  117. package/worker/computer_use.py +221 -0
  118. package/worker/connector_search.py +43 -0
  119. package/worker/context_manager.py +60 -0
  120. package/worker/conversation.py +144 -0
  121. package/worker/deploy_pack.py +116 -0
  122. package/worker/design_director.py +240 -0
  123. package/worker/dev_jobs.py +166 -0
  124. package/worker/edit_guard.py +99 -0
  125. package/worker/env_setup.py +129 -0
  126. package/worker/evidence.py +109 -0
  127. package/worker/fast_search.py +24 -0
  128. package/worker/git_sync.py +333 -0
  129. package/worker/goals.py +156 -0
  130. package/worker/handover.py +98 -0
  131. package/worker/harness_memory.py +194 -0
  132. package/worker/image_generation.py +173 -0
  133. package/worker/intelligence.py +149 -0
  134. package/worker/intent_model.py +78 -0
  135. package/worker/intent_weights.json +1 -0
  136. package/worker/ios_simulator.py +87 -0
  137. package/worker/kimi_bridge.py +997 -0
  138. package/worker/kimi_compact.py +93 -0
  139. package/worker/kimi_gates.py +304 -0
  140. package/worker/kimi_hook.py +617 -0
  141. package/worker/lifecycle.py +95 -0
  142. package/worker/lsp.py +77 -0
  143. package/worker/mcp_local.py +293 -0
  144. package/worker/memory.py +99 -0
  145. package/worker/mlai_auto_review.py +177 -0
  146. package/worker/mlai_hooks.py +966 -0
  147. package/worker/mlai_mcp.py +441 -0
  148. package/worker/mlai_permissions.py +283 -0
  149. package/worker/model_stream.py +75 -0
  150. package/worker/nested_repos.py +76 -0
  151. package/worker/offline_guard.py +17 -0
  152. package/worker/preview.py +806 -0
  153. package/worker/proc_watch.py +124 -0
  154. package/worker/project_context.py +72 -0
  155. package/worker/project_rules.py +99 -0
  156. package/worker/quality.py +180 -0
  157. package/worker/reply_language.py +56 -0
  158. package/worker/repo_hygiene.py +132 -0
  159. package/worker/repo_memory.py +101 -0
  160. package/worker/repo_policy.py +269 -0
  161. package/worker/roles.json +3173 -0
  162. package/worker/roles.py +303 -0
  163. package/worker/runner.py +1795 -0
  164. package/worker/runtime_control.py +205 -0
  165. package/worker/secret_scan.py +168 -0
  166. package/worker/session_hub.py +80 -0
  167. package/worker/skill_library.py +129 -0
  168. package/worker/skill_pack.py +533 -0
  169. package/worker/subagents.py +91 -0
  170. package/worker/task_controller.py +139 -0
  171. package/worker/task_skills.py +159 -0
  172. package/worker/team_checkpoint.py +33 -0
  173. package/worker/token_count.py +32 -0
  174. package/worker/tool_catalog.py +38 -0
  175. package/worker/upload_storage.py +531 -0
  176. package/worker/verification.py +725 -0
  177. package/worker/vision.py +84 -0
  178. package/worker/wakeups.py +63 -0
  179. package/worker/web_tools.py +203 -0
  180. package/worker/winproc.py +135 -0
  181. package/worker/work_ledger.py +117 -0
  182. package/worker/worktrees.py +79 -0
@@ -0,0 +1,303 @@
1
+ """Engineering roles: one definition (roles.json) drives the prompt, mapped skills, build planning, the design step and a done-check.
2
+
3
+ Roles are guidance plus a bounded completion check. They never grant permissions."""
4
+ import fnmatch, json, re, subprocess
5
+ from pathlib import Path
6
+
7
+ _DATA = None
8
+ MOCK_OK = re.compile(r'\b(?:mock(?:ed|s|up)?|dummy|fake|placeholder|sample data|fixture|prototype|demo data|lorem)\b', re.I)
9
+ SKIP_PATH = re.compile(r'(?:^|/)(?:tests?|__tests__|spec|specs|e2e|mocks?|__mocks__|fixtures?|seeds?|stories|storybook|examples?|docs?)(?:/|$)|\.(?:test|spec|stories)\.[a-z]+$|(?:^|/)test_[^/]+$|_test\.[a-z]+$|(?:^|/)seed[^/]*$|\.md$', re.I)
10
+ CODE_EXT = re.compile(r'\.(?:[cm]?[jt]sx?|py|go|rb|java|kt|swift|rs|php|cs|vue|svelte|sql|c|h|cpp|hpp|ino|tf|ya?ml|toml|json|sh|ipynb|r)$|(?:^|/)(?:Dockerfile[^/]*|Makefile|Procfile)$', re.I)
11
+ DOMAIN_REPO_ROLES = {'embedded', 'mobile', 'data-eng', 'data-science', 'ml'}
12
+ MOCK_PATTERNS = [
13
+ (re.compile(r'\b(?:mock|fake|dummy|sample|hardcoded|MOCK|FAKE|DUMMY|SAMPLE)_?[A-Z][A-Za-z]*s\b'), 'mock/sample data identifier'),
14
+ (re.compile(r'@faker-js/faker|\bfrom faker import|\bfaker\.[a-z]', re.I), 'faker-generated data'),
15
+ (re.compile(r'lorem ipsum', re.I), 'lorem ipsum text'),
16
+ (re.compile(r'\b(?:mock|fake|dummy|sample|placeholder|hardcoded)_?(?:data|users?|items?|orders?|products?|posts?|stats?|metrics?|rows?|records?|customers?|transactions?|results?|responses?|list|entries|events|leads|tickets|invoices)\b', re.I), 'mock/sample data identifier'),
17
+ (re.compile(r'Math\.random\(\)\s*\*\s*\d{2,}|Math\.floor\(\s*Math\.random\(\)\s*\*\s*\d{2,}'), 'random numbers posing as data'),
18
+ (re.compile(r'\brandom\.randint\(|\bnp\.random\.(?:rand|randint|randn|normal)\('), 'random values posing as data'),
19
+ (re.compile(r'(?:TODO|FIXME|XXX)[^\n]{0,60}\b(?:real|api|backend|fetch|database|db|wire|hook up|connect)\b', re.I), 'TODO left instead of a real integration'),
20
+ (re.compile(r'(?:return|resolve)\s*\(?\s*\{\s*["\']?(?:success|ok)["\']?\s*:\s*true\s*\}\s*\)?\s*;?\s*(?://|#)?\s*(?:stub|mock|fake|todo)', re.I), 'stubbed response'),
21
+ ]
22
+
23
+
24
+ def data():
25
+ global _DATA
26
+ if _DATA is None:
27
+ _DATA = json.loads((Path(__file__).with_name('roles.json')).read_text())
28
+ return _DATA
29
+
30
+
31
+ def roles():
32
+ return {r['id']: r for r in data()['roles']}
33
+
34
+
35
+ def ids():
36
+ return [r['id'] for r in data()['roles']]
37
+
38
+
39
+ def _hit(text, phrase):
40
+ return re.search(r'(?<![a-z0-9])' + re.escape(phrase) + r'(?:s|es)?(?![a-z0-9])', text) is not None
41
+
42
+
43
+ def _repo_files(repo, limit=3000):
44
+ root = Path(repo)
45
+ skip = {'.git', 'node_modules', '.next', 'dist', 'build', '.venv', 'venv', '__pycache__', '.mini', 'target'}
46
+ out = []
47
+ try:
48
+ for path in root.rglob('*'):
49
+ rel = path.relative_to(root)
50
+ if any(part in skip for part in rel.parts):
51
+ continue
52
+ if path.is_file():
53
+ out.append(rel.as_posix())
54
+ if len(out) >= limit:
55
+ break
56
+ except OSError:
57
+ pass
58
+ return out
59
+
60
+
61
+ def match(path, globs):
62
+ p = path.lower()
63
+ name = p.rsplit('/', 1)[-1]
64
+ for g in globs:
65
+ g = g.lower()
66
+ if fnmatch.fnmatch(p, g) or fnmatch.fnmatch(name, g) or (g.startswith('**/') and (fnmatch.fnmatch(p, g[3:]) or fnmatch.fnmatch(name, g[3:]))):
67
+ return True
68
+ return False
69
+
70
+
71
+ # A broad build whose strong signals span both sides of the product is a full-stack job, not a backend or frontend one.
72
+ CLIENT_SIDE = {'frontend', 'a11y', 'design-eng', 'i18n'}
73
+ SERVER_SIDE = {'backend', 'api', 'dba', 'devops', 'security', 'realtime'}
74
+ BUILDER_ROLES = {'fullstack', 'frontend', 'backend', 'mobile', 'embedded', 'desktop', 'game', 'cli', 'extension', 'api', 'data-eng', 'ml', 'web3', 'realtime'}
75
+
76
+ def table_title(role_id):
77
+ r = roles().get(role_id) or {}
78
+ return str(r.get('label') or r.get('title') or role_id)
79
+
80
+ def _broad(task, ranked):
81
+ """A long, multi-part request whose signals spread over several specialties (no single one dominates)."""
82
+ if not ranked: return False
83
+ bullets = len(re.findall(r'^\s*(?:[-*]|\d+[.)])\s+\S', task, re.M))
84
+ long = len(task) > 1200 or bullets >= 6
85
+ strong = [r for r, v in ranked if v >= 3]
86
+ top, second = ranked[0][1], (ranked[1][1] if len(ranked) > 1 else 0)
87
+ spread = len(strong) >= 3 or (second and second >= 0.6 * top)
88
+ return bool(long and spread)
89
+
90
+ def detect(task, repo=None, build=False):
91
+ """Pick a role for Auto. Returns {id, reason, score, scores}. Low-signal requests return id None (no role layer)."""
92
+ text = (task or '')[-6000:].lower()
93
+ files = _repo_files(repo) if repo else []
94
+ scores, why = {}, {}
95
+ for role in data()['roles']:
96
+ d = role.get('detect') or {}
97
+ if not d:
98
+ continue
99
+ score, hits = 0, []
100
+ for phrase, weight in (d.get('keywords') or {}).items():
101
+ if _hit(text, phrase):
102
+ score += weight
103
+ hits.append(phrase)
104
+ repo_hits = [g for g in (d.get('files') or []) if any(match(f, [g]) for f in files)]
105
+ if repo_hits:
106
+ # Domain repos (firmware, mobile, data, ML) define the job even for vague requests; generic files only nudge.
107
+ score += min(4, 2 * len(repo_hits)) if role['id'] in DOMAIN_REPO_ROLES else min(2, len(repo_hits))
108
+ if score:
109
+ scores[role['id']] = score
110
+ why[role['id']] = (hits, repo_hits)
111
+ # Both halves of a full-stack product named explicitly: that is a full-stack request.
112
+ if scores.get('backend', 0) >= 3 and scores.get('frontend', 0) >= 3 and 'fullstack' in scores:
113
+ scores['fullstack'] += 3
114
+ ranked = sorted(scores.items(), key=lambda kv: (-kv[1], ids().index(kv[0])))
115
+ broad = _broad(task or '', ranked)
116
+ strong = {r for r, v in ranked if v >= 3}
117
+ two_sided = (ranked and ranked[0][0] in SERVER_SIDE and strong & CLIENT_SIDE) or (ranked and ranked[0][0] in CLIENT_SIDE and strong & SERVER_SIDE)
118
+ if broad and build and ranked and (ranked[0][0] not in BUILDER_ROLES or (ranked[0][0] in ('backend', 'frontend', 'api') and two_sided)):
119
+ # ROLE-001: a broad product request that mentions accessibility, tests and performance among many other
120
+ # things is not an accessibility job. Build it end to end; the specialist areas stay as checks.
121
+ areas = [table_title(r) for r, _ in ranked[:4]]
122
+ return {'id': 'fullstack', 'reason': 'Broad product request covering ' + ', '.join(areas[:-1]) + (' and ' + areas[-1] if len(areas) > 1 else areas[0] if areas else '') + ', so it is built end to end with those areas as checks.',
123
+ 'score': scores.get('fullstack', 0), 'scores': dict(ranked[:5]), 'broad': True}
124
+ if ranked and ranked[0][1] >= 4:
125
+ best = ranked[0][0]
126
+ elif build:
127
+ best = 'fullstack' # an app request with no stronger signal: build it properly end to end
128
+ why.setdefault(best, ([], []))
129
+ else:
130
+ return {'id': None, 'reason': 'No strong role signal; using the general engineer.', 'score': ranked[0][1] if ranked else 0, 'scores': dict(ranked[:5])}
131
+ hits, repo_hits = why.get(best, ([], []))
132
+ parts = []
133
+ if hits:
134
+ parts.append('you mentioned ' + ', '.join('"' + h + '"' for h in hits[:4]))
135
+ if repo_hits:
136
+ parts.append('the repo has ' + ', '.join(repo_hits[:3]))
137
+ if not parts:
138
+ parts.append('this is a product build, so every layer is built for real')
139
+ return {'id': best, 'reason': '; '.join(parts).capitalize() + '.', 'score': scores.get(best, 0), 'scores': dict(ranked[:5])}
140
+
141
+
142
+ def resolve(config, repo=None, build=False):
143
+ """Explicit role wins; 'auto' (or missing) detects. Returns resolved info dict or None for the general engineer."""
144
+ wanted = str(config.get('role') or 'auto')
145
+ table = roles()
146
+ if wanted != 'auto' and wanted in table:
147
+ role = table[wanted]
148
+ return {'id': wanted, 'label': role['label'], 'title': role['title'], 'auto': False, 'reason': 'Selected by you.'}
149
+ picked = detect(config.get('task', ''), repo, build)
150
+ if not picked['id']:
151
+ return None
152
+ role = table[picked['id']]
153
+ return {'id': role['id'], 'label': role['label'], 'title': role['title'], 'auto': True, 'reason': picked['reason'], 'scores': picked['scores']}
154
+
155
+
156
+ def prompt(resolved, readonly=False):
157
+ if not resolved:
158
+ return ''
159
+ role = roles()[resolved['id']]
160
+ how = 'picked automatically: ' + resolved['reason'] if resolved.get('auto') else 'selected by the user'
161
+ lines = ['Engineering role: ' + role['title'] + ' (' + how + '). Work as a senior ' + role['title'].lower() + ' would, inside the user\'s scope.']
162
+ lines += ['- ' + f for f in role['focus']]
163
+ if role.get('design'):
164
+ lines.append('Design standard (this role leads design for every screen it touches):')
165
+ lines += ['- ' + d for d in role['design']]
166
+ if role.get('tools'):
167
+ lines.append('Tools this role reaches for (prefer what the repo already uses): ' + '; '.join(role['tools']) + '.')
168
+ if role.get('decides'):
169
+ lines.append('Decisions this role owns and must state explicitly in the plan or summary: ' + '; '.join(role['decides']) + '.')
170
+ if readonly:
171
+ lines.append('This turn is read-only: apply this lens to the answer or plan; do not claim work was done.')
172
+ else:
173
+ lines.append('Definition of done for this role (the runner checks it before completion): ' + '; '.join(role['done']) + '.')
174
+ if (role.get('gate') or {}).get('noMock'):
175
+ lines.append('No fake data: do not ship hardcoded arrays, faker output, random numbers or stubbed handlers in place of real data paths. Seed or fixture data belongs in seed scripts or test fixtures. If the user explicitly asks for mock data, label it as mock in code and in the summary.')
176
+ lines.append('If something the role requires is impossible here (missing credentials, no GPU, no cluster), build everything else for real, then state the gap and the exact command or secret needed.')
177
+ return '\n'.join(lines)
178
+
179
+
180
+ def preferred_skills(resolved, lead=None):
181
+ skills = list(roles()[resolved['id']]['skills']) if resolved else []
182
+ if lead == 'full':
183
+ # The first three role skills are loaded in full, so the design skill goes first.
184
+ skills = [DESIGN_SKILL] + [s for s in skills if s != DESIGN_SKILL]
185
+ return skills
186
+
187
+
188
+ # In Auto, the Frontend engineer leads design for anything with a screen, whichever specialist does the work.
189
+ DESIGN_LEAD = 'frontend'
190
+ DESIGN_SKILL = 'frontend-design'
191
+ UI_TOUCH = re.compile(r'\b(?:ui|ux|page|pages|screen|screens|button|buttons|form|forms|modal|dialog|navbar|sidebar|header|footer|menu|layout|theme|dark mode|colou?rs?|fonts?|typography|icons?|css|tailwind|styles?|styling|responsive|website|landing|dashboard|component|components|card|cards|hero|banner|animation|spacing|padding|margin|design|redesign|look)\b', re.I)
192
+
193
+
194
+ def design_lead(config, resolved, task=None):
195
+ """How much of the Frontend design standard to layer on in Auto: 'full', 'light' or None.
196
+
197
+ 'full': Auto picked another interface role (full-stack, mobile, game, ...), so Frontend's design standard applies in full.
198
+ 'light': the general engineer on a task that touches the interface gets a one-paragraph reminder.
199
+ None: the user chose a role themselves, Auto picked Frontend (which already owns design), or nothing on screen changes."""
200
+ if str((config or {}).get('role') or 'auto') != 'auto':
201
+ return None
202
+ if not resolved:
203
+ text = (config or {}).get('task', '') if task is None else task
204
+ return 'light' if UI_TOUCH.search(str(text or '')[-6000:]) else None
205
+ if resolved.get('id') == DESIGN_LEAD or not resolved.get('auto'):
206
+ return None
207
+ return 'full' if roles().get(resolved['id'], {}).get('ui') else None
208
+
209
+
210
+ def design_prompt(lead, resolved=None):
211
+ """The Frontend design standard as prompt text for a run led by another engineer. Empty when there is no lead."""
212
+ spec = roles()[DESIGN_LEAD]
213
+ if lead == 'light':
214
+ return 'Design lead: Frontend engineer. ' + spec['designShort']
215
+ if lead != 'full':
216
+ return ''
217
+ title = roles()[resolved['id']]['title'].lower() if resolved else 'engineer'
218
+ lines = ['Design lead: Frontend engineer. Every screen this task touches follows the Frontend design standard below, alongside the ' + title + ' work. Start UI work with a five-line design brief (who it is for, the one job of each screen, the mood in three words, the chosen direction, the one thing that makes it memorable) and follow the project\'s selected design direction when one exists.']
219
+ lines += ['- ' + d for d in spec['design']]
220
+ return '\n'.join(lines)
221
+
222
+
223
+ def phase1(resolved):
224
+ return roles()[resolved['id']].get('phase1', '') if resolved else ''
225
+
226
+
227
+ def design_allowed(resolved):
228
+ return True if not resolved else bool(roles()[resolved['id']].get('ui'))
229
+
230
+
231
+ def _added_lines(repo, base, path):
232
+ """Added lines of one changed file relative to base (whole file when untracked)."""
233
+ full = Path(repo) / path
234
+ try:
235
+ tracked = subprocess.run(['git', 'ls-files', '--error-unmatch', '--', path], cwd=repo, capture_output=True, timeout=10).returncode == 0
236
+ if not tracked:
237
+ if full.is_file() and full.stat().st_size < 400000:
238
+ return list(enumerate(full.read_text(errors='replace').splitlines(), 1))
239
+ return []
240
+ diff = subprocess.run(['git', 'diff', '-U0', base or 'HEAD', '--', path], cwd=repo, capture_output=True, text=True, timeout=15).stdout
241
+ except (OSError, subprocess.SubprocessError):
242
+ return []
243
+ out, line = [], 0
244
+ for row in diff.splitlines():
245
+ m = re.match(r'^@@ -\d+(?:,\d+)? \+(\d+)', row)
246
+ if m:
247
+ line = int(m.group(1))
248
+ continue
249
+ if row.startswith('+') and not row.startswith('+++'):
250
+ out.append((line, row[1:]))
251
+ line += 1
252
+ elif not row.startswith('-'):
253
+ line += 1
254
+ return out
255
+
256
+
257
+ def mock_findings(repo, base, changed, limit=8):
258
+ found = []
259
+ for path in changed:
260
+ if SKIP_PATH.search(path) or not CODE_EXT.search(path):
261
+ continue
262
+ for number, text in _added_lines(repo, base, path):
263
+ for pattern, label in MOCK_PATTERNS:
264
+ if pattern.search(text):
265
+ found.append({'file': path, 'line': number, 'kind': label, 'text': text.strip()[:140]})
266
+ break
267
+ if len(found) >= limit:
268
+ return found
269
+ return found
270
+
271
+
272
+ def changed_files(repo, base=None):
273
+ """Changed and untracked file paths (untracked directories expanded), relative to base when given."""
274
+ out = []
275
+ try:
276
+ diff = subprocess.run(['git', 'diff', '--name-only', base or 'HEAD'], cwd=repo, capture_output=True, text=True, timeout=15)
277
+ if diff.returncode == 0:
278
+ out += diff.stdout.splitlines()
279
+ new = subprocess.run(['git', 'ls-files', '--others', '--exclude-standard'], cwd=repo, capture_output=True, text=True, timeout=15)
280
+ if new.returncode == 0:
281
+ out += new.stdout.splitlines()
282
+ except (OSError, subprocess.SubprocessError):
283
+ return []
284
+ return [p for p in dict.fromkeys(x.strip() for x in out) if p and not p.startswith('.mini/')][:400]
285
+
286
+
287
+ def gate(resolved, repo, base, changed, task=''):
288
+ """Issues that block completion once for this role. Empty when the role is satisfied or not applicable."""
289
+ if not resolved or not changed:
290
+ return []
291
+ role = roles()[resolved['id']]
292
+ spec = role.get('gate') or {}
293
+ issues = []
294
+ code_changed = any(CODE_EXT.search(p) for p in changed)
295
+ if code_changed or role['id'] == 'architect':
296
+ for artifact in spec.get('artifacts') or []:
297
+ if not any(match(p, artifact['globs']) for p in changed):
298
+ issues.append({'kind': 'artifact', 'label': artifact['label'], 'message': 'Missing for the ' + role['title'] + ' done-check: ' + artifact['label'] + '.'})
299
+ if spec.get('noMock') and not MOCK_OK.search(task or ''):
300
+ hits = mock_findings(repo, base, changed)
301
+ if hits:
302
+ issues.append({'kind': 'mock', 'label': 'Fake or placeholder data', 'message': 'Fake or placeholder data in shipped code: ' + '; '.join(h['file'] + ':' + str(h['line']) + ' (' + h['kind'] + ')' for h in hits), 'findings': hits})
303
+ return issues