@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,168 +0,0 @@
1
- import { chmod, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
2
- import { homedir } from 'node:os'
3
- import { dirname, join } from 'node:path'
4
- import type { ReviewMode, ReviewRequest } from './events.js'
5
-
6
- export interface ReviewHistoryEntry {
7
- id: string
8
- projectId: number
9
- projectPath: string
10
- mrIid: number
11
- mode: ReviewMode
12
- scope: 'mr' | 'discussion'
13
- trigger: ReviewRequest['trigger']
14
- status: 'running' | 'completed' | 'failed'
15
- startedAt: number
16
- finishedAt?: number
17
- summary?: string
18
- error?: string
19
- /** MR head_sha at review start — baseline for incremental re-reviews (H6). */
20
- headSha?: string
21
- }
22
-
23
- const HISTORY_CAP = 100
24
- const STALE_RUNNING_MS = 2 * 60 * 60_000 // 2h — host restart can leave running without finish
25
-
26
- export function historyPath(dshHome?: string): string {
27
- const home = dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
28
- return join(home, 'dsh-maestro-review', 'reviews.json')
29
- }
30
-
31
-
32
- async function readAll(dshHome?: string): Promise<ReviewHistoryEntry[]> {
33
- try {
34
- const parsed: unknown = JSON.parse(await readFile(historyPath(dshHome), 'utf-8'))
35
- if (!Array.isArray(parsed)) return []
36
- return parsed.filter((entry): entry is ReviewHistoryEntry =>
37
- typeof entry === 'object' && entry !== null && typeof (entry as ReviewHistoryEntry).id === 'string')
38
- } catch {
39
- // Missing or corrupt store: start from an empty log rather than failing reviews.
40
- return []
41
- }
42
- }
43
-
44
- async function writeAll(entries: ReviewHistoryEntry[], dshHome?: string): Promise<void> {
45
- const path = historyPath(dshHome)
46
- await mkdir(dirname(path), { recursive: true, mode: 0o700 })
47
- await writeFile(path, JSON.stringify(entries, null, 2), { encoding: 'utf-8', mode: 0o600 })
48
- await chmod(path, 0o600)
49
- }
50
-
51
- function failStaleRunning(entries: ReviewHistoryEntry[]): boolean {
52
- let mutated = false
53
- const now = Date.now()
54
- for (const e of entries) {
55
- if (e.status === 'running' && now - e.startedAt > STALE_RUNNING_MS) {
56
- e.status = 'failed'
57
- e.error = e.error ?? 'auto-failed: stale running review (host restart or crash)'
58
- e.finishedAt = e.finishedAt ?? now
59
- mutated = true
60
- }
61
- }
62
- return mutated
63
- }
64
-
65
- /** Prepend a running entry; the oldest entries fall off past `HISTORY_CAP`. */
66
- export async function recordReviewStart(entry: Omit<ReviewHistoryEntry, 'status'>, dshHome?: string): Promise<void> {
67
- return withHistoryLock(async () => {
68
- const all = await readAll(dshHome)
69
- if (failStaleRunning(all)) await writeAll(all, dshHome)
70
- all.unshift({ ...entry, status: 'running' })
71
- await writeAll(all.slice(0, HISTORY_CAP), dshHome)
72
- })
73
- }
74
-
75
- /** Attach an outcome to the entry with this id; unknown ids are ignored. */
76
- export async function recordReviewFinish(
77
- id: string,
78
- patch: { status: 'completed' | 'failed'; summary?: string; error?: string },
79
- dshHome?: string,
80
- ): Promise<void> {
81
- return withHistoryLock(async () => {
82
- const all = await readAll(dshHome)
83
- const entry = all.find((candidate) => candidate.id === id)
84
- if (entry === undefined) return
85
- Object.assign(entry, patch, { finishedAt: Date.now() })
86
- await writeAll(all, dshHome)
87
- })
88
- }
89
-
90
- /** Newest-first slice of the log. */
91
- export async function listReviews(limit = 20, dshHome?: string): Promise<ReviewHistoryEntry[]> {
92
- return (await readAll(dshHome)).slice(0, limit)
93
- }
94
-
95
- /** Whether any review of this MR ever completed — gates push re-reviews. */
96
- export async function hasCompletedReview(projectId: number, mrIid: number, dshHome?: string): Promise<boolean> {
97
- return (await readAll(dshHome)).some(entry =>
98
- entry.projectId === projectId && entry.mrIid === mrIid && entry.status === 'completed')
99
- }
100
-
101
- /** Newest completed entry for this MR — carries headSha for H6 incrementality. */
102
- export async function lastCompletedReview(projectId: number, mrIid: number, dshHome?: string): Promise<ReviewHistoryEntry | undefined> {
103
- return (await readAll(dshHome)).find(entry =>
104
- entry.projectId === projectId && entry.mrIid === mrIid && entry.status === 'completed' && typeof entry.headSha === 'string')
105
- }
106
-
107
- /**
108
- * Drop history entries and failed-report files older than `retentionDays`.
109
- * `0` disables pruning entirely. Maestro records only — DSH session
110
- * transcripts are never touched. Entries still `running` are always kept:
111
- * a prune must never delete a review that just started (see D3).
112
- */
113
- export async function pruneHistory(retentionDays: number, dshHome?: string): Promise<void> {
114
- if (!Number.isFinite(retentionDays) || retentionDays <= 0) return
115
- return withHistoryLock(async () => {
116
- const all = await readAll(dshHome)
117
- failStaleRunning(all)
118
- const cutoff = Date.now() - retentionDays * DAY_MS
119
- const kept: ReviewHistoryEntry[] = []
120
- for (const entry of all) {
121
- if (entry.status === 'running') {
122
- kept.push(entry)
123
- continue
124
- }
125
- if ((entry.finishedAt ?? entry.startedAt) < cutoff) continue
126
- kept.push(entry)
127
- }
128
- await writeAll(kept, dshHome)
129
- }).then(async () => {
130
- const home = dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
131
- const failedDir = join(home, 'maestro', 'failed-reports')
132
- const cutoff = Date.now() - retentionDays * DAY_MS
133
- let names: string[]
134
- try {
135
- names = await readdir(failedDir)
136
- } catch {
137
- return
138
- }
139
- await Promise.all(names.map(async (name) => {
140
- // Failed reports are named `<mrIid>-<epoch-ms>.md`.
141
- const match = /^-?\d+-(\d{13,})\.md$/.exec(name)
142
- if (match === null) return
143
- const stamp = Number(match[1])
144
- if (!Number.isFinite(stamp) || stamp >= cutoff) return
145
- await rm(join(failedDir, name), { force: true }).catch(() => {})
146
- }))
147
- })
148
- }
149
-
150
- /**
151
- * In-process promise-chain mutex serializing the read-modify-write cycles of
152
- * `recordReviewStart` / `recordReviewFinish` / `pruneHistory`, so a
153
- * fire-and-forget `void pruneHistory()` can no longer clobber an entry that
154
- * started concurrently (last-writer-wins on a stale read). Two `dsh web`
155
- * processes sharing one `DSH_HOME` is unsupported, so a cross-process file
156
- * lock is deliberately out of scope.
157
- */
158
- let historyMutex: Promise<void> = Promise.resolve()
159
- function withHistoryLock<T>(work: () => Promise<T>): Promise<T> {
160
- const next = historyMutex.then(work, work)
161
- historyMutex = next.then(
162
- () => undefined,
163
- () => undefined,
164
- )
165
- return next
166
- }
167
-
168
- const DAY_MS = 24 * 60 * 60_000
@@ -1,25 +0,0 @@
1
- /**
2
- * Machine-readable review comment identity (spec: coexistence §4-5).
3
- *
4
- * Every posted review comment (webhook + CI, quick + deep) ends with an
5
- * invisible marker so the CI flow can detect "this head SHA already has a
6
- * completed review" without access to the webhook's history store.
7
- */
8
-
9
- export type ReviewFlow = 'ci-quick' | 'ci-deep' | 'webhook'
10
-
11
- export function reviewMarker(sha: string, flow: ReviewFlow): string {
12
- return `<!-- maestro-review sha=${sha} flow=${flow} status=completed -->`
13
- }
14
-
15
- export function parseReviewMarker(body: string): { sha: string; flow: string; status: string } | undefined {
16
- const m = /<!-- maestro-review sha=([0-9a-fA-F]+) flow=([a-z-]+) status=([a-z]+) -->/.exec(body)
17
- if (!m) return undefined
18
- return { sha: m[1], flow: m[2], status: m[3] }
19
- }
20
-
21
- /** CI detection is env-based (established pattern): the reviewer job always sets these. */
22
- export function resolveFlow(mode: 'quick' | 'deep'): ReviewFlow {
23
- if (process.env.SOURCE_PROJECT_ID === undefined) return 'webhook'
24
- return mode === 'deep' ? 'ci-deep' : 'ci-quick'
25
- }
@@ -1,83 +0,0 @@
1
- /**
2
- * MR award-emoji acknowledgements: the MR shows "eyes" while a review runs and
3
- * a final marker when it completes or fails. Signalling is best-effort — any
4
- * GitLab error is swallowed so it can never fail the review itself.
5
- */
6
-
7
- import { gitlabAuthHeaders } from './gitlab-auth.js'
8
- import { fetchWithTimeout } from './gitlab-client.js'
9
-
10
- export interface ReviewSignals {
11
- start(): Promise<void>
12
- finish(outcome: 'completed' | 'failed'): Promise<void>
13
- }
14
-
15
- async function award(baseUrl: string, token: string, projectId: number, mrIid: number, name: string): Promise<void> {
16
- const response = await fetchWithTimeout(`${baseUrl}/api/v4/projects/${projectId}/merge_requests/${mrIid}/award_emoji`, {
17
- method: 'POST',
18
- headers: { ...gitlabAuthHeaders(token), 'Content-Type': 'application/json' },
19
- body: JSON.stringify({ name }),
20
- })
21
- // fetchWithTimeout only throws on a network/abort failure; a non-2xx status
22
- // (expired token, missing scope, rate-limited) resolves normally and must
23
- // be checked explicitly, or the caller's failure logging never fires.
24
- if (!response.ok) throw new Error(`GitLab API error ${response.status} awarding "${name}": ${await response.text()}`)
25
- }
26
-
27
- /** Every marker name this bot ever awards — kept in one place so `unawardOwn` can always clear all of them, leaving at most one visible at a time. */
28
- const MARKER_NAMES = ['eyes', 'white_check_mark', 'warning'] as const
29
-
30
- /**
31
- * Remove this bot's own markers among `names`; other users' awards stay untouched.
32
- * Callers pass `MARKER_NAMES` (not just "eyes") so a stale terminal marker from a
33
- * prior run (e.g. `white_check_mark`) is cleared before re-awarding the same name —
34
- * GitLab rejects a duplicate award of the same name by the same user with a 404
35
- * ("Award Emoji Name has already been taken"), which otherwise surfaces as a
36
- * confusing failure on the second consecutive completed/failed review of one MR.
37
- */
38
- async function unawardOwn(baseUrl: string, token: string, projectId: number, mrIid: number, botUsername: string, names: readonly string[]): Promise<void> {
39
- const response = await fetchWithTimeout(`${baseUrl}/api/v4/projects/${projectId}/merge_requests/${mrIid}/award_emoji`, {
40
- headers: gitlabAuthHeaders(token),
41
- })
42
- if (!response.ok) throw new Error(`GitLab API error ${response.status} listing award emoji: ${await response.text()}`)
43
- const awards = (await response.json()) as Array<{ id?: number; name?: string; user?: { username?: string } }>
44
- for (const awardItem of Array.isArray(awards) ? awards : []) {
45
- if (awardItem.name === undefined || !names.includes(awardItem.name) || awardItem.user?.username !== botUsername || typeof awardItem.id !== 'number') continue
46
- const deleteResponse = await fetchWithTimeout(`${baseUrl}/api/v4/projects/${projectId}/merge_requests/${mrIid}/award_emoji/${awardItem.id}`, {
47
- method: 'DELETE',
48
- headers: gitlabAuthHeaders(token),
49
- }).catch((err: unknown) => {
50
- console.error(`review-signals: failed to delete stale ${awardItem.name} marker ${awardItem.id} on MR !${mrIid}`, err)
51
- return undefined
52
- })
53
- if (deleteResponse !== undefined && !deleteResponse.ok) {
54
- console.error(`review-signals: GitLab API error ${deleteResponse.status} deleting stale ${awardItem.name} marker ${awardItem.id} on MR !${mrIid}`)
55
- }
56
- }
57
- }
58
-
59
- export function createReviewSignals(options: { baseUrl: string; token: string; projectId: number; mrIid: number; botUsername: string }): ReviewSignals {
60
- const { baseUrl, token, projectId, mrIid, botUsername } = options
61
- return {
62
- async start() {
63
- try {
64
- await unawardOwn(baseUrl, token, projectId, mrIid, botUsername, MARKER_NAMES)
65
- await award(baseUrl, token, projectId, mrIid, 'eyes')
66
- } catch (err) {
67
- // Signalling must never break the review, but a swallowed failure
68
- // here is exactly what leaves a stale "eyes" marker stuck on the MR
69
- // forever (blocking the push-gate's 👀-running check for both the
70
- // webhook and CI flows) with zero trace of why — log it.
71
- console.error(`review-signals: failed to set the running marker on MR !${mrIid}`, err)
72
- }
73
- },
74
- async finish(outcome) {
75
- try {
76
- await unawardOwn(baseUrl, token, projectId, mrIid, botUsername, MARKER_NAMES)
77
- await award(baseUrl, token, projectId, mrIid, outcome === 'completed' ? 'white_check_mark' : 'warning')
78
- } catch (err) {
79
- console.error(`review-signals: failed to clear the running marker / award the final marker on MR !${mrIid}`, err)
80
- }
81
- },
82
- }
83
- }
@@ -1,109 +0,0 @@
1
- import type { Context } from '@deepseek-ai/cordis'
2
- import { defineTool } from '@deepseek-ai/dsh-tools'
3
- import z from '@deepseek-ai/schemastery'
4
-
5
- export const name='maestro-scope-split-tool'
6
- export const inject=['tools']
7
- export const Config:z<{rootPath?:string}>=z.object({rootPath:z.string()})
8
-
9
- const DEEP_EXTS=new Set(['.php'])
10
- const QUICK_PATH_HINTS=/^(view\/frontend|view\/adminhtml|i18n)\//
11
- const DEEP_PATH_HINTS=/(Plugin\/|Observer\/|Controller\/|Setup\/|Model\/|etc\/(di|acl|webapi)\.xml|composer\.json|registration\.php)/
12
-
13
- function extOf(f:string):string{ const i=f.lastIndexOf('.'); return i>=0? f.slice(i).toLowerCase(): ''}
14
-
15
- export interface SplitInput{ files:string[], addedLinesPerFile?:Record<string,number>, baseRef?:string}
16
- export interface SplitResult{
17
- split:{quick:{files:string[], reason:string}, deep:{files:string[], reason:string}},
18
- reason:string,
19
- estimatedSavingsTokens:number,
20
- estimatedSavingsPercent:number,
21
- manifest:{totalFiles:number, totalAddedLines:number, riskBreakdown:Array<{risk:string,count:number,examples:string[]}>},
22
- warnings:string[]
23
- }
24
-
25
- export function splitScope(diffStats: SplitInput, mode:'quick'|'deep'): SplitResult{
26
- const warnings:string[]=[]
27
- const quick:string[]=[]
28
- const deep:string[]=[]
29
- if(mode==='quick'){
30
- for(const f of diffStats.files) quick.push(f)
31
- } else {
32
- for(const f of diffStats.files){
33
- const ext=extOf(f)
34
- if(DEEP_PATH_HINTS.test(f)){ deep.push(f); continue }
35
- if(QUICK_PATH_HINTS.test(f)){ quick.push(f); continue }
36
- if(ext==='.phtml' || ext==='.html' || ext==='.js' || ext==='.ts' || ext==='.less' || ext==='.css' || ext==='.csv' || ext==='.json'){
37
- quick.push(f); continue
38
- }
39
- if(ext==='.xml'){
40
- // layout xml is quick, other xml deep? Treat layout as quick
41
- if(f.includes('/layout/') || f.includes('view/')) quick.push(f)
42
- else deep.push(f)
43
- continue
44
- }
45
- if(DEEP_EXTS.has(ext) || ext==='.php'){ deep.push(f); continue }
46
- // unknown ext
47
- deep.push(f)
48
- warnings.push(`unknown extension ${ext||'(none)'} for ${f} → deep (fail-safe)`)
49
- }
50
- }
51
- const estimatedSavingsTokens=quick.length*1400
52
- const totalFiles=diffStats.files.length
53
- const totalAddedLines=diffStats.addedLinesPerFile? Object.values(diffStats.addedLinesPerFile).reduce((a,b)=>a+b,0): 0
54
- const totalTokensIfAllDeep=totalFiles*1800
55
- const estimatedSavingsPercent= totalTokensIfAllDeep>0 ? Math.round(estimatedSavingsTokens/totalTokensIfAllDeep*100) : 0
56
- const reason = `split ${quick.length} quick (phtml/js/less/xml) vs ${deep.length} deep (php/di.xml/Plugin) → saves ~${estimatedSavingsTokens} tokens (${estimatedSavingsPercent}%)`
57
- const manifest={
58
- totalFiles,
59
- totalAddedLines,
60
- riskBreakdown:[
61
- {risk:'quick', count:quick.length, examples:quick.slice(0,3)},
62
- {risk:'deep', count:deep.length, examples:deep.slice(0,3)},
63
- ]
64
- }
65
- return {
66
- split:{
67
- quick:{files:quick, reason:'quick: templates, frontend assets'},
68
- deep:{files:deep, reason:'deep: php, di.xml, Plugin/Observer'},
69
- },
70
- reason,
71
- estimatedSavingsTokens,
72
- estimatedSavingsPercent,
73
- manifest,
74
- warnings,
75
- }
76
- }
77
-
78
- export function apply(ctx:Context, _config:{rootPath?:string}={}):void{
79
- ctx.effect(()=>ctx.tools.register(defineTool({
80
- name:'maestro_review_scope_split',
81
- description:'Deterministic QA split for MR diff: quick (templates) vs deep (php/di.xml/Plugin) with token savings estimate.',
82
- parameters:{
83
- diffStats:{type:'object', required:true, additionalProperties:false, properties:{files:{type:'array', items:{type:'string'}, required:true}, addedLinesPerFile:{type:'object', additionalProperties:true}, baseRef:{type:'string'}}},
84
- mode:{type:'string', enum:['quick','deep'], required:true},
85
- quickExtensions:{type:'array', items:{type:'string'}},
86
- deepExtensions:{type:'array', items:{type:'string'}},
87
- maxDeepFiles:{type:'number'},
88
- },
89
- output:{
90
- schema:{
91
- type:'object', additionalProperties:false,
92
- properties:{
93
- split:{type:'object', required:true, additionalProperties:true},
94
- reason:{type:'string', required:true},
95
- estimatedSavingsTokens:{type:'number', required:true},
96
- estimatedSavingsPercent:{type:'number', required:true},
97
- manifest:{type:'object', required:true, additionalProperties:true},
98
- warnings:{type:'array', required:true},
99
- }
100
- },
101
- render:(_a,v:{reason:string})=>[{type:'text', text:v.reason}],
102
- },
103
- async execute(args){
104
- const diffStats=(args as {diffStats:SplitInput}).diffStats
105
- const mode=(args as {mode:'quick'|'deep'}).mode
106
- return splitScope(diffStats, mode) as never
107
- }
108
- }), 'scope split'))
109
- }
@@ -1,152 +0,0 @@
1
- import { basename, extname, join, resolve, sep } from 'node:path'
2
- import { readdir, readFile, realpath } 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-search-tool'
8
- export const inject = ['tools']
9
-
10
- export interface Config {
11
- rootPath?: string
12
- }
13
-
14
- export const Config: z<Config> = z.object({
15
- rootPath: z.string(),
16
- })
17
-
18
- /**
19
- * Root resolution: explicit config wins, otherwise the calling agent's
20
- * per-session workspace so review agents search their own worktree instead of
21
- * the harness process cwd.
22
- */
23
- interface SessionCwdSource {
24
- agent?: { session?: { header?: { cwd?: string } } }
25
- }
26
-
27
- function workspaceRootFor(configuredRoot: string | undefined, exec: unknown): string {
28
- if (configuredRoot !== undefined) return configuredRoot
29
- const cwd = (exec as SessionCwdSource | undefined)?.agent?.session?.header?.cwd
30
- return typeof cwd === 'string' && cwd !== '' ? cwd : process.cwd()
31
- }
32
-
33
- async function isInsideRoot(rootPath: string, target: string): Promise<boolean> {
34
- const absoluteRoot = resolve(rootPath)
35
- const resolved = resolve(absoluteRoot, target)
36
- if (resolved !== absoluteRoot && !resolved.startsWith(absoluteRoot + sep)) return false
37
- try {
38
- const realRoot = await realpath(absoluteRoot)
39
- const realTarget = await realpath(resolved)
40
- return realTarget === realRoot || realTarget.startsWith(realRoot + sep)
41
- } catch {
42
- // Unresolvable paths (broken symlinks etc.) cannot be proven contained.
43
- return false
44
- }
45
- }
46
-
47
- const SKIP_DIRS = new Set(['.git', 'node_modules'])
48
- const MAX_FILE_BYTES = 1024 * 1024
49
- const MAX_FILES = 2000
50
- const MAX_MATCHES = 50
51
-
52
- function globToRegExp(glob: string): RegExp | undefined {
53
- if (glob === '' || glob === '*') return undefined
54
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\u0000/g, '.*')
55
- return new RegExp(`^${escaped}$`)
56
- }
57
-
58
- /** Bounded recursive walk yielding file paths relative to `dir`. */
59
- async function* walkFiles(dir: string, base: string, budget: { files: number }): AsyncGenerator<string> {
60
- if (budget.files <= 0) return
61
- let entries
62
- try {
63
- entries = await readdir(dir, { withFileTypes: true })
64
- } catch {
65
- return
66
- }
67
- for (const entry of entries) {
68
- if (budget.files <= 0) return
69
- if (entry.isDirectory()) {
70
- if (SKIP_DIRS.has(entry.name)) continue
71
- yield* walkFiles(join(dir, entry.name), base, budget)
72
- continue
73
- }
74
- if (!entry.isFile()) continue
75
- budget.files -= 1
76
- yield join(dir, entry.name)
77
- }
78
- }
79
-
80
- /**
81
- * Grep-style content search over the review workspace. Reviewers have no
82
- * shell; this is how they verify claims against the actual project sources
83
- * (tailwind.config.js extensions/safelist, class usages, block wiring).
84
- */
85
- export function apply(ctx: Context, config: Config = {}): void {
86
- const configuredRoot = config.rootPath
87
-
88
- ctx.effect(() => ctx.tools.register(defineTool({
89
- name: 'maestro_search_files',
90
- description: 'Search file contents under the current workspace root with a regular expression. Returns matching lines as "path:line: text". Use this before claiming something does or does not exist in the codebase.',
91
- parameters: {
92
- pattern: { type: 'string', required: true, description: 'Regular expression (JavaScript syntax) matched against each line.' },
93
- path: { type: 'string', description: 'Optional directory or file prefix, relative to the workspace root.' },
94
- glob: { type: 'string', description: 'Optional filename filter, e.g. "*.phtml" or "**/*.css".' },
95
- },
96
- output: {
97
- schema: {
98
- type: 'object',
99
- additionalProperties: false,
100
- properties: {
101
- text: { type: 'string', required: true },
102
- truncated: { type: 'boolean', required: true },
103
- },
104
- },
105
- render: (_args, value) => [{ type: 'text', text: value.text }],
106
- },
107
- async execute(args, exec) {
108
- const root = workspaceRootFor(configuredRoot, exec)
109
- const requested = args.path ?? ''
110
- if (!(await isInsideRoot(root, requested))) {
111
- return { text: `Path "${requested}" escapes the workspace root.`, truncated: false } as never
112
- }
113
- const searchRoot = requested === '' ? root : resolve(root, requested)
114
-
115
- let pattern: RegExp
116
- try {
117
- pattern = new RegExp(args.pattern)
118
- } catch (err) {
119
- return { text: `Invalid regular expression: ${err instanceof Error ? err.message : String(err)}`, truncated: false } as never
120
- }
121
- const nameFilter = args.glob === undefined ? undefined : globToRegExp(args.glob)
122
-
123
- const budget = { files: MAX_FILES }
124
- const lines: string[] = []
125
- let totalMatched = 0
126
- let truncated = false
127
- for await (const file of walkFiles(searchRoot, root, budget)) {
128
- if (nameFilter !== undefined && !nameFilter.test(basename(file))) continue
129
- if (extname(file) === '.zip') continue
130
- let content: string
131
- try {
132
- const stat = await readFile(file)
133
- if (stat.byteLength > MAX_FILE_BYTES) continue
134
- content = stat.toString('utf-8')
135
- } catch {
136
- continue
137
- }
138
- const relative = file.startsWith(root + sep) ? file.slice(root.length + 1) : basename(file)
139
- content.split('\n').forEach((row, index) => {
140
- if (!pattern.test(row)) return
141
- totalMatched += 1
142
- if (totalMatched <= MAX_MATCHES) {
143
- lines.push(`${relative}:${index + 1}: ${row.trim().slice(0, 240)}`)
144
- }
145
- })
146
- }
147
- if (budget.files <= 0 || totalMatched > MAX_MATCHES) truncated = true
148
- const header = lines.length === 0 ? `No matches for /${args.pattern}/` : `${lines.length} match(es)${truncated ? ' (truncated)' : ''}:`
149
- return { text: [header, ...lines].join('\n'), truncated } as never
150
- },
151
- }), 'maestro search tool'))
152
- }
@@ -1,94 +0,0 @@
1
- import { existsSync } from 'node:fs'
2
- import { readFile, stat } from 'node:fs/promises'
3
- import { dirname, join } from 'node:path'
4
- import type { SkillCandidate, SkillDefinition, SkillLookupOptions } from '@deepseek-ai/dsh-skill'
5
-
6
- const SKILL_NAME = 'dsh-native-tools'
7
-
8
- /**
9
- * Resolve the package-root `skills/` dir regardless of module layout. The built
10
- * host lib is flat (`lib/index.js` → `../skills`), but under vitest the same
11
- * module loads from `src/host/` (→ `../../skills`). Walking to the nearest
12
- * `package.json` yields the same package-root `skills/` in both layouts.
13
- */
14
- export function resolveSkillsDir(fromDir: string): string {
15
- let dir = fromDir
16
- for (let i = 0; i < 6; i++) {
17
- try {
18
- if (existsSync(join(dir, 'package.json'))) return join(dir, 'skills')
19
- } catch { /* keep walking */ }
20
- const parent = dirname(dir)
21
- if (parent === dir) break
22
- dir = parent
23
- }
24
- return join(fromDir, '..', 'skills')
25
- }
26
-
27
- /** Minimal frontmatter reader for our own SKILL.md — enough for the provider contract. */
28
- function parseFrontmatter(raw: string): { name: string; description: string; body: string } {
29
- // `\r?\n` on both delimiters and on the line split: a SKILL.md checked out
30
- // with CRLF (git core.autocrlf, a Windows editor) otherwise parses to an
31
- // empty description with no error at all.
32
- const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/)
33
- if (!m) return { name: SKILL_NAME, description: '', body: raw }
34
- const fm = m[1].split(/\r?\n/).reduce<Record<string, string>>((acc, line) => {
35
- const kv = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/)
36
- if (kv) acc[kv[1]] = kv[2].replace(/^["']|["']$/g, '')
37
- return acc
38
- }, {})
39
- return { name: fm.name || SKILL_NAME, description: fm.description || '', body: m[2] }
40
- }
41
-
42
- /**
43
- * Provider for the bundled DSH tool map. Served here rather than in the public
44
- * `maestro-skills` plugin on purpose: the map names harness tools, and that
45
- * repo's catalog test requires its skill content to stay tool-neutral.
46
- */
47
- export function makeSkillProvider(skillsDir: string) {
48
- return {
49
- // The dsh-skill service attributes candidates through the provider object's
50
- // own `name`; a missing one surfaces at runtime as `skill provider
51
- // "undefined" returned skill ...` and fails every turn.
52
- name: 'maestro-review',
53
- async list(_options: SkillLookupOptions): Promise<SkillCandidate[]> {
54
- const entry = join(skillsDir, SKILL_NAME)
55
- const st = await stat(entry).catch(() => null)
56
- if (!st?.isDirectory()) return []
57
- const skillFilePath = join(entry, 'SKILL.md')
58
- const fileSt = await stat(skillFilePath).catch(() => null)
59
- if (!fileSt?.isFile()) return []
60
- const raw = await readFile(skillFilePath, 'utf-8').catch(() => null)
61
- if (raw === null) return []
62
- const { name, description } = parseFrontmatter(raw)
63
- return [{
64
- name,
65
- description,
66
- invocation: { modelInvocable: true, userInvocable: true },
67
- source: 'custom',
68
- provider: 'maestro-review',
69
- rank: 360,
70
- locator: skillFilePath,
71
- path: skillFilePath,
72
- resourceBase: { kind: 'directory', path: entry },
73
- metadata: { name, description },
74
- }]
75
- },
76
- async get(candidate: SkillCandidate, _options: SkillLookupOptions): Promise<SkillDefinition | undefined> {
77
- try {
78
- const raw = await readFile(candidate.path as string, 'utf-8')
79
- const { name, description, body } = parseFrontmatter(raw)
80
- return {
81
- name,
82
- description,
83
- invocation: candidate.invocation,
84
- source: candidate.source,
85
- provider: candidate.provider,
86
- resourceBase: candidate.resourceBase,
87
- path: candidate.path,
88
- content: body,
89
- metadata: candidate.metadata,
90
- }
91
- } catch { return undefined }
92
- },
93
- }
94
- }