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,132 @@
1
+ """Keep generated repositories clean after a run.
2
+
3
+ Conservative by design: only ignore rules are added (never removed), only
4
+ untracked accidental files are deleted, and cache files are untracked (kept on
5
+ disk). Nothing here rewrites history or touches source files.
6
+ """
7
+ import fnmatch
8
+ import os
9
+ import re
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ # `.env` itself is left alone: deploys include untracked files that are not ignored, and some apps rely on it.
14
+ BASE_RULES = ('.DS_Store', '.env*.local', 'npm-debug.log*', 'yarn-error.log*')
15
+ NODE_RULES = ('node_modules/', '.next/', 'coverage/', 'test-results/', 'playwright-report/', '*.tsbuildinfo', '.vercel/', '.turbo/')
16
+ PYTHON_RULES = ('__pycache__/', '*.pyc', '.pytest_cache/', '.venv/')
17
+ RULES = NODE_RULES + PYTHON_RULES + BASE_RULES
18
+ # Cache files that never belong in version control.
19
+ CACHE = re.compile(r'(^|/)(__pycache__/|\.pytest_cache/)|\.py[co]$|(^|/)\.DS_Store$')
20
+ # A file whose name is a shell flag or redirect fragment ("-w", "2", "&1") is a typo in a command, not work.
21
+ ACCIDENTAL = re.compile(r'^(-[^/]*|&\d?|\d|=)$')
22
+ NOISE_DIRS = ('node_modules/', '.next/', '.git/', '__pycache__/', '.pytest_cache/', '.turbo/', '.vercel/', '.venv/', 'venv/')
23
+
24
+
25
+ def _git(repo, *args, timeout=15):
26
+ return subprocess.run(['git', *args], cwd=repo, capture_output=True, text=True, timeout=timeout)
27
+
28
+
29
+ def change_path(line):
30
+ """Turn a `git status --porcelain` or `git diff --name-status` line into a plain path."""
31
+ line = str(line or '').rstrip('\n')
32
+ if '\t' in line:
33
+ path = line.split('\t')[-1]
34
+ else:
35
+ m = re.match(r'^[ MADRCUT?!]{1,2} (.+)$', line)
36
+ path = m.group(1) if m else line.strip()
37
+ if ' -> ' in path: path = path.split(' -> ')[-1]
38
+ path = path.strip()
39
+ if len(path) > 1 and path[0] == path[-1] == '"':
40
+ path = path[1:-1].encode('latin-1', 'backslashreplace').decode('unicode_escape').encode('latin-1', 'replace').decode('utf-8', 'replace')
41
+ return path
42
+
43
+
44
+ def is_noise(path):
45
+ p = str(path or '')
46
+ return bool(CACHE.search(p)) or any(p.startswith(d) or ('/' + d) in p for d in NOISE_DIRS)
47
+
48
+
49
+ DIR_RULES = {r.rstrip('/') for r in RULES if r.endswith('/')}
50
+ GLOB_RULES = [r for r in RULES if not r.endswith('/')]
51
+
52
+
53
+ def _untracked_junk(repo, max_dirs=20000):
54
+ """Build output and cache paths that exist and are untracked and not ignored yet.
55
+ A bounded walk finds candidates (git collapses new folders, hiding nested caches); git then filters them."""
56
+ found, seen = [], 0
57
+ for top, dirs, files in os.walk(repo):
58
+ rel = os.path.relpath(top, repo)
59
+ rel = '' if rel == '.' else rel.replace(os.sep, '/') + '/'
60
+ keep = []
61
+ for d in dirs:
62
+ if d == '.git': continue
63
+ if d in DIR_RULES: found.append(rel + d + '/')
64
+ elif not os.path.islink(os.path.join(top, d)): keep.append(d)
65
+ dirs[:] = keep
66
+ found += [rel + f for f in files if any(fnmatch.fnmatch(f, g) for g in GLOB_RULES)]
67
+ seen += 1
68
+ if seen >= max_dirs or len(found) > 2000: break
69
+ if not found: return []
70
+ listed = _git(repo, 'ls-files', '--others', '--exclude-standard', '--directory', '--', *found[:2000])
71
+ return listed.stdout.splitlines() if listed.returncode == 0 else []
72
+
73
+
74
+ def _matches(rule, entry):
75
+ """Does an ignore rule cover this untracked path (from `git ls-files --others --directory`)?"""
76
+ entry = entry.rstrip('/')
77
+ if rule.endswith('/'):
78
+ name = rule.rstrip('/')
79
+ return entry == name or entry.startswith(name + '/') or ('/' + name + '/') in ('/' + entry + '/')
80
+ return fnmatch.fnmatch(entry.rsplit('/', 1)[-1], rule)
81
+
82
+
83
+ def ensure_gitignore(repo):
84
+ """Add ignore rules only for build output and caches that are actually present and untracked,
85
+ so a clean project is never given a .gitignore it does not need. Returns the rules added."""
86
+ root = Path(repo)
87
+ path = root / '.gitignore'
88
+ if path.is_symlink(): return []
89
+ entries = _untracked_junk(repo)
90
+ if not entries: return []
91
+ current = path.read_text(errors='replace') if path.is_file() else ''
92
+ have = {l.strip().lstrip('/').rstrip('/') for l in current.splitlines() if l.strip() and not l.startswith('#')}
93
+ wanted = [r for r in RULES if r.rstrip('/') not in have and any(_matches(r, e) for e in entries)]
94
+ if not wanted: return []
95
+ block = ('' if not current or current.endswith('\n') else '\n') + ('\n' if current.strip() else '') + '# Added by ML AI Code: build output and caches\n' + '\n'.join(wanted) + '\n'
96
+ path.write_text(current + block)
97
+ return wanted
98
+
99
+
100
+ def tidy(repo, since=None):
101
+ """Clean the working tree after a run. Returns a short summary dict (empty when nothing changed).
102
+ Stray files (for example "-w" from a mistyped command) are deleted only when created after `since`."""
103
+ if _git(repo, 'rev-parse', '--is-inside-work-tree').returncode != 0: return {}
104
+ cached = _git(repo, 'ls-files', '--cached')
105
+ caches = [n for n in (cached.stdout.splitlines() if cached.returncode == 0 else []) if CACHE.search(n)]
106
+ untracked_cache = []
107
+ for i in range(0, len(caches), 200):
108
+ if _git(repo, 'rm', '--cached', '--quiet', '--', *caches[i:i + 200]).returncode == 0:
109
+ untracked_cache += caches[i:i + 200]
110
+ removed = []
111
+ if since is not None:
112
+ untracked = _git(repo, 'ls-files', '--others', '--exclude-standard')
113
+ for name in (untracked.stdout.splitlines() if untracked.returncode == 0 else []):
114
+ target = Path(repo) / name
115
+ try:
116
+ if '/' not in name and ACCIDENTAL.match(name) and target.is_file() and not target.is_symlink() and target.stat().st_size < 1_000_000 and target.stat().st_mtime >= since:
117
+ target.unlink(); removed.append(name)
118
+ except OSError: pass
119
+ added = ensure_gitignore(repo)
120
+ out = {}
121
+ if added: out['ignored'] = added
122
+ if removed: out['removed'] = removed
123
+ if untracked_cache: out['untracked'] = untracked_cache
124
+ return out
125
+
126
+
127
+ def summary(result):
128
+ parts = []
129
+ if result.get('removed'): parts.append('removed stray file%s %s' % ('' if len(result['removed']) == 1 else 's', ', '.join(result['removed'][:5])))
130
+ if result.get('untracked'): parts.append('stopped tracking %d cache file%s' % (len(result['untracked']), '' if len(result['untracked']) == 1 else 's'))
131
+ if result.get('ignored'): parts.append('added %s to .gitignore' % ', '.join(result['ignored'][:6]) + (' and more' if len(result['ignored']) > 6 else ''))
132
+ return ('Tidied the repository: ' + '; '.join(parts) + '.') if parts else ''
@@ -0,0 +1,101 @@
1
+ """Repository memory: short, committed notes in .mlai/ that every task reads first.
2
+
3
+ ARCHITECTURE.md how the system is put together
4
+ CONVENTIONS.md how code is written here
5
+ DECISIONS.md choices already made and why
6
+ DEPLOY.md how the project is built, released and rolled back
7
+
8
+ The agent never edits these files directly. It proposes an update with memory_propose; the proposal
9
+ waits in .mini/memory-proposal.json until a person approves it in the app, which writes the file."""
10
+ import json, re, time
11
+ from pathlib import Path
12
+
13
+ FILES = ('ARCHITECTURE.md', 'CONVENTIONS.md', 'DECISIONS.md', 'DEPLOY.md')
14
+ PER_FILE = 4000
15
+ TOTAL = 12000
16
+ MAX_PROPOSAL = 8000
17
+
18
+
19
+ def read(repo):
20
+ """Existing memory files as {name: text}, each capped, symlinks ignored."""
21
+ base = Path(repo) / '.mlai'
22
+ out = {}
23
+ if not base.is_dir() or base.is_symlink():
24
+ return out
25
+ for name in FILES:
26
+ f = base / name
27
+ if f.is_file() and not f.is_symlink():
28
+ try:
29
+ out[name] = f.read_text(errors='replace')[:PER_FILE]
30
+ except OSError:
31
+ pass
32
+ return out
33
+
34
+
35
+ def prompt(repo):
36
+ """Text placed ahead of the task. Empty files still get the curator instruction so memory can start."""
37
+ files = read(repo)
38
+ used = 0
39
+ parts = []
40
+ for name, text in files.items():
41
+ text = text.strip()
42
+ if not text or used >= TOTAL:
43
+ continue
44
+ text = text[:TOTAL - used]
45
+ used += len(text)
46
+ parts.append('.mlai/' + name + ':\n' + text)
47
+ head = ('Repository memory (.mlai/, committed by the team; reference for how this project works. Current instructions and permissions take precedence):\n'
48
+ + '\n\n'.join(parts) + '\n\n') if parts else ''
49
+ return head + ('Memory curator: when you finish, if this task taught something a teammate would need next time (architecture, a convention, a decision and its reason, '
50
+ 'deploy or release steps), call mcp__mlai__memory_propose once per file with the complete new content of that .mlai file. Keep each file short and factual. '
51
+ 'Do not edit .mlai files yourself; the user approves the proposal in the app.\n\n')
52
+
53
+
54
+ def _clean(text):
55
+ text = str(text or '').replace('\r\n', '\n')
56
+ # Never let a secret-looking value into committed memory.
57
+ text = re.sub(r'(?i)(api[_-]?key|token|secret|password)(\s*[:=]\s*)\S+', r'\1\2[redacted]', text)
58
+ text = re.sub(r'\b(sk|ghp|gho|github_pat|xox[abp])[-_][A-Za-z0-9_\-]{12,}', '[redacted]', text)
59
+ return text
60
+
61
+
62
+ def propose(root, repo, args):
63
+ """Record one proposed file update. Several calls in one task merge; the newest content per file wins."""
64
+ name = str(args.get('file') or '').strip()
65
+ if name.startswith('.mlai/'):
66
+ name = name[6:]
67
+ if name not in FILES:
68
+ raise ValueError('file must be one of ' + ', '.join(FILES))
69
+ content = _clean(args.get('content'))
70
+ if not content.strip():
71
+ raise ValueError('content is empty')
72
+ if len(content) > MAX_PROPOSAL:
73
+ raise ValueError('Keep each memory file under %d characters' % MAX_PROPOSAL)
74
+ reason = _clean(args.get('reason'))[:300]
75
+ path = Path(root) / 'memory-proposal.json'
76
+ try:
77
+ current = json.loads(path.read_text())
78
+ if not isinstance(current, dict) or not isinstance(current.get('files'), list):
79
+ current = None
80
+ except Exception:
81
+ current = None
82
+ request = {}
83
+ try:
84
+ request = json.loads((Path(root) / 'request.json').read_text())
85
+ except Exception:
86
+ pass
87
+ if not current or current.get('runId') != request.get('runId'):
88
+ current = {'runId': request.get('runId'), 'created': time.time(), 'files': []}
89
+ before = read(repo).get(name, '')
90
+ current['files'] = [f for f in current['files'] if f.get('file') != name][:3] + [{'file': name, 'before': before, 'after': content, 'reason': reason}]
91
+ tmp = path.with_suffix('.tmp')
92
+ tmp.write_text(json.dumps(current))
93
+ tmp.replace(path)
94
+ return {'proposed': name, 'note': 'Saved as a proposal. The user reviews and approves it in the app; do not write .mlai files yourself.'}
95
+
96
+
97
+ TOOL = {'name': 'memory_propose',
98
+ 'description': 'Propose an update to the repository memory in .mlai/ (ARCHITECTURE.md, CONVENTIONS.md, DECISIONS.md or DEPLOY.md). Give the complete new file content. '
99
+ 'The user approves it in the app before it is written. Use at the end of a task, only for durable knowledge a teammate needs.',
100
+ 'inputSchema': {'type': 'object', 'properties': {'file': {'type': 'string', 'enum': list(FILES)}, 'content': {'type': 'string'}, 'reason': {'type': 'string'}},
101
+ 'required': ['file', 'content']}}
@@ -0,0 +1,269 @@
1
+ """Per-repository policy: `.mlai/policy.yml` in the repo (reviewed like code) plus an account/org override that the
2
+ server writes to `.mini/policy-override.json`. The override can only tighten the repo file, never loosen it.
3
+
4
+ Schema (every key optional):
5
+
6
+ production:
7
+ branch: main # the production branch (default: the imported branch)
8
+ require_pr: true # no direct pushes to the production branch from the product
9
+ require_ci_green: true # every check (preview build, secret scan, GitHub CI) must pass before promotion
10
+ auto_promote: false # let an Auto-mode agent promote a ready preview without a person (off by default)
11
+ promote_requires: [releaser]
12
+ min_approvals: 1
13
+ block_paths_without_review: ["infra/**", "payments/**", "db/migrations/**"]
14
+ agent:
15
+ modes_allowed: [plan, brief, guided, auto]
16
+ max_tokens_per_run: 2000000
17
+ network: open | allowlist
18
+ network_allow: [api.stripe.com]
19
+ commands:
20
+ allow: ["npm test", "pytest*", "npx next build"] # run without asking (never overrides a hard refusal)
21
+ deny: ["npm publish*", "terraform apply*"] # never run, in any mode
22
+ secrets:
23
+ scan: true
24
+ allow: ["sk_test_fixture_value_used_in_tests"] # exact literals that are known fakes
25
+ ignore_paths: ["tests/fixtures/**"]
26
+
27
+ CLI: python3 repo_policy.py show | validate <file> | check-push <branch> (JSON on stdout)
28
+ """
29
+ import fnmatch, json, os, re, sys
30
+ from pathlib import Path
31
+
32
+ MODES = ('plan', 'brief', 'guided', 'auto')
33
+ # Always refused, whatever the repo says: piping the internet into a shell, publishing packages outside the release flow,
34
+ # reading SSH keys, and rewriting shared history.
35
+ BUILTIN_DENY = ['curl * | sh*', 'curl * | bash*', 'wget * | sh*', 'wget * | bash*', 'curl *|sh*', 'curl *|bash*',
36
+ 'npm publish*', 'pnpm publish*', 'yarn publish*', 'yarn npm publish*', 'twine upload*', 'cargo publish*', 'gem push*',
37
+ '*~/.ssh*', '*/.ssh/id_*', 'git push --force*', 'git push -f *', 'git push * --force*', 'git push * -f',
38
+ # Production deploys go through the deploy card only.
39
+ 'vercel --prod*', 'vercel * --prod*', 'vercel promote*', 'vercel rollback*', 'npx vercel --prod*', 'npx vercel * --prod*', 'npx vercel promote*', 'npx vercel rollback*',
40
+ 'netlify deploy --prod*', 'netlify deploy * --prod*', 'npx netlify deploy --prod*', 'npx netlify deploy * --prod*', 'fly deploy*', 'flyctl deploy*',
41
+ 'wrangler deploy*', 'npx wrangler deploy*', 'wrangler rollback*', 'npx wrangler rollback*', 'wrangler pages deployment rollback*', 'railway up*', 'railway redeploy*']
42
+ DEFAULT_NETWORK_ALLOW = ['registry.npmjs.org', 'registry.yarnpkg.com', 'pypi.org', 'files.pythonhosted.org', 'github.com',
43
+ 'codeload.github.com', 'objects.githubusercontent.com', 'raw.githubusercontent.com', 'api.github.com',
44
+ 'nodejs.org', 'deb.debian.org', 'crates.io', 'static.crates.io', 'proxy.golang.org', 'localhost', '127.0.0.1', '0.0.0.0']
45
+
46
+
47
+ def default_policy():
48
+ return {
49
+ 'production': {'branch': '', 'require_pr': False, 'require_ci_green': False, 'auto_promote': False, 'promote_requires': ['releaser'], 'min_approvals': 1, 'block_paths_without_review': []},
50
+ 'agent': {'modes_allowed': list(MODES), 'max_tokens_per_run': 0, 'network': 'open', 'network_allow': [], 'commands': {'allow': [], 'deny': []}},
51
+ 'secrets': {'scan': True, 'allow': [], 'ignore_paths': []},
52
+ 'source': 'defaults', 'errors': [],
53
+ }
54
+
55
+
56
+ # ------------------------------------------------------------------ a small, safe YAML subset (maps, lists, scalars)
57
+ def _scalar(v):
58
+ v = v.strip()
59
+ if not v: return None
60
+ if v[0] in '"\'' and v[-1] == v[0] and len(v) >= 2: return v[1:-1]
61
+ if v.startswith('[') and v.endswith(']'):
62
+ inner = v[1:-1].strip()
63
+ if not inner: return []
64
+ items, cur, q = [], '', ''
65
+ for ch in inner:
66
+ if q:
67
+ if ch == q: q = ''
68
+ else: cur += ch
69
+ elif ch in '"\'': q = ch
70
+ elif ch == ',': items.append(cur.strip()); cur = ''
71
+ else: cur += ch
72
+ if cur.strip(): items.append(cur.strip())
73
+ return [str(i) for i in items]
74
+ low = v.lower()
75
+ if low in ('true', 'yes', 'on'): return True
76
+ if low in ('false', 'no', 'off'): return False
77
+ if low in ('null', '~'): return None
78
+ if re.fullmatch(r'-?\d+', v.replace('_', '')): return int(v.replace('_', ''))
79
+ return v
80
+
81
+
82
+ def parse_yaml(text):
83
+ try:
84
+ import yaml # type: ignore
85
+ data = yaml.safe_load(text)
86
+ return data if isinstance(data, dict) else {}
87
+ except ImportError:
88
+ pass
89
+ lines = []
90
+ for raw in text.splitlines():
91
+ s = raw.split(' #')[0].rstrip() if not raw.lstrip().startswith('#') else ''
92
+ if s.strip(): lines.append((len(s) - len(s.lstrip(' ')), s.strip()))
93
+ root = {}; stack = [(-1, root)]
94
+ for i, (ind, s) in enumerate(lines):
95
+ while stack and ind <= stack[-1][0]: stack.pop()
96
+ parent = stack[-1][1]
97
+ if s.startswith('- '):
98
+ if isinstance(parent, list): parent.append(_scalar(s[2:]))
99
+ continue
100
+ if ':' not in s: raise ValueError('line ' + str(i + 1) + ': expected "key: value"')
101
+ key, _, val = s.partition(':'); key = key.strip().strip('"\'')
102
+ if val.strip():
103
+ if isinstance(parent, dict): parent[key] = _scalar(val)
104
+ continue
105
+ nxt = lines[i + 1] if i + 1 < len(lines) else None
106
+ child = [] if nxt and nxt[0] > ind and nxt[1].startswith('- ') else {}
107
+ if isinstance(parent, dict): parent[key] = child
108
+ stack.append((ind, child))
109
+ return root
110
+
111
+
112
+ # ------------------------------------------------------------------ merge and validation
113
+ def _strs(v): return [str(x) for x in v if isinstance(x, (str, int))] if isinstance(v, list) else []
114
+
115
+
116
+ def apply(base, data, tighten_only=False, errors=None):
117
+ errors = errors if errors is not None else []
118
+ if not isinstance(data, dict): errors.append('Policy must be a map of sections'); return base
119
+ for k in data:
120
+ if k not in ('production', 'agent', 'secrets', 'version'): errors.append('Unknown section "' + str(k) + '"')
121
+ p, a, s = data.get('production') or {}, data.get('agent') or {}, data.get('secrets') or {}
122
+ bp, ba, bs = base['production'], base['agent'], base['secrets']
123
+ if isinstance(p, dict):
124
+ if isinstance(p.get('branch'), str) and p['branch'].strip() and (not tighten_only or not bp['branch']): bp['branch'] = p['branch'].strip()
125
+ for key in ('require_pr', 'require_ci_green'):
126
+ if isinstance(p.get(key), bool): bp[key] = (bp[key] or p[key]) if tighten_only else p[key]
127
+ if isinstance(p.get('auto_promote'), bool): bp['auto_promote'] = (bp['auto_promote'] and p['auto_promote']) if tighten_only else p['auto_promote']
128
+ elif 'auto_promote' in p: errors.append('production.auto_promote must be true or false')
129
+ if 'promote_requires' in p: bp['promote_requires'] = _strs(p['promote_requires']) or bp['promote_requires']
130
+ if isinstance(p.get('min_approvals'), int): bp['min_approvals'] = max(bp['min_approvals'], p['min_approvals']) if tighten_only else max(1, p['min_approvals'])
131
+ bp['block_paths_without_review'] = sorted(set(bp['block_paths_without_review']) | set(_strs(p.get('block_paths_without_review'))))
132
+ if isinstance(a, dict):
133
+ if 'modes_allowed' in a:
134
+ modes = [m for m in _strs(a['modes_allowed']) if m in MODES]
135
+ bad = [m for m in _strs(a['modes_allowed']) if m not in MODES]
136
+ if bad: errors.append('Unknown mode(s): ' + ', '.join(bad) + ' (use plan, brief, guided, auto)')
137
+ ba['modes_allowed'] = [m for m in ba['modes_allowed'] if m in modes] if tighten_only else modes
138
+ if not ba['modes_allowed']: ba['modes_allowed'] = ['plan']
139
+ if isinstance(a.get('max_tokens_per_run'), int) and a['max_tokens_per_run'] > 0:
140
+ ba['max_tokens_per_run'] = min(x for x in (ba['max_tokens_per_run'] or a['max_tokens_per_run'], a['max_tokens_per_run']))
141
+ if a.get('network') in ('open', 'allowlist'): ba['network'] = 'allowlist' if (tighten_only and ba['network'] == 'allowlist') else a['network']
142
+ elif 'network' in a: errors.append('agent.network must be "open" or "allowlist"')
143
+ ba['network_allow'] = sorted(set(ba['network_allow']) | set(_strs(a.get('network_allow')))) if not tighten_only or not ba['network_allow'] else sorted(set(ba['network_allow']) & set(_strs(a.get('network_allow'))) or set(ba['network_allow']))
144
+ c = a.get('commands') or {}
145
+ if isinstance(c, dict):
146
+ if not tighten_only: ba['commands']['allow'] = sorted(set(ba['commands']['allow']) | set(_strs(c.get('allow'))))
147
+ ba['commands']['deny'] = sorted(set(ba['commands']['deny']) | set(_strs(c.get('deny'))))
148
+ if isinstance(s, dict):
149
+ if isinstance(s.get('scan'), bool): bs['scan'] = (bs['scan'] or s['scan']) if tighten_only else s['scan']
150
+ if not tighten_only:
151
+ bs['allow'] = sorted(set(bs['allow']) | set(_strs(s.get('allow'))))
152
+ bs['ignore_paths'] = sorted(set(bs['ignore_paths']) | set(_strs(s.get('ignore_paths'))))
153
+ return base
154
+
155
+
156
+ def load_policy(repo, root=None):
157
+ pol = default_policy(); errors = pol['errors']
158
+ f = Path(repo) / '.mlai' / 'policy.yml'
159
+ if not f.is_file(): f = Path(repo) / '.mlai' / 'policy.yaml'
160
+ if f.is_file() and not f.is_symlink():
161
+ try:
162
+ apply(pol, parse_yaml(f.read_text(errors='replace')[:50000]), errors=errors); pol['source'] = '.mlai/' + f.name
163
+ except Exception as e:
164
+ errors.append('Could not read ' + f.name + ': ' + str(e)[:200])
165
+ root = Path(root or os.getenv('MINI_ROOT', '/vercel/sandbox/.mini'))
166
+ try:
167
+ override = json.loads((root / 'policy-override.json').read_text())
168
+ apply(pol, override, tighten_only=True, errors=errors); pol['source'] += ' + account rules'
169
+ except (OSError, ValueError):
170
+ pass
171
+ return pol
172
+
173
+
174
+ # ------------------------------------------------------------------ evaluation
175
+ def path_matches(rel, patterns):
176
+ rel = rel.lstrip('./')
177
+ for pat in patterns:
178
+ pat = pat.lstrip('./')
179
+ if fnmatch.fnmatch(rel, pat) or (pat.endswith('/**') and (rel == pat[:-3] or rel.startswith(pat[:-2]))): return pat
180
+ return None
181
+
182
+
183
+ def _segments(command):
184
+ return [s.strip() for s in re.split(r'&&|\|\||;|\n', command) if s.strip()]
185
+
186
+
187
+ def _cmd_match(command, pat):
188
+ c = ' '.join(command.split()); p = ' '.join(pat.split())
189
+ return fnmatch.fnmatch(c, p) or (not any(ch in p for ch in '*?[') and (c == p or c.startswith(p + ' ')))
190
+
191
+
192
+ def command_rule(command, pol):
193
+ """('deny', pattern) | ('allow', pattern) | (None, None). Deny wins; allow needs every segment to match."""
194
+ whole = ' '.join(str(command).split())
195
+ for pat in BUILTIN_DENY + pol['agent']['commands']['deny']:
196
+ if _cmd_match(whole, pat) or any(_cmd_match(seg, pat) for seg in _segments(whole)): return 'deny', pat
197
+ allow = pol['agent']['commands']['allow']
198
+ segs = [s for s in _segments(whole) if not re.fullmatch(r'cd\s+\S+', s)]
199
+ if allow and segs and '|' not in whole and '`' not in whole and '$(' not in whole:
200
+ hits = [next((p for p in allow if _cmd_match(seg, p)), None) for seg in segs]
201
+ if all(hits): return 'allow', hits[0]
202
+ return None, None
203
+
204
+
205
+ HOST = re.compile(r'https?://([A-Za-z0-9.-]+)(?::\d+)?', re.I)
206
+
207
+
208
+ def network_hosts_outside(command, pol):
209
+ if pol['agent']['network'] != 'allowlist': return []
210
+ allowed = set(DEFAULT_NETWORK_ALLOW) | set(pol['agent']['network_allow'])
211
+ out = []
212
+ for h in HOST.findall(str(command)):
213
+ h = h.lower().rstrip('.')
214
+ if not any(h == a or h.endswith('.' + a) for a in allowed) and h not in out: out.append(h)
215
+ return out
216
+
217
+
218
+ def clamp_mode(mode, pol):
219
+ """App mode names: plan, brief, approve (Guided), auto. Returns the strictest allowed mode at or below the request."""
220
+ want = {'approve': 'guided'}.get(mode, mode)
221
+ allowed = pol['agent']['modes_allowed']
222
+ if want in allowed: return mode
223
+ for m in ('guided', 'brief', 'plan'):
224
+ if m in allowed and MODES.index(m) < MODES.index(want if want in MODES else 'auto'): return 'approve' if m == 'guided' else m
225
+ return 'plan'
226
+
227
+
228
+ def check_push(branch, pol, default_branch=''):
229
+ prod = pol['production']['branch'] or default_branch
230
+ if pol['production']['require_pr'] and prod and branch == prod:
231
+ return 'This repository\'s policy requires a pull request for changes to ' + prod + '. Open a draft PR instead of pushing directly.'
232
+ return None
233
+
234
+
235
+ def summary(pol):
236
+ """Plain-language list of the rules in force, for the Security screen and the agent prompt."""
237
+ p, a, s = pol['production'], pol['agent'], pol['secrets']; out = []
238
+ if p['require_pr']: out.append('Changes to ' + (p['branch'] or 'the production branch') + ' need a pull request')
239
+ if p['require_ci_green']: out.append('Every check must pass before promotion')
240
+ out.append('Production changes only after a person approves' if not p.get('auto_promote') else 'Auto mode may promote ready previews without a person')
241
+ if p['block_paths_without_review']: out.append('Always ask before editing ' + ', '.join(p['block_paths_without_review']))
242
+ if set(a['modes_allowed']) != set(MODES): out.append('Modes allowed: ' + ', '.join(a['modes_allowed']))
243
+ if a['max_tokens_per_run']: out.append('At most ' + format(a['max_tokens_per_run'], ',') + ' tokens per task')
244
+ if a['network'] == 'allowlist': out.append('Network limited to package registries' + (' and ' + ', '.join(a['network_allow']) if a['network_allow'] else ''))
245
+ if a['commands']['allow']: out.append('Runs without asking: ' + ', '.join(a['commands']['allow']))
246
+ if a['commands']['deny']: out.append('Never runs: ' + ', '.join(a['commands']['deny']))
247
+ out.append('Secret scanning ' + ('on' if s['scan'] else 'off') + ' for agent edits and pushes')
248
+ return out
249
+
250
+
251
+ def main(argv):
252
+ repo = os.getenv('MINI_REPO', os.getcwd())
253
+ if argv[:1] == ['validate']:
254
+ errors = []
255
+ try: apply(default_policy(), parse_yaml(Path(argv[1]).read_text()[:50000] if len(argv) > 1 else sys.stdin.read()[:50000]), errors=errors)
256
+ except Exception as e: errors.append(str(e)[:300])
257
+ print(json.dumps({'ok': not errors, 'errors': errors})); return
258
+ pol = load_policy(repo)
259
+ if argv[:1] == ['check-push']:
260
+ print(json.dumps({'blocked': check_push(argv[1] if len(argv) > 1 else '', pol, argv[2] if len(argv) > 2 else '')})); return
261
+ text = ''
262
+ for name in ('policy.yml', 'policy.yaml'):
263
+ f = Path(repo) / '.mlai' / name
264
+ if f.is_file() and not f.is_symlink(): text = f.read_text(errors='replace')[:50000]; break
265
+ print(json.dumps({'policy': {k: v for k, v in pol.items() if k not in ('errors',)}, 'errors': pol['errors'], 'rules': summary(pol), 'text': text, 'builtinDeny': BUILTIN_DENY}))
266
+
267
+
268
+ if __name__ == '__main__':
269
+ main(sys.argv[1:])