@routinecrew/routinecode 2.31.85 → 2.31.86

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 (102) hide show
  1. package/bin/cli.sh +10 -0
  2. package/bin/prompt-vault.dat +1 -1
  3. package/bin/rc-board.js +58 -0
  4. package/bin/rc-skills.js +31 -0
  5. package/bin/setup.js +1 -1
  6. package/hooks/hooks-config.json +10 -1
  7. package/hooks/lib/agent_telemetry.py +143 -0
  8. package/hooks/lib/board-golden.json +268 -0
  9. package/hooks/lib/board.py +503 -0
  10. package/hooks/lib/board_sync.py +535 -0
  11. package/hooks/lib/completion_log.py +12 -5
  12. package/hooks/lib/config_bash_track.py +14 -26
  13. package/hooks/lib/config_guard.py +133 -4
  14. package/hooks/lib/edit_tracker.py +182 -0
  15. package/hooks/lib/i18n.py +14 -0
  16. package/hooks/lib/knowledge_items.py +74 -8
  17. package/hooks/lib/usage_v2.py +12 -0
  18. package/hooks/post-agent-return.sh +5 -0
  19. package/hooks/post-edit-track.sh +19 -28
  20. package/hooks/post-orch-decision.sh +17 -0
  21. package/hooks/pre-account-guard.sh +1 -1
  22. package/hooks/pre-credit-guard.sh +1 -1
  23. package/hooks/pre-edit-board.sh +44 -0
  24. package/hooks/pre-edit-check.sh +27 -3
  25. package/hooks/pre-mark-complete.sh +17 -3
  26. package/hooks/session-start.sh +63 -3
  27. package/hooks/skill-knowledge.sh +6 -0
  28. package/mcp-routinecode/dist/board.js +1 -0
  29. package/mcp-routinecode/dist/build-id.js +1 -0
  30. package/mcp-routinecode/dist/changeset.js +1 -1
  31. package/mcp-routinecode/dist/config-auth.js +1 -1
  32. package/mcp-routinecode/dist/config-map/applied.js +1 -0
  33. package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
  34. package/mcp-routinecode/dist/config-map/architect-store.js +1 -7
  35. package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
  36. package/mcp-routinecode/dist/config-map/audit.js +1 -1
  37. package/mcp-routinecode/dist/config-map/blocks.js +1 -1
  38. package/mcp-routinecode/dist/config-map/convention-candidates.js +1 -1
  39. package/mcp-routinecode/dist/config-map/decisions.js +1 -1
  40. package/mcp-routinecode/dist/config-map/dup-safety.js +1 -1
  41. package/mcp-routinecode/dist/config-map/field-contract.js +1 -1
  42. package/mcp-routinecode/dist/config-map/hash.js +1 -1
  43. package/mcp-routinecode/dist/config-map/index-store.js +62 -5
  44. package/mcp-routinecode/dist/config-map/link.js +1 -1
  45. package/mcp-routinecode/dist/config-map/linked-repos.js +1 -1
  46. package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
  47. package/mcp-routinecode/dist/config-map/proposals.js +1 -1
  48. package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
  49. package/mcp-routinecode/dist/config-map/route-security.js +1 -1
  50. package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
  51. package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
  52. package/mcp-routinecode/dist/config-map/shape.js +1 -1
  53. package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
  54. package/mcp-routinecode/dist/config-map/sole-impl.js +1 -1
  55. package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
  56. package/mcp-routinecode/dist/config-map/store.js +1 -1
  57. package/mcp-routinecode/dist/config-map/swagger-check.js +1 -1
  58. package/mcp-routinecode/dist/config-map/templates.js +1 -1
  59. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  60. package/mcp-routinecode/dist/coverage.js +1 -1
  61. package/mcp-routinecode/dist/edit-tracker.js +1 -0
  62. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  63. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  64. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  65. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  66. package/mcp-routinecode/dist/index.js +1 -1
  67. package/mcp-routinecode/dist/known-solutions.js +1 -1
  68. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  69. package/mcp-routinecode/dist/normalize-sig.js +1 -1
  70. package/mcp-routinecode/dist/observed-draft.js +1 -1
  71. package/mcp-routinecode/dist/observed-escalation.js +1 -0
  72. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  73. package/mcp-routinecode/dist/route-match.js +1 -1
  74. package/mcp-routinecode/dist/routines.js +1 -1
  75. package/mcp-routinecode/dist/rule-engine.js +1 -1
  76. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  77. package/mcp-routinecode/dist/session-registry.js +1 -0
  78. package/mcp-routinecode/dist/skill-pack/sync.js +629 -0
  79. package/mcp-routinecode/dist/skill-pack/validate.js +278 -0
  80. package/mcp-routinecode/dist/test-runner.js +1 -1
  81. package/mcp-routinecode/dist/verification.js +1 -1
  82. package/mcp-routinecode/package.json +1 -1
  83. package/package.json +2 -2
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/agents/analyzer.md.sealed +1 -1
  86. package/plugin/agents/architect.md.sealed +1 -1
  87. package/plugin/agents/crawler.md.sealed +1 -1
  88. package/plugin/agents/explorer.md.sealed +1 -1
  89. package/plugin/agents/implementor.md.sealed +1 -1
  90. package/plugin/agents/looker.md.sealed +1 -1
  91. package/plugin/agents/planner.md.sealed +1 -1
  92. package/plugin/agents/recorder.md.sealed +1 -1
  93. package/plugin/agents/reviewer.md.sealed +1 -1
  94. package/plugin/agents/verifier.md.sealed +1 -1
  95. package/plugin/commands/analyze.md.sealed +1 -1
  96. package/plugin/commands/plan.md.sealed +1 -1
  97. package/plugin/commands/rc.md.sealed +1 -1
  98. package/plugin/commands/receipt.md.sealed +1 -1
  99. package/plugin/commands/recharge.md.sealed +1 -1
  100. package/plugin/commands/routines.md.sealed +1 -1
  101. package/plugin/commands/share.md.sealed +1 -1
  102. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -0,0 +1,278 @@
1
+ /**
2
+ * skill-pack/validate — 디자인 스킬 팩 검증·다이제스트 (설계 23 §3·§3.1) — 클라 이식본(2 단계).
3
+ *
4
+ * 같은 규칙의 구현은 세 벌이다: 운영 빌드 scripts/skill-pack/validate.mjs, 서버 knowledge skill-pack.validate.ts, 이 파일.
5
+ * 판정·첫 위반 사유 코드·다이제스트 일치는 공용 골든(micro-backend-knowledge/.../skill-pack/__tests__/skill-pack.golden.json)으로 확인한다.
6
+ * 다이제스트는 cert-lib.bundleDigest, `@meta` 직렬화는 index-store.canonicalJson 을 재사용한다.
7
+ * npm 배포본에서 평문 유지(obfuscate.js PLAIN_DIST — 내려받은 내용을 검사하는 모듈, §8).
8
+ */
9
+ import { bundleDigest } from '../config-map/cert-lib.js';
10
+ import { canonicalJson } from '../config-map/index-store.js';
11
+ export const SKILLPACK_FORMAT = 1;
12
+ export const SKILLPACK_MAX_SKILLS = 6;
13
+ export const SKILLPACK_MAX_FILE_BYTES = 64 * 1024;
14
+ export const SKILLPACK_MAX_PACK_BYTES = 256 * 1024;
15
+ export const SKILLPACK_MAX_DESC_CHARS = 1536;
16
+ export const SKILLPACK_FRONTMATTER_KEYS = ['name', 'description', 'when_to_use', 'license', 'metadata'];
17
+ export const SKILLPACK_LICENSES = ['Apache-2.0', 'MIT', 'BSD-2-Clause', 'BSD-3-Clause', 'CC-BY-4.0'];
18
+ export const SKILLPACK_FIRST_PARTY_PREFIX = 'routinecrew/';
19
+ export const SKILLPACK_FIXED_FILES = ['SKILL.md', 'LICENSE.txt', 'NOTICE.md'];
20
+ export const META_ID = '@meta';
21
+ const PACK_KEYS = ['format', 'minClientVersion', 'line', 'serial', 'packId', 'version', 'validFrom', 'validTo', 'skills', 'sha256'];
22
+ const SKILL_KEYS = ['dir', 'source', 'modified', 'files'];
23
+ const SOURCE_KEYS = ['repo', 'path', 'commit', 'license'];
24
+ const SHA_RE = /^[0-9a-f]{64}$/;
25
+ const COMMIT_RE = /^[0-9a-f]{40}$/;
26
+ export const SKILL_DIR_RE = /^rc-[a-z0-9-]{1,61}$/;
27
+ const LINE_RE = /^[a-z][a-z0-9-]{0,31}$/;
28
+ const PACK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,63}$/;
29
+ const DATE_RE = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
30
+ const VERSION_RE = /^\d{1,5}\.\d{1,5}\.\d{1,6}$/;
31
+ const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
32
+ const SRC_SEG_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}$/;
33
+ const LICENSE_ID_RE = /^[A-Za-z0-9.+-]{1,64}$/;
34
+ const SEG_RE = /^[a-z0-9][a-z0-9.-]{0,99}$/;
35
+ const FILE_EXT_RE = /\.(?:md|txt)$/;
36
+ const FM_KEY_LINE_RE = /^([A-Za-z_][A-Za-z0-9_-]*):(?:[ \t]+(.*))?$/;
37
+ const SHELL_FENCE_RE = /^\s*(`{3,}|~{3,})\s*!/m;
38
+ const AT_PATH_CHAR_RE = /[~./\w-]/;
39
+ const EMAIL_LOCAL_CHAR_RE = /[A-Za-z0-9._%+-]/;
40
+ const EMAIL_DOMAIN_RE = /^@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/;
41
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
42
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
43
+ export function packMeta(pack) {
44
+ const skills = (Array.isArray(pack.skills) ? pack.skills : []).map((s) => ({
45
+ dir: s.dir,
46
+ source: isObj(s.source) ? { repo: s.source.repo, path: s.source.path, commit: s.source.commit, license: s.source.license } : s.source,
47
+ modified: s.modified,
48
+ }));
49
+ skills.sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));
50
+ return {
51
+ format: pack.format, minClientVersion: pack.minClientVersion, line: pack.line, serial: pack.serial,
52
+ packId: pack.packId, version: pack.version, validFrom: pack.validFrom, validTo: pack.validTo, skills,
53
+ };
54
+ }
55
+ export function packMetaJson(pack) {
56
+ return canonicalJson(packMeta(pack));
57
+ }
58
+ export function packDigestFiles(pack) {
59
+ const out = {};
60
+ for (const s of pack.skills)
61
+ for (const n of Object.keys(s.files))
62
+ out[`${s.dir}/${n}`] = s.files[n];
63
+ out[META_ID] = packMetaJson(pack);
64
+ return out;
65
+ }
66
+ export function packDigest(pack) {
67
+ return bundleDigest(packDigestFiles(pack));
68
+ }
69
+ /** x.y.z 비교 (-1/0/1) */
70
+ export function compareVersion(a, b) {
71
+ const pa = String(a).split('.').map(Number);
72
+ const pb = String(b).split('.').map(Number);
73
+ for (let i = 0; i < 3; i++) {
74
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0))
75
+ return (pa[i] ?? 0) < (pb[i] ?? 0) ? -1 : 1;
76
+ }
77
+ return 0;
78
+ }
79
+ /** 프런트매터 파싱(고정 규칙 §3.1) — scripts/skill-pack/validate.mjs parseFrontmatter 와 같은 함수 */
80
+ export function parseFrontmatter(text) {
81
+ const fail = (reason) => ({ reason, fields: {}, body: '' });
82
+ if (typeof text !== 'string')
83
+ return fail('frontmatter-missing');
84
+ if (text.includes('\r'))
85
+ return fail('crlf');
86
+ if (!text.startsWith('---\n'))
87
+ return fail('frontmatter-missing');
88
+ const end = text.indexOf('\n---\n', 3);
89
+ if (end < 0)
90
+ return fail('frontmatter-unterminated');
91
+ const fm = end > 3 ? text.slice(4, end) : '';
92
+ const raw = {};
93
+ let cur = null;
94
+ for (const line of fm.split('\n')) {
95
+ if (line.trim() === '')
96
+ continue;
97
+ if (/^[ \t]/.test(line)) {
98
+ if (cur === null)
99
+ return fail('frontmatter-syntax');
100
+ raw[cur].push(line.trim());
101
+ continue;
102
+ }
103
+ if (line.startsWith('#'))
104
+ continue;
105
+ const m = FM_KEY_LINE_RE.exec(line);
106
+ if (!m)
107
+ return fail('frontmatter-syntax');
108
+ if (has(raw, m[1]))
109
+ return fail('frontmatter-dup-key');
110
+ raw[m[1]] = [m[2] === undefined ? '' : m[2].trim()];
111
+ cur = m[1];
112
+ }
113
+ const fields = {};
114
+ for (const k of Object.keys(raw)) {
115
+ const parts = raw[k].slice();
116
+ if (parts.length && /^[>|][+-]?$/.test(parts[0]))
117
+ parts.shift();
118
+ let v = parts.filter((p) => p !== '').join(' ');
119
+ if (v.length >= 2 && ((v[0] === '"' && v[v.length - 1] === '"') || (v[0] === "'" && v[v.length - 1] === "'")))
120
+ v = v.slice(1, -1);
121
+ fields[k] = v;
122
+ }
123
+ return { reason: null, fields, body: text.slice(end + 5) };
124
+ }
125
+ export function hasAtReference(text) {
126
+ for (let i = text.indexOf('@'); i >= 0; i = text.indexOf('@', i + 1)) {
127
+ const next = text[i + 1];
128
+ if (next === undefined || !AT_PATH_CHAR_RE.test(next))
129
+ continue;
130
+ const isEmail = i > 0 && EMAIL_LOCAL_CHAR_RE.test(text[i - 1]) && EMAIL_DOMAIN_RE.test(text.slice(i));
131
+ if (!isEmail)
132
+ return true;
133
+ }
134
+ return false;
135
+ }
136
+ export function contentProblem(text) {
137
+ if (text.includes('!`'))
138
+ return 'shell-inline';
139
+ if (SHELL_FENCE_RE.test(text))
140
+ return 'shell-fence';
141
+ if (hasAtReference(text))
142
+ return 'at-reference';
143
+ if (text.includes('${CLAUDE_') || text.includes('$ARGUMENTS') || /\$[0-9]/.test(text))
144
+ return 'substitution';
145
+ return null;
146
+ }
147
+ export function filePathOk(p) {
148
+ if (typeof p !== 'string' || !p)
149
+ return false;
150
+ const segs = p.split('/');
151
+ if (segs.length > 2)
152
+ return false;
153
+ if (segs.length === 1 && SKILLPACK_FIXED_FILES.includes(p))
154
+ return true;
155
+ return segs.every((s) => SEG_RE.test(s));
156
+ }
157
+ function sourceOk(src) {
158
+ if (!isObj(src))
159
+ return false;
160
+ for (const k of Object.keys(src))
161
+ if (!SOURCE_KEYS.includes(k))
162
+ return false;
163
+ if (typeof src.repo !== 'string' || !REPO_RE.test(src.repo))
164
+ return false;
165
+ if (typeof src.path !== 'string' || !src.path.split('/').every((s) => SRC_SEG_RE.test(s)))
166
+ return false;
167
+ if (typeof src.commit !== 'string' || !COMMIT_RE.test(src.commit))
168
+ return false;
169
+ if (typeof src.license !== 'string' || !LICENSE_ID_RE.test(src.license))
170
+ return false;
171
+ return true;
172
+ }
173
+ function metaOk(p) {
174
+ if (typeof p.minClientVersion !== 'string' || !VERSION_RE.test(p.minClientVersion))
175
+ return false;
176
+ if (typeof p.line !== 'string' || !LINE_RE.test(p.line))
177
+ return false;
178
+ if (!Number.isSafeInteger(p.serial) || p.serial < 1)
179
+ return false;
180
+ if (typeof p.packId !== 'string' || !PACK_ID_RE.test(p.packId))
181
+ return false;
182
+ if (!Number.isSafeInteger(p.version) || p.version < 1)
183
+ return false;
184
+ if (typeof p.validFrom !== 'string' || !DATE_RE.test(p.validFrom))
185
+ return false;
186
+ if (typeof p.validTo !== 'string' || !DATE_RE.test(p.validTo))
187
+ return false;
188
+ if (p.validFrom > p.validTo)
189
+ return false;
190
+ return true;
191
+ }
192
+ export const isFirstParty = (src) => isObj(src) && typeof src.repo === 'string' && src.repo.startsWith(SKILLPACK_FIRST_PARTY_PREFIX);
193
+ /** 팩 검증(§3.1) — 첫 위반 사유 코드 또는 null. 검사 순서는 scripts/skill-pack/validate.mjs packProblem 과 같다 */
194
+ export function packProblem(pack, opts = {}) {
195
+ if (!isObj(pack))
196
+ return 'pack-not-object';
197
+ for (const k of Object.keys(pack))
198
+ if (!PACK_KEYS.includes(k))
199
+ return 'pack-unknown-key';
200
+ if (pack.format !== SKILLPACK_FORMAT)
201
+ return 'format-unsupported';
202
+ if (!metaOk(pack))
203
+ return 'meta-invalid';
204
+ const skills = pack.skills;
205
+ if (!Array.isArray(skills) || skills.length < 1 || skills.length > SKILLPACK_MAX_SKILLS)
206
+ return 'skills-count';
207
+ const seen = new Set();
208
+ let total = 0;
209
+ for (const s of skills) {
210
+ if (!isObj(s))
211
+ return 'skill-invalid';
212
+ for (const k of Object.keys(s))
213
+ if (!SKILL_KEYS.includes(k))
214
+ return 'skill-invalid';
215
+ if (typeof s.dir !== 'string' || !SKILL_DIR_RE.test(s.dir))
216
+ return 'skill-dir';
217
+ if (seen.has(s.dir))
218
+ return 'skill-dir-dup';
219
+ seen.add(s.dir);
220
+ if (!sourceOk(s.source))
221
+ return 'source-invalid';
222
+ if (typeof s.modified !== 'boolean')
223
+ return 'skill-invalid';
224
+ const firstParty = isFirstParty(s.source);
225
+ if (!firstParty && !SKILLPACK_LICENSES.includes(s.source.license))
226
+ return 'license';
227
+ if (!isObj(s.files))
228
+ return 'skill-invalid';
229
+ const files = s.files;
230
+ const names = Object.keys(files).sort();
231
+ if (!names.length)
232
+ return 'skill-invalid';
233
+ for (const n of names) {
234
+ if (!filePathOk(n))
235
+ return 'path';
236
+ if (!FILE_EXT_RE.test(n))
237
+ return 'file-type';
238
+ const c = files[n];
239
+ if (typeof c !== 'string')
240
+ return 'skill-invalid';
241
+ const len = Buffer.byteLength(c, 'utf8');
242
+ if (len > SKILLPACK_MAX_FILE_BYTES)
243
+ return 'file-size';
244
+ total += len;
245
+ }
246
+ if (!has(files, 'SKILL.md'))
247
+ return 'skill-md-missing';
248
+ if (!firstParty && !has(files, 'LICENSE.txt'))
249
+ return 'license-file-missing';
250
+ }
251
+ if (total > SKILLPACK_MAX_PACK_BYTES)
252
+ return 'pack-size';
253
+ for (const s of skills) {
254
+ const fm = parseFrontmatter(s.files['SKILL.md']);
255
+ if (fm.reason)
256
+ return fm.reason;
257
+ for (const k of Object.keys(fm.fields))
258
+ if (!SKILLPACK_FRONTMATTER_KEYS.includes(k))
259
+ return 'frontmatter-key';
260
+ if (fm.fields.name !== s.dir)
261
+ return 'name-mismatch';
262
+ if (!fm.fields.description)
263
+ return 'description-missing';
264
+ if ((fm.fields.description + (fm.fields.when_to_use ?? '')).length > SKILLPACK_MAX_DESC_CHARS)
265
+ return 'description-length';
266
+ for (const n of Object.keys(s.files).sort()) {
267
+ const r = contentProblem(s.files[n]);
268
+ if (r)
269
+ return r;
270
+ }
271
+ }
272
+ if (opts.checkDigest !== false) {
273
+ const p = pack;
274
+ if (typeof p.sha256 !== 'string' || !SHA_RE.test(p.sha256) || packDigest(p) !== p.sha256)
275
+ return 'digest-mismatch';
276
+ }
277
+ return null;
278
+ }
@@ -1 +1 @@
1
- import*as a57a from'fs';import*as a57b from'path';import{spawn,execFileSync}from'child_process';import*as a57c from'os';import{fileURLToPath}from'url';import*as a57d from'crypto';import{appendAttestation}from'./attestation.js';import{attestedChangedFiles,GIT_SAFE,gitConfigRaw,filteredFiles,repoOf,taskWindowStartMs,trackedFiles}from'./changeset.js';import{computeDiffCoverage}from'./coverage.js';const TIMEOUT_MS=0x927c0,TAIL_BYTES=0xfa0,ALLOWLIST=[/^(npm|pnpm|yarn)\s+(test|run\s+(test|typecheck)[\w:.-]*)(\s+[\w:.=/@-]+)*$/,/^npx\s+(vitest|jest|playwright\s+test|tsc\s+--noEmit)(\s+[\w:.=/@-]+)*$/,/^(python3?\s+-m\s+)?pytest(\s+[\w:.=/@-]+)*$/,/^node\s+--test(\s+[\w:.=/@*-]+)*$/,/^bash\s+[\w./-]+\.test\.sh$/,/^go\s+test(\s+\.\/(?:[\w./-]*\/)?\.\.\.)+$/,/^cargo\s+test$/],SHELL_META=/[;|&$`><\r\n\\]/,DENY_FLAGS=/(^|\s)(--import|--require|-r|--loader|--experimental-loader|--test-name-pattern|--test-skip-pattern|--test-only|--test-reporter|--testNamePattern|--testPathIgnorePatterns|-t|-k|--passWithNoTests|--grep|-g|--onlyChanged|-o|--lf|--last-failed|--deselect|--ignore|--ignore-glob|--run|-run|--skip|-skip|--exclude|--no-fail-on-empty|--silent-fail|--forceExit|--co|--collect-only|--listTests|--list|--shard|--test-shard|--testPathPattern|--testPathPatterns|--testRegex|--roots|--findRelatedTests|--config|-c|--rootdir|-p|--project|--changed|--changedSince|--watch|--watchAll|--dir|--exclude-glob|-u|--updateSnapshot|--update-snapshots|--snapshot-update|--ci=false|--no-ci|--update|--override-ini|--selectProjects|--project-name)(=|\s|$)|--ci\s+false\b/,LIST_ONLY=/\b(vitest\s+list|jest\s+--showConfig|playwright\s+test\s+--list)\b/;export function isAllowedCommand(a){const b=a['trim']();if(!b||SHELL_META['test'](b)||DENY_FLAGS['test'](b)||LIST_ONLY['test'](b))return![];if(/\bpytest\b.*\s-m(\s|=|$)/['test'](b))return![];return ALLOWLIST['some'](d=>d['test'](b));}export function isSelectiveCommand(a,b){const d=a['trim']()['replace'](/\s+/g,'\x20'),e=readPkg(b)?.['scripts']?.['test']?.['trim']()['replace'](/\s+/g,'\x20');if(e&&d===e)return![];if(/^(npm|pnpm|yarn) (test|run [\w:.-]+)$/['test'](d))return![];if(/^bash \S+\.test\.sh$/['test'](d)||/^cargo test$/['test'](d))return![];const f=d['split']('\x20')['filter']((h,j)=>j>0x0&&!h['startsWith']('-'));if(/^npx (jest|vitest)\b/['test'](d))return f['filter'](h=>!/^(jest|vitest|run)$/['test'](h))['length']>0x0;if(/\bpytest\b/['test'](d))return f['filter'](h=>!/^(python3?|pytest)$/['test'](h))['length']>0x0;if(/^go test/['test'](d))return!/^go test \.\/\.\.\.$/['test'](d);if(/^node --test/['test'](d)){const h=f['filter'](i=>i!=='--test');if(h['length']===0x0)return![];return!(h['length']===0x1&&/^[\w.-]+\/?$/['test'](h[0x0]));}const g=f['filter'](i=>!/^(npm|pnpm|yarn|npx|vitest|jest|playwright|test|run|pytest|python3?|node)$/['test'](i));return g['some'](i=>/\.[a-z]{1,5}$/i['test'](i)||i['includes']('*'));}function readPkg(a){try{return JSON['parse'](a57a['readFileSync'](a57b['join'](a,'package.json'),'utf-8'));}catch{return null;}}export function detectCommand(a,b){const c=readPkg(a),d=c?.['scripts']??{};if(b==='typecheck'){if(d['typecheck'])return'npm\x20run\x20typecheck';if(a57a['existsSync'](a57b['join'](a,'tsconfig.json')))return'npx\x20tsc\x20--noEmit';return null;}const e=d['test'];if(e&&!/no test specified/i['test'](e))return'npm\x20test';const f=a57a['existsSync'](a57b['join'](a,'pytest.ini'))||a57a['existsSync'](a57b['join'](a,'conftest.py'))||((()=>{try{return/\[tool\.pytest/['test'](a57a['readFileSync'](a57b['join'](a,'pyproject.toml'),'utf-8'));}catch{return![];}})());if(f)return'python3\x20-m\x20pytest\x20-q';if(a57a['existsSync'](a57b['join'](a,'go.mod')))return'go\x20test\x20./...';if(a57a['existsSync'](a57b['join'](a,'Cargo.toml')))return'cargo\x20test';return null;}function lastInt(a,b){let c,d=null;const e=new RegExp(a['source'],a['flags']['includes']('g')?a['flags']:a['flags']+'g');while((c=e['exec'](b))!==null)d=parseInt(c[0x1],0xa);return d;}export function parseCounts(a){const b=a['replace'](/\x1b\[[0-9;]*m/g,''),c=lastInt(/^# pass (\d+)/m,b),d=lastInt(/^# fail (\d+)/m,b);if(c!==null||d!==null)return{'passed':c??0x0,'failed':d??0x0};const e=lastInt(/^\s*(\d+) pass\s*$/m,b),g=lastInt(/^\s*(\d+) fail\s*$/m,b);if(e!==null||g!==null)return{'passed':e??0x0,'failed':g??0x0};const h=/Tests:\s+(.*?)\d+ total/['exec'](b);if(h){const n=h[0x1],o=/(\d+) passed/['exec'](n),q=/(\d+) failed/['exec'](n);return{'passed':o?+o[0x1]:0x0,'failed':q?+q[0x1]:0x0};}const i=/^\s*Tests\s+(.*)\(\d+\)\s*$/m['exec'](b);if(i){const r=/(\d+) passed/['exec'](i[0x1]),s=/(\d+) failed/['exec'](i[0x1]);return{'passed':r?+r[0x1]:0x0,'failed':s?+s[0x1]:0x0};}const j=/(?:^|=)\s*(?:(\d+) failed,?\s*)?(\d+) passed[^\n]* in [\d.]+s/m['exec'](b);if(j)return{'passed':+j[0x2],'failed':j[0x1]?+j[0x1]:0x0};const k=/(?:^|=)\s*(\d+) failed[^\n]* in [\d.]+s/m['exec'](b);if(k)return{'passed':0x0,'failed':+k[0x1]};const l=(b['match'](/^\s*(?:✓|PASS\b)/gm)||[])['length'],m=(b['match'](/^\s*(?:✗|FAIL\b)/gm)||[])['length'];if(l+m>0x0)return{'passed':l,'failed':m};return{'passed':null,'failed':null};}export function parseFailedNames(a){const b=a['replace'](/\x1b\[[0-9;]*m/g,''),c=new Set(),d=g=>{const h=g['trim']()['replace'](/\s+\[[\d.]+m?s\]$/,'')['slice'](0x0,0xc8);if(h)c['add'](h);};let e;const f=[/^\s*● (.+›.+)$/gm,/^\s*(?:×|✗|FAIL)\s+(.+\.(?:test|spec)\.[cm]?[jt]sx?\s*>\s*.+)$/gm,/^FAILED (\S+)/gm,/^\(fail\) (.+)$/gm,/^\s*✗ (.+?)(?:\s+—\s+got:.*)?$/gm,/^--- FAIL: (\S+)/gm,/^test (\S+) \.\.\. FAILED$/gm];for(const g of f){g['lastIndex']=0x0;while((e=g['exec'](b))!==null)d(e[0x1]);}for(const h of tapLeafFailures(b))d(h);return Array['from'](c)['slice'](0x0,0x12c);}export function tapLeafFailures(b){const c=[],d=[];for(const e of b['split']('\x0a')){const f=/^(\s*)# Subtest: (.+)$/['exec'](e);if(f){const o=f[0x1]['length'];while(c['length']&&c[c['length']-0x1]['indent']>o)c['pop']();c['push']({'indent':o,'name':f[0x2]['trim'](),'childFailed':![]});continue;}const g=/^(\s*)(not ok|ok) \d+ - (.+)$/['exec'](e);if(!g)continue;const h=g[0x1]['length'],j=g[0x3]['replace'](/\s+#\s*(SKIP|TODO).*$/,'')['trim'](),k=/\s#\s*(SKIP|TODO)/['test'](g[0x3]);let l=-0x1;for(let p=c['length']-0x1;p>=0x0;p--){if(c[p]['indent']===h&&c[p]['name']===j){l=p;break;}if(c[p]['indent']<h)break;}const m=l>=0x0?c[l]:null,n=c['filter'](q=>q['indent']<h);if(l>=0x0)c['splice'](l);if(g[0x2]==='not\x20ok'&&!k&&!(m&&m['childFailed'])){d['push']([...n['map'](q=>q['name']),j]['join']('\x20>\x20'));for(const q of n)q['childFailed']=!![];}}return d;}function isNoTests(a){return/no tests? (found|ran|to run)|No test files found|collected 0 items/i['test'](a);}function execShell(a,b,c=null){return new Promise(d=>{let e='',f=![];const g={...process.env,'CI':'1','FORCE_COLOR':'0'};delete g['NODE_TEST_CONTEXT'],delete g['NODE_V8_COVERAGE'];if(c)g['NODE_V8_COVERAGE']=c;const h=spawn(a,{'cwd':b,'shell':!![],'env':g}),i=setTimeout(()=>{f=!![],h['kill']('SIGKILL');},TIMEOUT_MS),j=k=>{e+=k['toString']();if(e['length']>0x30d40)e=e['slice'](-0x186a0);};h['stdout']?.['on']('data',j),h['stderr']?.['on']('data',j),h['on']('error',k=>{clearTimeout(i),d({'exitCode':null,'output':e+String(k),'timedOut':![]});}),h['on']('close',k=>{clearTimeout(i),d({'exitCode':k,'output':e,'timedOut':f});});});}function isTreeClean(a){if(gitText(['status','--porcelain','--untracked-files=no','--ignore-submodules=none'],a)!=='')return![];if(hasIndexFlags(a))return![];if(gitConfigRaw('core.fsmonitor',a))return![];if(repoOf(a57b['join'](a,'.rc-probe'))['kind']==='redirect')return![];const b=gitText(['rev-parse','--show-toplevel'],a);if(b&&filteredFiles(b)['length']>0x0)return![];if(gitText(['for-each-ref','refs/replace'],a))return![];return!![];}function hasIndexFlags(a){const b=gitText(['ls-files','-v'],a);return!!b&&b['split']('\x0a')['some'](c=>c['length']>0x2&&(c[0x0]==='S'||c[0x0]>='a'&&c[0x0]<='z'));}function gitText(a,b){try{return execFileSync('git',[...GIT_SAFE,'-C',b,...a],{'encoding':'utf-8','timeout':0xea60,'stdio':['ignore','pipe','ignore']})['trim']();}catch{return null;}}function linkModules(a,b,c,e){a57a['mkdirSync'](b,{'recursive':!![]});for(const f of a57a['readdirSync'](a,{'withFileTypes':!![]})){const g=a57b['join'](a,f['name']),h=a57b['join'](b,f['name']);if(f['name']['startsWith']('@')&&f['isDirectory']()){linkModules(g,h,c,e);continue;}let i=g;try{i=a57a['realpathSync'](g);}catch{}const j=i['startsWith'](c+a57b['sep'])&&!i['split'](a57b['sep'])['includes']('node_modules'),k=j?a57b['join'](e,a57b['relative'](c,i)):g;try{a57a['symlinkSync'](k,h,f['isDirectory']()||j?'dir':'file');}catch{}}}const ENV_DIR=/(^|\/)(venv|\.venv|__pycache__|\.cache|\.turbo|\.tox|\.mypy_cache|\.pytest_cache)\/?$/;function snapDir(a){const b=process['platform']==='darwin'||process['platform']==='win32',c=b?a['toLowerCase']():a,d=process.env.ROUTINECODE_KNOWLEDGE_DIR||a57b['join'](a57c['homedir'](),'.routinecode','knowledge');return a57b['join'](d,'baseline-snap',a57d['createHash']('sha256')['update'](c,'utf-8')['digest']('hex')['slice'](0x0,0x10));}const HOOK_LIB=a57b['resolve'](a57b['dirname'](fileURLToPath(import.meta.url)),'..','..','hooks','lib');function snapshotIfNoEditsYet(a){const b=trackedFiles()['some'](d=>{let e=d;try{e=a57a['realpathSync']['native'](d);}catch{}return e['startsWith'](a+a57b['sep']);});if(b)return![];let c=taskWindowStartMs();try{const d=process.env.ROUTINECODE_KNOWLEDGE_DIR||a57b['join'](a57c['homedir'](),'.routinecode','knowledge'),e=JSON['parse'](a57a['readFileSync'](a57b['join'](d,'task-heads.json'),'utf-8'))?.['__at__']?.[a];if(typeof e==='number')c=e;}catch{}try{return execFileSync('python3',['-c','import\x20sys;sys.path.insert(0,'+JSON['stringify'](HOOK_LIB)+');import\x20attest_reader\x20as\x20a;a.snapshot_local_files('+JSON['stringify'](a)+',\x20created_before_ms='+c+')'],{'timeout':0x1d4c0,'stdio':['ignore','ignore','ignore']}),!![];}catch{return![];}}function restoreSnapshot(a,c){for(const i of(gitText(['ls-files','-oi','--exclude-standard','--directory','-z'],a)??'')['split']('\x00')){if(!i||!ENV_DIR['test'](i))continue;const j=a57b['join'](c,i['replace'](/\/$/,''));if(a57a['existsSync'](j))continue;try{a57a['mkdirSync'](a57b['dirname'](j),{'recursive':!![]}),a57a['symlinkSync'](a57b['join'](a,i['replace'](/\/$/,'')),j,'dir');}catch{}}const e=snapDir(a),f=((()=>{try{return JSON['parse'](a57a['readFileSync'](a57b['join'](e,'manifest.json'),'utf-8'))['createdAt']>=taskWindowStartMs();}catch{return![];}})());if(!f)snapshotIfNoEditsYet(a);let g;try{g=JSON['parse'](a57a['readFileSync'](a57b['join'](e,'manifest.json'),'utf-8'));}catch{return{'ok':![],'reason':'no\x20task-start\x20environment\x20snapshot\x20(files\x20were\x20edited\x20before\x20any\x20snapshot)','pendingBig':[],'truncated':![]};}if(typeof g['createdAt']!=='number'||g['createdAt']<taskWindowStartMs())return{'ok':![],'reason':'environment\x20snapshot\x20predates\x20this\x20task','pendingBig':[],'truncated':![]};for(const k of g['files']??[]){const l=a57b['join'](c,k);if(a57a['existsSync'](l))continue;try{a57a['mkdirSync'](a57b['dirname'](l),{'recursive':!![]}),a57a['copyFileSync'](a57b['join'](e,'files',k),l);}catch{}}const h=[];for(const n of g['big']??[]){const o=a57b['join'](a,n['rel']),p=a57b['join'](c,n['rel']);if(a57a['existsSync'](p))continue;try{const q=a57a['statSync'](o);if(q['size']===n['size']&&Math['abs'](Math['floor'](q['mtimeMs'])-n['mtimeMs'])<=0x1){a57a['mkdirSync'](a57b['dirname'](p),{'recursive':!![]}),a57a['copyFileSync'](o,p,a57a['constants']['COPYFILE_FICLONE']);continue;}}catch{}h['push'](n['rel']);}return{'ok':!![],'pendingBig':h,'truncated':!!g['truncated']};}export async function runBaseline(a){const b=a57b['resolve'](a['projectDir']),c=(k,l=null)=>({'success':![],'command':l,'headSha':null,'passed':null,'failed':null,'valid':![],'attested':![],'outputTail':'','error':k}),d=a['command']?.['trim']()||detectCommand(b,'tests');if(!d)return c('no\x20test\x20command\x20detected\x20in\x20'+b);if(!isAllowedCommand(d))return c('command\x20not\x20allowlisted',d);const e=gitText(['rev-parse','--show-toplevel'],b),f=gitText(['rev-parse','HEAD'],b);if(!e||!f)return c('baseline\x20requires\x20a\x20git\x20repository\x20with\x20at\x20least\x20one\x20commit',d);const g=a57a['realpathSync']['native'](e),h=a57b['relative'](g,a57a['realpathSync']['native'](b)),j=a57a['mkdtempSync'](a57b['join'](a57c['tmpdir'](),'rc-baseline-'));a57a['rmSync'](j,{'recursive':!![],'force':!![]});if(gitText(['worktree','add','--detach',j,f],g)===null)return c('git\x20worktree\x20add\x20failed',d);try{let k=a57b['join'](g,h);for(let w=0x0;w<0xc;w++){const x=a57b['join'](k,'node_modules'),y=a57b['join'](j,a57b['relative'](g,k),'node_modules');a57a['existsSync'](x)&&a57a['existsSync'](a57b['dirname'](y))&&!a57a['existsSync'](y)&&linkModules(x,y,g,j);if(k===g)break;k=a57b['dirname'](k);}if(a57a['existsSync'](a57b['join'](j,'.gitmodules'))){const z=gitText(['-c','protocol.file.allow=always','submodule','update','--init','--recursive'],j);if(z===null)return c('baseline\x20could\x20not\x20initialise\x20submodules\x20at\x20HEAD\x20(network/remote?)\x20—\x20use\x20a\x20clean\x20pre-edit\x20run_tests\x20instead',d);}const l=restoreSnapshot(g,j),m=a57b['join'](j,h);if(!a57a['existsSync'](m))return c(h+'\x20does\x20not\x20exist\x20at\x20HEAD',d);const n=readPkg(m);if(n?.['scripts']?.['build'])await execShell('npm\x20run\x20build',m);const o=l['pendingBig']['filter'](A=>!a57a['existsSync'](a57b['join'](j,A))),p=Date['now'](),{exitCode:q,output:r}=await execShell(d,m),{passed:s,failed:t}=parseCounts(r),u=typeof s==='number'&&s>0x0&&typeof t==='number',v=u&&appendAttestation({'kind':'tests','projectDir':b,'success':q===0x0,'detail':{'command':d,'exitCode':q,'passed':s,'failed':t,'startedAt':p,'baseline':'HEAD','headSha':f,'failedNames':parseFailedNames(r),...!l['ok']||o['length']>0x0||l['truncated']?{'envIncomplete':{'reason':l['reason']??(l['truncated']?'snapshot\x20truncated':'large\x20local\x20files\x20changed\x20since\x20the\x20snapshot'),'missing':o['slice'](0x0,0x14),'missingCount':o['length']}}:{}}});return{'success':q===0x0,'command':d,'headSha':f,'passed':s,'failed':t,'valid':u,'attested':v,'outputTail':r['slice'](-TAIL_BYTES),...u?{}:{'error':'baseline\x20run\x20produced\x20no\x20passing\x20tests\x20(environment\x20likely\x20broken)\x20—\x20not\x20recorded'}};}finally{gitText(['worktree','remove','--force',j],g);try{a57a['rmSync'](j,{'recursive':!![],'force':!![]});}catch{}gitText(['worktree','prune'],g);}}export async function runTests(a){const b=a['kind']??'tests',c=a['projectDir'],d={'success':![],'kind':b,'command':null,'exitCode':null,'passed':null,'failed':null,'noTests':![],'timedOut':![],'outputTail':'','attested':![]},e=a['command']?.['trim']()||detectCommand(c,b);if(!e)return{...d,'noTests':!![],'error':'no\x20'+b+'\x20command\x20detected\x20in\x20'+c+';\x20pass\x20an\x20allowlisted\x20command'};if(!isAllowedCommand(e))return{...d,'command':e,'error':'command\x20not\x20allowlisted\x20(test/typecheck\x20runners\x20only,\x20no\x20shell\x20metacharacters)'};const f=Date['now']();let g=null;if(b==='tests')try{g=a57a['mkdtempSync'](a57b['join'](a57c['tmpdir'](),'rc-v8cov-'));}catch{g=null;}const {exitCode:h,output:i,timedOut:j}=await execShell(e,c,g),{passed:k,failed:l}=parseCounts(i),m=b==='tests'&&(isNoTests(i)||h===0x0&&k===0x0&&(l??0x0)===0x0),n=h===0x0&&!j&&!m&&(l??0x0)===0x0;let o;if(g){try{o=computeDiffCoverage(attestedChangedFiles(c)['files'],g);}catch{o=undefined;}try{a57a['rmSync'](g,{'recursive':!![],'force':!![]});}catch{}}const p=appendAttestation({'kind':b,'projectDir':c,'success':n,'detail':{'command':e,'exitCode':h,'passed':k,'failed':l,'noTests':m,'timedOut':j,'startedAt':f,'selective':isSelectiveCommand(e,c),'treeClean':isTreeClean(c),'headSha':gitText(['rev-parse','HEAD'],c),'failedNames':parseFailedNames(i),...o?{'coverage':{'measured':o['measured'],'ratio':o['ratio'],'files':o['files']['slice'](0x0,0x64)['map'](q=>({'file':q['file'],'mode':q['mode'],'ratio':Math['round'](q['ratio']*0x3e8)/0x3e8,...q['functions']?.['missed']['length']?{'missed':q['functions']['missed']['slice'](0x0,0x14)}:{},...q['stale']?{'stale':!![]}:{}}))}}:{}}});return{'success':n,'kind':b,'command':e,'exitCode':h,'passed':k,'failed':l,'noTests':m,'timedOut':j,'outputTail':i['slice'](-TAIL_BYTES),'attested':p,...o?{'coverage':o}:{}};}
1
+ import*as a63a from'fs';import*as a63b from'path';import{spawn,execFileSync}from'child_process';import*as a63c from'os';import{fileURLToPath}from'url';import*as a63d from'crypto';import{appendAttestation}from'./attestation.js';import{attestedChangedFiles,GIT_SAFE,gitConfigRaw,filteredFiles,repoOf,taskWindowStartMs,trackedFiles}from'./changeset.js';import{computeDiffCoverage}from'./coverage.js';const TIMEOUT_MS=0x927c0,TAIL_BYTES=0xfa0,ALLOWLIST=[/^(npm|pnpm|yarn)\s+(test|run\s+(test|typecheck)[\w:.-]*)(\s+[\w:.=/@-]+)*$/,/^npx\s+(vitest|jest|playwright\s+test|tsc\s+--noEmit)(\s+[\w:.=/@-]+)*$/,/^(python3?\s+-m\s+)?pytest(\s+[\w:.=/@-]+)*$/,/^node\s+--test(\s+[\w:.=/@*-]+)*$/,/^bash\s+[\w./-]+\.test\.sh$/,/^go\s+test(\s+\.\/(?:[\w./-]*\/)?\.\.\.)+$/,/^cargo\s+test$/],SHELL_META=/[;|&$`><\r\n\\]/,DENY_FLAGS=/(^|\s)(--import|--require|-r|--loader|--experimental-loader|--test-name-pattern|--test-skip-pattern|--test-only|--test-reporter|--testNamePattern|--testPathIgnorePatterns|-t|-k|--passWithNoTests|--grep|-g|--onlyChanged|-o|--lf|--last-failed|--deselect|--ignore|--ignore-glob|--run|-run|--skip|-skip|--exclude|--no-fail-on-empty|--silent-fail|--forceExit|--co|--collect-only|--listTests|--list|--shard|--test-shard|--testPathPattern|--testPathPatterns|--testRegex|--roots|--findRelatedTests|--config|-c|--rootdir|-p|--project|--changed|--changedSince|--watch|--watchAll|--dir|--exclude-glob|-u|--updateSnapshot|--update-snapshots|--snapshot-update|--ci=false|--no-ci|--update|--override-ini|--selectProjects|--project-name)(=|\s|$)|--ci\s+false\b/,LIST_ONLY=/\b(vitest\s+list|jest\s+--showConfig|playwright\s+test\s+--list)\b/;export function isAllowedCommand(a){const b=a['trim']();if(!b||SHELL_META['test'](b)||DENY_FLAGS['test'](b)||LIST_ONLY['test'](b))return![];if(/\bpytest\b.*\s-m(\s|=|$)/['test'](b))return![];return ALLOWLIST['some'](d=>d['test'](b));}export function isSelectiveCommand(a,b){const d=a['trim']()['replace'](/\s+/g,'\x20'),e=readPkg(b)?.['scripts']?.['test']?.['trim']()['replace'](/\s+/g,'\x20');if(e&&d===e)return![];if(/^(npm|pnpm|yarn) (test|run [\w:.-]+)$/['test'](d))return![];if(/^bash \S+\.test\.sh$/['test'](d)||/^cargo test$/['test'](d))return![];const f=d['split']('\x20')['filter']((h,j)=>j>0x0&&!h['startsWith']('-'));if(/^npx (jest|vitest)\b/['test'](d))return f['filter'](h=>!/^(jest|vitest|run)$/['test'](h))['length']>0x0;if(/\bpytest\b/['test'](d))return f['filter'](h=>!/^(python3?|pytest)$/['test'](h))['length']>0x0;if(/^go test/['test'](d))return!/^go test \.\/\.\.\.$/['test'](d);if(/^node --test/['test'](d)){const h=f['filter'](i=>i!=='--test');if(h['length']===0x0)return![];return!(h['length']===0x1&&/^[\w.-]+\/?$/['test'](h[0x0]));}const g=f['filter'](i=>!/^(npm|pnpm|yarn|npx|vitest|jest|playwright|test|run|pytest|python3?|node)$/['test'](i));return g['some'](i=>/\.[a-z]{1,5}$/i['test'](i)||i['includes']('*'));}function readPkg(a){try{return JSON['parse'](a63a['readFileSync'](a63b['join'](a,'package.json'),'utf-8'));}catch{return null;}}export function detectCommand(a,b){const c=readPkg(a),d=c?.['scripts']??{};if(b==='typecheck'){if(d['typecheck'])return'npm\x20run\x20typecheck';if(a63a['existsSync'](a63b['join'](a,'tsconfig.json')))return'npx\x20tsc\x20--noEmit';return null;}const e=d['test'];if(e&&!/no test specified/i['test'](e))return'npm\x20test';const f=a63a['existsSync'](a63b['join'](a,'pytest.ini'))||a63a['existsSync'](a63b['join'](a,'conftest.py'))||((()=>{try{return/\[tool\.pytest/['test'](a63a['readFileSync'](a63b['join'](a,'pyproject.toml'),'utf-8'));}catch{return![];}})());if(f)return'python3\x20-m\x20pytest\x20-q';if(a63a['existsSync'](a63b['join'](a,'go.mod')))return'go\x20test\x20./...';if(a63a['existsSync'](a63b['join'](a,'Cargo.toml')))return'cargo\x20test';return null;}function lastInt(a,b){let c,d=null;const e=new RegExp(a['source'],a['flags']['includes']('g')?a['flags']:a['flags']+'g');while((c=e['exec'](b))!==null)d=parseInt(c[0x1],0xa);return d;}export function parseCounts(a){const b=a['replace'](/\x1b\[[0-9;]*m/g,''),c=lastInt(/^# pass (\d+)/m,b),d=lastInt(/^# fail (\d+)/m,b);if(c!==null||d!==null)return{'passed':c??0x0,'failed':d??0x0};const e=lastInt(/^\s*(\d+) pass\s*$/m,b),g=lastInt(/^\s*(\d+) fail\s*$/m,b);if(e!==null||g!==null)return{'passed':e??0x0,'failed':g??0x0};const h=/Tests:\s+(.*?)\d+ total/['exec'](b);if(h){const n=h[0x1],o=/(\d+) passed/['exec'](n),q=/(\d+) failed/['exec'](n);return{'passed':o?+o[0x1]:0x0,'failed':q?+q[0x1]:0x0};}const i=/^\s*Tests\s+(.*)\(\d+\)\s*$/m['exec'](b);if(i){const r=/(\d+) passed/['exec'](i[0x1]),s=/(\d+) failed/['exec'](i[0x1]);return{'passed':r?+r[0x1]:0x0,'failed':s?+s[0x1]:0x0};}const j=/(?:^|=)\s*(?:(\d+) failed,?\s*)?(\d+) passed[^\n]* in [\d.]+s/m['exec'](b);if(j)return{'passed':+j[0x2],'failed':j[0x1]?+j[0x1]:0x0};const k=/(?:^|=)\s*(\d+) failed[^\n]* in [\d.]+s/m['exec'](b);if(k)return{'passed':0x0,'failed':+k[0x1]};const l=(b['match'](/^\s*(?:✓|PASS\b)/gm)||[])['length'],m=(b['match'](/^\s*(?:✗|FAIL\b)/gm)||[])['length'];if(l+m>0x0)return{'passed':l,'failed':m};return{'passed':null,'failed':null};}export function parseFailedNames(a){const b=a['replace'](/\x1b\[[0-9;]*m/g,''),c=new Set(),d=g=>{const h=g['trim']()['replace'](/\s+\[[\d.]+m?s\]$/,'')['slice'](0x0,0xc8);if(h)c['add'](h);};let e;const f=[/^\s*● (.+›.+)$/gm,/^\s*(?:×|✗|FAIL)\s+(.+\.(?:test|spec)\.[cm]?[jt]sx?\s*>\s*.+)$/gm,/^FAILED (\S+)/gm,/^\(fail\) (.+)$/gm,/^\s*✗ (.+?)(?:\s+—\s+got:.*)?$/gm,/^--- FAIL: (\S+)/gm,/^test (\S+) \.\.\. FAILED$/gm];for(const g of f){g['lastIndex']=0x0;while((e=g['exec'](b))!==null)d(e[0x1]);}for(const h of tapLeafFailures(b))d(h);return Array['from'](c)['slice'](0x0,0x12c);}export function tapLeafFailures(b){const c=[],d=[];for(const e of b['split']('\x0a')){const f=/^(\s*)# Subtest: (.+)$/['exec'](e);if(f){const o=f[0x1]['length'];while(c['length']&&c[c['length']-0x1]['indent']>o)c['pop']();c['push']({'indent':o,'name':f[0x2]['trim'](),'childFailed':![]});continue;}const g=/^(\s*)(not ok|ok) \d+ - (.+)$/['exec'](e);if(!g)continue;const h=g[0x1]['length'],j=g[0x3]['replace'](/\s+#\s*(SKIP|TODO).*$/,'')['trim'](),k=/\s#\s*(SKIP|TODO)/['test'](g[0x3]);let l=-0x1;for(let p=c['length']-0x1;p>=0x0;p--){if(c[p]['indent']===h&&c[p]['name']===j){l=p;break;}if(c[p]['indent']<h)break;}const m=l>=0x0?c[l]:null,n=c['filter'](q=>q['indent']<h);if(l>=0x0)c['splice'](l);if(g[0x2]==='not\x20ok'&&!k&&!(m&&m['childFailed'])){d['push']([...n['map'](q=>q['name']),j]['join']('\x20>\x20'));for(const q of n)q['childFailed']=!![];}}return d;}function isNoTests(a){return/no tests? (found|ran|to run)|No test files found|collected 0 items/i['test'](a);}function execShell(a,b,c=null){return new Promise(d=>{let e='',f=![];const g={...process.env,'CI':'1','FORCE_COLOR':'0'};delete g['NODE_TEST_CONTEXT'],delete g['NODE_V8_COVERAGE'];if(c)g['NODE_V8_COVERAGE']=c;const h=spawn(a,{'cwd':b,'shell':!![],'env':g}),i=setTimeout(()=>{f=!![],h['kill']('SIGKILL');},TIMEOUT_MS),j=k=>{e+=k['toString']();if(e['length']>0x30d40)e=e['slice'](-0x186a0);};h['stdout']?.['on']('data',j),h['stderr']?.['on']('data',j),h['on']('error',k=>{clearTimeout(i),d({'exitCode':null,'output':e+String(k),'timedOut':![]});}),h['on']('close',k=>{clearTimeout(i),d({'exitCode':k,'output':e,'timedOut':f});});});}function isTreeClean(a){if(gitText(['status','--porcelain','--untracked-files=no','--ignore-submodules=none'],a)!=='')return![];if(hasIndexFlags(a))return![];if(gitConfigRaw('core.fsmonitor',a))return![];if(repoOf(a63b['join'](a,'.rc-probe'))['kind']==='redirect')return![];const b=gitText(['rev-parse','--show-toplevel'],a);if(b&&filteredFiles(b)['length']>0x0)return![];if(gitText(['for-each-ref','refs/replace'],a))return![];return!![];}function hasIndexFlags(a){const b=gitText(['ls-files','-v'],a);return!!b&&b['split']('\x0a')['some'](c=>c['length']>0x2&&(c[0x0]==='S'||c[0x0]>='a'&&c[0x0]<='z'));}function gitText(a,b){try{return execFileSync('git',[...GIT_SAFE,'-C',b,...a],{'encoding':'utf-8','timeout':0xea60,'stdio':['ignore','pipe','ignore']})['trim']();}catch{return null;}}function linkModules(a,b,c,e){a63a['mkdirSync'](b,{'recursive':!![]});for(const f of a63a['readdirSync'](a,{'withFileTypes':!![]})){const g=a63b['join'](a,f['name']),h=a63b['join'](b,f['name']);if(f['name']['startsWith']('@')&&f['isDirectory']()){linkModules(g,h,c,e);continue;}let i=g;try{i=a63a['realpathSync'](g);}catch{}const j=i['startsWith'](c+a63b['sep'])&&!i['split'](a63b['sep'])['includes']('node_modules'),k=j?a63b['join'](e,a63b['relative'](c,i)):g;try{a63a['symlinkSync'](k,h,f['isDirectory']()||j?'dir':'file');}catch{}}}const ENV_DIR=/(^|\/)(venv|\.venv|__pycache__|\.cache|\.turbo|\.tox|\.mypy_cache|\.pytest_cache)\/?$/;function snapDir(a){const b=process['platform']==='darwin'||process['platform']==='win32',c=b?a['toLowerCase']():a,d=process.env.ROUTINECODE_KNOWLEDGE_DIR||a63b['join'](a63c['homedir'](),'.routinecode','knowledge');return a63b['join'](d,'baseline-snap',a63d['createHash']('sha256')['update'](c,'utf-8')['digest']('hex')['slice'](0x0,0x10));}const HOOK_LIB=a63b['resolve'](a63b['dirname'](fileURLToPath(import.meta.url)),'..','..','hooks','lib');function snapshotIfNoEditsYet(a){const b=trackedFiles()['some'](d=>{let e=d;try{e=a63a['realpathSync']['native'](d);}catch{}return e['startsWith'](a+a63b['sep']);});if(b)return![];let c=taskWindowStartMs();try{const d=process.env.ROUTINECODE_KNOWLEDGE_DIR||a63b['join'](a63c['homedir'](),'.routinecode','knowledge'),e=JSON['parse'](a63a['readFileSync'](a63b['join'](d,'task-heads.json'),'utf-8'))?.['__at__']?.[a];if(typeof e==='number')c=e;}catch{}try{return execFileSync('python3',['-c','import\x20sys;sys.path.insert(0,'+JSON['stringify'](HOOK_LIB)+');import\x20attest_reader\x20as\x20a;a.snapshot_local_files('+JSON['stringify'](a)+',\x20created_before_ms='+c+')'],{'timeout':0x1d4c0,'stdio':['ignore','ignore','ignore']}),!![];}catch{return![];}}function restoreSnapshot(a,c){for(const i of(gitText(['ls-files','-oi','--exclude-standard','--directory','-z'],a)??'')['split']('\x00')){if(!i||!ENV_DIR['test'](i))continue;const j=a63b['join'](c,i['replace'](/\/$/,''));if(a63a['existsSync'](j))continue;try{a63a['mkdirSync'](a63b['dirname'](j),{'recursive':!![]}),a63a['symlinkSync'](a63b['join'](a,i['replace'](/\/$/,'')),j,'dir');}catch{}}const e=snapDir(a),f=((()=>{try{return JSON['parse'](a63a['readFileSync'](a63b['join'](e,'manifest.json'),'utf-8'))['createdAt']>=taskWindowStartMs();}catch{return![];}})());if(!f)snapshotIfNoEditsYet(a);let g;try{g=JSON['parse'](a63a['readFileSync'](a63b['join'](e,'manifest.json'),'utf-8'));}catch{return{'ok':![],'reason':'no\x20task-start\x20environment\x20snapshot\x20(files\x20were\x20edited\x20before\x20any\x20snapshot)','pendingBig':[],'truncated':![]};}if(typeof g['createdAt']!=='number'||g['createdAt']<taskWindowStartMs())return{'ok':![],'reason':'environment\x20snapshot\x20predates\x20this\x20task','pendingBig':[],'truncated':![]};for(const k of g['files']??[]){const l=a63b['join'](c,k);if(a63a['existsSync'](l))continue;try{a63a['mkdirSync'](a63b['dirname'](l),{'recursive':!![]}),a63a['copyFileSync'](a63b['join'](e,'files',k),l);}catch{}}const h=[];for(const n of g['big']??[]){const o=a63b['join'](a,n['rel']),p=a63b['join'](c,n['rel']);if(a63a['existsSync'](p))continue;try{const q=a63a['statSync'](o);if(q['size']===n['size']&&Math['abs'](Math['floor'](q['mtimeMs'])-n['mtimeMs'])<=0x1){a63a['mkdirSync'](a63b['dirname'](p),{'recursive':!![]}),a63a['copyFileSync'](o,p,a63a['constants']['COPYFILE_FICLONE']);continue;}}catch{}h['push'](n['rel']);}return{'ok':!![],'pendingBig':h,'truncated':!!g['truncated']};}export async function runBaseline(a){const b=a63b['resolve'](a['projectDir']),c=(k,l=null)=>({'success':![],'command':l,'headSha':null,'passed':null,'failed':null,'valid':![],'attested':![],'outputTail':'','error':k}),d=a['command']?.['trim']()||detectCommand(b,'tests');if(!d)return c('no\x20test\x20command\x20detected\x20in\x20'+b);if(!isAllowedCommand(d))return c('command\x20not\x20allowlisted',d);const e=gitText(['rev-parse','--show-toplevel'],b),f=gitText(['rev-parse','HEAD'],b);if(!e||!f)return c('baseline\x20requires\x20a\x20git\x20repository\x20with\x20at\x20least\x20one\x20commit',d);const g=a63a['realpathSync']['native'](e),h=a63b['relative'](g,a63a['realpathSync']['native'](b)),j=a63a['mkdtempSync'](a63b['join'](a63c['tmpdir'](),'rc-baseline-'));a63a['rmSync'](j,{'recursive':!![],'force':!![]});if(gitText(['worktree','add','--detach',j,f],g)===null)return c('git\x20worktree\x20add\x20failed',d);try{let k=a63b['join'](g,h);for(let w=0x0;w<0xc;w++){const x=a63b['join'](k,'node_modules'),y=a63b['join'](j,a63b['relative'](g,k),'node_modules');a63a['existsSync'](x)&&a63a['existsSync'](a63b['dirname'](y))&&!a63a['existsSync'](y)&&linkModules(x,y,g,j);if(k===g)break;k=a63b['dirname'](k);}if(a63a['existsSync'](a63b['join'](j,'.gitmodules'))){const z=gitText(['-c','protocol.file.allow=always','submodule','update','--init','--recursive'],j);if(z===null)return c('baseline\x20could\x20not\x20initialise\x20submodules\x20at\x20HEAD\x20(network/remote?)\x20—\x20use\x20a\x20clean\x20pre-edit\x20run_tests\x20instead',d);}const l=restoreSnapshot(g,j),m=a63b['join'](j,h);if(!a63a['existsSync'](m))return c(h+'\x20does\x20not\x20exist\x20at\x20HEAD',d);const n=readPkg(m);if(n?.['scripts']?.['build'])await execShell('npm\x20run\x20build',m);const o=l['pendingBig']['filter'](A=>!a63a['existsSync'](a63b['join'](j,A))),p=Date['now'](),{exitCode:q,output:r}=await execShell(d,m),{passed:s,failed:t}=parseCounts(r),u=typeof s==='number'&&s>0x0&&typeof t==='number',v=u&&appendAttestation({'kind':'tests','projectDir':b,'success':q===0x0,'detail':{'command':d,'exitCode':q,'passed':s,'failed':t,'startedAt':p,'baseline':'HEAD','headSha':f,'failedNames':parseFailedNames(r),...!l['ok']||o['length']>0x0||l['truncated']?{'envIncomplete':{'reason':l['reason']??(l['truncated']?'snapshot\x20truncated':'large\x20local\x20files\x20changed\x20since\x20the\x20snapshot'),'missing':o['slice'](0x0,0x14),'missingCount':o['length']}}:{}}});return{'success':q===0x0,'command':d,'headSha':f,'passed':s,'failed':t,'valid':u,'attested':v,'outputTail':r['slice'](-TAIL_BYTES),...u?{}:{'error':'baseline\x20run\x20produced\x20no\x20passing\x20tests\x20(environment\x20likely\x20broken)\x20—\x20not\x20recorded'}};}finally{gitText(['worktree','remove','--force',j],g);try{a63a['rmSync'](j,{'recursive':!![],'force':!![]});}catch{}gitText(['worktree','prune'],g);}}export async function runTests(a){const b=a['kind']??'tests',c=a['projectDir'],d={'success':![],'kind':b,'command':null,'exitCode':null,'passed':null,'failed':null,'noTests':![],'timedOut':![],'outputTail':'','attested':![]},e=a['command']?.['trim']()||detectCommand(c,b);if(!e)return{...d,'noTests':!![],'error':'no\x20'+b+'\x20command\x20detected\x20in\x20'+c+';\x20pass\x20an\x20allowlisted\x20command'};if(!isAllowedCommand(e))return{...d,'command':e,'error':'command\x20not\x20allowlisted\x20(test/typecheck\x20runners\x20only,\x20no\x20shell\x20metacharacters)'};const f=Date['now']();let g=null;if(b==='tests')try{g=a63a['mkdtempSync'](a63b['join'](a63c['tmpdir'](),'rc-v8cov-'));}catch{g=null;}const {exitCode:h,output:i,timedOut:j}=await execShell(e,c,g),{passed:k,failed:l}=parseCounts(i),m=b==='tests'&&(isNoTests(i)||h===0x0&&k===0x0&&(l??0x0)===0x0),n=h===0x0&&!j&&!m&&(l??0x0)===0x0;let o;if(g){try{o=computeDiffCoverage(attestedChangedFiles(c)['files'],g);}catch{o=undefined;}try{a63a['rmSync'](g,{'recursive':!![],'force':!![]});}catch{}}const p=appendAttestation({'kind':b,'projectDir':c,'success':n,'detail':{'command':e,'exitCode':h,'passed':k,'failed':l,'noTests':m,'timedOut':j,'startedAt':f,'selective':isSelectiveCommand(e,c),'treeClean':isTreeClean(c),'headSha':gitText(['rev-parse','HEAD'],c),'failedNames':parseFailedNames(i),...o?{'coverage':{'measured':o['measured'],'ratio':o['ratio'],'files':o['files']['slice'](0x0,0x64)['map'](q=>({'file':q['file'],'mode':q['mode'],'ratio':Math['round'](q['ratio']*0x3e8)/0x3e8,...q['functions']?.['missed']['length']?{'missed':q['functions']['missed']['slice'](0x0,0x14)}:{},...q['stale']?{'stale':!![]}:{}}))}}:{}}});return{'success':n,'kind':b,'command':e,'exitCode':h,'passed':k,'failed':l,'noTests':m,'timedOut':j,'outputTail':i['slice'](-TAIL_BYTES),'attested':p,...o?{'coverage':o}:{}};}