@ddtcorex/dsh-maestro-review 0.12.1 → 0.14.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.
Files changed (162) hide show
  1. package/README.md +31 -58
  2. package/cordis.patch.yml +13 -18
  3. package/lib/config-store.d.ts +9 -1
  4. package/lib/config-store.d.ts.map +1 -1
  5. package/lib/config-store.js +1 -1
  6. package/lib/config-store.js.map +1 -1
  7. package/lib/events.d.ts +5 -45
  8. package/lib/events.d.ts.map +1 -1
  9. package/lib/host-orchestrator.d.ts +128 -0
  10. package/lib/host-orchestrator.d.ts.map +1 -0
  11. package/lib/host-orchestrator.js +408 -0
  12. package/lib/host-orchestrator.js.map +1 -0
  13. package/lib/index.d.ts +7 -2
  14. package/lib/index.d.ts.map +1 -1
  15. package/lib/index.js +7 -43
  16. package/lib/index.js.map +1 -1
  17. package/lib/review-intake.d.ts +1 -1
  18. package/lib/review-intake.d.ts.map +1 -1
  19. package/lib/settings-rpc.js +1 -1
  20. package/lib/settings-rpc.js.map +1 -1
  21. package/package.json +19 -36
  22. package/src/client/index.tsx +1 -1
  23. package/src/host/augment.d.ts +3 -1
  24. package/src/host/config-store.ts +2 -2
  25. package/src/host/events.ts +5 -45
  26. package/src/host/host-orchestrator.ts +461 -0
  27. package/src/host/index.ts +7 -35
  28. package/src/host/providers/gitlab.ts +1 -1
  29. package/src/host/review-intake.ts +1 -1
  30. package/src/host/settings-rpc.ts +1 -1
  31. package/lib/ci-clone.d.ts +0 -21
  32. package/lib/ci-clone.d.ts.map +0 -1
  33. package/lib/ci-clone.js +0 -35
  34. package/lib/ci-clone.js.map +0 -1
  35. package/lib/ci-coexist.d.ts +0 -11
  36. package/lib/ci-coexist.d.ts.map +0 -1
  37. package/lib/ci-coexist.js +0 -38
  38. package/lib/ci-coexist.js.map +0 -1
  39. package/lib/gitlab-auth.d.ts +0 -11
  40. package/lib/gitlab-auth.d.ts.map +0 -1
  41. package/lib/gitlab-auth.js +0 -15
  42. package/lib/gitlab-auth.js.map +0 -1
  43. package/lib/gitlab-client.d.ts +0 -78
  44. package/lib/gitlab-client.d.ts.map +0 -1
  45. package/lib/gitlab-client.js +0 -270
  46. package/lib/gitlab-client.js.map +0 -1
  47. package/lib/govard-lint-detection.d.ts +0 -20
  48. package/lib/govard-lint-detection.d.ts.map +0 -1
  49. package/lib/govard-lint-detection.js +0 -48
  50. package/lib/govard-lint-detection.js.map +0 -1
  51. package/lib/hyva-csp-scan-tool.d.ts +0 -11
  52. package/lib/hyva-csp-scan-tool.d.ts.map +0 -1
  53. package/lib/hyva-csp-scan-tool.js +0 -193
  54. package/lib/hyva-csp-scan-tool.js.map +0 -1
  55. package/lib/hyva-theme-inspect-tool.d.ts +0 -10
  56. package/lib/hyva-theme-inspect-tool.d.ts.map +0 -1
  57. package/lib/hyva-theme-inspect-tool.js +0 -299
  58. package/lib/hyva-theme-inspect-tool.js.map +0 -1
  59. package/lib/incremental.d.ts +0 -28
  60. package/lib/incremental.d.ts.map +0 -1
  61. package/lib/incremental.js +0 -62
  62. package/lib/incremental.js.map +0 -1
  63. package/lib/layout-xml-tool.d.ts +0 -11
  64. package/lib/layout-xml-tool.d.ts.map +0 -1
  65. package/lib/layout-xml-tool.js +0 -239
  66. package/lib/layout-xml-tool.js.map +0 -1
  67. package/lib/module-check-tool.d.ts +0 -11
  68. package/lib/module-check-tool.d.ts.map +0 -1
  69. package/lib/module-check-tool.js +0 -303
  70. package/lib/module-check-tool.js.map +0 -1
  71. package/lib/orchestrator.d.ts +0 -357
  72. package/lib/orchestrator.d.ts.map +0 -1
  73. package/lib/orchestrator.js +0 -1497
  74. package/lib/orchestrator.js.map +0 -1
  75. package/lib/perf-log-stats-tool.d.ts +0 -13
  76. package/lib/perf-log-stats-tool.d.ts.map +0 -1
  77. package/lib/perf-log-stats-tool.js +0 -245
  78. package/lib/perf-log-stats-tool.js.map +0 -1
  79. package/lib/phtml-escape-scan-tool.d.ts +0 -11
  80. package/lib/phtml-escape-scan-tool.d.ts.map +0 -1
  81. package/lib/phtml-escape-scan-tool.js +0 -166
  82. package/lib/phtml-escape-scan-tool.js.map +0 -1
  83. package/lib/providers/ci-trigger.d.ts +0 -44
  84. package/lib/providers/ci-trigger.d.ts.map +0 -1
  85. package/lib/providers/ci-trigger.js +0 -150
  86. package/lib/providers/ci-trigger.js.map +0 -1
  87. package/lib/review-findings-tool.d.ts +0 -20
  88. package/lib/review-findings-tool.d.ts.map +0 -1
  89. package/lib/review-findings-tool.js +0 -39
  90. package/lib/review-findings-tool.js.map +0 -1
  91. package/lib/review-history.d.ts +0 -40
  92. package/lib/review-history.d.ts.map +0 -1
  93. package/lib/review-history.js +0 -136
  94. package/lib/review-history.js.map +0 -1
  95. package/lib/review-marker.d.ts +0 -17
  96. package/lib/review-marker.d.ts.map +0 -1
  97. package/lib/review-marker.js +0 -23
  98. package/lib/review-marker.js.map +0 -1
  99. package/lib/review-signals.d.ts +0 -17
  100. package/lib/review-signals.d.ts.map +0 -1
  101. package/lib/review-signals.js +0 -79
  102. package/lib/review-signals.js.map +0 -1
  103. package/lib/scope-split-tool.d.ts +0 -42
  104. package/lib/scope-split-tool.d.ts.map +0 -1
  105. package/lib/scope-split-tool.js +0 -108
  106. package/lib/scope-split-tool.js.map +0 -1
  107. package/lib/search-tool.d.ts +0 -15
  108. package/lib/search-tool.d.ts.map +0 -1
  109. package/lib/search-tool.js +0 -144
  110. package/lib/search-tool.js.map +0 -1
  111. package/lib/skill-provider.d.ts +0 -19
  112. package/lib/skill-provider.d.ts.map +0 -1
  113. package/lib/skill-provider.js +0 -101
  114. package/lib/skill-provider.js.map +0 -1
  115. package/lib/skills-tool.d.ts +0 -29
  116. package/lib/skills-tool.d.ts.map +0 -1
  117. package/lib/skills-tool.js +0 -185
  118. package/lib/skills-tool.js.map +0 -1
  119. package/lib/source.d.ts +0 -23
  120. package/lib/source.d.ts.map +0 -1
  121. package/lib/source.js +0 -16
  122. package/lib/source.js.map +0 -1
  123. package/lib/tool-policy.d.ts +0 -20
  124. package/lib/tool-policy.d.ts.map +0 -1
  125. package/lib/tool-policy.js +0 -42
  126. package/lib/tool-policy.js.map +0 -1
  127. package/presets/maestro-auditor.patch.yml +0 -54
  128. package/presets/maestro-coder/agent.cordis.yml +0 -223
  129. package/presets/maestro-coder/preset.yml +0 -2
  130. package/presets/maestro-reviewer.patch.yml +0 -55
  131. package/profiles/reviewer-ci/cordis.patch.yml +0 -78
  132. package/profiles/reviewer-ci/package.json +0 -19
  133. package/profiles/reviewer-ci/pnpm-lock.yaml +0 -8201
  134. package/profiles/reviewer-ci/pnpm-workspace.yaml +0 -36
  135. package/skills/dsh-native-tools/SKILL.md +0 -80
  136. package/src/host/ci-clone.ts +0 -54
  137. package/src/host/ci-coexist.ts +0 -45
  138. package/src/host/dsh-skill.d.ts +0 -72
  139. package/src/host/gitlab-auth.ts +0 -13
  140. package/src/host/gitlab-client.ts +0 -332
  141. package/src/host/govard-lint-detection.ts +0 -47
  142. package/src/host/hyva-csp-scan-tool.ts +0 -165
  143. package/src/host/hyva-theme-inspect-tool.ts +0 -258
  144. package/src/host/incremental.ts +0 -86
  145. package/src/host/layout-xml-tool.ts +0 -190
  146. package/src/host/module-check-tool.ts +0 -187
  147. package/src/host/orchestrator.ts +0 -1641
  148. package/src/host/perf-log-stats-tool.ts +0 -224
  149. package/src/host/phtml-escape-scan-tool.ts +0 -112
  150. package/src/host/providers/ci-trigger.ts +0 -168
  151. package/src/host/review-findings-tool.ts +0 -59
  152. package/src/host/review-history.ts +0 -168
  153. package/src/host/review-marker.ts +0 -25
  154. package/src/host/review-signals.ts +0 -83
  155. package/src/host/scope-split-tool.ts +0 -109
  156. package/src/host/search-tool.ts +0 -152
  157. package/src/host/skill-provider.ts +0 -94
  158. package/src/host/skills-tool.ts +0 -218
  159. package/src/host/source.ts +0 -26
  160. package/src/host/tool-policy.ts +0 -49
  161. package/templates/reviewer-project.gitlab-ci.yml +0 -93
  162. package/templates/source-project.gitlab-ci.yml +0 -48
@@ -1,224 +0,0 @@
1
- import { basename, dirname, join, resolve, sep } from 'node:path'
2
- import { readFile, realpath, stat } from 'node:fs/promises'
3
- import { spawn } from 'node:child_process'
4
- import type { Context } from '@deepseek-ai/cordis'
5
- import { defineTool } from '@deepseek-ai/dsh-tools'
6
- import z from '@deepseek-ai/schemastery'
7
-
8
- export const name='maestro-perf-log-stats-tool'
9
- export const inject=['tools']
10
- export const Config:z<{rootPath?:string}> = z.object({rootPath:z.string()})
11
- interface SC{agent?:{session?:{header?:{cwd?:string}}}}
12
- function workspaceRootFor(c:string|undefined,e:unknown):string{ if(c!==undefined) return c; const cwd=(e as SC|undefined)?.agent?.session?.header?.cwd; return typeof cwd==='string'&&cwd!==''?cwd:process.cwd()}
13
- async function isInsideRoot(r:string,t:string):Promise<boolean>{
14
- const ar=resolve(r); const rs=resolve(ar,t)
15
- if(rs!==ar && !rs.startsWith(ar+sep)) return false
16
- let realRoot:string
17
- try{ realRoot=await realpath(ar) }catch{
18
- // if root does not exist yet (e.g. .worktrees not created), fallback to lexical check only
19
- return true
20
- }
21
- let existing=rs
22
- const pending:string[]=[]
23
- while(true){
24
- let real:string
25
- try{ real=await realpath(existing) }catch(err){
26
- if((err as NodeJS.ErrnoException).code!=='ENOENT') return false
27
- const parent=dirname(existing)
28
- if(parent===existing) return false
29
- pending.unshift(basename(existing))
30
- existing=parent
31
- continue
32
- }
33
- const realTarget=pending.length>0 ? resolve(real, ...pending) : real
34
- if(realTarget!==realRoot && !realTarget.startsWith(realRoot+sep)) return false
35
- return true
36
- }
37
- }
38
- export const MAX_FILE_BYTES=2*1024*1024
39
-
40
- export function cleanJson(raw:string):string{
41
- // strip trailing ERROR line outside JSON (large audit 2.8MB case, sed '$d' before jq)
42
- // Handles both "\n ERROR audit run ..." and " ERROR audit run ..." suffix
43
- return raw.replace(/\n\s*ERROR audit run.*$/s, '').replace(/\s{2,}ERROR audit run.*$/s, '').trimEnd()
44
- }
45
-
46
- async function govardShCat(worktreePath:string, relPath:string):Promise<{text:string, bytes:number, truncated:boolean}|null>{
47
- // streaming cat var/debug/db.log server-side bounded 2MiB via govard sh
48
- // returns null on govard not found or not a govard project, caller falls back to fs
49
- return new Promise((res)=>{
50
- const child=spawn('govard', ['sh','-c', `head -c ${MAX_FILE_BYTES} "${relPath.replace(/"/g,'\\"')}" 2>/dev/null`], {cwd: worktreePath})
51
- let out=''
52
- let err=''
53
- child.stdout?.on('data',(c:Buffer)=> out+=c.toString())
54
- child.stderr?.on('data',(c:Buffer)=> err+=c.toString())
55
- child.on('error',()=> res(null))
56
- child.on('close', async (code)=>{
57
- const combined=out+err
58
- if(code!==0){
59
- // govard not found, no container, or file missing -> fallback to fs
60
- res(null)
61
- return
62
- }
63
- if(combined.includes('Error response from daemon') || combined.includes('No such container')){
64
- res(null)
65
- return
66
- }
67
- // Try to get full file size for truncated flag via fs stat (best effort)
68
- try{
69
- const abs=resolve(worktreePath, relPath)
70
- const s=await stat(abs)
71
- const truncated=s.size>MAX_FILE_BYTES
72
- const text=truncated ? out.slice(0, MAX_FILE_BYTES) : out
73
- res({text, bytes:s.size, truncated})
74
- }catch{
75
- // if stat fails (file missing or container-only file), infer from output length
76
- // but if file missing, out is empty and code was 0? head on missing returns 1, already handled
77
- // so infer truncated from size
78
- const truncated=Buffer.byteLength(out,'utf-8')>=MAX_FILE_BYTES
79
- // if out empty and code 0, file empty -> exists true with empty text; but we already filtered code !=0 for missing
80
- // For safety, if out empty and we are here, treat as exists with empty
81
- res({text:out.slice(0,MAX_FILE_BYTES), bytes:Buffer.byteLength(out,'utf-8'), truncated})
82
- }
83
- })
84
- })
85
- }
86
-
87
- async function boundedRead(p:string, worktreePath?:string, relPath?:string):Promise<{exists:boolean, text:string|null, bytes:number, truncated:boolean}>{
88
- // Prefer govard sh streaming when worktreePath+relPath supplied and govard available
89
- if(worktreePath && relPath){
90
- const via=await govardShCat(worktreePath, relPath)
91
- if(via) return {exists:true, text:via.text, bytes:via.bytes, truncated:via.truncated}
92
- }
93
- try{
94
- const s=await stat(p)
95
- if(s.size>MAX_FILE_BYTES){
96
- const b=await readFile(p)
97
- // bounded 2MiB streaming server-side cat equivalent: slice to MAX
98
- return {exists:true, text:b.toString('utf-8').slice(0,MAX_FILE_BYTES), bytes:s.size, truncated:true}
99
- }
100
- const b=await readFile(p)
101
- return {exists:true, text:b.toString('utf-8'), bytes:b.byteLength, truncated:false}
102
- }catch{ return {exists:false, text:null, bytes:0, truncated:false} }
103
- }
104
- function normalizeShape(sql:string):string{
105
- return sql.replace(/'[^']*'/g, '?').replace(/"[^"]*"/g,'?').replace(/\b\d+\b/g,'?').replace(/\s+/g,' ').trim().slice(0,200)
106
- }
107
-
108
- export function apply(ctx:Context, config:{rootPath?:string}={}):void{
109
- const configuredRoot=config.rootPath
110
- ctx.effect(()=>ctx.tools.register(defineTool({
111
- name:'maestro_perf_log_stats',
112
- description:'Parse Magento query log and profiler CSV for slow queries, n+1, cache flush storms, crawler overload.',
113
- parameters:{
114
- worktreePath:{type:'string'},
115
- queryLogPath:{type:'string'},
116
- profilerCsvPath:{type:'string'},
117
- systemLogPath:{type:'string'},
118
- debugLogPath:{type:'string'},
119
- topN:{type:'number'},
120
- repeatThreshold:{type:'number'},
121
- timeThresholdMs:{type:'number'},
122
- },
123
- output:{
124
- schema:{
125
- type:'object', additionalProperties:false,
126
- properties:{
127
- ok:{type:'boolean', required:true},
128
- slowQueries:{type:'array', required:true},
129
- nPlusOneCandidates:{type:'array', required:true},
130
- warnings:{type:'array', required:true},
131
- }
132
- },
133
- render:(_a,v:{warnings:string[]})=>[{type:'text', text: v.warnings.join('\n') || 'perf stats parsed'}],
134
- },
135
- async execute(args, exec){
136
- const rawWorktree=(args as {worktreePath?:string}).worktreePath
137
- const root=workspaceRootFor(configuredRoot, exec)
138
- if(rawWorktree!==undefined && !(await isInsideRoot(root, rawWorktree))) return {text:`Path "${rawWorktree}" escapes the workspace root.`, truncated:false} as never
139
- const worktreePath = rawWorktree ? resolve(root, rawWorktree) : root
140
- const queryLogPath=(args as {queryLogPath?:string}).queryLogPath ?? 'var/debug/db.log'
141
- const profilerCsvPath=(args as {profilerCsvPath?:string}).profilerCsvPath ?? 'artifacts/profiler/profile.csv'
142
- const topN=(args as {topN?:number}).topN ?? 10
143
- const repeatThreshold=(args as {repeatThreshold?:number}).repeatThreshold ?? 5
144
- const timeThresholdMs=(args as {timeThresholdMs?:number}).timeThresholdMs ?? 1000
145
- if(rawWorktree!==undefined && !(await isInsideRoot(root, worktreePath))){ /* already checked */ }
146
-
147
- const qLogAbs=resolve(worktreePath, queryLogPath)
148
- if(!(await isInsideRoot(worktreePath, queryLogPath)) && queryLogPath!== 'var/debug/db.log') return {text:`Path "${queryLogPath}" escapes the workspace root.`, truncated:false} as never
149
-
150
- const warnings:string[]=[]
151
- const qRead=await boundedRead(qLogAbs, worktreePath, queryLogPath)
152
- const pRead=await boundedRead(resolve(worktreePath, profilerCsvPath), worktreePath, profilerCsvPath)
153
-
154
- const inputs={
155
- queryLog:{path:queryLogPath, exists:qRead.exists, bytes:qRead.bytes, truncated:qRead.truncated},
156
- profilerCsv:{path:profilerCsvPath, exists:pRead.exists, bytes:pRead.bytes, truncated:pRead.truncated},
157
- systemLog:{path:'var/log/system.log', exists:false, bytes:0, truncated:false},
158
- debugLog:{path:'var/log/debug.log', exists:false, bytes:0, truncated:false},
159
- }
160
- if(!qRead.exists) warnings.push('query log not found — run dev:query-log:enable')
161
- if(!pRead.exists) warnings.push('profiler CSV not found')
162
- if(qRead.exists && qRead.text && qRead.text.length===0) warnings.push('query log empty')
163
- if(qRead.truncated) warnings.push(`query log truncated to ${MAX_FILE_BYTES} bytes (bounded 2MiB streaming)`)
164
- if(pRead.truncated) warnings.push(`profiler CSV truncated to ${MAX_FILE_BYTES} bytes (bounded 2MiB streaming)`)
165
- // parse db.log
166
- const shapeMap=new Map<string,{count:number, totalMs:number, maxMs:number, example:string, callers:string[]}>()
167
- if(qRead.text){
168
- const blocks=qRead.text.split(/##\s*\d+\s*##\s*QUERY/g)
169
- for(const block of blocks){
170
- if(!block.trim()) continue
171
- const sqlMatch=/SQL:\s*([^\n]+)/.exec(block)
172
- const timeMatch=/TIME:\s*([0-9.]+)/.exec(block)
173
- const traceMatch=/TRACE:\s*([\s\S]*?)(?:\n##|$)/.exec(block) // capture trace
174
- const sql=sqlMatch?sqlMatch[1].trim():null
175
- const timeSec=timeMatch? parseFloat(timeMatch[1]):0
176
- const trace=traceMatch? traceMatch[1] : block
177
- const isFrontend = /App\\Http|App\/Http|Http\.php/.test(trace)
178
- if(!sql) continue
179
- if(!isFrontend) continue
180
- const ms=timeSec*1000
181
- const shape=normalizeShape(sql)
182
- let entry=shapeMap.get(shape)
183
- if(!entry){ entry={count:0, totalMs:0, maxMs:0, example:sql, callers:[]}; shapeMap.set(shape, entry)}
184
- entry.count++
185
- entry.totalMs+=ms
186
- entry.maxMs=Math.max(entry.maxMs, ms)
187
- // extract caller
188
- const callerLine=(trace.split('\n').find(l=>l.includes('app/code'))||'').trim().slice(0,120)
189
- if(callerLine && !entry.callers.includes(callerLine)) entry.callers.push(callerLine)
190
- }
191
- }
192
- const slowQueries:Array<{query:string, shape:string, count:number, avgMs:number, maxMs:number, exampleCallerStack:string}>=[]
193
- const nPlusOneCandidates:Array<{shape:string, count:number, model:string|null, callerStack:string}>=[]
194
- for(const [shape, v] of shapeMap.entries()){
195
- const avg=v.totalMs/v.count
196
- if(v.maxMs>=timeThresholdMs || avg>=timeThresholdMs){
197
- slowQueries.push({query:shape, shape, count:v.count, avgMs:Math.round(avg), maxMs:Math.round(v.maxMs), exampleCallerStack:v.callers.join(' | ')})
198
- }
199
- if(v.count>=repeatThreshold){
200
- // infer model from caller
201
- const modelMatch=v.callers.join(' ').match(/app\/code\/[^\/]+\/[^\/]+\/Model\/(\w+)/)
202
- const model=modelMatch?modelMatch[1]:null
203
- nPlusOneCandidates.push({shape, count:v.count, model, callerStack:v.callers.join(' | ')})
204
- }
205
- }
206
- slowQueries.sort((a,b)=>b.maxMs-a.maxMs)
207
- nPlusOneCandidates.sort((a,b)=>b.count-a.count)
208
-
209
- return {
210
- ok:true,
211
- worktreePath,
212
- inputs,
213
- slowQueries: slowQueries.slice(0, topN),
214
- nPlusOneCandidates: nPlusOneCandidates.slice(0, topN),
215
- cacheFlushStorm:{eventsPerMin:0, rawEvents:[], windowMin:5},
216
- crawlerOverload:false,
217
- crawlerEvidence:{hitsPerMin:0, topUA:null, topIP:null},
218
- queryShapes: Array.from(shapeMap.entries()).map(([shape,c])=>({shape, count:c.count})),
219
- topTimers: [],
220
- warnings,
221
- } as never
222
- }
223
- }), 'perf log stats'))
224
- }
@@ -1,112 +0,0 @@
1
- import { join, resolve, sep, basename } from 'node:path'
2
- import { readFile, readdir, realpath, stat } from 'node:fs/promises'
3
- import type { Context } from '@deepseek-ai/cordis'
4
- import z from '@deepseek-ai/schemastery'
5
- import { defineTool } from '@deepseek-ai/dsh-tools'
6
-
7
- export const name='maestro-phtml-escape-scan-tool'
8
- export const inject=['tools']
9
- export const Config:z<{rootPath?:string}>=z.object({rootPath:z.string()})
10
- interface SC{agent?:{session?:{header?:{cwd?:string}}}}
11
- function workspaceRootFor(c:string|undefined,e:unknown):string{ if(c!==undefined) return c; const cwd=(e as SC|undefined)?.agent?.session?.header?.cwd; return typeof cwd==='string'&&cwd!==''?cwd:process.cwd()}
12
- async function isInsideRoot(r:string,t:string):Promise<boolean>{ const ar=resolve(r); const rs=resolve(ar,t); if(rs!==ar && !rs.startsWith(ar+sep)) return false; try{ const rr=await realpath(ar); const rt=await realpath(rs); return rt===rr||rt.startsWith(rr+sep)}catch{return false}}
13
- const MAX_FILE_BYTES=1024*1024
14
- const MAX_PHTML_FILES=200
15
- const MAX_FINDINGS=200
16
- const SKIP_DIRS=new Set(['.git','node_modules','vendor','pub/static'])
17
- async function exists(p:string):Promise<boolean>{ try{await stat(p); return true}catch{return false}}
18
- async function* walkPhtml(dir:string, budget:{files:number}):AsyncGenerator<string>{
19
- if(budget.files<=0) return
20
- let entries; try{entries=await readdir(dir,{withFileTypes:true})}catch{return}
21
- for(const e of entries){
22
- if(budget.files<=0) return
23
- if(e.isDirectory()){ if(SKIP_DIRS.has(e.name)) continue; yield* walkPhtml(join(dir,e.name), budget); continue }
24
- if(!e.isFile()) continue
25
- if(!e.name.endsWith('.phtml')) continue
26
- budget.files-=1; yield join(dir,e.name)
27
- }
28
- }
29
- export function apply(ctx:Context, config:{rootPath?:string}={}):void{
30
- const configuredRoot=config.rootPath
31
- ctx.effect(()=>ctx.tools.register(defineTool({
32
- name:'phtml_escape_scan',
33
- description:'Scan .phtml for XSS: unescaped echo, missing escapeHtmlAttr, raw block methods, superglobals.',
34
- parameters:{
35
- scope:{type:'string', enum:['diff','paths'], required:true},
36
- paths:{type:'array', items:{type:'string'}},
37
- },
38
- output:{
39
- schema:{
40
- type:'object', additionalProperties:false,
41
- properties:{
42
- findings:{type:'array', required:true},
43
- scannedFiles:{type:'number', required:true},
44
- skippedFiles:{type:'number', required:true},
45
- truncated:{type:'boolean', required:true},
46
- summary:{type:'object', required:true, additionalProperties:true},
47
- }
48
- },
49
- render:(_a,v:{findings:unknown[]})=>[{type:'text', text:`${(v.findings as unknown[]).length} findings`}],
50
- },
51
- async execute(args, exec){
52
- const root=workspaceRootFor(configuredRoot, exec)
53
- const scope=(args as {scope:string}).scope
54
- const paths=(args as {paths?:string[]}).paths ?? []
55
- for(const p of paths){ if(!(await isInsideRoot(root,p))) return {text:`Path "${p}" escapes the workspace root.`, truncated:false} as never }
56
- let files:string[]=[]
57
- if(scope==='paths'){
58
- for(const p of paths){
59
- if(!p.endsWith('.phtml')) continue
60
- const abs=resolve(root,p); if(await exists(abs)) files.push(p)
61
- }
62
- } else {
63
- // diff: walk all phtml bounded
64
- const budget={files:MAX_PHTML_FILES}
65
- for await(const f of walkPhtml(root, budget)){
66
- const rel=f.startsWith(root+sep)? f.slice(root.length+1): basename(f)
67
- files.push(rel); if(files.length>=MAX_PHTML_FILES) break
68
- }
69
- }
70
- const findings:Array<{file:string,line:number,type:string,snippet:string,confidence:string,rule:string,escaperHint:string}>=[]
71
- let scannedFiles=0, skippedFiles=0
72
- for(const rel of files.slice(0,MAX_PHTML_FILES)){
73
- if(findings.length>=MAX_FINDINGS) break
74
- const abs=resolve(root,rel)
75
- let text:string
76
- try{ const b=await readFile(abs); if(b.byteLength>MAX_FILE_BYTES){skippedFiles++; continue} text=b.toString('utf-8') }catch{skippedFiles++; continue}
77
- scannedFiles++
78
- const lines=text.split('\n')
79
- lines.forEach((line, idx)=>{
80
- if(findings.length>=MAX_FINDINGS) return
81
- const snippet=line.trim().slice(0,240)
82
- const lineNo=idx+1
83
- // superglobal always flagged
84
- if(/\$_GET|\$_POST|\$_REQUEST|\$_COOKIE/.test(line)){
85
- findings.push({file:rel,line:lineNo,type:'direct-superglobal',snippet,confidence:'high',rule:'M2-SEC-superglobal',escaperHint:'validate/sanitize input, do not echo raw'})
86
- return
87
- }
88
- // check <?= ... ?> echo
89
- const echoRe=/<\?=\s*([^?]*?)\s*\?>/g
90
- let m:RegExpExecArray|null
91
- while((m=echoRe.exec(line))!==null){
92
- const inner=m[1]
93
- // safe if contains escaper
94
- if(/\$escaper\s*->\s*escape/.test(inner) || /\$block\s*->\s*escape/.test(inner) || /->\s*get\w*Html\s*\(/.test(inner)) continue
95
- // attr check: if line has title=" <?= ... ?> and not escapeHtmlAttr -> unescaped-attr
96
- if(/title\s*=\s*"/.test(line) && !/escapeHtmlAttr/.test(inner)){
97
- findings.push({file:rel,line:lineNo,type:'unescaped-attr',snippet,confidence:'high',rule:'M2-SEC-attr',escaperHint:'$escaper->escapeHtmlAttr() for attributes'})
98
- } else if(/^\s*\$[a-zA-Z_][\w$]*\s*$/.test(inner.trim()) || /\$\w+/.test(inner)){
99
- // bare variable echo
100
- // if this was already handled as attr, don't double count
101
- if(findings.some(f=>f.file===rel && f.line===lineNo && f.type==='unescaped-attr')) continue
102
- findings.push({file:rel,line:lineNo,type:'unescaped-echo',snippet,confidence:'high',rule:'M2-SEC-echo',escaperHint:'$escaper->escapeHtml() or $block->escapeHtml()'})
103
- }
104
- }
105
- })
106
- }
107
- const truncated=files.length>=MAX_PHTML_FILES || findings.length>=MAX_FINDINGS
108
- const summary={high:findings.filter(f=>f.confidence==='high').length, medium:findings.filter(f=>f.confidence==='medium').length, low:findings.filter(f=>f.confidence==='low').length, filesWithFindings: new Set(findings.map(f=>f.file)).size}
109
- return {findings:findings.slice(0,MAX_FINDINGS), scannedFiles, skippedFiles, truncated, summary} as never
110
- },
111
- }), 'phtml escape'))
112
- }
@@ -1,168 +0,0 @@
1
- import type { Context } from '@deepseek-ai/cordis'
2
- import z from '@deepseek-ai/schemastery'
3
- import { join } from 'node:path'
4
- import type { ReviewRequest, ReviewResult } from '../events.js'
5
- import { lastCompletedReview } from '../review-history.js'
6
- import type { ReviewSkillProfile } from '../skills-tool.js'
7
- import { gitlabAuthHeaders } from '../gitlab-auth.js'
8
- import { hasCompletedReviewForSha, hasRunningEyes } from '../ci-coexist.js'
9
-
10
- export const name = 'maestro-review-ci-trigger'
11
- export const inject = ['reviewRunner'] as const
12
-
13
- const REVIEW_PROFILES = ['magento2', 'laravel', 'symfony', 'wordpress', 'generic'] as const
14
-
15
- export interface CiEnvConfig {
16
- gitlabBaseUrl: string
17
- gitlabToken: string
18
- sourceProjectId: number
19
- mrIid: number
20
- mode: 'quick' | 'deep'
21
- dryRun: boolean
22
- reviewProfile?: ReviewSkillProfile
23
- /** Mirror of Settings UI autoRereviewOnPush (default off): re-review new pushes. */
24
- rereviewOnPush: boolean
25
- }
26
-
27
- export const CiEnvConfig: z<CiEnvConfig> = z.object({
28
- gitlabBaseUrl: z.string().required(),
29
- gitlabToken: z.string().role('secret').required(),
30
- sourceProjectId: z.number().required(),
31
- mrIid: z.number().required(),
32
- mode: z.union([z.const('quick'), z.const('deep')]).default('quick'),
33
- dryRun: z.boolean().default(false),
34
- reviewProfile: z.union([z.const('magento2'), z.const('laravel'), z.const('symfony'), z.const('wordpress'), z.const('generic')]),
35
- rereviewOnPush: z.boolean().default(false),
36
- })
37
-
38
- /**
39
- * Reads the CI contract env vars (spec §5.2) — not Cordis-supplied config, since these are
40
- * per-run values a static profile config cannot hold. schemastery's `.required()` only rejects
41
- * `undefined`, not an empty string, so GITLAB_HOST/MAESTRO_GITLAB_TOKEN presence is checked here
42
- * before defaulting to `''` — otherwise a missing env var would silently pass validation.
43
- */
44
- export function parseCiEnvConfig(env: Record<string, string | undefined>): CiEnvConfig {
45
- if (env.GITLAB_HOST === undefined) throw new Error('missing GITLAB_HOST')
46
- if (env.MAESTRO_GITLAB_TOKEN === undefined) throw new Error('missing MAESTRO_GITLAB_TOKEN')
47
- if (env.REVIEW_PROFILE !== undefined && !(REVIEW_PROFILES as readonly string[]).includes(env.REVIEW_PROFILE)) {
48
- throw new Error(`unsupported REVIEW_PROFILE "${env.REVIEW_PROFILE}" (supported: ${REVIEW_PROFILES.join(', ')})`)
49
- }
50
- return CiEnvConfig({
51
- gitlabBaseUrl: `https://${env.GITLAB_HOST}`,
52
- gitlabToken: env.MAESTRO_GITLAB_TOKEN,
53
- sourceProjectId: Number(env.SOURCE_PROJECT_ID),
54
- mrIid: Number(env.MR_IID),
55
- mode: env.REVIEW_MODE === 'deep' ? 'deep' : 'quick',
56
- dryRun: env.REVIEW_DRY_RUN === '1',
57
- reviewProfile: env.REVIEW_PROFILE as ReviewSkillProfile | undefined,
58
- rereviewOnPush: env.REVIEW_ON_PUSH === '1',
59
- })
60
- }
61
-
62
- /** The one field a webhook payload carries that env vars don't — orchestrator fetches the diff itself. */
63
- export async function fetchMrSourceBranch(config: CiEnvConfig, fetcher: typeof fetch = fetch): Promise<string> {
64
- return (await fetchMrDetail(config, fetcher)).sourceBranch
65
- }
66
-
67
- /** MR detail pieces CI needs in one call: source branch (worktree) + head SHA (push-gate) + project path (comment header/link). */
68
- export async function fetchMrDetail(config: CiEnvConfig, fetcher: typeof fetch = fetch): Promise<{ sourceBranch: string; headSha: string; projectPath: string }> {
69
- const url = `${config.gitlabBaseUrl}/api/v4/projects/${config.sourceProjectId}/merge_requests/${config.mrIid}`
70
- const res = await fetcher(url, { headers: gitlabAuthHeaders(config.gitlabToken) })
71
- if (!res.ok) throw new Error(`GitLab API error ${res.status}: ${await res.text()}`)
72
- const body = await res.json() as { source_branch?: string; sha?: string; references?: { full?: string } }
73
- if (typeof body.source_branch !== 'string') throw new Error('GitLab merge request response is missing source_branch')
74
- if (typeof body.sha !== 'string') throw new Error('GitLab merge request response is missing sha')
75
- // references.full looks like "group/sub/project!123" — the real path feeds the
76
- // comment header and View-MR link. Absent on old servers: fall back to project/<id>.
77
- const full = body.references?.full
78
- const projectPath = typeof full === 'string' && full.includes('!') ? full.slice(0, full.indexOf('!')) : `project/${config.sourceProjectId}`
79
- return { sourceBranch: body.source_branch, headSha: body.sha, projectPath }
80
- }
81
-
82
- export async function runCiTrigger(
83
- ctx: Context,
84
- config: CiEnvConfig,
85
- deps: {
86
- fetcher?: typeof fetch
87
- writeFile?: typeof import('node:fs/promises').writeFile
88
- history?: { lastCompletedReview(projectId: number, mrIid: number): Promise<{ headSha?: string } | undefined> }
89
- } = {},
90
- ): Promise<ReviewResult> {
91
- const { sourceBranch, headSha, projectPath } = await fetchMrDetail(config, deps.fetcher)
92
- // Push-gate (mirror of the webhook autoRereviewOnPush semantics): the bridge fires
93
- // on every MR pipeline, so skip when this exact head SHA already completed — and
94
- // skip new pushes too unless REVIEW_ON_PUSH=1. A re-run then gets the H6 incremental
95
- // block from history for free. Cache miss (no history) fails open toward running.
96
- const history = deps.history ?? { lastCompletedReview }
97
- const prior = await history.lastCompletedReview(config.sourceProjectId, config.mrIid)
98
- let result: ReviewResult
99
- if (prior?.headSha === headSha) {
100
- result = { ok: true, summary: `already reviewed at ${headSha}, skipping`, failures: [], durationMs: 0 }
101
- } else if (prior !== undefined && !config.rereviewOnPush) {
102
- result = { ok: true, summary: `new commits since ${prior.headSha} but REVIEW_ON_PUSH is not set, skipping`, failures: [], durationMs: 0 }
103
- } else {
104
- // Coexistence (CI yields to webhook): the CI history store is invisible to
105
- // the webhook flow and vice versa, so check the MR itself for a completed
106
- // review marker of this SHA or an in-flight eyes marker before booting.
107
- const coFetcher = deps.fetcher ?? fetch
108
- if (await hasCompletedReviewForSha(coFetcher, config.gitlabBaseUrl, config.gitlabToken, config.sourceProjectId, config.mrIid, headSha)) {
109
- result = { ok: true, summary: `webhook already reviewed ${headSha} — skipping`, failures: [], durationMs: 0 }
110
- } else if (await hasRunningEyes(coFetcher, config.gitlabBaseUrl, config.gitlabToken, config.sourceProjectId, config.mrIid)) {
111
- result = { ok: true, summary: 'another review is running — skipping', failures: [], durationMs: 0 }
112
- } else {
113
- // The reviewer-ci profile's own projectMappings is always [], so the
114
- // orchestrator's mapping lookup on projectPath never matches regardless
115
- // of its exact value — but the real path feeds the comment header and
116
- // View-MR link, so prefer it over the synthetic project/<id> fallback.
117
- const request: ReviewRequest = {
118
- projectPath,
119
- projectId: config.sourceProjectId,
120
- mrIid: config.mrIid,
121
- sourceBranch,
122
- headSha,
123
- trigger: 'mention',
124
- mode: config.mode,
125
- scope: { kind: 'mr' },
126
- reviewProfile: config.reviewProfile,
127
- }
128
- result = await ctx.reviewRunner(request)
129
- }
130
- }
131
- const { writeFile } = deps.writeFile !== undefined ? { writeFile: deps.writeFile } : await import('node:fs/promises')
132
- // entrypoint.sh cds into deepseek-harness before execing dsh, so a bare relative
133
- // path would land inside the harness checkout (lost with the container). The
134
- // entrypoint exports REVIEW_REPORT_DIR=$PWD captured before the cd, so reports land
135
- // in the CI job's working directory where `artifacts:` picks them up.
136
- const reportDir = process.env.REVIEW_REPORT_DIR?.trim() || '.'
137
- const report = { ...result, projectId: config.sourceProjectId, mrIid: config.mrIid, mode: config.mode, generatedAt: new Date().toISOString() }
138
- await writeFile(join(reportDir, 'review-report.json'), JSON.stringify(report, null, 2), 'utf-8')
139
- const md = `# Review Report\n\n**Project:** ${config.sourceProjectId} !${config.mrIid}\n**Mode:** ${config.mode}\n**Duration:** ${result.durationMs}ms\n\n${result.summary ?? '(no summary)'}\n${result.failures.length > 0 ? `\nFailures:\n${result.failures.map(f => `- ${f}`).join('\n')}\n` : ''}`
140
- await writeFile(join(reportDir, 'review-report.md'), md, 'utf-8')
141
- return result
142
- }
143
-
144
- export function apply(ctx: Context): void {
145
- ctx.effect(() => {
146
- void (async () => {
147
- try {
148
- const config = parseCiEnvConfig(process.env)
149
- console.log(`[review] ci-trigger starting: project ${config.sourceProjectId} !${config.mrIid} mode=${config.mode} dryRun=${config.dryRun}`)
150
- const result = config.dryRun
151
- ? { ok: true, summary: '[dry-run] config valid, skipping review', failures: [], durationMs: 0 }
152
- : await runCiTrigger(ctx, config)
153
- console.log(`[review] ci-trigger finished: ok=${result.ok} summary=${JSON.stringify(result.summary)} failures=${result.failures.length}`)
154
- for (const failure of result.failures) console.error(`[review] ci-trigger failure: ${failure}`)
155
- const exit = ctx.get('appExit')
156
- if (exit === undefined) {
157
- console.error('[review] ctx.get(\'appExit\') is undefined — the launcher did not provide it, process cannot signal its real exit code')
158
- } else {
159
- exit(result.ok ? 0 : 1)
160
- }
161
- } catch (err) {
162
- console.error('maestro-review-ci-trigger:', err instanceof Error ? err.message : String(err))
163
- ctx.get('appExit')?.(1)
164
- }
165
- })()
166
- return () => {}
167
- }, 'maestro-review-ci-trigger run')
168
- }
@@ -1,59 +0,0 @@
1
- import type { Context } from '@deepseek-ai/cordis'
2
- import { defineTool } from '@deepseek-ai/dsh-tools'
3
-
4
- export const name = 'maestro-review-findings-tool'
5
- export const inject = ['tools']
6
-
7
- export type FindingSeverity = 'blocking' | 'major' | 'minor' | 'nit'
8
-
9
- export interface ReviewFinding {
10
- status: 'new' | 'reply'
11
- body: string
12
- path?: string
13
- line?: number
14
- discussionId?: string
15
- /** Assigned by the reviewer; missing values are treated as `minor`. */
16
- severity?: FindingSeverity
17
- /** Optional area tag, e.g. security, correctness, perf, style. */
18
- category?: string
19
- }
20
-
21
- export interface Config {
22
- onReport: (findings: ReviewFinding[]) => void
23
- }
24
-
25
- export function apply(ctx: Context, config: Config): void {
26
- ctx.tools.register(defineTool({
27
- name: 'report_review_findings',
28
- description: 'Submit your complete list of review findings exactly once, when done analyzing. Each finding is {status: "new", path, line, body, severity, category?} for a location with no existing thread, or {status: "reply", discussionId, body, severity, category?} to update an existing thread returned by gitlab_list_own_review_threads (reply to a resolved thread reopens it — prefer reply over new when the substance matches). Severity (required in spirit, defaults to minor): blocking = must fix before merge (regression, data loss, real XSS/RCE); major = should fix (correctness bug, security hardening with a realistic path); minor = nice to fix (perf nit with impact, stale docs, fragile coupling); nit = style/micro with no behavior impact.',
29
- parameters: {
30
- findings: {
31
- type: 'array',
32
- required: true,
33
- description: 'The complete list of findings for this review.',
34
- items: {
35
- type: 'object',
36
- additionalProperties: false,
37
- properties: {
38
- status: { type: 'string', enum: ['new', 'reply'], required: true },
39
- body: { type: 'string', required: true },
40
- path: { type: 'string' },
41
- line: { type: 'number' },
42
- discussionId: { type: 'string' },
43
- severity: { type: 'string', enum: ['blocking', 'major', 'minor', 'nit'] },
44
- category: { type: 'string' },
45
- },
46
- },
47
- },
48
- },
49
- output: {
50
- schema: { type: 'object', additionalProperties: false, properties: { received: { type: 'number', required: true } } },
51
- render: (_args, value) => [{ type: 'text', text: `Recorded ${value.received} finding(s).` }],
52
- },
53
- async execute(args) {
54
- const findings = args.findings as ReviewFinding[]
55
- config.onReport(findings)
56
- return { received: findings.length }
57
- },
58
- }))
59
- }