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,205 @@
1
+ """Cancelable inference and factual completion evidence; no automatic effect replay."""
2
+ import json, queue, re, shlex, threading, time, urllib.request
3
+ from pathlib import Path
4
+
5
+ # Keep this classification aligned with lib/conversation-view.ts. A command's exit
6
+ # status is not proof when the verifier rejected it or the runner found no tests.
7
+ ZERO_TEST_OUTPUT = re.compile(r'\b(collected 0 items|no tests ran|ran 0 tests|0 passed|no tests found|no test files found|0 tests? (passed|completed|run)|tests:\s+0 total|no specs? found|no tests to run|tests\s+0\b|0 passing|files\s+0 passed|test suites:\s*0)', re.I)
8
+ EXTERNAL_SCOPES = frozenset(('remote', 'ci', 'external'))
9
+
10
+ PLUMBING = [
11
+ (re.compile(r'^\s*set -o pipefail\s*(;|&&)\s*'), ''),
12
+ (re.compile(r'\s*;\s*exit \$\{?PIPESTATUS\[0\]\}?\s*$|\s*;\s*exit \$\?\s*$'), ''),
13
+ (re.compile(r'\s+\|&?\s*(tail|head|grep|tee|cat|less|sed|awk)\b.*$'), ''),
14
+ (re.compile(r'\s+[12]?>&[12]|\s+2>/dev/null|\s+>\s*/dev/null'), ''),
15
+ (re.compile(r'^\s*(?:timeout\s+\d+[smh]?\s+|(?:CI|FORCE_COLOR|NO_COLOR)=\S+\s+)+'), ''),
16
+ ]
17
+
18
+ # Extra arguments that only narrow a suite to some tests (files or name filters).
19
+ NARROWING = re.compile(r'\.(?:test|spec)\.[cm]?[jt]sx?\b|\btest_\w+\.py\b|_test\.(?:py|go)\b|::|(?:^|\s)-(?:t|k|g)\s|--grep\b|--testNamePattern\b|--filter\b|--project[= ]')
20
+
21
+ def check_key(command):
22
+ """The command without output plumbing: `npm test 2>&1 | tail -30` and `npm test` are the same check (VERIFY-001)."""
23
+ c = str(command or '').strip()
24
+ for rx, rep in PLUMBING: c = rx.sub(rep, c)
25
+ return re.sub(r'\s+', ' ', c).strip()
26
+
27
+ def latest_checks(checks):
28
+ """A rerun of the same check (ignoring output plumbing) supersedes an earlier result, and a later passing run of
29
+ the whole suite supersedes an earlier failing run of part of it (`npx vitest run` after `npx vitest run a.test.ts`)."""
30
+ latest = {}
31
+ for i, check in enumerate(checks or []):
32
+ if not isinstance(check, dict): continue
33
+ key = (check.get('scope') or 'repository', check_key(check.get('command')) or check.get('label') or ('anonymous', i))
34
+ latest.pop(key, None); latest[key] = check
35
+ items = list(latest.items())
36
+ out = []
37
+ for n, (key, check) in enumerate(items):
38
+ broader = [c for k, c in items[n + 1:] if k[0] == key[0] and isinstance(k[1], str) and isinstance(key[1], str)
39
+ and key[1].startswith(k[1] + ' ') and NARROWING.search(key[1][len(k[1]):]) and check_status(c) == 'passed']
40
+ if broader and check_status(check) == 'failed': continue
41
+ out.append(check)
42
+ return out
43
+
44
+ def check_status(check):
45
+ if check.get('executed') is not True: return 'not_run'
46
+ verdict = check.get('verdict') or {}
47
+ if verdict.get('status') in ('failed', 'blocked'): return 'failed'
48
+ if check.get('returncode') not in (0, None): return 'failed'
49
+ if check.get('returncode') is None or (verdict.get('status') not in (None, 'passed')) or ZERO_TEST_OUTPUT.search(str(check.get('output') or '')):
50
+ return 'inconclusive'
51
+ # A pass recorded before the last code edit describes code that no longer exists.
52
+ if check.get('stale') is True: return 'stale'
53
+ return 'passed'
54
+
55
+ def check_summary(checks):
56
+ result = dict(passed=0, failed=0, notRun=0, inconclusive=0, stale=0, externalPending=0, externalFailed=0, externalPassed=0, supporting=0)
57
+ for check in latest_checks(checks):
58
+ scope = check.get('scope') or 'repository'
59
+ status = check_status(check)
60
+ if scope in EXTERNAL_SCOPES:
61
+ result[{'passed': 'externalPassed', 'failed': 'externalFailed'}.get(status, 'externalPending')] += 1
62
+ elif scope != 'repository':
63
+ result['supporting'] += 1
64
+ else:
65
+ result[{'not_run': 'notRun'}.get(status, status)] += 1
66
+ result['needsAttention'] = bool(result['failed'] or result['notRun'] or result['inconclusive'] or result['stale'] or result['externalPending'] or result['externalFailed'])
67
+ # Local work is verified and the only open item is a remote result nobody has observed yet.
68
+ result['remotePendingOnly'] = bool(result['externalPending'] and result['passed'] and not (result['failed'] or result['notRun'] or result['inconclusive'] or result['stale'] or result['externalFailed']))
69
+ return result
70
+
71
+ def request_json(request, cancelled, timeout=100):
72
+ result=queue.Queue(maxsize=1)
73
+ def fetch():
74
+ try:
75
+ with urllib.request.urlopen(request,timeout=timeout) as response: value=json.load(response)
76
+ result.put((True,value))
77
+ except Exception as exc: result.put((False,exc))
78
+ threading.Thread(target=fetch,daemon=True).start()
79
+ deadline=time.monotonic()+timeout+1
80
+ while True:
81
+ cancelled()
82
+ try: ok,value=result.get(timeout=.15)
83
+ except queue.Empty:
84
+ if time.monotonic()>deadline: raise TimeoutError('Model request timed out')
85
+ continue
86
+ cancelled()
87
+ if not ok: raise value
88
+ return value
89
+
90
+ def completion_paths(repo,base=None):
91
+ import subprocess
92
+ from repo_hygiene import change_path,is_noise
93
+ # -uall lists new files individually instead of collapsing them into a bare folder name.
94
+ git=subprocess.run(['git','status','--porcelain','-uall'],cwd=repo,capture_output=True,text=True,timeout=10)
95
+ lines=git.stdout.splitlines() if git.returncode==0 else []
96
+ if base:
97
+ diff=subprocess.run(['git','diff','--name-status',base],cwd=repo,capture_output=True,text=True,timeout=10)
98
+ if diff.returncode==0:lines=diff.stdout.splitlines()+[line for line in lines if line.startswith('??')]
99
+ # Plain paths, without git status codes or caches, so every consumer shows the same clean list.
100
+ return [p for p in dict.fromkeys(change_path(l) for l in lines) if p and not is_noise(p)]
101
+
102
+
103
+ def completion_report(root,repo,base=None):
104
+ import subprocess
105
+ root=Path(root)
106
+ def read(name,fallback):
107
+ try:return json.loads((root/name).read_text())
108
+ except (OSError,ValueError):return fallback
109
+ checks=read('checks.json',[]);todos=read('todos.json',[])
110
+ changes=completion_paths(repo,base)
111
+ summary = check_summary(checks)
112
+ unfinished = [t.get('text','') for t in todos if isinstance(t, dict) and t.get('status') not in ('done','cancelled')]
113
+ note = ('Local checks: %(passed)d passed, %(failed)d failed, %(notRun)d not run, %(inconclusive)d inconclusive.' % summary) if checks else 'No verification checks recorded.'
114
+ if summary['stale']: note += ' %d passed before the last code edit and must be rerun.' % summary['stale']
115
+ if summary['externalPending'] or summary['externalFailed'] or summary['externalPassed']:
116
+ note += ' Remote/CI: %(externalPassed)d passed, %(externalFailed)d failed, %(externalPending)d pending or unverified.' % summary
117
+ if summary['supporting']: note += ' %d supporting evidence checks are not repository verification.' % summary['supporting']
118
+ if unfinished: note += ' %d plan items remain unfinished.' % len(unfinished)
119
+ status = 'remote_pending' if summary['remotePendingOnly'] and not unfinished else 'needs_attention' if summary['needsAttention'] or unfinished else 'passed' if summary['passed'] else 'unverified'
120
+ if status == 'remote_pending': note += ' Local checks passed; the remote result has not been observed, so this is not yet confirmed end to end.'
121
+ return {'changedFiles':changes[:100], 'checksPassed':summary['passed'], 'checksFailed':summary['failed'],
122
+ 'checksNotRun':summary['notRun'], 'checksInconclusive':summary['inconclusive'], 'checksStale':summary['stale'], 'externalChecksPassed':summary['externalPassed'],
123
+ 'externalChecksPending':summary['externalPending'], 'externalChecksFailed':summary['externalFailed'],
124
+ 'unfinishedTasks':unfinished, 'verification':note, 'verificationStatus':status, 'created':time.time()}
125
+
126
+
127
+ def _fingerprint(repo,path):
128
+ """What a changed path looks like now: file contents, or for a nested repository its commit plus its own status."""
129
+ import subprocess,hashlib
130
+ target=Path(repo)/path
131
+ try:
132
+ if target.is_dir():
133
+ head=subprocess.run(['git','rev-parse','HEAD'],cwd=target,capture_output=True,text=True,timeout=10).stdout
134
+ st=subprocess.run(['git','status','--porcelain'],cwd=target,capture_output=True,text=True,timeout=10).stdout
135
+ return 'dir:'+hashlib.sha256((head+st).encode()).hexdigest()
136
+ if target.is_file() or target.is_symlink():
137
+ if target.stat().st_size>50_000_000:return 'big:%d:%d'%(target.stat().st_size,int(target.stat().st_mtime))
138
+ return 'file:'+hashlib.sha256(target.read_bytes()).hexdigest()
139
+ except (OSError,subprocess.SubprocessError):return 'error'
140
+ return 'missing'
141
+
142
+
143
+ def dirty_snapshot(repo,base=None,limit=400):
144
+ """Paths that were already changed when the turn started, with a fingerprint of each."""
145
+ try:paths=completion_paths(repo,base)
146
+ except Exception:return {}
147
+ return {p:_fingerprint(repo,p) for p in paths[:limit]}
148
+
149
+
150
+ def changed_during_turn(repo,changed,snapshot):
151
+ """Of the paths changed now, the ones the turn itself changed: new, or different from the start snapshot."""
152
+ if not isinstance(snapshot,dict):return list(changed or [])
153
+ return [p for p in changed or [] if p not in snapshot or snapshot[p]!=_fingerprint(repo,p)]
154
+
155
+
156
+ SAFE_PROGRAMS=frozenset(('ls','cat','head','tail','wc','grep','rg','pwd','echo','tree','stat','file','du','df','which','whoami','date','uname','jq','sort','uniq','cut','tr','basename','dirname','realpath','diff','true','nl','column'))
157
+ SAFE_GIT=frozenset(('status','diff','log','show','branch','ls-files','rev-parse','remote','blame','describe','shortlog','grep'))
158
+ UNSAFE_CHARS=re.compile(r'[;`<>]|\$\(|(?<!&)&(?!&)|\n')
159
+
160
+ def safe_command(command):
161
+ """Read-only inspection commands that Guided mode can run without asking.
162
+ Conservative: every pipeline/&& segment must be a known read-only program with no redirects, substitution or writes."""
163
+ command=str(command or '').strip()
164
+ if not command or len(command)>2000 or UNSAFE_CHARS.search(command.replace('2>&1','').replace('2>/dev/null','')):return False
165
+ for segment in re.split(r'\|\||&&|\|',command.replace('2>&1','').replace('2>/dev/null','')):
166
+ try:words=shlex.split(segment)
167
+ except ValueError:return False
168
+ if not words:return False
169
+ if re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=\S*',words[0]):return False
170
+ prog=words[0].rsplit('/',1)[-1]
171
+ if prog=='cd' and len(words)<=2:continue
172
+ if prog=='git':
173
+ sub=[w for w in words[1:] if not w.startswith('-')]
174
+ if not sub or sub[0] not in SAFE_GIT or (sub[0]=='branch' and len(sub)>1) or (sub[0]=='remote' and len(sub)>1 and sub[1] not in ('-v','show')):return False
175
+ continue
176
+ if prog=='sed' and '-n' in words and not any(w.startswith('-i') or w=='--in-place' for w in words):continue
177
+ if prog=='find' and not any(w in ('-exec','-execdir','-delete','-ok','-okdir','-fprint','-fprintf','-fls') for w in words):continue
178
+ if prog in ('node','npm','python','python3','pnpm','yarn','tsc','npx') and len(words)==2 and words[1] in ('--version','-v','-V','version'):continue
179
+ if prog in SAFE_PROGRAMS:continue
180
+ return False
181
+ return True
182
+
183
+ def approve_operation(root,mode,description,cancelled,emit):
184
+ import os
185
+ if mode=='plan':raise ValueError('Plan mode cannot perform this operation')
186
+ if mode=='auto':return
187
+ root=Path(root);ident=os.urandom(8).hex();pending={'id':ident,'command':description}
188
+ temp=root/'pending.json.tmp';temp.write_text(json.dumps(pending));temp.replace(root/'pending.json');emit('approval',**pending)
189
+ decision=root/('decision-'+ident);deadline=time.monotonic()+600
190
+ try:
191
+ while not decision.exists():
192
+ cancelled()
193
+ if time.monotonic()>deadline:raise ValueError('Approval timed out')
194
+ time.sleep(.15)
195
+ verdict=decision.read_text()
196
+ if verdict not in ('approve','approve_all'):raise ValueError('Operation rejected')
197
+ return verdict
198
+ finally:
199
+ decision.unlink(missing_ok=True);(root/'pending.json').unlink(missing_ok=True)
200
+
201
+
202
+ def clip(text, limit):
203
+ """Shorten for display with a visible ellipsis, so a shortened command is never read (or rerun) as a complete one."""
204
+ text = ' '.join(str(text or '').split())
205
+ return text if len(text) <= limit else text[:max(1, limit - 1)].rstrip() + '\u2026'
@@ -0,0 +1,168 @@
1
+ """Secret scanning shared by the agent's write gate and the server's push/PR gate.
2
+
3
+ The patterns mirror lib/vault-detect.ts (the composer's paste detector), so the same credential is caught whether it is
4
+ pasted into chat, written by the agent, or about to leave the sandbox in a push. A test keeps both lists in step.
5
+
6
+ CLI (run inside the workspace):
7
+ python3 secret_scan.py diff [--base REF] -> JSON {findings:[{file,line,kind,name,preview}]} for added lines + untracked files
8
+ python3 secret_scan.py text < file -> JSON findings for stdin
9
+ """
10
+ import json, os, re, subprocess, sys
11
+
12
+ PATTERNS = [
13
+ ('pem', 'PRIVATE_KEY', r'-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----'),
14
+ ('github', 'GITHUB_TOKEN', r'\b(?:github_pat_[A-Za-z0-9_]{40,255}|gh[pousr]_[A-Za-z0-9]{30,255})\b'),
15
+ ('anthropic', 'ANTHROPIC_API_KEY', r'\bsk-ant-[A-Za-z0-9_-]{20,300}'),
16
+ ('openrouter', 'OPENROUTER_API_KEY', r'\bsk-or-v1-[A-Za-z0-9]{32,128}\b'),
17
+ ('openai', 'OPENAI_API_KEY', r'\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,300}'),
18
+ ('stripe', 'STRIPE_SECRET_KEY', r'\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,255}\b'),
19
+ ('stripe_webhook', 'STRIPE_WEBHOOK_SECRET', r'\bwhsec_[A-Za-z0-9]{24,255}\b'),
20
+ ('slack', 'SLACK_TOKEN', r'\bxox[abposr]-[A-Za-z0-9-]{10,255}\b'),
21
+ ('aws', 'AWS_ACCESS_KEY_ID', r'\b(?:AKIA|ASIA)[A-Z0-9]{16}\b'),
22
+ ('google', 'GOOGLE_API_KEY', r'\bAIza[A-Za-z0-9_-]{35}\b'),
23
+ ('supabase', 'SUPABASE_ACCESS_TOKEN', r'\bsbp_[a-f0-9]{40}\b'),
24
+ ('supabase_secret', 'SUPABASE_SECRET_KEY', r'\bsb_secret_[A-Za-z0-9_-]{20,255}\b'),
25
+ ('vercel', 'VERCEL_TOKEN', r'\bvc[pkiar]_[A-Za-z0-9]{24,255}\b'),
26
+ ('linear', 'LINEAR_API_KEY', r'\blin_api_[A-Za-z0-9]{32,64}\b'),
27
+ ('notion', 'NOTION_TOKEN', r'\b(?:secret_[A-Za-z0-9]{43}|ntn_[A-Za-z0-9]{40,60})\b'),
28
+ ('sentry', 'SENTRY_AUTH_TOKEN', r'\bsntr[ysu]_[A-Za-z0-9_=+/-]{30,300}'),
29
+ ('huggingface', 'HF_TOKEN', r'\bhf_[A-Za-z0-9]{30,60}\b'),
30
+ ('npm', 'NPM_TOKEN', r'\bnpm_[A-Za-z0-9]{36}\b'),
31
+ ('pypi', 'PYPI_TOKEN', r'\bpypi-[A-Za-z0-9_-]{50,300}'),
32
+ ('tavily', 'TAVILY_API_KEY', r'\btvly-[A-Za-z0-9_-]{20,100}\b'),
33
+ ('firecrawl', 'FIRECRAWL_API_KEY', r'\bfc-[a-f0-9]{32}\b'),
34
+ ('groq', 'GROQ_API_KEY', r'\bgsk_[A-Za-z0-9]{40,60}\b'),
35
+ ('replicate', 'REPLICATE_API_TOKEN', r'\br8_[A-Za-z0-9]{30,60}\b'),
36
+ ('sendgrid', 'SENDGRID_API_KEY', r'\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b'),
37
+ ('mailgun', 'MAILGUN_API_KEY', r'\bkey-[a-f0-9]{32}\b'),
38
+ ('twilio', 'TWILIO_API_KEY', r'\bSK[a-f0-9]{32}\b'),
39
+ ('digitalocean', 'DIGITALOCEAN_TOKEN', r'\bdop_v1_[a-f0-9]{64}\b'),
40
+ ('gitlab', 'GITLAB_TOKEN', r'\bglpat-[A-Za-z0-9_-]{20,64}\b'),
41
+ ('cloudflare', 'CLOUDFLARE_API_TOKEN', r'\bcf[atu]_[A-Za-z0-9]{40,60}\b'),
42
+ ('mlai_device', 'MLAI_DEVICE_TOKEN', r'\bmlaid_[A-Za-z0-9_-]{24,1700}\.[A-Za-z0-9_-]{43}\b'),
43
+ ('mlai', 'MLAI_TOKEN', r'\bmlai_[A-Za-z0-9_-]{24,255}\b'),
44
+ ('jwt', 'JWT_TOKEN', r'\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{20,}'),
45
+ ]
46
+ COMPILED = [(k, n, re.compile(p)) for k, n, p in PATTERNS]
47
+ ASSIGN = re.compile(r'\b([A-Z][A-Z0-9_]{1,62}(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?))\s*[:=]\s*["\']?([^\s"\'`]{8,4096})')
48
+ PLACEHOLDER = re.compile(r'^(?:x+|\*+|<[^>]*>|\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|\{\{.*\}\}|your[-_].*|changeme|example.*|placeholder|null|undefined|true|false|\.\.\.|process\.env\..*|os\.environ.*|env\(.*|import\.meta\.env\..*)$', re.I)
49
+ # Files that legitimately hold fake credentials or are generated noise.
50
+ # SEC-001: `WORKSPACE_STORAGE_KEY = 'incident-atlas:workspace:v1'` names a storage slot, it is not a credential.
51
+ # Names for lookup keys, and *_KEY values that read as lowercase words joined by separators, are identifiers.
52
+ IDENTIFIER_NAME = re.compile(r'(?:STORAGE|CACHE|QUERY|LOCALSTORAGE|SESSION|STATE|ROUTE|EVENT|MAP|SORT|PARTITION|PRIMARY|FOREIGN|HOT|SHORTCUT|I18N|TRANSLATION|INDEX|LOOKUP|PREF|PREFERENCE|SETTINGS?|FEATURE|FLAG|DB|TABLE|COLUMN|FIELD|MESSAGE|DEDUPE|IDEMPOTENCY|REDIS|BUCKET|NAMESPACE|PREFIX)_KEY$')
53
+ IDENTIFIER_VALUE = re.compile(r'^[a-z][a-z0-9]*(?:[-_:./@][a-z0-9]+){1,12}$')
54
+
55
+ CREDENTIAL_NAME = re.compile(r'SECRET|PRIVATE|API|ACCESS|AUTH|SIGNING|ENCRYPTION|MASTER|ACCOUNT|LICENSE|CLIENT|SERVICE|ADMIN')
56
+
57
+ def identifier(name, value):
58
+ """Only lowercase, separator-joined values qualify (real keys such as AZURE_STORAGE_KEY are mixed-case base64)."""
59
+ if not name.endswith('KEY') or not IDENTIFIER_VALUE.match(value) or re.search(r'[0-9]{5,}|[a-z0-9]{24,}', value): return False
60
+ if IDENTIFIER_NAME.search(name) and not re.search(r'ACCOUNT|ACCESS|SECRET|PRIVATE', name): return True
61
+ return not CREDENTIAL_NAME.search(name)
62
+
63
+ SKIP_FILES = re.compile(r'(^|/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|poetry\.lock|Cargo\.lock|go\.sum)$|\.(?:png|jpe?g|gif|webp|ico|pdf|zip|gz|woff2?|ttf|mp4|mov)$', re.I)
64
+
65
+
66
+ def mask(value):
67
+ v = str(value)
68
+ return v[:4] + '…' + v[-2:] if len(v) > 10 else v[:2] + '…'
69
+
70
+
71
+ def scan_text(text, allow=()):
72
+ """Return [(kind, name, value, offset)] for credentials in text, ignoring placeholders and allowed literals."""
73
+ if not text or len(text) > 2_000_000: return []
74
+ found = []
75
+ def free(a, b): return not any(a < e and b > s for _, _, _, s, e in found)
76
+ for kind, name, rx in COMPILED:
77
+ for m in rx.finditer(text):
78
+ if m.group(0) in allow: continue
79
+ if free(m.start(), m.end()): found.append((kind, name, m.group(0), m.start(), m.end()))
80
+ for m in ASSIGN.finditer(text):
81
+ value = re.sub(r'[.,;)\]}]+$', '', m.group(2))
82
+ if PLACEHOLDER.match(value) or len(value) < 8 or value in allow: continue
83
+ start = m.start(2); end = start + len(value)
84
+ hit = next((i for i, f in enumerate(found) if start < f[4] and end > f[3]), None)
85
+ if hit is not None:
86
+ k, _, v, s, e = found[hit]; found[hit] = (k, m.group(1), v, s, e); continue
87
+ if not re.search(r'[0-9]', value) or not re.search(r'[A-Za-z]', value): continue
88
+ if identifier(m.group(1), value): continue
89
+ found.append(('secret', m.group(1), value, start, end))
90
+ found.sort(key=lambda f: f[3])
91
+ return [(k, n, v, s) for k, n, v, s, _ in found]
92
+
93
+
94
+ def findings_for(path, text, allow=()):
95
+ out = []
96
+ for kind, name, value, offset in scan_text(text, allow):
97
+ line = text.count('\n', 0, offset) + 1
98
+ out.append({'file': path, 'line': line, 'kind': kind, 'name': name, 'preview': mask(value)})
99
+ return out
100
+
101
+
102
+ def describe(f):
103
+ label = {'stripe': 'a Stripe key', 'github': 'a GitHub token', 'aws': 'an AWS access key', 'openai': 'an OpenAI key', 'anthropic': 'an Anthropic key', 'pem': 'a private key', 'vercel': 'a Vercel token', 'jwt': 'a signed token (JWT)', 'mlai': 'an ML AI Code token'}.get(f['kind'], 'a credential (' + f['name'] + ')')
104
+ return label + ' at ' + f['file'] + ':' + str(f['line'])
105
+
106
+
107
+ def added_lines(diff):
108
+ """Map file -> text of added lines (with original line numbers preserved by padding), from a unified diff."""
109
+ files, cur, line = {}, None, 0
110
+ for raw in diff.splitlines():
111
+ if raw.startswith('+++ '):
112
+ p = raw[4:].strip()
113
+ cur = None if p == '/dev/null' else (p[2:] if p.startswith(('a/', 'b/')) else p)
114
+ if cur is not None: files.setdefault(cur, {})
115
+ continue
116
+ if raw.startswith('@@'):
117
+ m = re.search(r'\+(\d+)', raw); line = int(m.group(1)) if m else 0; continue
118
+ if cur is None or raw.startswith('--- '): continue
119
+ if raw.startswith('+'): files[cur][line] = raw[1:]; line += 1
120
+ elif raw.startswith(' '): line += 1
121
+ return files
122
+
123
+
124
+ def scan_diff(diff, allow=(), skip=None):
125
+ out = []
126
+ for path, lines in added_lines(diff).items():
127
+ if SKIP_FILES.search(path) or (skip and skip(path)): continue
128
+ for n, text in lines.items():
129
+ for f in findings_for(path, text, allow): f['line'] = n; out.append(f)
130
+ return out
131
+
132
+
133
+ def repo_diff(repo, base=None):
134
+ run = lambda a: subprocess.run(a, cwd=repo, capture_output=True, text=True, errors='replace').stdout
135
+ if not base:
136
+ up = run(['git', 'rev-parse', '--verify', '-q', '@{upstream}']).strip()
137
+ base = run(['git', 'merge-base', 'HEAD', up]).strip() if up else ''
138
+ if not base:
139
+ # No upstream: the baseline the workspace recorded at import, else the first commit.
140
+ base = run(['git', 'rev-list', '--max-parents=0', 'HEAD']).strip().splitlines()[:1]
141
+ base = base[0] if base else ''
142
+ diff = run(['git', 'diff', base, '--no-ext-diff', '-M']) if base else run(['git', 'diff', '--cached', '--no-ext-diff'])
143
+ for f in run(['git', 'ls-files', '--others', '--exclude-standard']).splitlines()[:500]:
144
+ p = os.path.join(repo, f)
145
+ if os.path.isfile(p) and os.path.getsize(p) <= 1_000_000: diff += run(['git', 'diff', '--no-index', '--no-ext-diff', '--', '/dev/null', f])
146
+ return diff
147
+
148
+
149
+ def main(argv):
150
+ allow, skip = (), None
151
+ try:
152
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
153
+ from repo_policy import load_policy, path_matches
154
+ pol = load_policy(os.getenv('MINI_REPO', os.getcwd()))
155
+ allow = tuple(pol['secrets']['allow'])
156
+ skip = (lambda p: path_matches(p, pol['secrets']['ignore_paths'])) if pol['secrets']['ignore_paths'] else None
157
+ if not pol['secrets']['scan']: print(json.dumps({'findings': [], 'disabled': True})); return
158
+ except Exception:
159
+ pass
160
+ if argv[:1] == ['diff']:
161
+ base = argv[argv.index('--base') + 1] if '--base' in argv else None
162
+ print(json.dumps({'findings': scan_diff(repo_diff(os.getenv('MINI_REPO', os.getcwd()), base), allow, skip)[:100]}))
163
+ else:
164
+ print(json.dumps({'findings': findings_for('stdin', sys.stdin.read(), allow)[:100]}))
165
+
166
+
167
+ if __name__ == '__main__':
168
+ main(sys.argv[1:])
@@ -0,0 +1,80 @@
1
+ """Chats message each other: list_sessions / send_message / read_messages for the agent.
2
+
3
+ The app gives a cloud run MLAI_HUB_URL and a short-lived MLAI_HUB_TOKEN scoped to this account and this chat.
4
+ A run on This Mac gets MLAI_HUB_URL only and authenticates with its run token (MODEL_API_KEY, mlrun_...), which the
5
+ server checks against the signed-in computer. The server enforces who may message whom; this module only shapes calls.
6
+ """
7
+ import json
8
+ import os
9
+ import urllib.error
10
+ import urllib.request
11
+
12
+ TOOLS = ('list_sessions', 'send_message', 'read_messages')
13
+ HELP = ('list_sessions {limit?} lists other chats on this account and team projects you can contribute to (id, title, '
14
+ 'state, unread). send_message {to,body,kind?:notify|ask|reply,reply_to?} sends a short note to another chat; '
15
+ 'it arrives as a message card there and, if that chat is running in the cloud, as a steering note. '
16
+ 'read_messages {limit?} reads messages other chats sent to this one. Never send secrets or private keys.')
17
+ NOT_CONFIGURED = 'Chat messaging is not available for this run. Start the task from the ML AI Code app to use it.'
18
+
19
+
20
+ def configured(env=None):
21
+ env = os.environ if env is None else env
22
+ return bool(env.get('MLAI_HUB_URL')) and bool(_token(env))
23
+
24
+
25
+ def _token(env):
26
+ tok = env.get('MLAI_HUB_TOKEN') or ''
27
+ if tok.startswith('mlhub_'):
28
+ return tok
29
+ key = env.get('MODEL_API_KEY') or ''
30
+ return key if key.startswith('mlrun_') else ''
31
+
32
+
33
+ def validate(tool, args):
34
+ if tool not in TOOLS:
35
+ raise ValueError('Unknown chat messaging tool')
36
+ if not isinstance(args, dict):
37
+ raise ValueError('Tool arguments must be an object')
38
+ if tool == 'send_message':
39
+ to, body = args.get('to'), args.get('body')
40
+ if not isinstance(to, str) or not to.strip():
41
+ raise ValueError('send_message needs "to": a chat id from list_sessions')
42
+ if not isinstance(body, str) or not body.strip():
43
+ raise ValueError('send_message needs a "body"')
44
+ if len(body) > 4000:
45
+ raise ValueError('Keep messages under 4000 characters')
46
+ kind = args.get('kind', 'notify')
47
+ if kind not in ('notify', 'ask', 'reply'):
48
+ raise ValueError('kind must be notify, ask or reply')
49
+ out = {'to': to.strip(), 'body': body.strip(), 'kind': kind}
50
+ if isinstance(args.get('reply_to'), str):
51
+ out['replyTo'] = args['reply_to']
52
+ return out
53
+ limit = args.get('limit')
54
+ return {'limit': max(1, min(50, int(limit)))} if isinstance(limit, int) and not isinstance(limit, bool) else {}
55
+
56
+
57
+ def call(tool, args, env=None, opener=None, timeout=20):
58
+ """POST one hub operation; returns the JSON text the agent sees. Raises ValueError with a plain reason."""
59
+ env = os.environ if env is None else env
60
+ body = validate(tool, args)
61
+ if not configured(env):
62
+ raise ValueError(NOT_CONFIGURED)
63
+ token = _token(env)
64
+ req = urllib.request.Request(env['MLAI_HUB_URL'], data=json.dumps({'op': tool, **body}).encode(), method='POST',
65
+ headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
66
+ try:
67
+ with (opener or urllib.request.urlopen)(req, timeout=timeout) as resp:
68
+ text = resp.read(200000).decode('utf-8', 'replace')
69
+ except urllib.error.HTTPError as exc:
70
+ try:
71
+ detail = json.loads(exc.read(20000).decode('utf-8', 'replace')).get('error') or ''
72
+ except Exception:
73
+ detail = ''
74
+ raise ValueError((detail or 'Chat messaging failed') + ' (' + str(exc.code) + ')') from None
75
+ except (urllib.error.URLError, OSError, TimeoutError) as exc:
76
+ raise ValueError('Chat messaging could not reach the app. If this chat uses a network allowlist, '
77
+ 'add the app domain in Settings. (' + type(exc).__name__ + ')') from None
78
+ if token and token in text:
79
+ text = text.replace(token, '[redacted]')
80
+ return text[:24000]
@@ -0,0 +1,129 @@
1
+ """Agent Skills with progressive disclosure: a short catalog up front, full bodies only when a task, path or the agent asks.
2
+
3
+ Skills are guidance, never permissions. Bodies are bounded and treated as project data."""
4
+ import fnmatch, json, re
5
+ from pathlib import Path
6
+
7
+ MAX_BODY = 20000
8
+ MAX_AUTO = 3
9
+ MAX_CATALOG = 60
10
+ _ID = re.compile(r'^[a-z0-9][a-z0-9-]{0,59}$')
11
+
12
+ def _clean(skill, source):
13
+ if not isinstance(skill, dict) or not _ID.match(str(skill.get('id', ''))) or not isinstance(skill.get('content'), str):
14
+ return None
15
+ words = lambda key: [str(x).strip().lower()[:60] for x in (skill.get(key) or []) if isinstance(x, str) and x.strip()][:20]
16
+ files = skill.get('files') if isinstance(skill.get('files'), dict) else {}
17
+ return {'id': skill['id'], 'name': str(skill.get('name') or skill['id'])[:100], 'description': str(skill.get('description') or '')[:300],
18
+ 'content': skill['content'][:MAX_BODY], 'triggers': words('triggers'), 'paths': words('paths'),
19
+ 'files': {str(k)[:80]: str(v)[:MAX_BODY] for k, v in list(files.items())[:10] if isinstance(v, str)},
20
+ 'always': skill.get('always') is True, 'enabled': skill.get('enabled', True) is not False, 'source': source}
21
+
22
+ def load_skills(root):
23
+ """Built-in pack plus workspace skills. A workspace file with the same id overrides the pack (including disabling it)."""
24
+ try:
25
+ from skill_pack import PACK, STARTER_TRIGGERS
26
+ except ImportError:
27
+ PACK, STARTER_TRIGGERS = [], {}
28
+ skills = {}
29
+ for raw in PACK:
30
+ s = _clean(raw, 'pack')
31
+ if s:
32
+ skills[s['id']] = s
33
+ try: # skills from plugins enabled for this project sit between the pack and the workspace's own files
34
+ from mlai_hooks import plugin_skills
35
+ for raw in plugin_skills(root):
36
+ s = _clean(raw, 'plugin')
37
+ if s:
38
+ skills[s['id']] = s
39
+ except Exception:
40
+ pass
41
+ directory = Path(root) / 'skills'
42
+ if directory.is_dir():
43
+ for file in sorted(directory.glob('*.json'))[:80]:
44
+ try:
45
+ raw = json.loads(file.read_text())
46
+ except (OSError, ValueError):
47
+ continue
48
+ if isinstance(raw, dict) and not raw.get('id'):
49
+ raw = dict(raw, id=re.sub(r'[^a-z0-9-]+', '-', file.stem.lower()).strip('-')[:60] or 'skill') # legacy files keyed by filename
50
+ s = _clean(raw, 'workspace')
51
+ if s:
52
+ if not s['triggers'] and not s['paths']:
53
+ if s['id'] in skills:
54
+ s['triggers'], s['paths'] = skills[s['id']]['triggers'], skills[s['id']]['paths']
55
+ elif s['id'] in STARTER_TRIGGERS:
56
+ s['triggers'] = list(STARTER_TRIGGERS[s['id']])
57
+ elif raw.get('always') is None:
58
+ s['always'] = True # a user-written skill without triggers keeps the old always-on behavior
59
+ skills[s['id']] = s
60
+ return [s for s in skills.values() if s['enabled']]
61
+
62
+ def _mentions(text, phrase):
63
+ return re.search(r'(?<![a-z0-9])' + re.escape(phrase) + r'(?![a-z0-9])', text) is not None
64
+
65
+ def select(task, skills, limit=MAX_AUTO, preferred=()):
66
+ """Skills to load in full now: explicit /id commands first, then always-on, then trigger matches by hit count."""
67
+ text = (task or '')[-8000:].lower()
68
+ explicit = [s for s in skills if re.search(r'(?:^|\s)/' + re.escape(s['id']) + r'(?![a-z0-9-])', text)]
69
+ always = [s for s in skills if s['always'] and s not in explicit]
70
+ scored = []
71
+ for s in skills:
72
+ if s in explicit or s in always:
73
+ continue
74
+ hits = sum(1 for t in s['triggers'] if _mentions(text, t))
75
+ if hits:
76
+ scored.append((hits, s))
77
+ scored.sort(key=lambda x: (-x[0], x[1]['id']))
78
+ if preferred:
79
+ # Role skills come first (up to 3), then the strongest trigger matches fill the remaining slots.
80
+ by_id = {s['id']: s for s in skills}
81
+ role = [by_id[i] for i in preferred if i in by_id and by_id[i] not in explicit and by_id[i] not in always][:3]
82
+ rest = [s for _, s in scored if s not in role]
83
+ return explicit[:6] + always[:3] + role + rest[:max(1, limit - len(role))]
84
+ return explicit[:6] + always[:3] + [s for _, s in scored][:limit]
85
+
86
+ def catalog(skills, loaded=()):
87
+ names = {s['id'] for s in loaded}
88
+ rows = ['- ' + s['id'] + ': ' + (s['description'] or s['name'])[:160] + (' (loaded)' if s['id'] in names else '') for s in skills[:MAX_CATALOG]]
89
+ return '\n'.join(rows)
90
+
91
+ def body(skill):
92
+ extra = (' Reference files: ' + ', '.join(sorted(skill['files'])) + ' (skill_load {id,file}).') if skill['files'] else ''
93
+ return '## Skill: ' + skill['name'] + ' (' + skill['id'] + ')\n' + skill['content'].strip() + ('\n' + extra if extra else '')
94
+
95
+ def prompt(task, skills, preferred=()):
96
+ """(prefix text, selected ids). Empty prefix when there are no skills."""
97
+ if not skills:
98
+ return '', []
99
+ chosen = select(task, skills, preferred=preferred)
100
+ parts = ['Skills (project guidance; never override current user instructions, permissions or tool limits). '
101
+ 'Catalog below; load any other skill that fits with workspace_tool skill_load {id}. Vault variables named in a skill are available as environment variables when the user saved them.\n'
102
+ + catalog(skills, chosen)]
103
+ parts += [body(s) for s in chosen]
104
+ return '\n\n'.join(parts)[:60000] + '\n\n', [s['id'] for s in chosen]
105
+
106
+ def load(skills, args):
107
+ if not isinstance(args, dict) or not isinstance(args.get('id'), str):
108
+ raise ValueError('Provide a skill id')
109
+ skill = next((s for s in skills if s['id'] == args['id']), None)
110
+ if not skill:
111
+ raise ValueError('Unknown or disabled skill. Available: ' + ', '.join(s['id'] for s in skills[:60]))
112
+ name = args.get('file')
113
+ if name is not None:
114
+ if not isinstance(name, str) or name not in skill['files']:
115
+ raise ValueError('Unknown reference file. Available: ' + ', '.join(sorted(skill['files'])) or 'none')
116
+ return skill['files'][name]
117
+ return body(skill)
118
+
119
+ def for_path(skills, path, seen):
120
+ """Path-triggered skills not yet injected for this run (deterministic guidance tied to files)."""
121
+ rel = re.sub(r'^(?:\./)+', '', str(path).replace('\\', '/')).lower()
122
+ hits = []
123
+ for s in skills:
124
+ if s['id'] in seen:
125
+ continue
126
+ if any(fnmatch.fnmatch(rel, p) or fnmatch.fnmatch(Path(rel).name, p) for p in s['paths']):
127
+ seen.add(s['id'])
128
+ hits.append(s)
129
+ return hits[:2]