@kriya-ai/harness 0.2.4 → 2.0.0
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.
- package/RELEASE_NOTES.md +121 -0
- package/SAFETY.md +181 -0
- package/THIRD_PARTY_NOTICES.md +113 -0
- package/bin/kriya.js +188 -2
- package/bundle/cordis.patch.yml +49 -0
- package/contract/SOURCE.md +3 -3
- package/contract/contract.json +504 -3
- package/contract/schemas/api.json +64 -0
- package/contract/schemas/auth_matrix.json +44 -0
- package/contract/schemas/component_states.json +33 -0
- package/contract/schemas/design_tokens.json +34 -0
- package/contract/schemas/scene_direction.json +82 -0
- package/contract/schemas/threat_model.json +44 -0
- package/package.json +2 -1
- package/plugins/changes/client.js +5 -3
- package/plugins/deploy/index.js +215 -0
- package/plugins/deploy/package.json +13 -0
- package/plugins/grounding/index.js +81 -0
- package/plugins/grounding/lookup.js +373 -0
- package/plugins/grounding/package.json +13 -0
- package/plugins/kriya-tools/index.js +2 -1
- package/plugins/loop/index.js +376 -10
- package/plugins/mcp/index.js +79 -0
- package/plugins/mcp/package.json +13 -0
- package/plugins/mirror/index.js +17 -0
- package/plugins/overview/client.js +5 -2
- package/plugins/preview/client.js +12 -6
- package/plugins/progress/client.js +7 -4
- package/plugins/repo/index.js +230 -0
- package/plugins/repo/package.json +13 -0
- package/plugins/repo/repo.js +348 -0
- package/plugins/runstrip/client.js +426 -0
- package/plugins/runstrip/index.js +301 -0
- package/plugins/runstrip/package.json +23 -0
- package/src/cartridges.js +133 -0
- package/src/contracts.js +130 -0
- package/src/critic.js +78 -0
- package/src/daemon.js +7 -1
- package/src/doctor.js +67 -0
- package/src/edit/core/effects.js +185 -0
- package/src/edit/core/ffmpeg.js +82 -5
- package/src/edit/core/layout.js +46 -1
- package/src/edit/core/ops.js +175 -3
- package/src/edit/core/plan.js +95 -9
- package/src/edit/core/project.d.ts +24 -0
- package/src/edit/core/project.js +64 -0
- package/src/edit/core/solver.js +34 -6
- package/src/edit/core/style-brief.js +211 -0
- package/src/edit/core/style-packs.js +57 -0
- package/src/edit/core/transitions.js +17 -0
- package/src/edit/core/type-kit.js +173 -0
- package/src/edit/director/ask.js +37 -3
- package/src/edit/director/assembly.js +829 -0
- package/src/edit/director/continuity.js +137 -0
- package/src/edit/director/custom-motion.js +88 -0
- package/src/edit/director/graphics.js +186 -0
- package/src/edit/director/intent.js +125 -0
- package/src/edit/director/mentions.js +52 -0
- package/src/edit/director/plan.js +89 -12
- package/src/edit/director/revise.js +172 -7
- package/src/edit/director/viewer.js +136 -0
- package/src/edit/director/watch-fix.js +119 -0
- package/src/edit/engine/captions.js +110 -5
- package/src/edit/engine/confine.js +81 -4
- package/src/edit/engine/custom.js +243 -0
- package/src/edit/engine/dna2.js +893 -0
- package/src/edit/engine/fonts.js +218 -0
- package/src/edit/engine/graphics.js +439 -0
- package/src/edit/engine/index.js +14 -5
- package/src/edit/engine/motion.js +153 -14
- package/src/edit/engine/music-bed.js +59 -1
- package/src/edit/engine/packs.js +11 -0
- package/src/edit/engine/reference2.js +26 -0
- package/src/edit/engine/sfx.js +56 -1
- package/src/edit/engine/tool.js +21 -5
- package/src/edit/gates/assembly.js +194 -0
- package/src/edit/gates/copy.js +7 -4
- package/src/edit/gates/index.js +76 -8
- package/src/edit/gates/picture.js +6 -3
- package/src/edit/gates/reference.js +115 -0
- package/src/edit/gates/tile.js +96 -0
- package/src/edit/host/client.js +4 -3
- package/src/edit/host/clips.js +33 -0
- package/src/edit/host/jobs.js +9 -3
- package/src/edit/host/layers.js +134 -0
- package/src/edit/host/main.js +17 -7
- package/src/edit/host/paths.js +34 -3
- package/src/edit/host/preview.js +108 -0
- package/src/edit/host/projects.js +494 -29
- package/src/edit/host/server.js +263 -19
- package/src/edit/host/tavi.js +77 -0
- package/src/edit/loop/make.js +44 -3
- package/src/edit/recipes/assembly.js +352 -0
- package/src/edit/recipes/graphic-clips.js +59 -0
- package/src/edit/recipes/openings.js +36 -0
- package/src/edit/recipes/reel.js +138 -17
- package/src/edit/recipes/reference-look.js +29 -0
- package/src/edit/recipes/short-from-long.js +3 -3
- package/src/edit/recipes/sound.js +71 -0
- package/src/edit/runtime/cli.js +26 -5
- package/src/edit/runtime/fetch.js +4 -3
- package/src/edit/runtime/licences.js +7 -1
- package/src/explore.js +103 -0
- package/src/failure.js +1 -1
- package/src/gate-commands.js +114 -0
- package/src/gates/api.js +127 -0
- package/src/gates/commands.js +111 -0
- package/src/gates/detectors.js +370 -0
- package/src/gates/http.js +62 -0
- package/src/gates/index.js +196 -0
- package/src/gates/page.js +264 -0
- package/src/gates/sast.js +64 -0
- package/src/gates/stack.js +110 -0
- package/src/gates/tenant.js +162 -0
- package/src/gates/three.js +407 -0
- package/src/gates/ui.js +111 -0
- package/src/launch.js +15 -3
- package/src/loop.js +199 -7
- package/src/mcp.js +126 -0
- package/src/milestones.js +188 -0
- package/src/modes.js +32 -0
- package/src/orchestra.js +43 -0
- package/src/outcomes.js +88 -0
- package/src/profiles.js +5 -0
- package/src/receipts.js +238 -0
- package/src/release.js +356 -0
- package/src/runstrip.js +122 -0
- package/src/stack.js +120 -0
- package/src/verify.js +67 -20
- package/studio/dist/fonts/fraunces.woff2 +0 -0
- package/studio/dist/fonts/geist.woff2 +0 -0
- package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
- package/studio/dist/studio.css +452 -3
- package/studio/dist/studio.js +3 -3
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
// Harness 2.0 W3: the fixed static detectors (Kriya-Tavi docs/kriya-harness/
|
|
2
|
+
// upgrade_2.0/CARTRIDGES.md §3–4, GATES.md G-DETECT). Each is plain code over
|
|
3
|
+
// one changed file: its path, its full text and the lines this work added.
|
|
4
|
+
// Findings point at added lines only, so code the project already had is
|
|
5
|
+
// never blamed. No detector runs anything, reads the network or takes a
|
|
6
|
+
// pattern from data: cartridges only name them by id, with a severity.
|
|
7
|
+
// Heuristic ones are warnings (feedback to the builder), never failures,
|
|
8
|
+
// unless a cartridge gives them severity "error".
|
|
9
|
+
|
|
10
|
+
const EXT = (re) => (path) => re.test(path)
|
|
11
|
+
const css = EXT(/\.(css|scss|sass|less)$/)
|
|
12
|
+
const ui = EXT(/\.(tsx|jsx|vue|svelte)$/)
|
|
13
|
+
const js = EXT(/\.(m?[jt]sx?|cjs)$/)
|
|
14
|
+
const py = EXT(/\.py$/)
|
|
15
|
+
const sql = EXT(/\.sql$/)
|
|
16
|
+
const tests = (path) => /(^|\/)(tests?|__tests__|spec|e2e)\//.test(path) || /\.(test|spec)\.[^/]+$/.test(path) || /(^|\/)test_[^/]+\.py$/.test(path)
|
|
17
|
+
const mobile = EXT(/\.(swift|kt|java|dart)$/)
|
|
18
|
+
const iac = EXT(/\.(tf|tfvars|json|ya?ml)$/)
|
|
19
|
+
const tokensFile = (path) => /(^|\/)(tokens|design-tokens|theme|globals|variables|colors?)\.[^/]+$/i.test(path)
|
|
20
|
+
const commentLine = (text) => /^\s*(\/\/|#|\*|\/\*|--|<!--)/.test(text)
|
|
21
|
+
|
|
22
|
+
/** Lines matching `re` among the added ones, as findings with `why`. */
|
|
23
|
+
const onAdded = (file, re, why, skip = commentLine) =>
|
|
24
|
+
file.added.filter(({ text }) => !skip(text) && re.test(text)).map(({ line }) => ({ line, why }))
|
|
25
|
+
|
|
26
|
+
/** The 1-based line of a character offset. */
|
|
27
|
+
const lineAt = (content, index) => content.slice(0, index).split("\n").length
|
|
28
|
+
|
|
29
|
+
/** Matches of a multi-line pattern whose first line was added. */
|
|
30
|
+
function onAddedSpans(file, re, why, keep = () => true) {
|
|
31
|
+
const added = new Set(file.added.map((a) => a.line))
|
|
32
|
+
const out = []
|
|
33
|
+
for (const m of file.content.matchAll(re)) {
|
|
34
|
+
const line = lineAt(file.content, m.index)
|
|
35
|
+
if (added.has(line) && keep(m)) out.push({ line, why })
|
|
36
|
+
}
|
|
37
|
+
return out
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const shannon = (s) => {
|
|
41
|
+
const counts = new Map()
|
|
42
|
+
for (const c of s) counts.set(c, (counts.get(c) ?? 0) + 1)
|
|
43
|
+
let h = 0
|
|
44
|
+
for (const n of counts.values()) h -= (n / s.length) * Math.log2(n / s.length)
|
|
45
|
+
return h
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 1-based line numbers inside the blocks whose opening line matches `header` (the callback's body). */
|
|
49
|
+
function blockLines(content, header) {
|
|
50
|
+
const lines = content.split("\n")
|
|
51
|
+
const hot = new Set()
|
|
52
|
+
for (let i = 0; i < lines.length; i++) {
|
|
53
|
+
if (!header.test(lines[i]) || !lines[i].includes("{")) continue
|
|
54
|
+
let depth = 0
|
|
55
|
+
for (let j = i; j < lines.length; j++) {
|
|
56
|
+
depth += (lines[j].match(/\{/g) ?? []).length - (lines[j].match(/\}/g) ?? []).length
|
|
57
|
+
if (j > i) hot.add(j + 1)
|
|
58
|
+
if (depth <= 0 && j > i) break
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return hot
|
|
62
|
+
}
|
|
63
|
+
const ANIMATION = /\b(function\s+(animate|render|tick|loop|frame)\b|(animate|render|tick|loop|frame)\s*=\s*(async\s*)?(\([^)]*\)|\w+)\s*=>|setAnimationLoop\s*\(|useFrame\s*\(|requestAnimationFrame\s*\()/
|
|
64
|
+
const GPU_RESOURCE = /\bnew\s+(THREE\.)?(\w*Geometry|\w*Material|\w*Texture|WebGLRenderTarget|WebGLRenderer)\s*\(|\bTextureLoader\s*\(\s*\)\s*\.load\s*\(/
|
|
65
|
+
const ASSET = /(^|\/)(assets|public|static|models|textures|hdri|media)\/.*\.(glb|gltf|hdr|exr|ktx2|png|jpe?g)$/i
|
|
66
|
+
|
|
67
|
+
/** Detector id → { files, find(file) }; `file` = { path, content, added: [{ line, text }] }. */
|
|
68
|
+
export const DETECTORS = {
|
|
69
|
+
"FE-HEX": {
|
|
70
|
+
files: (p) => (ui(p) || css(p)) && !tokensFile(p),
|
|
71
|
+
find: (f) => onAdded(f, /(?<![\w&/])#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b(?![\w-])/, "a raw colour value; use a design token"),
|
|
72
|
+
},
|
|
73
|
+
"FE-PX": {
|
|
74
|
+
files: (p) => (ui(p) || css(p)) && !tokensFile(p),
|
|
75
|
+
find: (f) =>
|
|
76
|
+
f.added
|
|
77
|
+
.filter(({ text }) => !commentLine(text))
|
|
78
|
+
.flatMap(({ line, text }) =>
|
|
79
|
+
[...text.matchAll(/\b(margin|padding|gap|top|left|right|bottom|inset)[\w-]*\s*:\s*['"]?([^;'"}]*)/gi)].flatMap((m) =>
|
|
80
|
+
[...m[2].matchAll(/(\d+)px/g)].filter((n) => Number(n[1]) > 2 && Number(n[1]) % 4 !== 0).map(() => ({ line, why: "spacing off the 4 px grid" }))
|
|
81
|
+
)
|
|
82
|
+
),
|
|
83
|
+
},
|
|
84
|
+
"FE-IMG-ALT": {
|
|
85
|
+
files: ui,
|
|
86
|
+
find: (f) => onAddedSpans(f, /<img\b[^>]*>/g, "an image without alt", (m) => !/\balt\s*=/.test(m[0])),
|
|
87
|
+
},
|
|
88
|
+
"FE-CLICK-DIV": {
|
|
89
|
+
files: ui,
|
|
90
|
+
find: (f) => onAddedSpans(f, /<(div|span|li|td)\b[^>]*\bonClick\s*=[^>]*>/g, "a click handler on a non-interactive element without a role and a key handler", (m) => !(/\brole\s*=/.test(m[0]) && /\bonKey(Down|Up|Press)\s*=/.test(m[0]))),
|
|
91
|
+
},
|
|
92
|
+
"FE-FETCH-EFFECT": {
|
|
93
|
+
files: (p) => ui(p) || js(p),
|
|
94
|
+
find: (f) => (/useEffect\s*\(/.test(f.content) && !/AbortController|signal\s*:/.test(f.content) ? onAdded(f, /\bfetch\s*\(/, "a fetch in an effect that can't be cancelled") : []),
|
|
95
|
+
},
|
|
96
|
+
"FE-GLASS-CONTENT": {
|
|
97
|
+
files: css,
|
|
98
|
+
find: (f) => onAddedSpans(f, /([^{}]*)\{[^{}]*backdrop-filter[^{}]*\}/g, "glass behind content; keep it for controls and navigation", (m) => /\b(article|prose|content|post|paragraph|body-text)\b/i.test(m[1])),
|
|
99
|
+
},
|
|
100
|
+
"FE-GLASS-FALLBACK": {
|
|
101
|
+
files: (p) => css(p) || ui(p),
|
|
102
|
+
find: (f) => {
|
|
103
|
+
if (!f.added.some(({ text }) => /backdrop-filter\s*:/.test(text))) return []
|
|
104
|
+
const missing = [
|
|
105
|
+
[/prefers-reduced-transparency/, "prefers-reduced-transparency"],
|
|
106
|
+
[/prefers-contrast/, "prefers-contrast"],
|
|
107
|
+
[/@supports\s+not\s*\(\s*(-webkit-)?backdrop-filter/, "@supports not (backdrop-filter)"],
|
|
108
|
+
].filter(([re]) => !re.test(f.content))
|
|
109
|
+
if (!missing.length) return []
|
|
110
|
+
const line = f.added.find(({ text }) => /backdrop-filter\s*:/.test(text)).line
|
|
111
|
+
return [{ line, why: `glass without its solid fallbacks: ${missing.map(([, n]) => n).join(", ")}` }]
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
"FE-TROPE": {
|
|
115
|
+
files: (p) => ui(p) || /\.(html|md|mdx)$/.test(p),
|
|
116
|
+
find: (f) => [
|
|
117
|
+
...onAdded(f, /\blorem ipsum\b/i, "placeholder text", () => false),
|
|
118
|
+
...onAdded(f, />\s*\p{Extended_Pictographic}\s*</u, "an emoji used as an icon", () => false),
|
|
119
|
+
],
|
|
120
|
+
},
|
|
121
|
+
"FE-FONT-LICENCE": {
|
|
122
|
+
files: EXT(/\.(woff2?|ttf|otf)$/),
|
|
123
|
+
find: (f) => (f.isNew && !f.siblings.some((n) => /^(OFL|LICEN[CS]E|COPYING)/i.test(n)) ? [{ line: 1, why: "a font file without its licence beside it" }] : []),
|
|
124
|
+
},
|
|
125
|
+
// Harness 2.0 W13 (WD-17; THREE_D_AND_CREATIVE.md §2): graphics
|
|
126
|
+
"GX-COLOR": {
|
|
127
|
+
files: js,
|
|
128
|
+
find: (f) =>
|
|
129
|
+
/\boutputColorSpace\b|\boutputEncoding\b/.test(f.content) && /\btoneMapping\s*=/.test(f.content)
|
|
130
|
+
? []
|
|
131
|
+
: onAdded(f, /\bnew\s+(THREE\.)?WebGL(GPU)?Renderer\s*\(/, "a renderer with no output colour space or tone mapping set; set renderer.outputColorSpace and one renderer.toneMapping"),
|
|
132
|
+
},
|
|
133
|
+
"GX-ALLOC-LOOP": {
|
|
134
|
+
files: js,
|
|
135
|
+
find: (f) => {
|
|
136
|
+
const hot = blockLines(f.content, ANIMATION)
|
|
137
|
+
return f.added
|
|
138
|
+
.filter(({ line, text }) => hot.has(line) && !commentLine(text) && /\bnew\s+(THREE\.\w+|Vector[234]|Matrix[34]|Quaternion|Color|Euler|Box3|Sphere|Ray|Raycaster)\s*\(/.test(text))
|
|
139
|
+
.map(({ line }) => ({ line, why: "an allocation in the animation callback; create it once outside and reuse it" }))
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
"GX-NO-DISPOSE": {
|
|
143
|
+
files: js,
|
|
144
|
+
find: (f) => {
|
|
145
|
+
if (/\.dispose\s*\(/.test(f.content)) return []
|
|
146
|
+
const first = f.added.find(({ text }) => !commentLine(text) && GPU_RESOURCE.test(text))
|
|
147
|
+
return first ? [{ line: first.line, why: "GPU resources created with no dispose path; dispose geometries, materials, textures and targets on unmount" }] : []
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
"GX-DPR": {
|
|
151
|
+
files: js,
|
|
152
|
+
find: (f) => onAdded(f, /setPixelRatio\s*\((?![^)]*\b(Math\.min|min|clamp)\s*\()[^)]*\bdevicePixelRatio\b/, "the pixel ratio follows devicePixelRatio uncapped; use Math.min(devicePixelRatio, the tier's cap)"),
|
|
153
|
+
},
|
|
154
|
+
"FE-ASSET-LICENCE": {
|
|
155
|
+
files: (p) => ASSET.test(p),
|
|
156
|
+
find: (f) => (f.isNew && !f.assetLicensed(f.path) ? [{ line: 1, why: "a new asset with no entry in scene_direction.json assets (path, licence, source)" }] : []),
|
|
157
|
+
},
|
|
158
|
+
"BE-SQL-INTERP": {
|
|
159
|
+
files: (p) => js(p) || py(p),
|
|
160
|
+
find: (f) => [
|
|
161
|
+
...onAddedSpans(f, /(\w*\.?)`[^`]*\b(SELECT|INSERT|UPDATE|DELETE)\b[^`]*\$\{[^`]*`/gi, "SQL built by string interpolation; use parameters", (m) => !/sql$/i.test(m[1])),
|
|
162
|
+
...onAdded(f, /\bf["'][^"']*\b(SELECT|INSERT|UPDATE|DELETE)\b[^"']*\{/i, "SQL built with an f-string; use parameters"),
|
|
163
|
+
...onAdded(f, /["'][^"']*\b(SELECT|INSERT|UPDATE|DELETE)\b[^"']*["']\s*\+\s*\w/i, "SQL built by concatenation; use parameters"),
|
|
164
|
+
],
|
|
165
|
+
},
|
|
166
|
+
"BE-EMPTY-CATCH": {
|
|
167
|
+
files: (p) => js(p) || py(p) || /\.(java|kt|cs)$/.test(p),
|
|
168
|
+
find: (f) => {
|
|
169
|
+
const out = onAdded(f, /\bcatch\s*(\([^)]*\))?\s*\{\s*\}/, "an empty catch: the error disappears")
|
|
170
|
+
const lines = f.content.split("\n")
|
|
171
|
+
for (const { line, text } of f.added)
|
|
172
|
+
if (/^\s*except\b[^:]*:\s*(pass)?\s*$/.test(text) && (/:\s*pass\s*$/.test(text) || /^\s*pass\s*$/.test(lines[line] ?? ""))) out.push({ line, why: "an except that only passes: the error disappears" })
|
|
173
|
+
return out
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
"BE-NO-TIMEOUT": {
|
|
177
|
+
files: js,
|
|
178
|
+
find: (f) => (/AbortSignal\.timeout|signal\s*:|timeout\s*:/.test(f.content) ? [] : onAdded(f, /\b(fetch|axios\.(get|post|put|patch|delete))\s*\(/, "an outbound call without a timeout or signal")),
|
|
179
|
+
},
|
|
180
|
+
"BE-LOG-SECRET": {
|
|
181
|
+
files: (p) => js(p) || py(p),
|
|
182
|
+
find: (f) => onAdded(f, /\b(console\.(log|info|warn|error|debug)|log(ger)?\.(info|warn|error|debug)|print)\s*\([^)]*\b(password|passwd|secret|api[_-]?key|apiKey|private[_-]?key|access[_-]?token|accessToken|refresh[_-]?token|refreshToken|auth[_-]?token|authToken)\b/i, "a log line that may print a secret"),
|
|
183
|
+
},
|
|
184
|
+
"FS-DTO-DUP": {
|
|
185
|
+
files: EXT(/\.tsx?$/),
|
|
186
|
+
find: (f) => {
|
|
187
|
+
const mine = new Set([...f.content.matchAll(/export\s+(?:interface|type)\s+(\w+)/g)].map((m) => m[1]))
|
|
188
|
+
const dup = [...mine].filter((name) => f.others.some((o) => o.path !== f.path && new RegExp(`export\\s+(?:interface|type)\\s+${name}\\b`).test(o.content)))
|
|
189
|
+
return dup.flatMap((name) => onAdded(f, new RegExp(`export\\s+(?:interface|type)\\s+${name}\\b`), `${name} is declared in two files; generate one from the contract`))
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
"MB-SYNC-IO": {
|
|
193
|
+
files: mobile,
|
|
194
|
+
find: (f) => onAdded(f, /\b(Data|String)\(contentsOf:|readAsStringSync\(|readAsBytesSync\(|\.execute\(\)\s*;?\s*$/, "synchronous I/O that can block the main thread"),
|
|
195
|
+
},
|
|
196
|
+
"MB-HARDCODE-DIM": {
|
|
197
|
+
files: mobile,
|
|
198
|
+
find: (f) => onAdded(f, /\b(width|height)\s*[:=(]\s*(320|360|375|390|393|412|414|428|430|768|812|844|852|896|926|932|1024)\b/, "a hard-coded screen dimension"),
|
|
199
|
+
},
|
|
200
|
+
"GM-ALLOC-TICK": {
|
|
201
|
+
files: (p) => js(p) || /\.(cs|cpp|cc|rs)$/.test(p),
|
|
202
|
+
find: (f) => {
|
|
203
|
+
const lines = f.content.split("\n")
|
|
204
|
+
const hot = new Set()
|
|
205
|
+
for (let i = 0; i < lines.length; i++) {
|
|
206
|
+
if (!/\b(update|tick|fixedUpdate|onFrame|step)\s*\([^)]*\)\s*(:\s*[\w<>[\]]+\s*)?\{/.test(lines[i])) continue
|
|
207
|
+
let depth = 0
|
|
208
|
+
for (let j = i; j < lines.length; j++) {
|
|
209
|
+
depth += (lines[j].match(/\{/g) ?? []).length - (lines[j].match(/\}/g) ?? []).length
|
|
210
|
+
if (j > i) hot.add(j + 1)
|
|
211
|
+
if (depth <= 0 && j > i) break
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return f.added.filter(({ line, text }) => hot.has(line) && !commentLine(text) && /\bnew\s+[A-Z]\w*\s*\(|=\s*\[\s*\]|=\s*\{\s*\}/.test(text)).map(({ line }) => ({ line, why: "an allocation in the per-frame loop; pool it" }))
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
"GM-DT-MISSING": {
|
|
218
|
+
files: (p) => js(p) || /\.(cs|gd|cpp|rs)$/.test(p),
|
|
219
|
+
find: (f) => onAdded(f, /\.(x|y|z)\s*[+-]=\s*[^;\n]*\b(speed|velocity|vel)\b(?![^;\n]*\b(dt|delta|deltaTime|elapsed|frameTime)\b)/, "movement without the timestep"),
|
|
220
|
+
},
|
|
221
|
+
"OPS-LATEST": {
|
|
222
|
+
files: (p) => /(^|\/)(Dockerfile|[^/]*\.dockerfile)$/i.test(p) || /(^|\/)docker-compose[^/]*\.ya?ml$/.test(p),
|
|
223
|
+
find: (f) => {
|
|
224
|
+
const stages = new Set([...f.content.matchAll(/^\s*FROM\s+\S+\s+AS\s+(\S+)/gim)].map((m) => m[1].toLowerCase()))
|
|
225
|
+
return f.added.flatMap(({ line, text }) => {
|
|
226
|
+
const from = /^\s*FROM\s+(?:--\S+\s+)*(\S+)/i.exec(text)?.[1]
|
|
227
|
+
const image = from ?? /^\s*image:\s*["']?([^"'\s]+)/.exec(text)?.[1]
|
|
228
|
+
if (!image || image === "scratch" || stages.has(image.toLowerCase()) || image.startsWith("$")) return []
|
|
229
|
+
if (image.includes("@sha256:")) return []
|
|
230
|
+
const tag = /:([^/]+)$/.exec(image)?.[1]
|
|
231
|
+
return !tag || tag === "latest" ? [{ line, why: `${image} isn't pinned to a version` }] : []
|
|
232
|
+
})
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
"OPS-SECRET-ENV": {
|
|
236
|
+
files: (p) => /(^|\/)(Dockerfile|[^/]*\.dockerfile)$/i.test(p) || /(^|\/)\.github\/workflows\/|\.gitlab-ci\.yml$|(^|\/)render\.yaml$|docker-compose[^/]*\.ya?ml$/.test(p),
|
|
237
|
+
find: (f) => [
|
|
238
|
+
...onAdded(f, /^\s*(ENV|ARG)\s+\w*(SECRET|TOKEN|PASSWORD|PASSWD|API_?KEY|PRIVATE_?KEY)\w*[= ]\s*\S+/i, "a secret given a value in the image"),
|
|
239
|
+
...onAdded(f, /\b\w*(secret|token|password|api_?key)\w*\s*:\s*["']?(?!\$\{\{)[A-Za-z0-9_\-/+=]{12,}["']?\s*$/i, "a secret written in a CI or deploy file"),
|
|
240
|
+
],
|
|
241
|
+
},
|
|
242
|
+
"OPS-MIGRATE-LOCK": {
|
|
243
|
+
files: sql,
|
|
244
|
+
find: (f) => [
|
|
245
|
+
...onAdded(f, /\badd\s+column\b(?![^;]*\bdefault\b)[^;]*\bnot\s+null\b/i, "a NOT NULL column without a default locks and fails on a filled table"),
|
|
246
|
+
...onAdded(f, /\bcreate\s+(unique\s+)?index\b(?!\s+concurrently)/i, "an index built without CONCURRENTLY locks writes"),
|
|
247
|
+
],
|
|
248
|
+
},
|
|
249
|
+
"CL-IAM-STAR": {
|
|
250
|
+
files: iac,
|
|
251
|
+
find: (f) => onAdded(f, /["']?(Action|Resource|actions|resources)["']?\s*[:=]\s*(\[\s*)?["']\*["']/, "a wildcard permission"),
|
|
252
|
+
},
|
|
253
|
+
"CL-PUBLIC": {
|
|
254
|
+
files: iac,
|
|
255
|
+
find: (f) => {
|
|
256
|
+
const out = onAdded(f, /\bpublicly_accessible\s*=\s*true\b|\bacl\s*=\s*["']public-read(-write)?["']|\bblock_public_(acls|policy)\s*=\s*false\b/, "a publicly reachable data store")
|
|
257
|
+
const lines = f.content.split("\n")
|
|
258
|
+
for (const { line, text } of f.added) {
|
|
259
|
+
if (!/0\.0\.0\.0\/0/.test(text)) continue
|
|
260
|
+
const block = lines.slice(Math.max(0, line - 8), line + 8).join("\n")
|
|
261
|
+
const ports = [...block.matchAll(/\b(from_port|to_port|port)\s*=\s*(\d+)/g)].map((m) => Number(m[2]))
|
|
262
|
+
if (/\bingress\b/.test(block) && ports.some((p) => p !== 80 && p !== 443)) out.push({ line, why: "ingress from anywhere on a non-web port" })
|
|
263
|
+
}
|
|
264
|
+
return out
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
"SY-UNSAFE-NOCOMMENT": {
|
|
268
|
+
files: EXT(/\.rs$/),
|
|
269
|
+
find: (f) => {
|
|
270
|
+
const lines = f.content.split("\n")
|
|
271
|
+
return f.added.filter(({ line, text }) => /\bunsafe\s*\{/.test(text) && !lines.slice(Math.max(0, line - 4), line - 1).some((l) => /SAFETY:/.test(l))).map(({ line }) => ({ line, why: "an unsafe block without a SAFETY: comment" }))
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
"SY-SPIN": {
|
|
275
|
+
files: EXT(/\.(rs|c|cc|cpp|h|hpp|go|java|m?[jt]s)$/),
|
|
276
|
+
find: (f) => onAdded(f, /\bwhile\s*\(.*\)\s*(\{\s*\}|;)\s*$|\bloop\s*\{\s*\}|\bfor\s*\(\s*;\s*;\s*\)\s*\{\s*\}/, "a busy wait without backoff"),
|
|
277
|
+
},
|
|
278
|
+
"DT-INSERT-NOKEY": {
|
|
279
|
+
files: (p) => /(^|\/)(dags|pipelines?|etl|jobs|models)\//.test(p) && (sql(p) || py(p)),
|
|
280
|
+
find: (f) => onAddedSpans(f, /\binsert\s+into\b[^;]*;?/gi, "an insert a retry would repeat; upsert or merge on a key", (m) => !/\bon\s+conflict\b|\bmerge\b/i.test(m[0])),
|
|
281
|
+
},
|
|
282
|
+
"ML-FIT-TEST": {
|
|
283
|
+
files: (p) => py(p) || /\.ipynb$/.test(p),
|
|
284
|
+
find: (f) => onAdded(f, /\.(fit|fit_transform|partial_fit)\s*\([^)]*\b(X_test|x_test|test_x|test_X|test_data|test_df|test_set|y_test)\b/, "fitting on the test split"),
|
|
285
|
+
},
|
|
286
|
+
"ML-SEED": {
|
|
287
|
+
files: (p) => /(^|\/)(train|training|eval|evaluate)[^/]*\.py$/.test(p),
|
|
288
|
+
find: (f) => (f.isNew && !/random_state|manual_seed|set_seed|np\.random\.seed|random\.seed|seed\s*=/.test(f.content) ? [{ line: 1, why: "a training or evaluation entry point without a fixed seed" }] : []),
|
|
289
|
+
},
|
|
290
|
+
"SEC-BODY-ID": {
|
|
291
|
+
files: (p) => js(p) || py(p),
|
|
292
|
+
find: (f) => onAdded(f, /\b(req\.body|req\.query|req\.params|request\.json\(\)|request\.args|request\.form|searchParams\.get\(|body)\W{1,3}["']?(user_?id|tenant_?id|userId|tenantId|org_?id|orgId|owner_?id|ownerId)\b/, "an owner or tenant id taken from the request; take it from the verified session"),
|
|
293
|
+
},
|
|
294
|
+
"SEC-EVAL": {
|
|
295
|
+
files: (p) => js(p) || py(p),
|
|
296
|
+
find: (f) => [
|
|
297
|
+
...onAdded(f, /(?<![\w.])(eval|exec)\s*\(|\bnew\s+Function\s*\(/, "code built from strings at run time"),
|
|
298
|
+
...onAdded(f, /\b(child_process\.)?(exec|execSync)\s*\(\s*`[^`]*\$\{|\bos\.system\s*\(\s*f["']|\bsubprocess\.\w+\([^)]*shell\s*=\s*True/, "a shell command built from input"),
|
|
299
|
+
],
|
|
300
|
+
},
|
|
301
|
+
"QA-ONLY": {
|
|
302
|
+
files: tests,
|
|
303
|
+
find: (f) => onAdded(f, /\b(it|test|describe|context)\.only\s*\(|\bf(it|describe)\s*\(/, "a focused test that silences the rest"),
|
|
304
|
+
},
|
|
305
|
+
"QA-SKIP": {
|
|
306
|
+
files: tests,
|
|
307
|
+
find: (f) => onAdded(f, /\b(it|test|describe)\.skip\s*\(|\bx(it|describe)\s*\(|@pytest\.mark\.skip|\bt\.Skip\(/, "a newly skipped test"),
|
|
308
|
+
},
|
|
309
|
+
"SD-SLEEP": {
|
|
310
|
+
files: tests,
|
|
311
|
+
find: (f) => onAdded(f, /\bwaitForTimeout\s*\(|\btime\.sleep\s*\(|\bThread\.sleep\s*\(|\bawait\s+sleep\s*\(|new\s+Promise\s*\(\s*\(?\s*\w+\s*\)?\s*=>\s*setTimeout\s*\(/, "a fixed sleep in a test; wait for a condition"),
|
|
312
|
+
},
|
|
313
|
+
"SD-XPATH": {
|
|
314
|
+
files: tests,
|
|
315
|
+
find: (f) => onAdded(f, /xpath=|["']\/\/\w+\[|:nth-child\(|["']\/html\/body/, "a brittle selector; use role, label or test id"),
|
|
316
|
+
},
|
|
317
|
+
"DB-NO-RLS": {
|
|
318
|
+
files: sql,
|
|
319
|
+
find: (f) =>
|
|
320
|
+
onAddedSpans(f, /\bcreate\s+table\s+(?:if\s+not\s+exists\s+)?([\w."]+)/gi, "a table without row-level security in the same migration", (m) => {
|
|
321
|
+
const name = m[1].replace(/"/g, "")
|
|
322
|
+
if (!f.tenantTables(name)) return false
|
|
323
|
+
const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
324
|
+
return !new RegExp(`alter\\s+table\\s+(only\\s+)?"?${esc.replace(/\\\./g, '"?\\."?')}"?\\s+enable\\s+row\\s+level\\s+security`, "i").test(f.content)
|
|
325
|
+
}),
|
|
326
|
+
},
|
|
327
|
+
"DB-FK-NOINDEX": {
|
|
328
|
+
files: sql,
|
|
329
|
+
find: (f) =>
|
|
330
|
+
f.added.flatMap(({ line, text }) => {
|
|
331
|
+
const col = /^\s*"?(\w+)"?\s+[\w ()]+\breferences\b/i.exec(text)?.[1]
|
|
332
|
+
if (!col) return []
|
|
333
|
+
return new RegExp(`create\\s+(unique\\s+)?index[^;]*\\(\\s*"?${col}"?`, "i").test(f.content) ? [] : [{ line, why: `the foreign key ${col} has no index` }]
|
|
334
|
+
}),
|
|
335
|
+
},
|
|
336
|
+
"DB-DROP": {
|
|
337
|
+
files: sql,
|
|
338
|
+
find: (f) => onAdded(f, /\bdrop\s+(table|column)\b|\balter\s+column\s+\w+\s+(set\s+data\s+)?type\b/i, "a destructive change; plan it in two releases"),
|
|
339
|
+
},
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** High-entropy secrets and known key shapes on added lines (G-SECRETS); the value itself is never returned. */
|
|
343
|
+
export const SECRET_RULES = [
|
|
344
|
+
["an AWS access key", /\bAKIA[0-9A-Z]{16}\b/],
|
|
345
|
+
["a GitHub token", /\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})\b/],
|
|
346
|
+
["a Slack token", /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/],
|
|
347
|
+
["a Stripe live key", /\b(sk|rk)_live_[A-Za-z0-9]{20,}\b/],
|
|
348
|
+
["a Google API key", /\bAIza[0-9A-Za-z_-]{35}\b/],
|
|
349
|
+
["an Anthropic or OpenAI key", /\bsk-(ant-)?[A-Za-z0-9_-]{32,}\b/],
|
|
350
|
+
["a private key", /-----BEGIN ([A-Z]+ )?PRIVATE KEY-----/],
|
|
351
|
+
["a JSON web token", /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/],
|
|
352
|
+
]
|
|
353
|
+
const SECRET_ASSIGN = /\b\w*(secret|token|password|passwd|api[_-]?key|private[_-]?key|access[_-]?key)\w*["']?\s*[:=]\s*["']([^"'\s]{32,})["']/i
|
|
354
|
+
const NOT_SECRETS = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|go\.sum)$|\.min\.(js|css)$|\.(png|jpe?g|gif|webp|woff2?|ttf|otf|ico|pdf|zip|gz)$/
|
|
355
|
+
|
|
356
|
+
/** @param {{ path: string, added: Array<{ line: number, text: string }> }} file */
|
|
357
|
+
export function findSecrets(file) {
|
|
358
|
+
if (NOT_SECRETS.test(file.path)) return []
|
|
359
|
+
const out = []
|
|
360
|
+
if (/(^|\/)\.env(\.[\w-]+)?$/.test(file.path) && !/\.(example|sample|template)$/.test(file.path)) out.push({ line: 1, why: "an environment file is in the changes; keep it out of git" })
|
|
361
|
+
for (const { line, text } of file.added) {
|
|
362
|
+
const rule = SECRET_RULES.find(([, re]) => re.test(text))
|
|
363
|
+
if (rule) out.push({ line, why: rule[0] })
|
|
364
|
+
else {
|
|
365
|
+
const m = SECRET_ASSIGN.exec(text)
|
|
366
|
+
if (m && shannon(m[2]) >= 4.5 && !/^\$\{|^process\.env|^os\.environ|^<|^your[_-]|^xxx|^changeme/i.test(m[2])) out.push({ line, why: "a high-entropy secret value" })
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return out
|
|
370
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { localUrl } from "../browser.js"
|
|
2
|
+
|
|
3
|
+
// Harness 2.0 W5: the only way the API and tenant gates reach an app
|
|
4
|
+
// (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md rule 4). Every URL must
|
|
5
|
+
// pass the agent browser's loopback rule; redirects are never followed (a 3xx
|
|
6
|
+
// is just the answer); each request is time-boxed and each gate run has a
|
|
7
|
+
// request budget, so a gate can't flood even the person's own app.
|
|
8
|
+
|
|
9
|
+
export const REQUEST_MS = 10_000
|
|
10
|
+
export const BUDGET = 80
|
|
11
|
+
|
|
12
|
+
export class Budget {
|
|
13
|
+
constructor(limit = BUDGET) {
|
|
14
|
+
this.left = limit
|
|
15
|
+
}
|
|
16
|
+
take() {
|
|
17
|
+
if (this.left <= 0) throw new Error(`the gate's request budget (${BUDGET}) ran out`)
|
|
18
|
+
this.left--
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** One request to the confirmed local app; never anything else. */
|
|
23
|
+
export async function local(base, path, { method = "GET", body, headers = {}, budget, request = fetch } = {}) {
|
|
24
|
+
const target = localUrl(new URL(path, base).href)
|
|
25
|
+
if (target.error) throw new Error(`refused ${path}: ${target.error}`)
|
|
26
|
+
budget?.take()
|
|
27
|
+
const started = performance.now()
|
|
28
|
+
let response
|
|
29
|
+
try {
|
|
30
|
+
response = await request(target.url, {
|
|
31
|
+
method,
|
|
32
|
+
redirect: "manual",
|
|
33
|
+
headers: { accept: "application/json", ...(body !== undefined && typeof body !== "string" && { "content-type": "application/json" }), ...headers },
|
|
34
|
+
...(body !== undefined && { body: typeof body === "string" ? body : JSON.stringify(body) }),
|
|
35
|
+
signal: AbortSignal.timeout(REQUEST_MS),
|
|
36
|
+
})
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { status: 0, error: String(error?.cause?.code ?? error?.name ?? error).slice(0, 80), ms: performance.now() - started }
|
|
39
|
+
}
|
|
40
|
+
const text = await response.text().catch(() => "")
|
|
41
|
+
let json
|
|
42
|
+
try {
|
|
43
|
+
json = text ? JSON.parse(text) : undefined
|
|
44
|
+
} catch {
|
|
45
|
+
// Not JSON
|
|
46
|
+
}
|
|
47
|
+
return { status: response.status, text: text.slice(0, 20_000), json, headers: response.headers, ms: performance.now() - started }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** "/orders/{id}" with { id: 7 } → "/orders/7" (values URI-encoded) */
|
|
51
|
+
export const fill = (path, values = {}) => String(path).replace(/\{(\w+)\}/g, (m, k) => (values[k] === undefined ? m : encodeURIComponent(String(values[k]))))
|
|
52
|
+
|
|
53
|
+
export const median = (xs) => {
|
|
54
|
+
if (!xs.length) return undefined
|
|
55
|
+
const s = [...xs].sort((a, b) => a - b)
|
|
56
|
+
return s[Math.floor(s.length / 2)]
|
|
57
|
+
}
|
|
58
|
+
export const p95 = (xs) => {
|
|
59
|
+
if (!xs.length) return undefined
|
|
60
|
+
const s = [...xs].sort((a, b) => a - b)
|
|
61
|
+
return s[Math.min(s.length - 1, Math.ceil(s.length * 0.95) - 1)]
|
|
62
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
|
|
5
|
+
import { contractProblems, CONTRACT_NAMES, CONTRACTS_DIR, drifted, ownedHashes } from "../contracts.js"
|
|
6
|
+
import { DETECTORS, findSecrets } from "./detectors.js"
|
|
7
|
+
import { apiGate } from "./api.js"
|
|
8
|
+
import { commandGate, dataGate, evalGate, simHeadlessGate } from "./commands.js"
|
|
9
|
+
import { sastGate } from "./sast.js"
|
|
10
|
+
import { stackGate } from "./stack.js"
|
|
11
|
+
import { tenantGate } from "./tenant.js"
|
|
12
|
+
import { threeGate } from "./three.js"
|
|
13
|
+
import { judgeA11y, judgeUi, uiReports } from "./ui.js"
|
|
14
|
+
|
|
15
|
+
// Harness 2.0 W3: the gate catalogue's runner (Kriya-Tavi docs/kriya-harness/
|
|
16
|
+
// upgrade_2.0/GATES.md). A gate is code with fixed logic; its configuration
|
|
17
|
+
// is typed data (the step's cartridge, the contracts), never a command, a
|
|
18
|
+
// pattern or a pass condition a model wrote. Gates run only after the
|
|
19
|
+
// person's own check passed; the first failing gate turns the run into a
|
|
20
|
+
// failure the builder gets back, like any other. Off unless kriya was started
|
|
21
|
+
// with --gates (KRIYA_GATES=on): off, verifyStep never calls this.
|
|
22
|
+
|
|
23
|
+
/** The gates built so far; a cartridge naming another one reads `not_checked: not built yet`. */
|
|
24
|
+
export const BUILT = ["G-CONTRACT", "G-DETECT", "G-SECRETS", "G-SAST", "G-STACK", "G-API", "G-TENANT", "G-UI", "G-A11Y", "G-DATA", "G-EVAL", "G-SAN", "G-IAC", "G-SIM", "G-SIM-HEADLESS", "G-FLAKE", "G-TRACE", "G-3D"]
|
|
25
|
+
/** Run for every step with gates on, whatever its role. */
|
|
26
|
+
export const ALWAYS = ["G-SECRETS", "G-CONTRACT"]
|
|
27
|
+
/**
|
|
28
|
+
* Gates whose `not_checked` makes a step fail instead of passing with a note.
|
|
29
|
+
* Code, never data: a cartridge or a proposal can add gates, never remove one
|
|
30
|
+
* here. A required gate counts only once the person set up what it needs
|
|
31
|
+
* (a gate's `optional` not_checked, e.g. no app confirmed, stays a note).
|
|
32
|
+
*/
|
|
33
|
+
export const REQUIRED = Object.freeze({ frontend: Object.freeze(["G-UI"]), database: Object.freeze(["G-STACK"]), security: Object.freeze(["G-TENANT"]) })
|
|
34
|
+
|
|
35
|
+
const LIMIT = 300 * 1024
|
|
36
|
+
const git = (cwd, args) =>
|
|
37
|
+
new Promise((done) => execFile("git", args, { cwd, maxBuffer: 32 * 1024 * 1024 }, (error, stdout) => done(error ? null : stdout)))
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The files this work changed (vs HEAD), with their text and the lines it
|
|
41
|
+
* added. Untracked files count as all added. Binary or huge files are listed
|
|
42
|
+
* with no text. `changed` comes from verifyStep's work tree.
|
|
43
|
+
*/
|
|
44
|
+
export async function changedFiles(root, changed) {
|
|
45
|
+
const files = []
|
|
46
|
+
for (const rel of changed) {
|
|
47
|
+
const abs = join(root, rel)
|
|
48
|
+
if (!existsSync(abs) || !statSync(abs).isFile()) continue
|
|
49
|
+
const size = statSync(abs).size
|
|
50
|
+
const siblings = readdirSync(dirname(abs))
|
|
51
|
+
const tracked = (await git(root, ["ls-files", "--error-unmatch", "--", rel])) !== null
|
|
52
|
+
if (size > LIMIT) {
|
|
53
|
+
files.push({ path: rel, content: "", added: [], isNew: !tracked, siblings })
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
const content = readFileSync(abs, "utf8")
|
|
57
|
+
let added
|
|
58
|
+
if (!tracked) added = content.split("\n").map((text, i) => ({ line: i + 1, text }))
|
|
59
|
+
else {
|
|
60
|
+
added = []
|
|
61
|
+
const diff = (await git(root, ["diff", "--no-color", "--no-ext-diff", "-U0", "HEAD", "--", rel])) ?? ""
|
|
62
|
+
let next = 0
|
|
63
|
+
for (const line of diff.split("\n")) {
|
|
64
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
|
|
65
|
+
if (hunk) next = Number(hunk[1])
|
|
66
|
+
else if (line.startsWith("+") && !line.startsWith("+++")) added.push({ line: next++, text: line.slice(1) })
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
files.push({ path: rel, content: content.includes("\u0000") ? "" : content, added: content.includes("\u0000") ? [] : added, isNew: !tracked, siblings })
|
|
70
|
+
}
|
|
71
|
+
return files
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const result = (id, status, extra = {}) => ({ id, status, ...extra })
|
|
75
|
+
|
|
76
|
+
/** G-DETECT: the cartridge's detectors on the added lines; `error` findings fail. */
|
|
77
|
+
export function detect(files, detectors, context = {}) {
|
|
78
|
+
const findings = []
|
|
79
|
+
for (const { id, severity } of detectors) {
|
|
80
|
+
const d = DETECTORS[id]
|
|
81
|
+
if (!d) continue
|
|
82
|
+
for (const f of files) {
|
|
83
|
+
if (!d.files(f.path)) continue
|
|
84
|
+
for (const hit of d.find({ ...f, others: files, tenantTables: context.tenantTables ?? (() => false), assetLicensed: context.assetLicensed ?? (() => false) })) findings.push({ id, severity, path: f.path, ...hit })
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return findings
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const where = (f) => `${f.path}:${f.line}`
|
|
91
|
+
const listed = (findings, n = 12) => findings.slice(0, n).map((f) => `- ${where(f)} ${f.id ? `${f.id}: ` : ""}${f.why}`).join("\n") + (findings.length > n ? `\n- … and ${findings.length - n} more` : "")
|
|
92
|
+
|
|
93
|
+
/** FE-ASSET-LICENCE: the asset paths scene_direction.json lists with a licence and a source. */
|
|
94
|
+
export function assetLicences(root) {
|
|
95
|
+
let listed = []
|
|
96
|
+
try {
|
|
97
|
+
listed = JSON.parse(readFileSync(join(root, CONTRACTS_DIR, "scene_direction.json"), "utf8")).assets ?? []
|
|
98
|
+
} catch {
|
|
99
|
+
// No direction: no asset is licensed
|
|
100
|
+
}
|
|
101
|
+
const paths = new Set((Array.isArray(listed) ? listed : []).filter((a) => a?.licence && a?.source).map((a) => String(a.path)))
|
|
102
|
+
return (path) => paths.has(path)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Tables that are tenant data, for DB-NO-RLS: the auth matrix's tenant-scoped
|
|
107
|
+
* resources, or every table in a Supabase project (its tables are exposed
|
|
108
|
+
* through the Data API unless RLS is on).
|
|
109
|
+
*/
|
|
110
|
+
export function tenantTables(root) {
|
|
111
|
+
let matrix = []
|
|
112
|
+
try {
|
|
113
|
+
matrix = JSON.parse(readFileSync(join(root, CONTRACTS_DIR, "auth_matrix.json"), "utf8"))
|
|
114
|
+
} catch {
|
|
115
|
+
// No matrix
|
|
116
|
+
}
|
|
117
|
+
const scoped = new Set((Array.isArray(matrix) ? matrix : []).filter((r) => r?.tenantScoped).map((r) => String(r.resource).toLowerCase()))
|
|
118
|
+
const supabase = existsSync(join(root, "supabase"))
|
|
119
|
+
return (name) => supabase || scoped.has(name.toLowerCase()) || scoped.has(name.toLowerCase().split(".").at(-1))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Two patterns: a /g one for match(), a plain one for test() (a /g regex keeps state between test calls)
|
|
123
|
+
const ACCEPTANCE = /\bAC-\d{1,3}\b/g
|
|
124
|
+
const ONE_ACCEPTANCE = /\bAC-\d{1,3}\b/
|
|
125
|
+
const PASSED = /(✔|✓|√|\bPASS(ED)?\b|\bok\b|\bpassed\b)/
|
|
126
|
+
const FAILED = /(✖|✗|✕|×|\bFAIL(ED)?\b|\bnot ok\b|\bfailed\b)/
|
|
127
|
+
|
|
128
|
+
/** G-TRACE: every AC-n named in the step's done-when has a passing test with that id in this run's output. */
|
|
129
|
+
export function trace(step, output) {
|
|
130
|
+
const ids = [...new Set(String(step?.doneWhen ?? "").match(ACCEPTANCE) ?? [])]
|
|
131
|
+
if (!ids.length) return result("G-TRACE", "not_checked", { reason: "the step's done-when names no acceptance criteria (AC-1, AC-2, …)" })
|
|
132
|
+
const lines = String(output ?? "").split("\n")
|
|
133
|
+
if (!lines.some((l) => ONE_ACCEPTANCE.test(l) && PASSED.test(l))) return result("G-TRACE", "not_checked", { reason: "the check's output doesn't list passing tests by name (use the runner's verbose or spec reporter)" })
|
|
134
|
+
const missing = ids.filter((id) => !lines.some((l) => new RegExp(`\\b${id}\\b`).test(l) && PASSED.test(l) && !FAILED.test(l)))
|
|
135
|
+
return missing.length ? result("G-TRACE", "fail", { kind: "gate", excerpt: `G-TRACE: no passing test is named for ${missing.join(", ")}. Name one test per criterion with its id, e.g. "${missing[0]}: …".` }) : result("G-TRACE", "pass")
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Runs the step's gates after a passing check, in catalogue order; stops at the first failure.
|
|
140
|
+
* @param {{ root: string, step?: { title: string, doneWhen: string }, cartridge?: { role: string, gates: string[], detectors: Array<{ id: string, severity: string }>, owns: string[] }, changed: string[], output: string, rerun: () => Promise<{ exitCode: number|null, timedOut: boolean, output: string }>, recorded?: Record<string, { sha: string }>, label: string }} input
|
|
141
|
+
* @returns {Promise<{ results: Array<{ id: string, status: string, reason?: string, kind?: string, excerpt?: string }>, failure?: { id: string, kind: string, excerpt: string }, contracts: Record<string, { sha: string, step: string }> }>}
|
|
142
|
+
*/
|
|
143
|
+
export async function runGates({ root, step, cartridge, changed, output, rerun, command, recorded = {}, label, launch, psql, request, exec }) {
|
|
144
|
+
const wanted = [...new Set([...ALWAYS, ...(cartridge?.gates ?? [])])]
|
|
145
|
+
const order = [...BUILT, ...wanted.filter((g) => !BUILT.includes(g))].filter((g) => wanted.includes(g))
|
|
146
|
+
const required = new Set(cartridge ? (REQUIRED[cartridge.role] ?? []) : [])
|
|
147
|
+
const results = []
|
|
148
|
+
let files
|
|
149
|
+
const load = async () => (files ??= await changedFiles(root, changed))
|
|
150
|
+
// One visit per route × viewport × scheme, shared by G-UI and G-A11Y
|
|
151
|
+
let ui
|
|
152
|
+
const pages = async () => (ui ??= await uiReports({ root, label, launch }))
|
|
153
|
+
for (const id of order) {
|
|
154
|
+
let r
|
|
155
|
+
if (id === "G-SECRETS") {
|
|
156
|
+
const found = (await load()).flatMap((f) => findSecrets(f).map((hit) => ({ path: f.path, ...hit })))
|
|
157
|
+
r = found.length ? result(id, "fail", { kind: "gate", excerpt: `G-SECRETS: secrets in the changes (values not shown):\n${listed(found)}\nMove them to the environment or a secret store.` }) : result(id, "pass")
|
|
158
|
+
} else if (id === "G-CONTRACT") {
|
|
159
|
+
const problems = CONTRACT_NAMES.flatMap((name) => contractProblems(root, name, { gates: BUILT }))
|
|
160
|
+
const moved = drifted(root, recorded, cartridge?.owns ?? [])
|
|
161
|
+
if (moved.length)
|
|
162
|
+
r = result(id, "fail", { kind: "contract changed", excerpt: `G-CONTRACT: ${moved.map((m) => `${m.file} ${m.removed ? "was removed" : "changed"}`).join("; ")}, but this step's role doesn't own ${moved.length === 1 ? "it" : "them"}. Build to the contract as written; if it is wrong, say so and stop instead of changing it.` })
|
|
163
|
+
else if (problems.length) r = result(id, "fail", { kind: "gate", excerpt: `G-CONTRACT:\n${problems.map((p) => `- ${p}`).join("\n")}` })
|
|
164
|
+
else r = result(id, "pass")
|
|
165
|
+
} else if (id === "G-DETECT") {
|
|
166
|
+
const found = detect(await load(), cartridge?.detectors ?? [], { tenantTables: tenantTables(root), assetLicensed: assetLicences(root) })
|
|
167
|
+
const errors = found.filter((f) => f.severity === "error")
|
|
168
|
+
const warnings = found.filter((f) => f.severity !== "error")
|
|
169
|
+
r = errors.length ? result(id, "fail", { kind: "gate", excerpt: `G-DETECT:\n${listed(errors)}${warnings.length ? `\nAlso worth fixing:\n${listed(warnings, 6)}` : ""}` }) : result(id, "pass", warnings.length ? { warnings: warnings.length, note: listed(warnings, 6) } : {})
|
|
170
|
+
} else if (id === "G-FLAKE") {
|
|
171
|
+
const runs = []
|
|
172
|
+
for (let i = 0; i < 2; i++) runs.push(await rerun())
|
|
173
|
+
const bad = runs.findIndex((x) => x.exitCode !== 0 || x.timedOut)
|
|
174
|
+
r = bad === -1 ? result(id, "pass") : result(id, "fail", { kind: "flaky", excerpt: `G-FLAKE: the check passed, then ${runs[bad].timedOut ? "timed out" : `exited ${runs[bad].exitCode}`} on run ${bad + 2} of 3 with no change. A flaky test is a bug: find the shared state, clock or race.\n${String(runs[bad].output ?? "").slice(-1500)}` })
|
|
175
|
+
} else if (id === "G-TRACE") r = trace(step, output)
|
|
176
|
+
else if (id === "G-UI") r = judgeUi(await pages())
|
|
177
|
+
else if (id === "G-A11Y") r = judgeA11y(await pages())
|
|
178
|
+
else if (id === "G-3D") r = await threeGate({ root, label, launch })
|
|
179
|
+
else if (id === "G-STACK") r = await stackGate({ root, changed, tenantTables: tenantTables(root), ...(psql && { run: psql }) })
|
|
180
|
+
else if (id === "G-API") r = await apiGate({ root, ...(request && { request }) })
|
|
181
|
+
else if (id === "G-TENANT") r = await tenantGate({ root, ...(request && { request }) })
|
|
182
|
+
else if (id === "G-SAST") r = await sastGate({ root, changed, ...(exec && { run: exec }) })
|
|
183
|
+
else if (["G-DATA", "G-EVAL", "G-SAN", "G-IAC", "G-SIM", "G-SIM-HEADLESS"].includes(id) && !command) r = result(id, "not_checked", { reason: "this check runs no command here" })
|
|
184
|
+
else if (id === "G-DATA") r = await dataGate({ root, command })
|
|
185
|
+
else if (id === "G-EVAL") r = await evalGate({ root, command, changed })
|
|
186
|
+
else if (id === "G-SAN") r = await commandGate({ root, command, gate: "san", id })
|
|
187
|
+
else if (id === "G-IAC") r = await commandGate({ root, command, gate: "iac", id })
|
|
188
|
+
else if (id === "G-SIM") r = await commandGate({ root, command, gate: "sim", id })
|
|
189
|
+
else if (id === "G-SIM-HEADLESS") r = await simHeadlessGate({ root, command })
|
|
190
|
+
else r = result(id, "not_checked", { reason: "not built yet" })
|
|
191
|
+
if (r.status === "not_checked" && !r.optional && required.has(id)) r = { ...r, status: "fail", kind: "not checked", excerpt: `${id} couldn't run (${r.reason}), and a ${cartridge.role} step needs it.` }
|
|
192
|
+
results.push(r)
|
|
193
|
+
if (r.status === "fail") return { results, failure: { id, kind: r.kind, excerpt: r.excerpt }, contracts: {} }
|
|
194
|
+
}
|
|
195
|
+
return { results, contracts: ownedHashes(root, cartridge?.owns ?? [], label) }
|
|
196
|
+
}
|