@ddtcorex/dsh-maestro-review 0.12.0 → 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 +23 -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 -8207
  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
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@ddtcorex/dsh-maestro-review",
3
+ "version": "0.14.0",
3
4
  "private": false,
4
- "version": "0.12.0",
5
- "description": "Maestro Review: GitLab review pipeline + orchestrator for automated MR review",
5
+ "description": "Maestro Review for the DeepSeek Harness: GitLab webhook intake, project mappings with local worktrees, the Settings section and Telegram digests, on top of the maestro-reviewer engine",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -24,34 +24,34 @@
24
24
  }
25
25
  },
26
26
  "files": [
27
- "README.md",
28
- "cordis.patch.yml",
29
27
  "lib",
30
28
  "src",
31
- "skills",
32
- "presets",
33
- "client",
34
- "profiles",
35
- "templates"
29
+ "cordis.patch.yml",
30
+ "README.md"
36
31
  ],
32
+ "dsh": {
33
+ "bundle": {
34
+ "patch": "./cordis.patch.yml"
35
+ },
36
+ "client": {
37
+ "platform": "web",
38
+ "inject": [
39
+ "@deepseek-ai/dsh-client-connection",
40
+ "@deepseek-ai/dsh-client-ui-slots"
41
+ ]
42
+ }
43
+ },
37
44
  "peerDependencies": {
38
45
  "@deepseek-ai/cordis": "~4.0.4",
39
46
  "@deepseek-ai/dsh-client-connection": "^0.1.0-rc.6 || >=0.1.1-rc.0 <0.3.0-0"
40
47
  },
41
48
  "dependencies": {
42
- "@deepseek-ai/schemastery": "~3.18.4"
49
+ "@deepseek-ai/schemastery": "~3.18.4",
50
+ "@ddtcorex/maestro-reviewer": "^0.14.0"
43
51
  },
44
52
  "devDependencies": {
45
53
  "@deepseek-ai/cordis": "~4.0.4",
46
- "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
47
- "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
48
- "@deepseek-ai/dsh-agent-preset-registry": "0.2.0-rc.2",
49
54
  "@deepseek-ai/dsh-client-connection": "0.2.0-rc.2",
50
- "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
51
- "@deepseek-ai/dsh-session": "0.2.0-rc.2",
52
- "@deepseek-ai/dsh-session-title": "0.2.0-rc.2",
53
- "@deepseek-ai/dsh-subagent": "0.2.0-rc.2",
54
- "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
55
55
  "@testing-library/jest-dom": "^7.0.1",
56
56
  "@testing-library/react": "^16.3.3",
57
57
  "@types/node": "^22.0.0",
@@ -65,26 +65,9 @@
65
65
  "vitest": "^3.2.4",
66
66
  "yaml": "^2.9.0"
67
67
  },
68
- "dsh": {
69
- "bundle": {
70
- "patch": [
71
- "./cordis.patch.yml",
72
- "./presets/maestro-reviewer.patch.yml",
73
- "./presets/maestro-auditor.patch.yml"
74
- ]
75
- },
76
- "client": {
77
- "platform": "web",
78
- "inject": [
79
- "@deepseek-ai/dsh-client-connection",
80
- "@deepseek-ai/dsh-client-ui-slots"
81
- ]
82
- }
83
- },
84
68
  "scripts": {
85
69
  "build": "tsc -p tsconfig.json && tsc -p tsconfig.client.json && node scripts/build-client.mjs",
86
- "test": "NODE_ENV=test vitest run",
87
70
  "verify": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
88
- "docker:build": "docker build -f docker/Dockerfile -t ddtcorex/maestro-reviewer:0.12.0 -t ddtcorex/maestro-reviewer:latest ."
71
+ "test": "NODE_ENV=test vitest run"
89
72
  }
90
73
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh-maestro-review — client bundle entry.
2
+ * dsh-maestro-review: client bundle entry.
3
3
  *
4
4
  * Registers `settings.section` id `maestro-review` (order 32): the GitLab and
5
5
  * Review keys this package owns.
@@ -1,4 +1,6 @@
1
- import type { ModelSelection } from '@deepseek-ai/dsh-agent'
1
+ import type { EngineRunOptions } from '@ddtcorex/maestro-reviewer/lib/engine.js'
2
+
3
+ type ModelSelection = EngineRunOptions['model']
2
4
 
3
5
  declare module '@deepseek-ai/dsh-host-webserver' {}
4
6
  declare module '@deepseek-ai/dsh-client-ui-slots' {}
@@ -1,7 +1,7 @@
1
1
  import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
2
2
  import { homedir } from 'node:os'
3
3
  import { dirname, join } from 'node:path'
4
- import type { ReviewSkillProfile } from './skills-tool.js'
4
+ import type { ReviewSkillProfile } from '@ddtcorex/maestro-reviewer/lib/skills-tool.js'
5
5
  import {
6
6
  RUNTIME_KEYS,
7
7
  readFlat,
@@ -93,7 +93,7 @@ const REVIEW_OWNED_KEYS = [
93
93
  * Machine runtime state (RUNTIME_KEYS) never enters settings — it stays in this
94
94
  * package's own sidecar so a settings edit can never silently flip tunnel state.
95
95
  */
96
- function runtimeStatePath(dshHome?: string): string {
96
+ export function runtimeStatePath(dshHome?: string): string {
97
97
  return join(resolveDshHome(dshHome), 'dsh-maestro-review', 'runtime.json')
98
98
  }
99
99
 
@@ -1,54 +1,14 @@
1
- export interface MrOpenedPayload {
2
- projectPath: string
3
- projectId: number
4
- mrIid: number
5
- sourceBranch: string
6
- }
7
-
8
- export type ReviewMode = 'quick' | 'deep'
9
-
10
- export type ReviewScope =
11
- | { kind: 'mr' }
12
- | { kind: 'discussion'; discussionId: string; path: string; line: number }
13
-
14
- import type { ReviewSkillProfile } from './skills-tool.js'
15
-
16
- export interface ReviewRequest extends MrOpenedPayload {
17
- /** `push` arrives only when auto re-review on push is enabled and passes the completed-history gate. */
18
- trigger: 'reviewer-assignment' | 'mention' | 'push'
19
- mode: ReviewMode
20
- scope: ReviewScope
21
- /**
22
- * CI-only override (ci-trigger sets it from REVIEW_PROFILE). The GitLab webhook
23
- * producer never sets it — mapped projects resolve their profile from the mapping.
24
- * Undefined preserves the legacy diff-only generic review.
25
- */
26
- reviewProfile?: ReviewSkillProfile
27
- /**
28
- * CI-only: MR head SHA from fetchMrDetail (ci-trigger sets it). Feeds the
29
- * comment marker so later CI runs can yield to this review. The GitLab
30
- * webhook producer never sets it — webhook comments stay marker-free.
31
- */
32
- headSha?: string
33
- /** Short (8-char) head-sha hint for `push` triggers, taken from the webhook
34
- * body — feeds the in-flight key so two concurrent pushes stop deduping
35
- * each other. Absent when the body carries no sha. */
36
- pushSha?: string
37
- }
38
-
39
- export interface ReviewResult {
40
- /** false = the review could not run or failed outright (infra error) — a CI caller should exit non-zero. */
41
- ok: boolean
42
- summary?: string
43
- failures: string[]
44
- durationMs: number
45
- }
1
+ import type { ReviewRequest, ReviewResult } from '@ddtcorex/maestro-reviewer/lib/events.js'
2
+ import type { ReviewEngine } from '@ddtcorex/maestro-reviewer/lib/engine.js'
46
3
 
4
+ /** Host contracts: the webhook emits review requests, the host orchestrator runs them. */
47
5
  declare module '@deepseek-ai/cordis' {
48
6
  interface Events {
49
7
  'maestro/review-request': (payload: ReviewRequest) => void
50
8
  }
51
9
  interface Context {
52
10
  reviewRunner: (payload: ReviewRequest) => Promise<ReviewResult>
11
+ /** Provided by the engine's `maestro-review-engine` row (redeclared here: the engine augments its own cordis copy). */
12
+ reviewEngine: ReviewEngine
53
13
  }
54
14
  }
@@ -0,0 +1,461 @@
1
+ import { mkdir, writeFile, symlink, stat, lstat } from 'node:fs/promises'
2
+ import { execFile } from 'node:child_process'
3
+ import { promisify } from 'node:util'
4
+ import { join } from 'node:path'
5
+ import type { Context } from '@deepseek-ai/cordis'
6
+ import z from '@deepseek-ai/schemastery'
7
+ import type { ReviewRequest, ReviewResult } from '@ddtcorex/maestro-reviewer/lib/events.js'
8
+ import type { ReviewSkillProfile } from '@ddtcorex/maestro-reviewer/lib/skills-tool.js'
9
+ import { govardOnPath } from '@ddtcorex/maestro-reviewer/lib/govard-lint-detection.js'
10
+ import { hasCompletedReview, pruneHistory, recordReviewFinish, recordReviewStart } from '@ddtcorex/maestro-reviewer/lib/review-history.js'
11
+ import { gitlabForge } from '@ddtcorex/maestro-reviewer/lib/forge/gitlab/index.js'
12
+ import { assertSafeBranchName, declineUnmappedDeepReview, isBranchNotFoundError, type ReviewCommentDeps } from '@ddtcorex/maestro-reviewer/lib/orchestrator.js'
13
+ import { DEDUPED_SUMMARY, removeWorktree, toModelSelection, writeFailedReport, type CodeAccess, type EngineGitlab, type EngineRunOptions } from '@ddtcorex/maestro-reviewer/lib/engine.js'
14
+
15
+ /** The engine's model selection type (its own dsh-agent copy). */
16
+ type ModelSelection = EngineRunOptions['model']
17
+ import { loadUserConfig, type MaestroUserConfig, type ProjectMapping, type ReviewModelSelection } from './config-store.js'
18
+ import { reviewDigestText, type NotifierLike } from './notify.js'
19
+ import './events.js'
20
+
21
+ /**
22
+ * Row `maestro-review-host-orchestrator`: the DSH host side of a review. It
23
+ * listens for `maestro/review-request` (webhook intake), resolves user
24
+ * settings and project mappings, applies the trigger gates, prepares worktrees
25
+ * (vendor and govard environment linking) and calls the engine.
26
+ */
27
+ export const name = 'maestro-review-host-orchestrator'
28
+ export const inject = ['reviewEngine', 'agentDefaultModel']
29
+
30
+ const execFileAsync = promisify(execFile)
31
+ const GIT_TIMEOUT_MS = 60_000
32
+
33
+ /**
34
+ * Resolve the model to use for an automated review. Priority: per-project
35
+ * override > global reviewModel (Maestro Settings) > row-config reviewModel
36
+ * (lets a headless profile such as reviewer-ci pin a model from env vars,
37
+ * where there is no Settings UI) > DSH default (`fallback`).
38
+ */
39
+ export function resolveReviewModel(
40
+ userConfig: MaestroUserConfig,
41
+ mapping: { reviewModel?: ReviewModelSelection | null; projectPath?: string } | undefined,
42
+ fallback: ModelSelection,
43
+ rowSelection?: ReviewModelSelection | null,
44
+ ): ModelSelection {
45
+ const raw = (mapping?.reviewModel as ReviewModelSelection | null | undefined) ?? userConfig.reviewModel ?? rowSelection
46
+ if (raw === undefined || raw === null) return fallback
47
+ return toModelSelection(raw)
48
+ }
49
+
50
+ /** Effective auto-trigger flags: per-project row overrides global, unset inherits (design §4). */
51
+ export function resolveReviewTriggers(
52
+ userConfig: MaestroUserConfig,
53
+ mapping?: ProjectMapping,
54
+ ): { onPush: boolean; onAssign: boolean } {
55
+ return {
56
+ onPush: mapping?.rereviewOnPush ?? userConfig.autoRereviewOnPush ?? false,
57
+ onAssign: mapping?.reviewOnAssign ?? userConfig.autoReviewOnAssign ?? true,
58
+ }
59
+ }
60
+
61
+ export interface Config {
62
+ projectMappings: Array<{ projectPath: string; localRepoPath: string; reviewProfile: ReviewSkillProfile }>
63
+ gitlabBaseUrl: string
64
+ /**
65
+ * Fallback when Maestro Settings has no token; optional so a deployment that
66
+ * configures everything through Settings boots without env vars.
67
+ */
68
+ gitlabToken?: string
69
+ botUsername: string
70
+ /** Hard ceiling on one automated agent's turn. */
71
+ agentTimeoutMs: number
72
+ /**
73
+ * Deployment-level model pin, below Maestro Settings in precedence. Lets a
74
+ * headless profile (reviewer-ci) select the review model from env vars —
75
+ * e.g. REVIEW_MODEL_PROVIDER/REVIEW_MODEL — where no Settings UI exists.
76
+ *
77
+ * Deliberately absent from the zod schema below: schemastery object schemas
78
+ * always descend into inner fields (probed — even `.required(false)` still
79
+ * throws on undefined), so declaring it would fail every boot without the
80
+ * vars. Unknown keys pass validation through (same precedent as mapping-level
81
+ * reviewModel, which the projectMappings schema doesn't declare either),
82
+ * and resolveReviewModel reads it at review time.
83
+ */
84
+ reviewModel?: ReviewModelSelection | null
85
+ }
86
+
87
+ export const DEFAULT_AGENT_TIMEOUT_MS = 20 * 60_000
88
+
89
+ export const Config: z<Config> = z.object({
90
+ projectMappings: z.array(z.object({
91
+ projectPath: z.string().required(),
92
+ localRepoPath: z.string().required(),
93
+ reviewProfile: z.union([z.const('magento2'), z.const('laravel'), z.const('symfony'), z.const('wordpress'), z.const('generic')]).default('magento2'),
94
+ })).required(),
95
+ gitlabBaseUrl: z.string().required(),
96
+ gitlabToken: z.string().role('secret'),
97
+ botUsername: z.string().required(),
98
+ agentTimeoutMs: z.number().min(1000).default(DEFAULT_AGENT_TIMEOUT_MS),
99
+ })
100
+
101
+ /** Upper bound for the best-effort `govard env down -v` run by the orchestrator. */
102
+ export const GOVARD_TEARDOWN_TIMEOUT_MS = 120_000
103
+
104
+ type TeardownRun = (file: string, args: string[], opts: { cwd: string; timeout: number }) => Promise<unknown>
105
+
106
+ /**
107
+ * Tear down the review worktree's govard environment (`govard env down -v`,
108
+ * cwd = the worktree, whose `.govard.local.yml` names the per-MR project).
109
+ * Never throws: it runs in cleanup paths where a failure must not mask the
110
+ * review result, so a failure is logged as a warning instead.
111
+ */
112
+ export async function teardownGovardEnvironment(worktreePath: string, run: TeardownRun = execFileAsync): Promise<void> {
113
+ try {
114
+ await run('govard', ['env', 'down', '-v'], { cwd: worktreePath, timeout: GOVARD_TEARDOWN_TIMEOUT_MS })
115
+ } catch (err) {
116
+ console.warn(`maestro-orchestrator: govard env down -v failed in ${worktreePath}: ${err instanceof Error ? err.message : String(err)}`)
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Keep a Govard audit worktree isolated from the developer's primary checkout.
122
+ * Without this local override, both checkouts inherit the same `project_name`
123
+ * and Govard may either reject the worktree or run commands in the wrong stack.
124
+ */
125
+ export function govardWorktreeOverride(projectId: number, mrIid: number, keySuffix?: string): string {
126
+ const name = `maestro-mr-${projectId}-${mrIid}${keySuffix === undefined ? '' : `-${keySuffix}`}`
127
+ // Xdebug stays off in review envs: the auditor runs no coverage, and an
128
+ // enabled Xdebug trips govard's lint perf-tax guard (exit 1, 0 findings).
129
+ return `project_name: ${name}\ndomain: ${name}.test\nstack:\n features:\n xdebug: false\n`
130
+ }
131
+
132
+
133
+ async function pathExists(path: string): Promise<boolean> {
134
+ try {
135
+ await stat(path)
136
+ return true
137
+ } catch {
138
+ return false
139
+ }
140
+ }
141
+
142
+ export async function ensureWorktree(localRepoPath: string, sourceBranch: string, projectId: number, mrIid: number, keySuffix?: string): Promise<string> {
143
+ assertSafeBranchName(sourceBranch)
144
+ const worktreePath = join('/tmp', `maestro-mr-${projectId}-${mrIid}${keySuffix === undefined ? '' : `-${keySuffix}`}`)
145
+ try {
146
+ await execFileAsync('git', ['fetch', '--', 'origin', sourceBranch], { cwd: localRepoPath, timeout: GIT_TIMEOUT_MS })
147
+ } catch (err) {
148
+ if (isBranchNotFoundError(err)) {
149
+ const e = new Error(`branch not found on origin: ${sourceBranch}`)
150
+ ;(e as unknown as { code: string }).code = 'BRANCH_NOT_FOUND'
151
+ ;(e as unknown as { cause: unknown }).cause = err
152
+ throw e
153
+ }
154
+ throw err
155
+ }
156
+ // A host restart can interrupt an active review before its `finally` cleanup.
157
+ // Recover only this deterministic Maestro-owned path so the next delivery can
158
+ // retry; an unrelated worktree is never targeted. An interrupted deep audit
159
+ // may also have left its govard containers up, so the stale worktree's
160
+ // environment goes down first (only when it carries the per-MR override that
161
+ // names the project, and best effort).
162
+ if (govardOnPath() && await pathExists(join(worktreePath, '.govard.local.yml'))) await teardownGovardEnvironment(worktreePath)
163
+ await execFileAsync('git', ['worktree', 'remove', '--force', worktreePath], { cwd: localRepoPath, timeout: GIT_TIMEOUT_MS })
164
+ .catch(() => {})
165
+ await execFileAsync('git', ['worktree', 'add', '--', worktreePath, `origin/${sourceBranch}`], { cwd: localRepoPath, timeout: GIT_TIMEOUT_MS })
166
+ await writeFile(join(worktreePath, '.govard.local.yml'), govardWorktreeOverride(projectId, mrIid, keySuffix), 'utf-8')
167
+ await linkVendorIntoWorktree(localRepoPath, worktreePath)
168
+ await writeContainerVendorOverride(localRepoPath, worktreePath)
169
+ return worktreePath
170
+ }
171
+
172
+ /**
173
+ * A vendor dir only counts as installed dependencies when the composer
174
+ * autoloader is a real file. Magento tracks `vendor/.htaccess`, so every
175
+ * worktree has a vendor/ stub — that stub must not pass for real deps, and
176
+ * must not block the container bind that provides them.
177
+ */
178
+ export async function vendorHasAutoload(dir: string): Promise<boolean> {
179
+ try {
180
+ return (await stat(join(dir, 'vendor', 'autoload.php'))).isFile()
181
+ } catch {
182
+ return false
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Share the primary checkout's `vendor/` (and `app/etc/env.php` when the
188
+ * auditor needs a database) into the review worktree via symlinks, so
189
+ * phpunit/static analysis run against real dependencies instead of falling
190
+ * back to static-only. Links point INTO the worktree only — the primary
191
+ * checkout is never written to — and `git worktree remove --force` deletes
192
+ * the links along with the worktree. Missing sources, or targets that
193
+ * already exist (e.g. Magento's tracked `vendor/.htaccess` stub), are
194
+ * skipped quietly: the review still runs, the auditor discloses it.
195
+ */
196
+ export async function linkVendorIntoWorktree(localRepoPath: string, worktreePath: string): Promise<string[]> {
197
+ const linked: string[] = []
198
+ const candidates: Array<{ source: string; target: string; dir: boolean; needsAutoload: boolean }> = [
199
+ { source: join(localRepoPath, 'vendor'), target: join(worktreePath, 'vendor'), dir: true, needsAutoload: true },
200
+ { source: join(localRepoPath, 'app', 'etc', 'env.php'), target: join(worktreePath, 'app', 'etc', 'env.php'), dir: false, needsAutoload: false },
201
+ ]
202
+ let advertised = false
203
+ for (const { source, target, dir, needsAutoload } of candidates) {
204
+ let isDir = false
205
+ try {
206
+ isDir = (await stat(source)).isDirectory()
207
+ if (dir !== isDir) continue
208
+ } catch {
209
+ continue
210
+ }
211
+ if (needsAutoload && !(await vendorHasAutoload(localRepoPath))) continue
212
+ if ((await lstat(target).catch(() => undefined)) !== undefined) {
213
+ console.error(`maestro-orchestrator: link target exists, skipping ${target}`)
214
+ continue
215
+ }
216
+ try {
217
+ if (!advertised) {
218
+ const sha = await execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: localRepoPath, timeout: GIT_TIMEOUT_MS })
219
+ .then(({ stdout }) => stdout.trim()).catch(() => 'unknown')
220
+ console.error(`maestro-orchestrator: linking vendor from ${localRepoPath} @ ${sha} into ${worktreePath}`)
221
+ advertised = true
222
+ }
223
+ if (!dir) await mkdir(join(worktreePath, 'app', 'etc'), { recursive: true })
224
+ await symlink(source, target, dir ? 'dir' : 'file')
225
+ linked.push(target)
226
+ } catch (err) {
227
+ console.error(`maestro-orchestrator: failed to link ${source} into worktree:`, err)
228
+ }
229
+ }
230
+ if (!advertised) {
231
+ console.error(`maestro-orchestrator: no vendor/ in ${localRepoPath} — worktree ${worktreePath} runs without shared dependencies`)
232
+ }
233
+ return linked
234
+ }
235
+
236
+ /** Container path of the project root inside govard services. */
237
+ const GOVARD_CONTAINER_WORKDIR = '/var/www/html'
238
+
239
+ /**
240
+ * Render a compose override that bind-mounts the primary checkout's vendor/
241
+ * read-only into the php service. A host-side symlink alone dangles inside
242
+ * containers (absolute host path), so container tools (phpunit) need this
243
+ * bind to see real dependencies.
244
+ *
245
+ * The project mount (`.`) MUST be repeated first: govard merges overrides
246
+ * with MergeMap, which REPLACES lists instead of appending — an override
247
+ * carrying only the vendor bind would wipe `.:<workdir>` and leave the
248
+ * container docroot holding nothing but vendor/. Relative `.` resolves
249
+ * against the project root because govard passes --project-directory.
250
+ *
251
+ * Only the always-present `php` service is targeted: `php-debug` drops out
252
+ * of the rendered base when xdebug is off, and a volumes-only override
253
+ * entry would recreate it as a hollow service that fails compose validation.
254
+ */
255
+ export function buildVendorOverrideYaml(vendorHostPath: string, envHostPath?: string, containerWorkDir: string = GOVARD_CONTAINER_WORKDIR): string {
256
+ const volumes = [
257
+ `.:${containerWorkDir}`,
258
+ `${vendorHostPath}:${containerWorkDir}/vendor:ro`,
259
+ ...(envHostPath !== undefined ? [`${envHostPath}:${containerWorkDir}/app/etc/env.php:ro`] : []),
260
+ ]
261
+ const service = ` volumes:\n${volumes.map((v) => ` - ${v}\n`).join('')}`
262
+ return `services:\n php:\n${service}`
263
+ }
264
+
265
+ /**
266
+ * Drop the vendor bind override into the worktree (merged by govard via
267
+ * `.govard/docker-compose.override.yml`). Binds only when the primary
268
+ * checkout carries installed deps and the worktree does not — never shadow
269
+ * real deps with a possibly stale bind. Returns the written path, or
270
+ * undefined when skipped.
271
+ */
272
+ export async function writeContainerVendorOverride(localRepoPath: string, worktreePath: string): Promise<string | undefined> {
273
+ const vendorHostPath = join(localRepoPath, 'vendor')
274
+ if (!(await vendorHasAutoload(localRepoPath))) return undefined
275
+ // Our own host-side symlink still needs the bind (it dangles in-container);
276
+ // only a real installed worktree vendor makes the bind redundant.
277
+ const wtLink = await lstat(join(worktreePath, 'vendor')).catch(() => undefined)
278
+ if (wtLink?.isSymbolicLink() !== true && await vendorHasAutoload(worktreePath)) return undefined
279
+ const overridePath = join(worktreePath, '.govard', 'docker-compose.override.yml')
280
+ await mkdir(join(worktreePath, '.govard'), { recursive: true })
281
+ // A linked env.php dangles in-container like the vendor symlink did — bind
282
+ // the real file over it when the primary checkout carries one.
283
+ const envHostPath = join(localRepoPath, 'app', 'etc', 'env.php')
284
+ let envBind: string | undefined
285
+ try {
286
+ if ((await stat(envHostPath)).isFile()) envBind = envHostPath
287
+ } catch {
288
+ envBind = undefined
289
+ }
290
+ await writeFile(overridePath, buildVendorOverrideYaml(vendorHostPath, envBind), 'utf-8')
291
+ console.error(`maestro-orchestrator: container vendor bind ${vendorHostPath} -> ${GOVARD_CONTAINER_WORKDIR}/vendor (ro) for ${worktreePath}`)
292
+ return overridePath
293
+ }
294
+
295
+ export function apply(ctx: Context, config: Config): void {
296
+ async function runReview(payload: ReviewRequest): Promise<ReviewResult> {
297
+ const t0 = Date.now()
298
+ try {
299
+ const userConfig = await loadUserConfig()
300
+ const effective = {
301
+ gitlabBaseUrl: userConfig.gitlabBaseUrl ?? config.gitlabBaseUrl,
302
+ gitlabToken: userConfig.gitlabToken ?? config.gitlabToken,
303
+ botUsername: userConfig.botUsername ?? config.botUsername,
304
+ projectMappings: userConfig.projectMappings ?? config.projectMappings,
305
+ }
306
+ // Resolved per review run from Settings so an agentTimeoutMs change takes
307
+ // effect without a plugin restart.
308
+ const agentTimeoutMs = typeof userConfig.agentTimeoutMs === 'number' && userConfig.agentTimeoutMs >= 1000
309
+ ? userConfig.agentTimeoutMs
310
+ : config.agentTimeoutMs
311
+ // Best-effort housekeeping; a prune failure must never block a review.
312
+ if (typeof userConfig.reviewSessionRetentionDays === 'number' && userConfig.reviewSessionRetentionDays > 0) {
313
+ void pruneHistory(userConfig.reviewSessionRetentionDays).catch((err: unknown) => {
314
+ console.error('maestro-orchestrator: review history prune failed:', err)
315
+ })
316
+ }
317
+ const mapping = effective.projectMappings.find(m => m.projectPath === payload.projectPath)
318
+ // Unmapped reviewer assignments remain no-ops. Only an explicit mention
319
+ // may opt into the intentionally limited, diff-only fallback below.
320
+ if (mapping === undefined && payload.trigger !== 'mention') {
321
+ console.error(`maestro-orchestrator: drop unmapped project=${payload.projectPath} mr=!${payload.mrIid} trigger=${payload.trigger}`)
322
+ return { ok: true, failures: [], durationMs: Date.now() - t0 }
323
+ }
324
+ const triggers = resolveReviewTriggers(userConfig, mapping)
325
+ // Gated-off auto-triggers stay fully silent: no history, no signals, no comment (host log only).
326
+ if (payload.trigger === 'reviewer-assignment' && !triggers.onAssign) {
327
+ console.error(`maestro-orchestrator: drop assign-gate-off project=${payload.projectPath} mr=!${payload.mrIid} trigger=${payload.trigger}`)
328
+ return { ok: true, failures: [], durationMs: Date.now() - t0 }
329
+ }
330
+ if (payload.trigger === 'push' && !triggers.onPush) {
331
+ console.error(`maestro-orchestrator: drop push-gate-off project=${payload.projectPath} mr=!${payload.mrIid} trigger=${payload.trigger}`)
332
+ return { ok: true, failures: [], durationMs: Date.now() - t0 }
333
+ }
334
+ // A push only re-reviews an MR that already has a completed review;
335
+ // otherwise every newly opened MR would be reviewed twice.
336
+ if (payload.trigger === 'push' && !(await hasCompletedReview(payload.projectId, payload.mrIid))) {
337
+ console.error(`maestro-orchestrator: drop push-no-completed-history project=${payload.projectPath} mr=!${payload.mrIid} trigger=${payload.trigger}`)
338
+ return { ok: true, failures: [], durationMs: Date.now() - t0 }
339
+ }
340
+ const { gitlabToken } = effective
341
+ if (gitlabToken === undefined) {
342
+ const message = `MR !${String(payload.mrIid)} for project ${payload.projectPath} has no GitLab token — set one in Maestro Settings or MAESTRO_GITLAB_TOKEN`
343
+ console.error(`maestro-orchestrator: drop missing-token project=${payload.projectPath} mr=!${String(payload.mrIid)} trigger=${payload.trigger} — ${message}`)
344
+ return { ok: false, failures: [message], durationMs: Date.now() - t0 }
345
+ }
346
+ const gitlab = { baseUrl: effective.gitlabBaseUrl, token: gitlabToken, botUsername: effective.botUsername }
347
+ const fallbackSelection: ModelSelection = (ctx.get?.('agentDefaultModel') as { currentSelection(): ModelSelection } | undefined)?.currentSelection()
348
+ ?? (ctx as unknown as { agentDefaultModel?: { currentSelection(): ModelSelection } }).agentDefaultModel?.currentSelection()
349
+ ?? { provider: 'fallback', model: 'fallback' }
350
+ const model = resolveReviewModel(userConfig, mapping, fallbackSelection, config.reviewModel)
351
+ // Opt-in Telegram digest; a delivery failure is logged and dropped.
352
+ const reviewStartMsOuter = Date.now()
353
+ const notifyTelegram = (status: 'completed' | 'failed', summary?: string, durationMs?: number): void => {
354
+ if (userConfig.telegramReviewNotifications !== true) return
355
+ const notifier = ctx.get?.('maestroNotifier') as NotifierLike | undefined
356
+ if (notifier === undefined) return
357
+ void notifier.send(
358
+ 'telegram',
359
+ { botToken: userConfig.telegramBotToken, chatId: userConfig.telegramChatId },
360
+ {
361
+ text: reviewDigestText({
362
+ projectPath: payload.projectPath,
363
+ mrIid: payload.mrIid,
364
+ status,
365
+ summary,
366
+ mode: payload.mode,
367
+ profile: mapping?.reviewProfile,
368
+ gitlabBaseUrl: gitlab.baseUrl,
369
+ // The engine measures from the MR signals start; the decline has no engine run.
370
+ durationMs: durationMs ?? Date.now() - reviewStartMsOuter,
371
+ }),
372
+ },
373
+ ).then((result) => {
374
+ if (!result.sent && result.reason === 'request-failed') {
375
+ console.error(`maestro-orchestrator: Telegram review notification for MR !${String(payload.mrIid)} failed to deliver`)
376
+ }
377
+ }).catch((err) => {
378
+ // Delivery is fire-and-forget: a rejection must not escape into the
379
+ // host's unhandled-rejection path, which exits the whole process.
380
+ console.error(
381
+ `maestro-orchestrator: Telegram review notification for MR !${String(payload.mrIid)} threw:`,
382
+ err instanceof Error ? err.message : err,
383
+ )
384
+ })
385
+ }
386
+ if (mapping === undefined && payload.mode === 'deep') {
387
+ return await declineUnmappedDeep(payload, gitlab, notifyTelegram, t0)
388
+ }
389
+ let access: CodeAccess
390
+ let reviewProfile: ReviewSkillProfile | undefined
391
+ if (mapping !== undefined) {
392
+ access = {
393
+ kind: 'workspace',
394
+ localRepoPath: mapping.localRepoPath,
395
+ ensureWorktree,
396
+ removeWorktree,
397
+ ...(govardOnPath() ? { teardownEnvironment: teardownGovardEnvironment } : {}),
398
+ auditor: 'runtime',
399
+ }
400
+ reviewProfile = mapping.reviewProfile
401
+ } else {
402
+ access = { kind: 'diff' }
403
+ }
404
+ return await ctx.reviewEngine.run(payload, { gitlab, access, reviewProfile, model, agentTimeoutMs, notify: notifyTelegram })
405
+ } catch (err) {
406
+ const message = err instanceof Error ? err.message : String(err)
407
+ console.error(`maestro-orchestrator: review run failed for MR !${String(payload.mrIid)}:`, err)
408
+ return { ok: false, summary: undefined, failures: [message], durationMs: Date.now() - t0 }
409
+ }
410
+ }
411
+
412
+ ctx.on('maestro/review-request', (payload) => { void runReview(payload) })
413
+ ctx.provide('reviewRunner', runReview)
414
+ }
415
+
416
+ /** Host-only: a deep request on an unmapped project gets a "not started" note, recorded like a run. */
417
+ async function declineUnmappedDeep(
418
+ payload: ReviewRequest,
419
+ gitlab: EngineGitlab,
420
+ notify: (status: 'completed' | 'failed', summary?: string) => void,
421
+ t0: number,
422
+ ): Promise<ReviewResult> {
423
+ const historyId = `${payload.projectId}-${payload.mrIid}-${Date.now()}`
424
+ const forge = gitlabForge(gitlab, payload)
425
+ const currentHeadSha = await forge.mrHeadSha().catch(() => undefined)
426
+ await recordReviewStart({
427
+ id: historyId,
428
+ projectId: payload.projectId,
429
+ projectPath: payload.projectPath,
430
+ mrIid: payload.mrIid,
431
+ mode: payload.mode,
432
+ scope: payload.scope.kind,
433
+ trigger: payload.trigger,
434
+ startedAt: Date.now(),
435
+ headSha: currentHeadSha,
436
+ })
437
+ const signals = payload.scope.kind === 'mr' ? forge.signals() : undefined
438
+ await signals?.start()
439
+ const postComment = (body: string) => forge.postNote(body)
440
+ const replyToDiscussion = (discussionId: string, body: string) => forge.replyToDiscussion(discussionId, body)
441
+ try {
442
+ const declined = await declineUnmappedDeepReview(payload, { postComment, replyToDiscussion, writeFailedReport, gitlabBaseUrl: gitlab.baseUrl } as unknown as ReviewCommentDeps)
443
+ if (!declined) {
444
+ console.error(`maestro-orchestrator: deduped duplicate in-flight review project=${payload.projectPath} mr=!${payload.mrIid} trigger=${payload.trigger}`)
445
+ await recordReviewFinish(historyId, { status: 'completed', summary: DEDUPED_SUMMARY })
446
+ await signals?.finish('completed')
447
+ return { ok: true, summary: DEDUPED_SUMMARY, failures: [], durationMs: Date.now() - t0 }
448
+ }
449
+ const summary = 'Deep review declined (unmapped project)'
450
+ await recordReviewFinish(historyId, { status: 'completed', summary })
451
+ notify('completed', summary)
452
+ await signals?.finish('completed')
453
+ return { ok: true, summary, failures: [], durationMs: Date.now() - t0 }
454
+ } catch (err) {
455
+ const message = err instanceof Error ? err.message : String(err)
456
+ await recordReviewFinish(historyId, { status: 'failed', error: message }).catch(() => {})
457
+ notify('failed', message)
458
+ await signals?.finish('failed')
459
+ return { ok: false, summary: undefined, failures: [message], durationMs: Date.now() - t0 }
460
+ }
461
+ }