agent-steward 0.0.4 → 0.0.5

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 (190) hide show
  1. package/CHANGELOG.md +134 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +52 -7
  4. package/ROADMAP-STRATEGY.md +21 -18
  5. package/ROADMAP.md +140 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/execution.d.ts +203 -0
  10. package/dist/core/execution.d.ts.map +1 -0
  11. package/dist/core/execution.js +309 -0
  12. package/dist/core/gate-integrity.d.ts +35 -0
  13. package/dist/core/gate-integrity.d.ts.map +1 -0
  14. package/dist/core/gate-integrity.js +132 -0
  15. package/dist/core/git-trigger.d.ts.map +1 -1
  16. package/dist/core/git-trigger.js +14 -2
  17. package/dist/core/guard-run.d.ts +4 -0
  18. package/dist/core/guard-run.d.ts.map +1 -0
  19. package/dist/core/guard-run.js +101 -0
  20. package/dist/core/guard.d.ts +52 -0
  21. package/dist/core/guard.d.ts.map +1 -0
  22. package/dist/core/guard.js +362 -0
  23. package/dist/core/lock.d.ts +41 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +141 -29
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +75 -15
  28. package/dist/core/mission.d.ts +83 -0
  29. package/dist/core/mission.d.ts.map +1 -0
  30. package/dist/core/mission.js +334 -0
  31. package/dist/core/pipeline-apply.d.ts +38 -0
  32. package/dist/core/pipeline-apply.d.ts.map +1 -0
  33. package/dist/core/pipeline-apply.js +117 -0
  34. package/dist/core/pipeline-io.d.ts +13 -0
  35. package/dist/core/pipeline-io.d.ts.map +1 -0
  36. package/dist/core/pipeline-io.js +64 -0
  37. package/dist/core/pipeline-map.d.ts +46 -0
  38. package/dist/core/pipeline-map.d.ts.map +1 -0
  39. package/dist/core/pipeline-map.js +196 -0
  40. package/dist/core/pipeline-spec.d.ts +109 -0
  41. package/dist/core/pipeline-spec.d.ts.map +1 -0
  42. package/dist/core/pipeline-spec.js +554 -0
  43. package/dist/core/ps-wrapper.d.ts +19 -2
  44. package/dist/core/ps-wrapper.d.ts.map +1 -1
  45. package/dist/core/ps-wrapper.js +250 -62
  46. package/dist/core/record-history.d.ts.map +1 -1
  47. package/dist/core/record-history.js +130 -29
  48. package/dist/core/router/rules.d.ts.map +1 -1
  49. package/dist/core/router/rules.js +6 -0
  50. package/dist/core/scheduler/linux.d.ts +8 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +34 -9
  53. package/dist/core/scheduler/mac.d.ts +44 -2
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +126 -15
  56. package/dist/core/scheduler/windows.d.ts.map +1 -1
  57. package/dist/core/scheduler/windows.js +15 -12
  58. package/dist/core/structured-log.d.ts +7 -1
  59. package/dist/core/structured-log.d.ts.map +1 -1
  60. package/dist/core/worktree-run.d.ts +4 -0
  61. package/dist/core/worktree-run.d.ts.map +1 -0
  62. package/dist/core/worktree-run.js +164 -0
  63. package/dist/core/worktree.d.ts +115 -0
  64. package/dist/core/worktree.d.ts.map +1 -0
  65. package/dist/core/worktree.js +462 -0
  66. package/dist/core/wrappers/bash.d.ts +17 -0
  67. package/dist/core/wrappers/bash.d.ts.map +1 -1
  68. package/dist/core/wrappers/bash.js +175 -24
  69. package/dist/db/capability-repo.d.ts +43 -2
  70. package/dist/db/capability-repo.d.ts.map +1 -1
  71. package/dist/db/capability-repo.js +96 -11
  72. package/dist/db/history-repo.d.ts +38 -5
  73. package/dist/db/history-repo.d.ts.map +1 -1
  74. package/dist/db/history-repo.js +88 -25
  75. package/dist/db/metrics-repo.js +2 -2
  76. package/dist/db/recovery.d.ts.map +1 -1
  77. package/dist/db/recovery.js +5 -4
  78. package/dist/db/run-journal.d.ts +33 -5
  79. package/dist/db/run-journal.d.ts.map +1 -1
  80. package/dist/db/run-journal.js +78 -14
  81. package/dist/db/run-resume.d.ts +5 -0
  82. package/dist/db/run-resume.d.ts.map +1 -1
  83. package/dist/db/run-resume.js +9 -2
  84. package/dist/db/runs-repo.d.ts +19 -2
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +22 -6
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +63 -2
  90. package/dist/history.d.ts +1 -1
  91. package/dist/history.d.ts.map +1 -1
  92. package/dist/i18n.d.ts +5 -0
  93. package/dist/i18n.d.ts.map +1 -1
  94. package/dist/i18n.js +11 -4
  95. package/dist/index.d.ts +136 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +378 -14
  98. package/dist/notifications.d.ts +22 -0
  99. package/dist/notifications.d.ts.map +1 -1
  100. package/dist/notifications.js +36 -8
  101. package/dist/profiles.d.ts.map +1 -1
  102. package/dist/profiles.js +25 -4
  103. package/dist/rpc.d.ts +246 -0
  104. package/dist/rpc.d.ts.map +1 -1
  105. package/dist/rpc.js +117 -0
  106. package/dist/server.d.ts +15 -0
  107. package/dist/server.d.ts.map +1 -1
  108. package/dist/server.js +77 -18
  109. package/dist/settings.d.ts +2 -2
  110. package/dist/settings.d.ts.map +1 -1
  111. package/dist/settings.js +3 -3
  112. package/dist/shared/jobs-view.d.ts +1 -1
  113. package/dist/shared/jobs-view.d.ts.map +1 -1
  114. package/dist/shared/jobs-view.js +2 -0
  115. package/dist/task-transfer.d.ts +16 -0
  116. package/dist/task-transfer.d.ts.map +1 -1
  117. package/dist/task-transfer.js +16 -0
  118. package/docs/ARCHITECTURE.md +281 -65
  119. package/docs/COMPATIBILITY.md +2 -2
  120. package/docs/CONCEPT.md +18 -4
  121. package/docs/CROSS_PLATFORM.ru.md +20 -0
  122. package/docs/CROSS_PLATFORM.zh.md +18 -0
  123. package/docs/EXECUTION-LOOP.md +22 -7
  124. package/docs/FEATURES.md +65 -4
  125. package/docs/FEATURES.zh.md +52 -4
  126. package/docs/MIGRATION.md +2 -2
  127. package/docs/PIPELINE.md +293 -0
  128. package/docs/README.ru.md +42 -3
  129. package/docs/README.zh.md +43 -3
  130. package/docs/SAFETY.md +23 -3
  131. package/gui-experimental.cjs +9 -8
  132. package/locales/en.json +17 -1
  133. package/locales/ru.json +17 -1
  134. package/locales/zh.json +17 -1
  135. package/opencode.pipeline.yaml +35 -0
  136. package/package.json +23 -4
  137. package/scripts/test-home.mjs +83 -0
  138. package/src/cli.ts +412 -0
  139. package/src/core/dry-run.ts +2 -2
  140. package/src/core/execution.ts +538 -0
  141. package/src/core/file-watcher.ts +2 -2
  142. package/src/core/gate-integrity.ts +160 -0
  143. package/src/core/git-trigger.ts +18 -5
  144. package/src/core/guard-run.ts +119 -0
  145. package/src/core/guard.ts +431 -0
  146. package/src/core/lock.ts +178 -37
  147. package/src/core/matrix.ts +95 -50
  148. package/src/core/mission.ts +485 -0
  149. package/src/core/native-notify.ts +1 -1
  150. package/src/core/pipeline-apply.ts +158 -0
  151. package/src/core/pipeline-io.ts +79 -0
  152. package/src/core/pipeline-map.ts +264 -0
  153. package/src/core/pipeline-spec.ts +775 -0
  154. package/src/core/ps-wrapper.ts +263 -63
  155. package/src/core/record-history.ts +164 -77
  156. package/src/core/router/rules.ts +6 -0
  157. package/src/core/schedule-gate.ts +1 -1
  158. package/src/core/scheduler/at-fallback.ts +1 -1
  159. package/src/core/scheduler/linux.ts +40 -11
  160. package/src/core/scheduler/logs.ts +2 -2
  161. package/src/core/scheduler/mac.ts +174 -14
  162. package/src/core/scheduler/registry.ts +2 -2
  163. package/src/core/scheduler/windows.ts +19 -15
  164. package/src/core/secrets.ts +8 -8
  165. package/src/core/structured-log.ts +22 -5
  166. package/src/core/telegram.ts +2 -2
  167. package/src/core/triage-worker.ts +7 -7
  168. package/src/core/triage.ts +2 -2
  169. package/src/core/worktree-run.ts +199 -0
  170. package/src/core/worktree.ts +600 -0
  171. package/src/core/wrappers/bash.ts +190 -23
  172. package/src/db/capability-repo.ts +127 -10
  173. package/src/db/history-repo.ts +129 -22
  174. package/src/db/metrics-repo.ts +2 -2
  175. package/src/db/recovery.ts +5 -4
  176. package/src/db/run-journal.ts +100 -13
  177. package/src/db/run-resume.ts +17 -1
  178. package/src/db/runs-repo.ts +36 -6
  179. package/src/db/schema.ts +65 -2
  180. package/src/gui.tsx +177 -13
  181. package/src/history.ts +1 -1
  182. package/src/i18n.ts +12 -4
  183. package/src/index.ts +524 -4
  184. package/src/notifications.ts +38 -8
  185. package/src/profiles.ts +26 -4
  186. package/src/rpc.ts +128 -0
  187. package/src/server.ts +94 -18
  188. package/src/settings.ts +5 -5
  189. package/src/shared/jobs-view.ts +3 -1
  190. package/src/task-transfer.ts +31 -0
@@ -0,0 +1,309 @@
1
+ /**
2
+ * AC-1: единый путь исполнения.
3
+ *
4
+ * Любой запуск — зарегистрированная задача или ad-hoc миссия — сначала
5
+ * превращается в `RunContext` (вход, задача, профиль, безопасность), затем в
6
+ * план `createRun → декомпозиция → маршрут → исполнение → GATE → ledger`.
7
+ * Транспорт (OpenCode, локальная модель, облако) скрыт за `StepExecutor`,
8
+ * поэтому ядро не зависит от конкретного CLI.
9
+ *
10
+ * Модуль намеренно не запускает процессы сам: исполнитель передаётся снаружи.
11
+ * Это позволяет тестировать путь без регистрации задачи в ОС и подменять
12
+ * OpenCode на любой другой транспорт.
13
+ */
14
+ import { createRun, finishRun, finishStep, getStep, startRun, } from "../db/runs-repo.js";
15
+ import { runStepStatefullyAsync } from "../db/run-journal.js";
16
+ import { planMission, } from "./router/planner.js";
17
+ import { routeStep } from "./router/dispatch.js";
18
+ function normalizeList(values) {
19
+ if (!Array.isArray(values))
20
+ return undefined;
21
+ const cleaned = values
22
+ .filter((value) => typeof value === "string")
23
+ .map((value) => value.trim())
24
+ .filter(Boolean);
25
+ return cleaned.length > 0 ? cleaned : undefined;
26
+ }
27
+ function assertNonEmpty(value, field) {
28
+ const text = value.trim();
29
+ if (!text)
30
+ throw new Error(`Пустой ${field}: запуск невозможен`);
31
+ return text;
32
+ }
33
+ function normalizePolicy(policy) {
34
+ return policy === "secure" || policy === "legacy" ? policy : "hybrid";
35
+ }
36
+ /**
37
+ * AC-1.1: контекст зарегистрированной задачи. Определение из БД — только
38
+ * источник данных; дальнейший путь не отличается от ad-hoc.
39
+ */
40
+ export function createRegisteredRunContext(definition, overrides = {}) {
41
+ const taskName = assertNonEmpty(overrides.taskName ?? definition.name, "имя задачи");
42
+ const prompt = assertNonEmpty(definition.prompt, "промпт задачи");
43
+ const cwd = overrides.cwd?.trim() ||
44
+ definition.workingDirectory?.trim() ||
45
+ definition.workdir?.trim() ||
46
+ process.cwd();
47
+ const safety = {
48
+ policy: normalizePolicy(overrides.safety?.policy ?? overrides.policy),
49
+ allowedTools: normalizeList(overrides.safety?.allowedTools ?? definition.allowedTools),
50
+ deniedTools: normalizeList(overrides.safety?.deniedTools ?? definition.deniedTools),
51
+ };
52
+ return {
53
+ origin: "registered",
54
+ trigger: overrides.trigger ?? definition.triggerType ?? "manual",
55
+ taskName,
56
+ mission: prompt,
57
+ prompt,
58
+ cwd,
59
+ ...(overrides.taskType ?? definition.taskType
60
+ ? { taskType: overrides.taskType ?? definition.taskType }
61
+ : {}),
62
+ profile: {
63
+ model: overrides.profile?.model ?? definition.model ?? null,
64
+ session: overrides.profile?.session ?? definition.session ?? "new",
65
+ sessionId: overrides.profile?.sessionId ?? definition.sessionId ?? null,
66
+ workspaceId: overrides.profile?.workspaceId ?? definition.workspaceId ?? null,
67
+ },
68
+ safety,
69
+ metadata: {
70
+ ...(overrides.metadata ?? {}),
71
+ schedule: definition.schedule ?? null,
72
+ priority: definition.priority ?? 5,
73
+ qualityGate: definition.qualityGate ?? null,
74
+ beforeScript: definition.beforeScript ?? null,
75
+ afterScript: definition.afterScript ?? null,
76
+ },
77
+ };
78
+ }
79
+ /** AC-1.1: контекст ad-hoc миссии — без записи в ОС и без task definition. */
80
+ export function createAdHocRunContext(mission, overrides = {}) {
81
+ const text = assertNonEmpty(mission, "миссия");
82
+ const taskName = assertNonEmpty(overrides.taskName ?? "ad-hoc", "имя запуска");
83
+ const cwd = overrides.cwd?.trim() || process.cwd();
84
+ return {
85
+ origin: "ad-hoc",
86
+ trigger: overrides.trigger ?? "manual",
87
+ taskName,
88
+ mission: text,
89
+ prompt: text,
90
+ cwd,
91
+ ...(overrides.taskType ? { taskType: overrides.taskType } : {}),
92
+ profile: {
93
+ model: overrides.profile?.model ?? null,
94
+ session: overrides.profile?.session ?? "new",
95
+ sessionId: overrides.profile?.sessionId ?? null,
96
+ workspaceId: overrides.profile?.workspaceId ?? null,
97
+ },
98
+ safety: {
99
+ policy: normalizePolicy(overrides.safety?.policy ?? overrides.policy),
100
+ allowedTools: normalizeList(overrides.safety?.allowedTools),
101
+ deniedTools: normalizeList(overrides.safety?.deniedTools),
102
+ },
103
+ metadata: overrides.metadata,
104
+ };
105
+ }
106
+ /** Проверяет контракт безопасности до создания запуска. */
107
+ export function validateRunContext(context) {
108
+ assertNonEmpty(context.taskName, "имя запуска");
109
+ assertNonEmpty(context.prompt, "промпт запуска");
110
+ assertNonEmpty(context.cwd, "рабочая директория");
111
+ if (!["hybrid", "secure", "legacy"].includes(context.safety.policy)) {
112
+ throw new Error(`Неизвестная политика безопасности: ${String(context.safety.policy)}`);
113
+ }
114
+ const allowed = new Set(context.safety.allowedTools ?? []);
115
+ const denied = context.safety.deniedTools ?? [];
116
+ const conflict = denied.find((tool) => allowed.has(tool));
117
+ if (conflict) {
118
+ throw new Error(`Инструмент "${conflict}" одновременно разрешён и запрещён`);
119
+ }
120
+ }
121
+ function planStepsForContext(context, options) {
122
+ if (context.taskType) {
123
+ return Promise.resolve({
124
+ steps: [{ stepName: context.taskName, taskType: context.taskType }],
125
+ source: "heuristic",
126
+ ambiguous: [],
127
+ });
128
+ }
129
+ return planMission(context.mission, {
130
+ maxSteps: options.maxSteps,
131
+ decomposer: options.decomposer,
132
+ }).then((plan) => ({
133
+ steps: plan.steps,
134
+ source: plan.source,
135
+ ambiguous: plan.ambiguousTaskTypes,
136
+ }));
137
+ }
138
+ /**
139
+ * AC-1.3: строит план и маршрут каждого шага до первого исполнения.
140
+ * Сам по себе план ничего не запускает — это и есть dry-run.
141
+ */
142
+ export async function buildExecutionPlan(context, options = {}) {
143
+ validateRunContext(context);
144
+ const planned = await planStepsForContext(context, options);
145
+ const warnings = [];
146
+ const steps = planned.steps.map((step, order) => {
147
+ const route = routeStep(step.taskType, options.thresholds);
148
+ if (route.target === "review" || route.target === "explore") {
149
+ warnings.push(`Шаг "${step.stepName}" (${step.taskType}) не исполняется автоматически: ${route.reason}`);
150
+ }
151
+ return { ...step, order, route };
152
+ });
153
+ return {
154
+ context,
155
+ steps,
156
+ source: planned.source,
157
+ ambiguousTaskTypes: planned.ambiguous,
158
+ warnings,
159
+ };
160
+ }
161
+ /** Человекочитаемая трассировка маршрута для dry-run и логов. */
162
+ export function describeExecutionPlan(plan) {
163
+ const lines = [
164
+ `План ${plan.context.origin}: ${plan.context.taskName} → ${plan.steps.length} шаг(ов), источник ${plan.source}`,
165
+ ];
166
+ for (const step of plan.steps) {
167
+ const route = step.route;
168
+ const target = route.executor ? `${route.executor}/${route.transport}` : route.target;
169
+ lines.push(` ${step.order + 1}. ${step.stepName} [${route.taskType}] → ${target} (${route.source}: ${route.reason})`);
170
+ }
171
+ for (const warning of plan.warnings)
172
+ lines.push(` ! ${warning}`);
173
+ return lines.join("\n");
174
+ }
175
+ export function createOpenCodeExecutor(invoke, id = "opencode") {
176
+ return {
177
+ id,
178
+ supports: (route) => route.executor !== null,
179
+ async execute({ step, context, plan }) {
180
+ const output = await invoke({
181
+ prompt: plan.context.prompt,
182
+ cwd: plan.context.cwd,
183
+ model: plan.context.profile.model ?? null,
184
+ session: plan.context.profile.session ?? "new",
185
+ sessionId: plan.context.profile.sessionId ?? null,
186
+ step,
187
+ context,
188
+ });
189
+ return { output };
190
+ },
191
+ };
192
+ }
193
+ /** Ошибка GATE: шаг выполнен, но результат не принят. */
194
+ export class GateRejectedError extends Error {
195
+ constructor(reason) {
196
+ super(reason);
197
+ this.name = "GateRejectedError";
198
+ }
199
+ }
200
+ function pickExecutor(step, executors) {
201
+ return executors.find((executor) => executor.supports(step.route));
202
+ }
203
+ function errorMessage(error) {
204
+ return error instanceof Error ? error.message : String(error);
205
+ }
206
+ /**
207
+ * AC-1.4: единое исполнение плана для зарегистрированной и ad-hoc миссии.
208
+ *
209
+ * Создаёт запуск в ledger, для каждого шага фиксирует running/passed/failed,
210
+ * применяет GATE и завершает запуск. Шаги `review`/`explore` пропускаются:
211
+ * их нельзя исполнить автоматически.
212
+ */
213
+ export async function executeExecutionPlan(plan, options) {
214
+ validateRunContext(plan.context);
215
+ const run = createRun({
216
+ taskName: plan.context.taskName,
217
+ steps: plan.steps.map((step) => ({ stepName: step.stepName })),
218
+ metadata: {
219
+ origin: plan.context.origin,
220
+ trigger: plan.context.trigger,
221
+ planSource: plan.source,
222
+ routes: plan.steps.map((step) => ({
223
+ stepName: step.stepName,
224
+ taskType: step.route.taskType,
225
+ target: step.route.target,
226
+ transport: step.route.transport,
227
+ executor: step.route.executor,
228
+ source: step.route.source,
229
+ reason: step.route.reason,
230
+ })),
231
+ ...(plan.context.metadata ?? {}),
232
+ ...(options.metadata ?? {}),
233
+ },
234
+ });
235
+ startRun(run.id);
236
+ const executed = [];
237
+ let firstError = null;
238
+ const stopOnError = options.stopOnError !== false;
239
+ for (const step of plan.steps) {
240
+ const executor = step.route.executor === null ? undefined : pickExecutor(step, options.executors);
241
+ // review/explore или нет подходящего транспорта — шаг не исполняется.
242
+ if (!executor) {
243
+ const record = getStep(run.id, step.stepName);
244
+ const reason = step.route.executor === null
245
+ ? `маршрут ${step.route.target}: ${step.route.reason}`
246
+ : `нет исполнителя для маршрута ${step.route.executor}/${String(step.route.transport)}`;
247
+ if (record) {
248
+ finishStep(record.id, "skipped", { error: reason });
249
+ }
250
+ executed.push({
251
+ stepName: step.stepName,
252
+ taskType: step.route.taskType,
253
+ target: step.route.target,
254
+ status: "skipped",
255
+ attempt: record?.attempt ?? 0,
256
+ error: reason,
257
+ });
258
+ continue;
259
+ }
260
+ try {
261
+ const execution = await runStepStatefullyAsync(run.id, step.stepName, async () => {
262
+ const result = await executor.execute({ step, context: plan.context, plan });
263
+ if (result.error) {
264
+ throw new Error(result.error);
265
+ }
266
+ if (options.gate) {
267
+ const verdict = await options.gate({ step, context: plan.context, plan, result });
268
+ if (!verdict.ok) {
269
+ throw new GateRejectedError(verdict.reason ?? "GATE отклонил результат шага");
270
+ }
271
+ }
272
+ return result.output;
273
+ });
274
+ executed.push({
275
+ stepName: step.stepName,
276
+ taskType: step.route.taskType,
277
+ target: step.route.target,
278
+ status: "passed",
279
+ attempt: execution.attempt,
280
+ output: execution.result,
281
+ });
282
+ }
283
+ catch (error) {
284
+ const message = errorMessage(error);
285
+ firstError = firstError ?? message;
286
+ executed.push({
287
+ stepName: step.stepName,
288
+ taskType: step.route.taskType,
289
+ target: step.route.target,
290
+ status: "failed",
291
+ attempt: getStep(run.id, step.stepName)?.attempt ?? 1,
292
+ error: message,
293
+ });
294
+ if (stopOnError)
295
+ break;
296
+ }
297
+ }
298
+ const failed = executed.some((step) => step.status === "failed");
299
+ finishRun(run.id, failed ? "failed" : "passed", {
300
+ ...(firstError ? { error: firstError } : {}),
301
+ });
302
+ return {
303
+ runId: run.id,
304
+ status: failed ? "failed" : "passed",
305
+ steps: executed,
306
+ error: firstError,
307
+ plan,
308
+ };
309
+ }
@@ -0,0 +1,35 @@
1
+ export declare const GATE_SNAPSHOT_VERSION = 1;
2
+ export declare const GATE_SNAPSHOT_DIR: string;
3
+ export interface GateSnapshotInputs {
4
+ /** Текст гейта: на Windows — содержимое hook-файла, на POSIX — команда. */
5
+ gate: string;
6
+ /** Текст промпта задачи. */
7
+ prompt: string;
8
+ /** Таймаут гейта в секундах. */
9
+ gateTimeoutSeconds: number;
10
+ }
11
+ export interface GateSnapshot {
12
+ version: number;
13
+ taskName: string;
14
+ createdAt: string;
15
+ hash: string;
16
+ }
17
+ /** Канонический хэш входов гейта. Порядок полей фиксирован контрактом. */
18
+ export declare function gateInputsHash(inputs: GateSnapshotInputs): string;
19
+ /** Путь snapshot'а задачи — вне рабочей директории задачи. */
20
+ export declare function gateSnapshotPath(taskName: string): string;
21
+ /** Пишет snapshot задачам на этапе создания обёртки (fail-closed при ошибке). */
22
+ export declare function createGateSnapshot(taskName: string, inputs: GateSnapshotInputs, snapshotFile?: string): string;
23
+ export declare function readGateSnapshot(file: string): GateSnapshot | null;
24
+ /** Сверяет текущие входы гейта с зафиксированными. При расхождении — fail-closed. */
25
+ export declare function verifyGateSnapshot(snapshotFile: string, inputs: GateSnapshotInputs): {
26
+ ok: boolean;
27
+ reason?: string;
28
+ };
29
+ /**
30
+ * CLI для обёрток: `node gate-integrity.js verify --snapshot <file>
31
+ * --gate-file <file> | --gate-command <text> --prompt-file <file> --timeout <n>`.
32
+ * exit 0 — входы совпадают, exit 1 — расхождение/отсутствие snapshot'а.
33
+ */
34
+ export declare function main(argv?: string[]): Promise<number>;
35
+ //# sourceMappingURL=gate-integrity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gate-integrity.d.ts","sourceRoot":"","sources":["../../src/core/gate-integrity.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,qBAAqB,IAAI,CAAC;AACvC,eAAO,MAAM,iBAAiB,QAA0C,CAAC;AAEzE,MAAM,WAAW,kBAAkB;IACjC,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,gCAAgC;IAChC,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,0EAA0E;AAC1E,wBAAgB,cAAc,CAAC,MAAM,EAAE,kBAAkB,GAAG,MAAM,CAQjE;AAED,8DAA8D;AAC9D,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGzD;AAWD,iFAAiF;AACjF,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,kBAAkB,EAC1B,YAAY,SAA6B,GACxC,MAAM,CAaR;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAgBlE;AAED,qFAAqF;AACrF,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,kBAAkB,GACzB;IAAE,EAAE,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAclC;AAOD;;;;GAIG;AACH,wBAAsB,IAAI,CAAC,IAAI,WAAwB,GAAG,OAAO,CAAC,MAAM,CAAC,CAyBxE"}
@@ -0,0 +1,132 @@
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 crypto from "node:crypto";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ import { PLUGIN_DIR, sanitizeName } from "../types.js";
17
+ export const GATE_SNAPSHOT_VERSION = 1;
18
+ export const GATE_SNAPSHOT_DIR = path.join(PLUGIN_DIR, "gate-snapshots");
19
+ /** Канонический хэш входов гейта. Порядок полей фиксирован контрактом. */
20
+ export function gateInputsHash(inputs) {
21
+ const canonical = JSON.stringify({
22
+ version: GATE_SNAPSHOT_VERSION,
23
+ gate: inputs.gate,
24
+ prompt: inputs.prompt,
25
+ gateTimeoutSeconds: inputs.gateTimeoutSeconds,
26
+ });
27
+ return crypto.createHash("sha256").update(canonical, "utf8").digest("hex");
28
+ }
29
+ /** Путь snapshot'а задачи — вне рабочей директории задачи. */
30
+ export function gateSnapshotPath(taskName) {
31
+ const segment = sanitizeName(taskName).slice(0, 80) || "task";
32
+ return path.join(GATE_SNAPSHOT_DIR, `${segment}.json`);
33
+ }
34
+ function readText(file) {
35
+ if (!file)
36
+ return "";
37
+ try {
38
+ return fs.readFileSync(file, "utf8");
39
+ }
40
+ catch {
41
+ return "";
42
+ }
43
+ }
44
+ /** Пишет snapshot задачам на этапе создания обёртки (fail-closed при ошибке). */
45
+ export function createGateSnapshot(taskName, inputs, snapshotFile = gateSnapshotPath(taskName)) {
46
+ const snapshot = {
47
+ version: GATE_SNAPSHOT_VERSION,
48
+ taskName,
49
+ createdAt: new Date().toISOString(),
50
+ hash: gateInputsHash(inputs),
51
+ };
52
+ fs.mkdirSync(path.dirname(snapshotFile), { recursive: true });
53
+ fs.writeFileSync(snapshotFile, `${JSON.stringify(snapshot, null, 2)}\n`, {
54
+ encoding: "utf8",
55
+ mode: 0o600,
56
+ });
57
+ return snapshotFile;
58
+ }
59
+ export function readGateSnapshot(file) {
60
+ try {
61
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
62
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
63
+ return null;
64
+ const value = parsed;
65
+ if (value.version !== GATE_SNAPSHOT_VERSION)
66
+ return null;
67
+ if (typeof value.hash !== "string" || !/^[0-9a-f]{64}$/.test(value.hash))
68
+ return null;
69
+ return {
70
+ version: value.version,
71
+ taskName: typeof value.taskName === "string" ? value.taskName : "",
72
+ createdAt: typeof value.createdAt === "string" ? value.createdAt : "",
73
+ hash: value.hash,
74
+ };
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ /** Сверяет текущие входы гейта с зафиксированными. При расхождении — fail-closed. */
81
+ export function verifyGateSnapshot(snapshotFile, inputs) {
82
+ const snapshot = readGateSnapshot(snapshotFile);
83
+ if (!snapshot) {
84
+ return { ok: false, reason: "snapshot гейта отсутствует или повреждён" };
85
+ }
86
+ const actual = gateInputsHash(inputs);
87
+ const expected = snapshot.hash;
88
+ const same = Buffer.byteLength(actual) === Buffer.byteLength(expected) &&
89
+ crypto.timingSafeEqual(Buffer.from(actual, "utf8"), Buffer.from(expected, "utf8"));
90
+ if (!same) {
91
+ return { ok: false, reason: "входы Quality Gate изменены с момента создания задачи" };
92
+ }
93
+ return { ok: true };
94
+ }
95
+ function optionValue(argv, name) {
96
+ const index = argv.indexOf(name);
97
+ return index >= 0 ? argv[index + 1] : undefined;
98
+ }
99
+ /**
100
+ * CLI для обёрток: `node gate-integrity.js verify --snapshot <file>
101
+ * --gate-file <file> | --gate-command <text> --prompt-file <file> --timeout <n>`.
102
+ * exit 0 — входы совпадают, exit 1 — расхождение/отсутствие snapshot'а.
103
+ */
104
+ export async function main(argv = process.argv.slice(2)) {
105
+ if (argv[0] !== "verify") {
106
+ console.error("gate-integrity: только команда verify поддерживается");
107
+ return 2;
108
+ }
109
+ const snapshotFile = optionValue(argv, "--snapshot");
110
+ if (!snapshotFile) {
111
+ console.error("gate-integrity: не задан --snapshot");
112
+ return 2;
113
+ }
114
+ const gateFile = optionValue(argv, "--gate-file");
115
+ const gateCommand = optionValue(argv, "--gate-command");
116
+ const gate = gateFile ? readText(gateFile) : gateCommand ?? "";
117
+ const timeoutRaw = Number(optionValue(argv, "--timeout") ?? 300);
118
+ const inputs = {
119
+ gate,
120
+ prompt: readText(optionValue(argv, "--prompt-file")),
121
+ gateTimeoutSeconds: Number.isFinite(timeoutRaw) ? timeoutRaw : 300,
122
+ };
123
+ const result = verifyGateSnapshot(snapshotFile, inputs);
124
+ if (!result.ok) {
125
+ console.error(`gate-integrity: ${result.reason ?? "проверка целостности не пройдена"}`);
126
+ return 1;
127
+ }
128
+ return 0;
129
+ }
130
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
131
+ process.exitCode = await main();
132
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"git-trigger.d.ts","sourceRoot":"","sources":["../../src/core/git-trigger.ts"],"names":[],"mappings":"AASA;;;;;;;;;GASG;AAEH,eAAO,MAAM,gCAAgC,KAAK,CAAC;AACnD,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAC9C,eAAO,MAAM,sBAAsB,QAAS,CAAC;AAE7C,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,qDAAqD;IACrD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,qEAAqE;IACrE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,MAAM,cAAc,GACtB,SAAS,GACT,UAAU,GACV,YAAY,GACZ,iBAAiB,GACjB,SAAS,GACT,SAAS,GACT,OAAO,CAAC;AAEZ,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,cAAc,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB;AA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A;KAAO;IAKzE,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,0EAA0E;IACpE,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC;IAgChC,qDAAqD;IAC/C,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAY7D,OAAO,CAAC,QAAQ;YAWF,IAAI;IAsBZ,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAK3B,6DAA6D;IAC7D,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;CAG/B;AAED,yDAAyD;AACzD,wBAAsB,eAAe,IAAI,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,CAIhF;AAED,oEAAoE;AACpE,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEnD"}
@@ -19,8 +19,20 @@ import { t } from "../i18n.js";
19
19
  export const GIT_TRIGGER_DEFAULT_POLL_SECONDS = 60;
20
20
  export const GIT_TRIGGER_MIN_POLL_SECONDS = 5;
21
21
  export const GIT_COMMAND_TIMEOUT_MS = 10000;
22
+ /**
23
+ * W-1 (0.0.6): опрос репозитория — служебная операция, а не пользовательская.
24
+ * Игнорируем пользовательские хуки и запрещаем интерактивный ввод пароля,
25
+ * чтобы длинная цепочка хуков или запрос credentials не блокировали опрос.
26
+ */
27
+ const GIT_SAFE_ARGS = ["-c", `core.hooksPath=${process.platform === "win32" ? "NUL" : "/dev/null"}`];
28
+ const GIT_SAFE_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
22
29
  const defaultRunner = (cwd, args) => new Promise((resolve, reject) => {
23
- execFile("git", ["-C", cwd, ...args], { timeout: GIT_COMMAND_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
30
+ execFile("git", ["-C", cwd, ...GIT_SAFE_ARGS, ...args], {
31
+ timeout: GIT_COMMAND_TIMEOUT_MS,
32
+ windowsHide: true,
33
+ maxBuffer: 4 * 1024 * 1024,
34
+ env: GIT_SAFE_ENV,
35
+ }, (err, stdout) => {
24
36
  if (err) {
25
37
  reject(err instanceof Error ? err : new Error(String(err)));
26
38
  return;
@@ -162,7 +174,7 @@ export async function checkGitTrigger(task, options = {}) {
162
174
  files: [],
163
175
  matched: [],
164
176
  message: t("gitTrigger.diffFailed", {
165
- error: err?.message ? String(err.message) : String(err),
177
+ error: err instanceof Error ? err.message : String(err),
166
178
  }),
167
179
  };
168
180
  }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ /** Точка входа для тестов: возвращает exit code, ничего не завершает. */
3
+ export declare function main(argv?: string[]): Promise<number>;
4
+ //# sourceMappingURL=guard-run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard-run.d.ts","sourceRoot":"","sources":["../../src/core/guard-run.ts"],"names":[],"mappings":";AA8DA,yEAAyE;AACzE,wBAAsB,IAAI,CAAC,IAAI,GAAE,MAAM,EAA0B,GAAG,OAAO,CAAC,MAAM,CAAC,CA0ClF"}
@@ -0,0 +1,101 @@
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 { evaluateGuards, GUARD_SKIP_EXIT_CODE, normalizeTaskGuards, } from "./guard.js";
19
+ function parseArgs(argv) {
20
+ const args = { json: false };
21
+ for (let index = 0; index < argv.length; index += 1) {
22
+ const flag = argv[index];
23
+ const value = argv[index + 1];
24
+ switch (flag) {
25
+ case "--json":
26
+ args.json = true;
27
+ break;
28
+ case "--cwd":
29
+ case "--guards-b64": {
30
+ if (!value || value.startsWith("--")) {
31
+ return { args, error: `Флаг ${flag} требует значение.` };
32
+ }
33
+ if (flag === "--cwd")
34
+ args.cwd = value;
35
+ if (flag === "--guards-b64")
36
+ args.guardsB64 = value;
37
+ index += 1;
38
+ break;
39
+ }
40
+ default:
41
+ return { args, error: `Неизвестный аргумент: ${flag}` };
42
+ }
43
+ }
44
+ return { args };
45
+ }
46
+ function usage() {
47
+ return [
48
+ "Использование:",
49
+ ' guard-run.js --cwd <dir> --guards-b64 "<base64 json>" [--json]',
50
+ ].join("\n");
51
+ }
52
+ /** Точка входа для тестов: возвращает exit code, ничего не завершает. */
53
+ export async function main(argv = process.argv.slice(2)) {
54
+ const parsed = parseArgs(argv);
55
+ if (parsed.error) {
56
+ process.stderr.write(`[guard] ${parsed.error}\n`);
57
+ return 1;
58
+ }
59
+ const { cwd, guardsB64 } = parsed.args;
60
+ if (!cwd || !guardsB64) {
61
+ process.stderr.write(`[guard] ${usage()}\n`);
62
+ return 1;
63
+ }
64
+ let raw;
65
+ try {
66
+ raw = JSON.parse(Buffer.from(guardsB64, "base64").toString("utf8"));
67
+ }
68
+ catch (error) {
69
+ process.stderr.write(`[guard] не удалось разобрать guards: ${error instanceof Error ? error.message : String(error)}\n`);
70
+ return 1;
71
+ }
72
+ const normalized = normalizeTaskGuards(raw);
73
+ if (!normalized.ok) {
74
+ process.stderr.write(`[guard] ${normalized.error}\n`);
75
+ return 1;
76
+ }
77
+ if (!normalized.guards) {
78
+ process.stderr.write("[guard] пустая конфигурация guard.\n");
79
+ return 1;
80
+ }
81
+ const result = await evaluateGuards(normalized.guards, { cwd });
82
+ if (parsed.args.json) {
83
+ process.stdout.write(`${JSON.stringify(result)}\n`);
84
+ }
85
+ else if (result.passed) {
86
+ process.stdout.write(`[guard] OK: ${result.checks.length} проверок пройдено\n`);
87
+ }
88
+ else {
89
+ process.stdout.write(`[guard] skipped: ${result.reasons.join("; ")}\n`);
90
+ }
91
+ return result.passed ? 0 : GUARD_SKIP_EXIT_CODE;
92
+ }
93
+ const invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : "";
94
+ if (import.meta.url === invokedPath) {
95
+ main().then((code) => {
96
+ process.exitCode = code;
97
+ }, (error) => {
98
+ process.stderr.write(`[guard] ${error instanceof Error ? error.message : String(error)}\n`);
99
+ process.exitCode = 1;
100
+ });
101
+ }