agent-steward 0.0.4 → 0.0.6

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 (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
@@ -0,0 +1,330 @@
1
+ /**
2
+ * G-1.2: проверяемый snapshot входов Quality Gate.
3
+ *
4
+ * Обёртка фиксирует хэш команды/хука гейта, промпта и таймаута в момент
5
+ * создания задачи (файл лежит в PLUGIN_DIR, вне write-scope агента) и
6
+ * сверяет его непосредственно перед запуском гейта. Подмена гейта или
7
+ * промпта после создания задачи приводит к fail-closed: гейт не выполняется,
8
+ * запуск помечается ошибкой. Snapshot защищает от подмены *definition*
9
+ * гейта; исходники, которые гейт проверяет, в хэш не входят (агент
10
+ * legitimately меняет их в ходе задачи).
11
+ */
12
+ import { execFileSync } from "node:child_process";
13
+ import crypto from "node:crypto";
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { PLUGIN_DIR, sanitizeName } from "../types.js";
18
+
19
+ export const GATE_SNAPSHOT_VERSION = 1;
20
+ export const GATE_SNAPSHOT_DIR = path.join(PLUGIN_DIR, "gate-snapshots");
21
+
22
+ export interface GateSnapshotInputs {
23
+ /** Текст гейта: на Windows — содержимое hook-файла, на POSIX — команда. */
24
+ gate: string;
25
+ /** Текст промпта задачи. */
26
+ prompt: string;
27
+ /** Таймаут гейта в секундах. */
28
+ gateTimeoutSeconds: number;
29
+ }
30
+
31
+ export interface GateSnapshot {
32
+ version: number;
33
+ taskName: string;
34
+ createdAt: string;
35
+ hash: string;
36
+ }
37
+
38
+ /** Канонический хэш входов гейта. Порядок полей фиксирован контрактом. */
39
+ export function gateInputsHash(inputs: GateSnapshotInputs): string {
40
+ const canonical = JSON.stringify({
41
+ version: GATE_SNAPSHOT_VERSION,
42
+ gate: inputs.gate,
43
+ prompt: inputs.prompt,
44
+ gateTimeoutSeconds: inputs.gateTimeoutSeconds,
45
+ });
46
+ return crypto.createHash("sha256").update(canonical, "utf8").digest("hex");
47
+ }
48
+
49
+ /** Путь snapshot'а задачи — вне рабочей директории задачи. */
50
+ export function gateSnapshotPath(taskName: string): string {
51
+ const segment = sanitizeName(taskName).slice(0, 80) || "task";
52
+ return path.join(GATE_SNAPSHOT_DIR, `${segment}.json`);
53
+ }
54
+
55
+ function readText(file: string | undefined): string {
56
+ if (!file) return "";
57
+ try {
58
+ return fs.readFileSync(file, "utf8");
59
+ } catch {
60
+ return "";
61
+ }
62
+ }
63
+
64
+ /** Пишет snapshot задачам на этапе создания обёртки (fail-closed при ошибке). */
65
+ export function createGateSnapshot(
66
+ taskName: string,
67
+ inputs: GateSnapshotInputs,
68
+ snapshotFile = gateSnapshotPath(taskName),
69
+ ): string {
70
+ const snapshot: GateSnapshot = {
71
+ version: GATE_SNAPSHOT_VERSION,
72
+ taskName,
73
+ createdAt: new Date().toISOString(),
74
+ hash: gateInputsHash(inputs),
75
+ };
76
+ fs.mkdirSync(path.dirname(snapshotFile), { recursive: true });
77
+ fs.writeFileSync(snapshotFile, `${JSON.stringify(snapshot, null, 2)}\n`, {
78
+ encoding: "utf8",
79
+ mode: 0o600,
80
+ });
81
+ return snapshotFile;
82
+ }
83
+
84
+ export function readGateSnapshot(file: string): GateSnapshot | null {
85
+ try {
86
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
87
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
88
+ const value = parsed as Partial<GateSnapshot>;
89
+ if (value.version !== GATE_SNAPSHOT_VERSION) return null;
90
+ if (typeof value.hash !== "string" || !/^[0-9a-f]{64}$/.test(value.hash)) return null;
91
+ return {
92
+ version: value.version,
93
+ taskName: typeof value.taskName === "string" ? value.taskName : "",
94
+ createdAt: typeof value.createdAt === "string" ? value.createdAt : "",
95
+ hash: value.hash,
96
+ };
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ /** Сверяет текущие входы гейта с зафиксированными. При расхождении — fail-closed. */
103
+ export function verifyGateSnapshot(
104
+ snapshotFile: string,
105
+ inputs: GateSnapshotInputs,
106
+ ): { ok: boolean; reason?: string } {
107
+ const snapshot = readGateSnapshot(snapshotFile);
108
+ if (!snapshot) {
109
+ return { ok: false, reason: "snapshot гейта отсутствует или повреждён" };
110
+ }
111
+ const actual = gateInputsHash(inputs);
112
+ const expected = snapshot.hash;
113
+ const same =
114
+ Buffer.byteLength(actual) === Buffer.byteLength(expected) &&
115
+ crypto.timingSafeEqual(Buffer.from(actual, "utf8"), Buffer.from(expected, "utf8"));
116
+ if (!same) {
117
+ return { ok: false, reason: "входы Quality Gate изменены с момента создания задачи" };
118
+ }
119
+ return { ok: true };
120
+ }
121
+
122
+ function optionValue(argv: string[], name: string): string | undefined {
123
+ const index = argv.indexOf(name);
124
+ return index >= 0 ? argv[index + 1] : undefined;
125
+ }
126
+
127
+ /**
128
+ * PL-25: состояние отслеживаемых исходников на границе прогона.
129
+ *
130
+ * Хэш входов гейта (G-1.2) защищает от подмены самой команды, но не от
131
+ * чужого незакоммиченного кода: параллельная задача может изменить `src/`
132
+ * между стартом runners и post-flight гейтом, и гейт «позеленеет» на
133
+ * уже другом дереве. Фиксируем HEAD + `git status --porcelain` для `src/`.
134
+ */
135
+ export interface WorktreeSnapshot {
136
+ version: number;
137
+ head: string;
138
+ status: string;
139
+ capturedAt: string;
140
+ }
141
+
142
+ export const WORKTREE_SNAPSHOT_VERSION = 1;
143
+
144
+ /** Пути, за которыми следит гейт; по умолчанию только исходники плагина. */
145
+ export function worktreeGuardPaths(env: NodeJS.ProcessEnv = process.env): string[] {
146
+ const raw = env.AGENT_STEWARD_GATE_GUARD_PATHS?.trim();
147
+ if (!raw) return ["src"];
148
+ const parts = raw.split(/[|;]/).map((item) => item.trim()).filter(Boolean);
149
+ return parts.length ? parts : ["src"];
150
+ }
151
+
152
+ /**
153
+ * PL-47: пути, которые задача изменить вправе (обычно из `-Files` afterScript).
154
+ * Исключаются из сравнения со snapshot: агент спокойно правит свои файлы,
155
+ * а чужие правки в остальной части `src/` по-прежнему срывают гейт.
156
+ */
157
+ export function worktreeAllowPaths(env: NodeJS.ProcessEnv = process.env): string[] {
158
+ const raw = env.AGENT_STEWARD_GATE_ALLOW_PATHS?.trim();
159
+ if (!raw) return [];
160
+ return raw
161
+ .split(/[|;]/)
162
+ .map((item) => item.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, ""))
163
+ .filter(Boolean);
164
+ }
165
+
166
+ function pathIsAllowed(relative: string, allowed: string[]): boolean {
167
+ const normalized = relative.replace(/\\/g, "/").replace(/^\.\//, "").trim();
168
+ return allowed.some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`));
169
+ }
170
+
171
+ function gitOutput(dir: string, args: string[]): string | null {
172
+ try {
173
+ return execFileSync("git", ["-C", dir, ...args], {
174
+ encoding: "utf8",
175
+ windowsHide: true,
176
+ stdio: ["ignore", "pipe", "ignore"],
177
+ });
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ /** Возвращает null, если каталог не git-репозиторий или git недоступен. */
184
+ export function readWorktreeState(
185
+ dir: string,
186
+ env: NodeJS.ProcessEnv = process.env,
187
+ ): { head: string; status: string } | null {
188
+ const head = gitOutput(dir, ["rev-parse", "HEAD"]);
189
+ if (head === null) return null;
190
+ const status = gitOutput(dir, ["status", "--porcelain", "--untracked-files=no", "--", ...worktreeGuardPaths(env)]);
191
+ if (status === null) return null;
192
+ const allowed = worktreeAllowPaths(env);
193
+ let filtered = status;
194
+ if (allowed.length > 0) {
195
+ filtered = status
196
+ .split("\n")
197
+ .filter((line) => {
198
+ if (line.length < 4) return false;
199
+ const relative = line.slice(3).split(" -> ").pop()?.trim() ?? "";
200
+ return !pathIsAllowed(relative, allowed);
201
+ })
202
+ .join("\n");
203
+ }
204
+ return { head: head.trim(), status: filtered };
205
+ }
206
+
207
+ /** Пишет snapshot дерева; null — не git-репозиторий (гейт не блокируем). */
208
+ export function captureWorktreeSnapshot(
209
+ dir: string,
210
+ outFile: string,
211
+ env: NodeJS.ProcessEnv = process.env,
212
+ ): string | null {
213
+ const state = readWorktreeState(dir, env);
214
+ if (!state) return null;
215
+ const snapshot: WorktreeSnapshot = {
216
+ version: WORKTREE_SNAPSHOT_VERSION,
217
+ ...state,
218
+ capturedAt: new Date().toISOString(),
219
+ };
220
+ fs.mkdirSync(path.dirname(outFile), { recursive: true });
221
+ fs.writeFileSync(outFile, `${JSON.stringify(snapshot, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
222
+ return outFile;
223
+ }
224
+
225
+ export function readWorktreeSnapshot(file: string): WorktreeSnapshot | null {
226
+ try {
227
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
228
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
229
+ const value = parsed as Partial<WorktreeSnapshot>;
230
+ if (value.version !== WORKTREE_SNAPSHOT_VERSION) return null;
231
+ if (typeof value.head !== "string" || typeof value.status !== "string") return null;
232
+ return {
233
+ version: WORKTREE_SNAPSHOT_VERSION,
234
+ head: value.head,
235
+ status: value.status,
236
+ capturedAt: typeof value.capturedAt === "string" ? value.capturedAt : "",
237
+ };
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+
243
+ /** Сверяет дерево со snapshot'ом, снятым на старте задачи. */
244
+ export function verifyWorktreeSnapshot(
245
+ dir: string,
246
+ file: string,
247
+ env: NodeJS.ProcessEnv = process.env,
248
+ ): { ok: boolean; reason?: string } {
249
+ const snapshot = readWorktreeSnapshot(file);
250
+ if (!snapshot) {
251
+ return { ok: false, reason: "snapshot рабочего дерева отсутствует или повреждён" };
252
+ }
253
+ const actual = readWorktreeState(dir, env);
254
+ // Не git-репозиторий: нечего сравнивать, гейт работает по старой схеме.
255
+ if (!actual) return { ok: true };
256
+ if (actual.head !== snapshot.head) {
257
+ return { ok: false, reason: "HEAD изменился с момента старта задачи" };
258
+ }
259
+ if (actual.status !== snapshot.status) {
260
+ const paths = worktreeGuardPaths(env).join(", ");
261
+ return { ok: false, reason: `защищённые пути (${paths}) изменились с момента старта задачи` };
262
+ }
263
+ return { ok: true };
264
+ }
265
+
266
+ /**
267
+ * CLI для обёрток: `node gate-integrity.js verify --snapshot <file>
268
+ * --gate-file <file> | --gate-command <text> --prompt-file <file> --timeout <n>`.
269
+ * exit 0 — входы совпадают, exit 1 — расхождение/отсутствие snapshot'а.
270
+ */
271
+ export async function main(argv = process.argv.slice(2)): Promise<number> {
272
+ if (argv[0] === "worktree-snapshot") {
273
+ const dir = optionValue(argv, "--dir");
274
+ const outFile = optionValue(argv, "--out");
275
+ if (!dir || !outFile) {
276
+ console.error("gate-integrity: worktree-snapshot требует --dir и --out");
277
+ return 2;
278
+ }
279
+ const allow = optionValue(argv, "--allow");
280
+ captureWorktreeSnapshot(dir, outFile, allow ? { ...process.env, AGENT_STEWARD_GATE_ALLOW_PATHS: allow } : process.env);
281
+ return 0;
282
+ }
283
+ if (argv[0] === "worktree-verify") {
284
+ const dir = optionValue(argv, "--dir");
285
+ const file = optionValue(argv, "--snapshot");
286
+ if (!dir || !file) {
287
+ console.error("gate-integrity: worktree-verify требует --dir и --snapshot");
288
+ return 2;
289
+ }
290
+ const allow = optionValue(argv, "--allow");
291
+ const result = verifyWorktreeSnapshot(
292
+ dir,
293
+ file,
294
+ allow ? { ...process.env, AGENT_STEWARD_GATE_ALLOW_PATHS: allow } : process.env,
295
+ );
296
+ if (!result.ok) {
297
+ console.error(`gate-integrity: ${result.reason ?? "рабочее дерево изменилось"}`);
298
+ return 1;
299
+ }
300
+ return 0;
301
+ }
302
+ if (argv[0] !== "verify") {
303
+ console.error("gate-integrity: поддерживаются verify, worktree-snapshot, worktree-verify");
304
+ return 2;
305
+ }
306
+ const snapshotFile = optionValue(argv, "--snapshot");
307
+ if (!snapshotFile) {
308
+ console.error("gate-integrity: не задан --snapshot");
309
+ return 2;
310
+ }
311
+ const gateFile = optionValue(argv, "--gate-file");
312
+ const gateCommand = optionValue(argv, "--gate-command");
313
+ const gate = gateFile ? readText(gateFile) : gateCommand ?? "";
314
+ const timeoutRaw = Number(optionValue(argv, "--timeout") ?? 300);
315
+ const inputs: GateSnapshotInputs = {
316
+ gate,
317
+ prompt: readText(optionValue(argv, "--prompt-file")),
318
+ gateTimeoutSeconds: Number.isFinite(timeoutRaw) ? timeoutRaw : 300,
319
+ };
320
+ const result = verifyGateSnapshot(snapshotFile, inputs);
321
+ if (!result.ok) {
322
+ console.error(`gate-integrity: ${result.reason ?? "проверка целостности не пройдена"}`);
323
+ return 1;
324
+ }
325
+ return 0;
326
+ }
327
+
328
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
329
+ process.exitCode = await main();
330
+ }
@@ -62,12 +62,25 @@ export type GitTriggerHandler = (taskName: string, info: GitCheckResult & { cwd:
62
62
 
63
63
  export type GitRunner = (cwd: string, args: string[]) => Promise<string>;
64
64
 
65
+ /**
66
+ * W-1 (0.0.6): опрос репозитория — служебная операция, а не пользовательская.
67
+ * Игнорируем пользовательские хуки и запрещаем интерактивный ввод пароля,
68
+ * чтобы длинная цепочка хуков или запрос credentials не блокировали опрос.
69
+ */
70
+ const GIT_SAFE_ARGS = ["-c", `core.hooksPath=${process.platform === "win32" ? "NUL" : "/dev/null"}`];
71
+ const GIT_SAFE_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
72
+
65
73
  const defaultRunner: GitRunner = (cwd, args) =>
66
74
  new Promise((resolve, reject) => {
67
75
  execFile(
68
76
  "git",
69
- ["-C", cwd, ...args],
70
- { timeout: GIT_COMMAND_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
77
+ ["-C", cwd, ...GIT_SAFE_ARGS, ...args],
78
+ {
79
+ timeout: GIT_COMMAND_TIMEOUT_MS,
80
+ windowsHide: true,
81
+ maxBuffer: 4 * 1024 * 1024,
82
+ env: GIT_SAFE_ENV,
83
+ },
71
84
  (err, stdout) => {
72
85
  if (err) {
73
86
  reject(err instanceof Error ? err : new Error(String(err)));
@@ -208,7 +221,7 @@ export async function checkGitTrigger(
208
221
  let files: string[];
209
222
  try {
210
223
  files = await gitChangedFiles(task.cwd, state.commitSha, probe.head, run);
211
- } catch (err: any) {
224
+ } catch (err: unknown) {
212
225
  // Не двигаем state: следующий опрос повторит сравнение с тем же коммитом,
213
226
  // и пропущенные изменения не потеряются.
214
227
  return {
@@ -219,7 +232,7 @@ export async function checkGitTrigger(
219
232
  files: [],
220
233
  matched: [],
221
234
  message: t("gitTrigger.diffFailed", {
222
- error: err?.message ? String(err.message) : String(err),
235
+ error: err instanceof Error ? err.message : String(err),
223
236
  }),
224
237
  };
225
238
  }
@@ -356,7 +369,7 @@ export class GitTriggerManager {
356
369
  } else if (result.status === "error") {
357
370
  console.error(`[agent-steward] git-триггер «${managed.def.name}»: ${result.message}`);
358
371
  }
359
- } catch (err: any) {
372
+ } catch (err: unknown) {
360
373
  console.error(
361
374
  `[agent-steward] git-триггер «${managed.def.name}»: ${
362
375
  err instanceof Error ? err.message : String(err)
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * W-3 (0.0.6): CLI-помощник guard-условий.
4
+ *
5
+ * Вызывается из сгенерированных обёрток до запуска opencode:
6
+ * node guard-run.js --cwd "<workdir>" --guards-b64 "<base64 json>" [--json]
7
+ *
8
+ * Коды выхода:
9
+ * 0 — все guard-проверки пройдены, можно запускать;
10
+ * 4 — проверки не пройдены, прогон нужно пропустить (skip);
11
+ * 1 — некорректные аргументы или конфигурация (fail-closed).
12
+ *
13
+ * В stdout печатается человекочитаемая причина (или JSON с --json),
14
+ * диагностика — в stderr. Модуль ничего не завершает при импорте.
15
+ */
16
+ import path from "node:path";
17
+ import { pathToFileURL } from "node:url";
18
+ import {
19
+ evaluateGuards,
20
+ GUARD_SKIP_EXIT_CODE,
21
+ normalizeTaskGuards,
22
+ } from "./guard.js";
23
+
24
+ interface HelperArgs {
25
+ cwd?: string;
26
+ guardsB64?: string;
27
+ json: boolean;
28
+ }
29
+
30
+ function parseArgs(argv: string[]): { args: HelperArgs; error?: string } {
31
+ const args: HelperArgs = { json: false };
32
+ for (let index = 0; index < argv.length; index += 1) {
33
+ const flag = argv[index];
34
+ const value = argv[index + 1];
35
+ switch (flag) {
36
+ case "--json":
37
+ args.json = true;
38
+ break;
39
+ case "--cwd":
40
+ case "--guards-b64": {
41
+ if (!value || value.startsWith("--")) {
42
+ return { args, error: `Флаг ${flag} требует значение.` };
43
+ }
44
+ if (flag === "--cwd") args.cwd = value;
45
+ if (flag === "--guards-b64") args.guardsB64 = value;
46
+ index += 1;
47
+ break;
48
+ }
49
+ default:
50
+ return { args, error: `Неизвестный аргумент: ${flag}` };
51
+ }
52
+ }
53
+ return { args };
54
+ }
55
+
56
+ function usage(): string {
57
+ return [
58
+ "Использование:",
59
+ ' guard-run.js --cwd <dir> --guards-b64 "<base64 json>" [--json]',
60
+ ].join("\n");
61
+ }
62
+
63
+ /** Точка входа для тестов: возвращает exit code, ничего не завершает. */
64
+ export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
65
+ const parsed = parseArgs(argv);
66
+ if (parsed.error) {
67
+ process.stderr.write(`[guard] ${parsed.error}\n`);
68
+ return 1;
69
+ }
70
+
71
+ const { cwd, guardsB64 } = parsed.args;
72
+ if (!cwd || !guardsB64) {
73
+ process.stderr.write(`[guard] ${usage()}\n`);
74
+ return 1;
75
+ }
76
+
77
+ let raw: unknown;
78
+ try {
79
+ raw = JSON.parse(Buffer.from(guardsB64, "base64").toString("utf8"));
80
+ } catch (error) {
81
+ process.stderr.write(
82
+ `[guard] не удалось разобрать guards: ${error instanceof Error ? error.message : String(error)}\n`,
83
+ );
84
+ return 1;
85
+ }
86
+
87
+ const normalized = normalizeTaskGuards(raw);
88
+ if (!normalized.ok) {
89
+ process.stderr.write(`[guard] ${normalized.error}\n`);
90
+ return 1;
91
+ }
92
+ if (!normalized.guards) {
93
+ process.stderr.write("[guard] пустая конфигурация guard.\n");
94
+ return 1;
95
+ }
96
+
97
+ const result = await evaluateGuards(normalized.guards, { cwd });
98
+ if (parsed.args.json) {
99
+ process.stdout.write(`${JSON.stringify(result)}\n`);
100
+ } else if (result.passed) {
101
+ process.stdout.write(`[guard] OK: ${result.checks.length} проверок пройдено\n`);
102
+ } else {
103
+ process.stdout.write(`[guard] skipped: ${result.reasons.join("; ")}\n`);
104
+ }
105
+ return result.passed ? 0 : GUARD_SKIP_EXIT_CODE;
106
+ }
107
+
108
+ const invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : "";
109
+ if (import.meta.url === invokedPath) {
110
+ main().then(
111
+ (code) => {
112
+ process.exitCode = code;
113
+ },
114
+ (error: unknown) => {
115
+ process.stderr.write(`[guard] ${error instanceof Error ? error.message : String(error)}\n`);
116
+ process.exitCode = 1;
117
+ },
118
+ );
119
+ }