agent-steward 0.0.5 → 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.
- package/CHANGELOG.md +176 -1
- package/README.md +9 -7
- package/ROADMAP-STRATEGY.md +5 -5
- package/ROADMAP.md +107 -17
- package/dist/cli.js +5 -0
- package/dist/core/analytics.d.ts +6 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +20 -3
- package/dist/core/audit.d.ts +6 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +24 -0
- package/dist/core/budget.d.ts +118 -0
- package/dist/core/budget.d.ts.map +1 -0
- package/dist/core/budget.js +206 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +38 -0
- package/dist/core/dry-run.d.ts +26 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +199 -8
- package/dist/core/feedback.d.ts +192 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +426 -0
- package/dist/core/gate-integrity.d.ts +36 -0
- package/dist/core/gate-integrity.d.ts.map +1 -1
- package/dist/core/gate-integrity.js +144 -1
- package/dist/core/local-ai.d.ts.map +1 -1
- package/dist/core/local-ai.js +7 -3
- package/dist/core/matrix.d.ts +8 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +57 -2
- package/dist/core/mission.d.ts +20 -0
- package/dist/core/mission.d.ts.map +1 -1
- package/dist/core/mission.js +45 -5
- package/dist/core/opencode-models.d.ts +2 -2
- package/dist/core/opencode-models.d.ts.map +1 -1
- package/dist/core/opencode-models.js +28 -21
- package/dist/core/opencode-usage.d.ts +35 -0
- package/dist/core/opencode-usage.d.ts.map +1 -0
- package/dist/core/opencode-usage.js +132 -0
- package/dist/core/pipeline-io.d.ts +1 -1
- package/dist/core/pipeline-io.d.ts.map +1 -1
- package/dist/core/pipeline-io.js +26 -12
- package/dist/core/pipeline-map.d.ts +6 -0
- package/dist/core/pipeline-map.d.ts.map +1 -1
- package/dist/core/pipeline-map.js +12 -0
- package/dist/core/ps-wrapper.d.ts +10 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +176 -5
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +76 -4
- package/dist/core/run-mode.d.ts +12 -0
- package/dist/core/run-mode.d.ts.map +1 -0
- package/dist/core/run-mode.js +17 -0
- package/dist/core/scheduler/logs.d.ts +4 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -1
- package/dist/core/scheduler/logs.js +25 -1
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +18 -8
- package/dist/core/self-analysis.d.ts +32 -2
- package/dist/core/self-analysis.d.ts.map +1 -1
- package/dist/core/self-analysis.js +38 -27
- package/dist/core/shutdown.d.ts +33 -2
- package/dist/core/shutdown.d.ts.map +1 -1
- package/dist/core/shutdown.js +58 -2
- package/dist/core/structured-log.d.ts +30 -0
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +37 -0
- package/dist/core/usage-surface.d.ts +25 -0
- package/dist/core/usage-surface.d.ts.map +1 -0
- package/dist/core/usage-surface.js +41 -0
- package/dist/core/wrappers/bash.d.ts +2 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +58 -6
- package/dist/db/history-repo.d.ts +32 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +85 -7
- package/dist/db/metrics-repo.d.ts +20 -2
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +33 -11
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +37 -17
- package/dist/db/recovery.d.ts +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +9 -4
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +71 -56
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +70 -1
- package/dist/db/templates-repo.d.ts +2 -2
- package/dist/db/templates-repo.d.ts.map +1 -1
- package/dist/db/templates-repo.js +5 -3
- package/dist/history.d.ts +6 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +4 -2
- package/dist/hook-output.d.ts +2 -0
- package/dist/hook-output.d.ts.map +1 -0
- package/dist/hook-output.js +31 -0
- package/dist/index.d.ts +247 -53
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +999 -211
- package/dist/notifications.d.ts +31 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +132 -13
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +66 -15
- package/dist/rpc.d.ts +108 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +28 -0
- package/dist/server.d.ts +17 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -12
- package/dist/settings.d.ts +42 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +82 -0
- package/dist/task-transfer.d.ts +5 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +48 -3
- package/dist/templates.d.ts +2 -2
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +3 -3
- package/dist/types.d.ts +22 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +34 -11
- package/docs/ARCHITECTURE.md +49 -12
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/EXECUTION-LOOP.md +6 -3
- package/docs/FEATURES.md +65 -4
- package/docs/FEATURES.zh.md +45 -2
- package/docs/QA-A2-GUI-TUI.md +205 -0
- package/docs/README.ru.md +3 -3
- package/docs/README.zh.md +2 -2
- package/gui-experimental.cjs +9 -9
- package/locales/en.json +42 -3
- package/locales/ru.json +42 -3
- package/locales/zh.json +42 -3
- package/package.json +15 -2
- package/scripts/check-eslint-baseline.mjs +139 -0
- package/scripts/gen-test-plan-counters.mjs +117 -0
- package/scripts/github-ci-fetch.ps1 +37 -0
- package/scripts/pl-commit.ps1 +112 -0
- package/scripts/qa-a2-commit.ps1 +104 -0
- package/scripts/test-home.mjs +26 -2
- package/skills/scheduled-job-best-practices/SKILL.md +95 -1
- package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
- package/src/cli.ts +5 -0
- package/src/core/analytics.ts +27 -4
- package/src/core/audit.ts +25 -0
- package/src/core/budget.ts +340 -0
- package/src/core/cron-to-schtasks.ts +42 -0
- package/src/core/dry-run.ts +233 -10
- package/src/core/feedback.ts +582 -0
- package/src/core/gate-integrity.ts +171 -1
- package/src/core/local-ai.ts +7 -3
- package/src/core/matrix.ts +63 -2
- package/src/core/mission.ts +51 -5
- package/src/core/opencode-models.ts +30 -21
- package/src/core/opencode-usage.ts +182 -0
- package/src/core/pipeline-io.ts +28 -11
- package/src/core/pipeline-map.ts +19 -0
- package/src/core/ps-wrapper.ts +173 -4
- package/src/core/record-history.ts +94 -4
- package/src/core/run-mode.ts +19 -0
- package/src/core/scheduler/logs.ts +32 -1
- package/src/core/secrets.ts +18 -11
- package/src/core/self-analysis.ts +75 -29
- package/src/core/shutdown.ts +90 -4
- package/src/core/structured-log.ts +67 -0
- package/src/core/usage-surface.ts +70 -0
- package/src/core/wrappers/bash.ts +60 -5
- package/src/db/history-repo.ts +153 -19
- package/src/db/metrics-repo.ts +38 -11
- package/src/db/migrate.ts +57 -32
- package/src/db/recovery.ts +10 -4
- package/src/db/runs-repo.ts +113 -61
- package/src/db/schema.ts +70 -1
- package/src/db/templates-repo.ts +5 -3
- package/src/gui.tsx +261 -5
- package/src/history.ts +10 -3
- package/src/hook-output.ts +39 -0
- package/src/index.ts +1407 -345
- package/src/notifications.ts +189 -39
- package/src/profiles.ts +72 -16
- package/src/rpc.ts +30 -0
- package/src/server.ts +107 -23
- package/src/settings.ts +120 -0
- package/src/task-transfer.ts +59 -6
- package/src/templates.ts +3 -3
- package/src/types.ts +23 -2
- package/src/workspaces.ts +37 -14
package/src/core/pipeline-io.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, resolve } from "node:path";
|
|
2
3
|
import { parseDocument } from "yaml";
|
|
3
4
|
import {
|
|
4
5
|
validatePipelineSpec,
|
|
@@ -64,16 +65,32 @@ export function parsePipelineYaml(source: string): PipelineParseResult {
|
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
/** Читает YAML-файл и валидирует его. Ошибки ввода-вывода также попадают в `errors`. */
|
|
67
|
-
export async function loadPipelineFile(
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
68
|
+
export async function loadPipelineFile(
|
|
69
|
+
filePath: string,
|
|
70
|
+
baseDir?: string,
|
|
71
|
+
): Promise<PipelineParseResult> {
|
|
72
|
+
// PL-34: cwd процесса-хоста OpenCode может не совпадать с каталогом задачи.
|
|
73
|
+
// Пробуем явный baseDir, затем cwd и подсказки окружения.
|
|
74
|
+
const roots = [
|
|
75
|
+
baseDir?.trim(),
|
|
76
|
+
process.cwd(),
|
|
77
|
+
process.env.OPENCODE_PROJECT_DIR,
|
|
78
|
+
process.env.INIT_CWD,
|
|
79
|
+
].filter((root): root is string => Boolean(root));
|
|
80
|
+
const candidates = isAbsolute(filePath)
|
|
81
|
+
? [filePath]
|
|
82
|
+
: roots.map((root) => resolve(root, filePath));
|
|
83
|
+
let lastError: unknown;
|
|
84
|
+
for (const candidate of [...new Set(candidates)]) {
|
|
85
|
+
try {
|
|
86
|
+
return parsePipelineYaml(await readFile(candidate, "utf8"));
|
|
87
|
+
} catch (err) {
|
|
88
|
+
lastError = err;
|
|
89
|
+
}
|
|
77
90
|
}
|
|
78
|
-
return
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
errors: [{ path: filePath, message: `Не удалось прочитать файл: ${issueMessage(lastError)}` }],
|
|
94
|
+
warnings: [],
|
|
95
|
+
};
|
|
79
96
|
}
|
package/src/core/pipeline-map.ts
CHANGED
|
@@ -151,6 +151,25 @@ export interface PipelineExportResult {
|
|
|
151
151
|
warnings: string[];
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
+
/**
|
|
155
|
+
* QA-P3.2: проверка, что конвейер действительно существует в наборе задач.
|
|
156
|
+
* `tasksToPipelineSpec` всегда возвращает spec (в т.ч. с нулём шагов), поэтому
|
|
157
|
+
* «не найден» должен определяться здесь, а не по `!result.spec`.
|
|
158
|
+
*/
|
|
159
|
+
export function pipelineExportLookupError(
|
|
160
|
+
tasks: TaskDefinition[],
|
|
161
|
+
pipelineName: string,
|
|
162
|
+
): string | null {
|
|
163
|
+
const hasSteps = tasks.some(
|
|
164
|
+
(task) =>
|
|
165
|
+
task.pipelineName?.toLowerCase() === pipelineName.toLowerCase() &&
|
|
166
|
+
Boolean(task.pipelineStepId),
|
|
167
|
+
);
|
|
168
|
+
return hasSteps
|
|
169
|
+
? null
|
|
170
|
+
: `Конвейер "${pipelineName}" не найден (не найдены задачи с pipelineName=${pipelineName} и pipelineStepId).`;
|
|
171
|
+
}
|
|
172
|
+
|
|
154
173
|
/**
|
|
155
174
|
* Обратный маппинг: задачи одного pipeline из БД → `PipelineSpec` для export.
|
|
156
175
|
*
|
package/src/core/ps-wrapper.ts
CHANGED
|
@@ -85,6 +85,8 @@ export const WRAPPER_SCRIPT = `param(
|
|
|
85
85
|
[string]$QualityGate,
|
|
86
86
|
# G-1.2: snapshot входов гейта, снятый при создании обёртки.
|
|
87
87
|
[string]$GateSnapshotFile = "",
|
|
88
|
+
# PL-47: пути, которые задача вправе изменить (из -Files afterScript).
|
|
89
|
+
[string]$GateAllowPaths = "",
|
|
88
90
|
[string]$BeforeScript,
|
|
89
91
|
[string]$AfterScript,
|
|
90
92
|
[string]$EnvFile,
|
|
@@ -178,6 +180,15 @@ $script:timedOut = $false
|
|
|
178
180
|
$script:attemptExitCode = 0
|
|
179
181
|
$startedAtIso = $startTime.ToUniversalTime().ToString("o")
|
|
180
182
|
$script:runId = ""
|
|
183
|
+
# PL-7.2: разделённые потоки последнего хука для структурированного журнала.
|
|
184
|
+
$script:lastHookStdout = ""
|
|
185
|
+
$script:lastHookStderr = ""
|
|
186
|
+
# PL-25: помощник целостности гейта и файл snapshot'а рабочего дерева.
|
|
187
|
+
$gateIntegrityFile = ""
|
|
188
|
+
if ($RecorderFile) {
|
|
189
|
+
$gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
|
|
190
|
+
}
|
|
191
|
+
$worktreeSnapshotFile = ""
|
|
181
192
|
|
|
182
193
|
# Hotfix 1.5.3.1: блокировка ДО записи в историю. Раньше lock существовал только
|
|
183
194
|
# в in-process пути (LockManager/withLock), а schtasks-запуск обёртки его не
|
|
@@ -276,6 +287,9 @@ function Invoke-HookScript {
|
|
|
276
287
|
if (-not $timeout -or $timeout -le 0) {
|
|
277
288
|
$output = & cmd.exe /c $Command 2>&1
|
|
278
289
|
$code = $LASTEXITCODE
|
|
290
|
+
# Без таймаута потоки.cmd объединены — сохраняем как stdout, stderr пуст.
|
|
291
|
+
$script:lastHookStdout = (@($output) -join "\`n")
|
|
292
|
+
$script:lastHookStderr = ""
|
|
279
293
|
foreach ($line in @($output)) {
|
|
280
294
|
Write-Log "[hook] $line"
|
|
281
295
|
}
|
|
@@ -321,6 +335,8 @@ function Invoke-HookScript {
|
|
|
321
335
|
$errText = ""
|
|
322
336
|
if ($outTask.Wait(5000)) { try { $outText = $outTask.Result } catch {} }
|
|
323
337
|
if ($errTask.Wait(5000)) { try { $errText = $errTask.Result } catch {} }
|
|
338
|
+
$script:lastHookStdout = $outText
|
|
339
|
+
$script:lastHookStderr = $errText
|
|
324
340
|
foreach ($text in @($outText, $errText)) {
|
|
325
341
|
foreach ($line in @($text -split "\r?\n")) {
|
|
326
342
|
if ($line -ne "") {
|
|
@@ -337,6 +353,26 @@ function Invoke-HookScript {
|
|
|
337
353
|
}
|
|
338
354
|
}
|
|
339
355
|
|
|
356
|
+
# PL-7.2: пишет отдельное событие hook.output с реальным exit code и
|
|
357
|
+
# разделёнными stdout/stderr. Наблюдаемость не должна ломать задачу.
|
|
358
|
+
function Write-HookStructuredOutput {
|
|
359
|
+
param([string]$Phase, [int]$ExitCode)
|
|
360
|
+
if (-not $RecorderFile) { return }
|
|
361
|
+
$helper = Join-Path (Split-Path $RecorderFile -Parent) "hook-output.js"
|
|
362
|
+
if (-not (Test-Path -LiteralPath $helper)) { return }
|
|
363
|
+
$outFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-out-" + [guid]::NewGuid().ToString("N") + ".txt")
|
|
364
|
+
$errFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-err-" + [guid]::NewGuid().ToString("N") + ".txt")
|
|
365
|
+
try {
|
|
366
|
+
Set-Content -LiteralPath $outFile -Value ([string]$script:lastHookStdout) -Encoding UTF8
|
|
367
|
+
Set-Content -LiteralPath $errFile -Value ([string]$script:lastHookStderr) -Encoding UTF8
|
|
368
|
+
& node "$helper" $Phase $TaskName $ExitCode $outFile $errFile "$script:runId" 2>$null | Out-Null
|
|
369
|
+
} catch {
|
|
370
|
+
} finally {
|
|
371
|
+
Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue
|
|
372
|
+
Remove-Item -LiteralPath $errFile -Force -ErrorAction SilentlyContinue
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
340
376
|
# Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
|
|
341
377
|
# Раньше TimeoutSeconds принимался, но нигде не использовался — задача работала
|
|
342
378
|
# до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
|
|
@@ -351,6 +387,10 @@ function Invoke-OpenCodeOnce {
|
|
|
351
387
|
|
|
352
388
|
$watch = $null
|
|
353
389
|
$timeoutMarker = ""
|
|
390
|
+
# PL-51: состояние health-check лога (отдельный сторожевой job).
|
|
391
|
+
$healthWatch = $null
|
|
392
|
+
$healthMarker = ""
|
|
393
|
+
$healthFailure = ""
|
|
354
394
|
if ($TimeoutSeconds -gt 0) {
|
|
355
395
|
$timeoutMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-timeout-" + [guid]::NewGuid().ToString("N") + ".flag")
|
|
356
396
|
$watch = Start-Job -ScriptBlock {
|
|
@@ -410,6 +450,51 @@ function Invoke-OpenCodeOnce {
|
|
|
410
450
|
} -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
|
|
411
451
|
}
|
|
412
452
|
|
|
453
|
+
# PL-51: health-check лога. Некоторые модели уходят в бесконечный retry
|
|
454
|
+
# (ECONNRESET / Free usage limit reached / Insufficient Balance) и висят
|
|
455
|
+
# до самого TimeoutSeconds, не делая полезной работы. Сторожевой job читает
|
|
456
|
+
# хвост лога и при повторяющейся ошибке пишет причину в лог, маркер и
|
|
457
|
+
# завершает дерево процесса задачи — как сторож таймаута.
|
|
458
|
+
# Пороги настраиваются env, по умолчанию: 15 с, 3 повтора, 40 строк.
|
|
459
|
+
if ($env:AGENT_STEWARD_HEALTH_CHECK -ne "0" -and $LogFile) {
|
|
460
|
+
$healthInterval = 15
|
|
461
|
+
$healthThreshold = 3
|
|
462
|
+
$healthTail = 40
|
|
463
|
+
try {
|
|
464
|
+
if ($env:AGENT_STEWARD_HEALTH_INTERVAL_SEC -match '^\\d+$') { $healthInterval = [Math]::Max(2, [int]$env:AGENT_STEWARD_HEALTH_INTERVAL_SEC) }
|
|
465
|
+
if ($env:AGENT_STEWARD_HEALTH_REPEAT_THRESHOLD -match '^\\d+$') { $healthThreshold = [Math]::Max(1, [int]$env:AGENT_STEWARD_HEALTH_REPEAT_THRESHOLD) }
|
|
466
|
+
if ($env:AGENT_STEWARD_HEALTH_TAIL_LINES -match '^\\d+$') { $healthTail = [Math]::Max(5, [int]$env:AGENT_STEWARD_HEALTH_TAIL_LINES) }
|
|
467
|
+
} catch {}
|
|
468
|
+
$healthMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-health-" + [guid]::NewGuid().ToString("N") + ".flag")
|
|
469
|
+
$healthWatch = Start-Job -ScriptBlock {
|
|
470
|
+
param([int]$RootId, [string]$Marker, [string]$LogPath, [int]$IntervalSec, [int]$Threshold, [int]$TailLines)
|
|
471
|
+
$pattern = 'ECONNRESET|Free usage limit reached|Insufficient Balance|ECONNREFUSED|ETIMEDOUT'
|
|
472
|
+
# Базовая линия: старые ошибки из предыдущих попыток не должны
|
|
473
|
+
# убивать здоровый запуск — реагируем только на рост числа ошибок.
|
|
474
|
+
$baseline = -1
|
|
475
|
+
while ($true) {
|
|
476
|
+
Start-Sleep -Seconds $IntervalSec
|
|
477
|
+
if (-not $LogPath -or -not (Test-Path -LiteralPath $LogPath)) { continue }
|
|
478
|
+
try { $tail = @(Get-Content -LiteralPath $LogPath -Tail $TailLines -ErrorAction Stop) } catch { continue }
|
|
479
|
+
$bad = @($tail | Where-Object { $_ -match $pattern })
|
|
480
|
+
if ($baseline -lt 0 -or $bad.Count -lt $baseline) { $baseline = $bad.Count; continue }
|
|
481
|
+
if ($bad.Count -ge $baseline + $Threshold) {
|
|
482
|
+
$reason = "PL-51: модель повторяет ошибку ($($bad.Count) за последние $TailLines строк): $($bad[-1])"
|
|
483
|
+
try { Add-Content -LiteralPath $LogPath -Value "[agent-steward] $reason" -Encoding UTF8 } catch {}
|
|
484
|
+
try { Set-Content -LiteralPath $Marker -Value $reason -Encoding UTF8 } catch {}
|
|
485
|
+
try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
|
|
486
|
+
break
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
} -ArgumentList $PID, $healthMarker, $LogFile, $healthInterval, $healthThreshold, $healthTail
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
# QV-8: дочерний opencode run не должен загружать инструменты планировщика
|
|
493
|
+
# (иначе ребёнок видит все 30 инструментов и может рекурсивно создавать задачи).
|
|
494
|
+
# Маркер живёт только время запуска ИИ и восстанавливается в finally.
|
|
495
|
+
$previousChildRun = $env:AGENT_STEWARD_CHILD_RUN
|
|
496
|
+
$env:AGENT_STEWARD_CHILD_RUN = "1"
|
|
497
|
+
|
|
413
498
|
$script:timedOut = $false
|
|
414
499
|
$script:attemptExitCode = 0
|
|
415
500
|
# Состояние фильтра лога сбрасываем на каждой попытке: иначе незакрытый
|
|
@@ -441,16 +526,31 @@ function Invoke-OpenCodeOnce {
|
|
|
441
526
|
}
|
|
442
527
|
}
|
|
443
528
|
} finally {
|
|
529
|
+
if ($null -eq $previousChildRun) {
|
|
530
|
+
Remove-Item Env:\AGENT_STEWARD_CHILD_RUN -ErrorAction SilentlyContinue
|
|
531
|
+
} else {
|
|
532
|
+
$env:AGENT_STEWARD_CHILD_RUN = $previousChildRun
|
|
533
|
+
}
|
|
444
534
|
if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
|
|
445
535
|
$script:timedOut = $true
|
|
446
536
|
}
|
|
537
|
+
if ($healthMarker -and (Test-Path -LiteralPath $healthMarker)) {
|
|
538
|
+
try { $healthFailure = (Get-Content -LiteralPath $healthMarker -Raw -ErrorAction Stop).Trim() } catch { $healthFailure = "модель повторяет ошибку подряд" }
|
|
539
|
+
}
|
|
447
540
|
if ($watch) {
|
|
448
541
|
Stop-Job -Job $watch -ErrorAction SilentlyContinue
|
|
449
542
|
Remove-Job -Job $watch -Force -ErrorAction SilentlyContinue
|
|
450
543
|
}
|
|
544
|
+
if ($healthWatch) {
|
|
545
|
+
Stop-Job -Job $healthWatch -ErrorAction SilentlyContinue
|
|
546
|
+
Remove-Job -Job $healthWatch -Force -ErrorAction SilentlyContinue
|
|
547
|
+
}
|
|
451
548
|
if ($timeoutMarker) {
|
|
452
549
|
Remove-Item -LiteralPath $timeoutMarker -Force -ErrorAction SilentlyContinue
|
|
453
550
|
}
|
|
551
|
+
if ($healthMarker) {
|
|
552
|
+
Remove-Item -LiteralPath $healthMarker -Force -ErrorAction SilentlyContinue
|
|
553
|
+
}
|
|
454
554
|
}
|
|
455
555
|
|
|
456
556
|
if ($script:timedOut) {
|
|
@@ -458,6 +558,11 @@ function Invoke-OpenCodeOnce {
|
|
|
458
558
|
$script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
|
|
459
559
|
return 124
|
|
460
560
|
}
|
|
561
|
+
if ($healthFailure) {
|
|
562
|
+
Write-Log "[agent-steward] PL-51: задача '$TaskName' остановлена health-check: $healthFailure"
|
|
563
|
+
$script:errorMessage = "Ошибка модели при запуске: $healthFailure"
|
|
564
|
+
return 125
|
|
565
|
+
}
|
|
461
566
|
return $script:attemptExitCode
|
|
462
567
|
}
|
|
463
568
|
|
|
@@ -552,7 +657,12 @@ function Get-UsageFromLog {
|
|
|
552
657
|
)
|
|
553
658
|
$costPatterns = @(
|
|
554
659
|
($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)'),
|
|
555
|
-
($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
|
|
660
|
+
($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)'),
|
|
661
|
+
# QA-F.1: OpenCode печатает costUsd=0.1 / cost_usd=0.75 / cost=0.25 без
|
|
662
|
+
# валютного знака. Без этих шаблонов PS-обёртка теряла стоимость, тогда
|
|
663
|
+
# как TS-парсер (src/core/record-history.ts) её уже распознавал.
|
|
664
|
+
($prefix + '(?i)(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*\\$?\\s*([0-9]+(?:[.,][0-9]+)?)'),
|
|
665
|
+
($prefix + '(?i)(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
|
|
556
666
|
)
|
|
557
667
|
|
|
558
668
|
# Идём с конца: OpenCode печатает итог последним, а более ранние строки
|
|
@@ -601,6 +711,16 @@ try {
|
|
|
601
711
|
Set-Location $Workdir
|
|
602
712
|
}
|
|
603
713
|
|
|
714
|
+
# PL-25: фиксируем состояние рабочего дерева до запуска ИИ. Перед гейтом
|
|
715
|
+
# сверяем его, чтобы чужие незакоммиченные правки src/ не давали ложный зелёный.
|
|
716
|
+
if ($QualityGate -and $GateSnapshotFile -and $Workdir -and $gateIntegrityFile -and (Test-Path -LiteralPath $gateIntegrityFile)) {
|
|
717
|
+
$worktreeSnapshotFile = [System.IO.Path]::ChangeExtension($GateSnapshotFile, ".worktree.json")
|
|
718
|
+
$snapAllowArgs = @()
|
|
719
|
+
if ($GateAllowPaths) { $snapAllowArgs = @("--allow", $GateAllowPaths) }
|
|
720
|
+
$snapOut = & node $gateIntegrityFile worktree-snapshot --dir "$Workdir" --out "$worktreeSnapshotFile" @snapAllowArgs 2>&1
|
|
721
|
+
foreach ($line in $snapOut) { Write-Log "[agent-steward] $line" }
|
|
722
|
+
}
|
|
723
|
+
|
|
604
724
|
if ($WorkspaceName) {
|
|
605
725
|
$gitBranch = "-"
|
|
606
726
|
$gitRemote = "-"
|
|
@@ -698,8 +818,10 @@ try {
|
|
|
698
818
|
if ($BeforeScript) {
|
|
699
819
|
Write-Log "[agent-steward] Pre-flight: $BeforeScript"
|
|
700
820
|
$preCode = Invoke-HookScript -Command $BeforeScript
|
|
821
|
+
Write-HookStructuredOutput -Phase "preFlight" -ExitCode $preCode
|
|
701
822
|
if ($preCode -ne 0) {
|
|
702
|
-
|
|
823
|
+
# PL-6.1: SilentlyContinue не гарантирует код 0 — подсказываем явный exit 0.
|
|
824
|
+
Write-Log "[agent-steward] ОШИБКА: Pre-flight script failed (код $preCode). Завершите хук явным 'exit 0' (например: if (Test-Path -LiteralPath '<path>') { Remove-Item -LiteralPath '<path>' -Force }; exit 0)."
|
|
703
825
|
$script:preFlightStatus = "error"
|
|
704
826
|
$script:errorMessage = "Pre-flight script failed"
|
|
705
827
|
$script:exitCode = 1
|
|
@@ -711,6 +833,14 @@ try {
|
|
|
711
833
|
}
|
|
712
834
|
|
|
713
835
|
if (-not $script:skipMainTask) {
|
|
836
|
+
# QA-P0.2: граница реального прогона для extractLastRunLog(). Маркер пишется
|
|
837
|
+
# без префикса времени и только после guard/pre-flight — отменённый запуск
|
|
838
|
+
# не должен выглядеть как реальный. Лог дописывается, показываем последний сегмент.
|
|
839
|
+
if ($LogFile) {
|
|
840
|
+
try {
|
|
841
|
+
Add-Content -Path $LogFile -Value ("[agent-steward] === Run started " + $startedAtIso + " (" + $TaskName + ") ===") -Encoding utf8
|
|
842
|
+
} catch {}
|
|
843
|
+
}
|
|
714
844
|
$prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
|
|
715
845
|
|
|
716
846
|
# W-1: запуск в одноразовом git worktree — сообщаем путь агенту.
|
|
@@ -803,7 +933,6 @@ try {
|
|
|
803
933
|
# снятым при создании задачи. При расхождении гейт НЕ выполняется.
|
|
804
934
|
$gateIntegrityOk = $false
|
|
805
935
|
if ($GateSnapshotFile -and (Test-Path -LiteralPath $GateSnapshotFile)) {
|
|
806
|
-
$gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
|
|
807
936
|
if (Test-Path -LiteralPath $gateIntegrityFile) {
|
|
808
937
|
$verifyOutput = & node $gateIntegrityFile verify --snapshot "$GateSnapshotFile" --gate-file "$QualityGate" --prompt-file "$PromptFile" --timeout $GateTimeoutSeconds 2>&1
|
|
809
938
|
$verifyCode = $LASTEXITCODE
|
|
@@ -826,6 +955,20 @@ try {
|
|
|
826
955
|
$script:exitCode = 1
|
|
827
956
|
}
|
|
828
957
|
|
|
958
|
+
if ($gateIntegrityOk -and $worktreeSnapshotFile -and (Test-Path -LiteralPath $worktreeSnapshotFile)) {
|
|
959
|
+
$verifyAllowArgs = @()
|
|
960
|
+
if ($GateAllowPaths) { $verifyAllowArgs = @("--allow", $GateAllowPaths) }
|
|
961
|
+
$worktreeOut = & node $gateIntegrityFile worktree-verify --dir "$Workdir" --snapshot "$worktreeSnapshotFile" @verifyAllowArgs 2>&1
|
|
962
|
+
$worktreeCode = $LASTEXITCODE
|
|
963
|
+
foreach ($line in $worktreeOut) { Write-Log "[agent-steward] $line" }
|
|
964
|
+
if ($worktreeCode -ne 0) {
|
|
965
|
+
$gateIntegrityOk = $false
|
|
966
|
+
Write-Log "[agent-steward] ОШИБКА: рабочее дерево изменилось во время прогона — гейт не доверяем."
|
|
967
|
+
$script:errorMessage = "Quality Gate: рабочее дерево изменилось во время прогона"
|
|
968
|
+
$script:exitCode = 1
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
|
|
829
972
|
if ($gateIntegrityOk) {
|
|
830
973
|
Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
|
|
831
974
|
# Тот же таймаут, что у хуков: зависший gate не должен держать lock.
|
|
@@ -846,7 +989,12 @@ try {
|
|
|
846
989
|
}
|
|
847
990
|
|
|
848
991
|
if ($script:exitCode -ne 0) {
|
|
849
|
-
|
|
992
|
+
# Раньше пустое errorMessage превращалось в "-" в истории: причина
|
|
993
|
+
# падения терялась (например, при отказе модели до вывода в лог).
|
|
994
|
+
if (-not $script:errorMessage) {
|
|
995
|
+
$script:errorMessage = "Код возврата $($script:exitCode)"
|
|
996
|
+
}
|
|
997
|
+
Write-Log "[agent-steward] ОШИБКА: задача '$TaskName' завершилась с кодом $($script:exitCode). $script:errorMessage"
|
|
850
998
|
} else {
|
|
851
999
|
Write-Log "[agent-steward] Задача '$TaskName' успешно завершена."
|
|
852
1000
|
}
|
|
@@ -860,6 +1008,7 @@ try {
|
|
|
860
1008
|
if ($AfterScript) {
|
|
861
1009
|
Write-Log "[agent-steward] Post-flight: $AfterScript"
|
|
862
1010
|
$postCode = Invoke-HookScript -Command $AfterScript
|
|
1011
|
+
Write-HookStructuredOutput -Phase "postFlight" -ExitCode $postCode
|
|
863
1012
|
if ($postCode -ne 0) {
|
|
864
1013
|
Write-Log "[agent-steward] ОШИБКА: Post-flight script failed (код $postCode)."
|
|
865
1014
|
$script:postFlightStatus = "error"
|
|
@@ -961,6 +1110,22 @@ export function lockFilePath(taskName: string): string {
|
|
|
961
1110
|
return path.join(PLUGIN_DIR, "locks", `${sanitizeName(taskName)}.lock`);
|
|
962
1111
|
}
|
|
963
1112
|
|
|
1113
|
+
/**
|
|
1114
|
+
* PL-47: извлекает список `-Files "a;b"` из PowerShell afterScript; возвращает
|
|
1115
|
+
* строку `a|b` для gate-integrity. Возвращает "", если afterScript не коммитит
|
|
1116
|
+
* через pl-commit.ps1 (тогда гейт работает по старой схеме).
|
|
1117
|
+
*/
|
|
1118
|
+
export function gateAllowPathsFromAfterScript(afterScript?: string): string {
|
|
1119
|
+
if (!afterScript) return "";
|
|
1120
|
+
const match = /-Files\s+"([^"]+)"/i.exec(afterScript);
|
|
1121
|
+
if (!match) return "";
|
|
1122
|
+
return match[1]
|
|
1123
|
+
.split(";")
|
|
1124
|
+
.map((item) => item.trim().replace(/\\/g, "/").replace(/^\.\//, ""))
|
|
1125
|
+
.filter(Boolean)
|
|
1126
|
+
.join("|");
|
|
1127
|
+
}
|
|
1128
|
+
|
|
964
1129
|
/**
|
|
965
1130
|
* Генерирует per-task .cmd-обёртку, которую schtasks вызывает через /tr.
|
|
966
1131
|
* Внутри .cmd — жёстко заданный вызов run-task.ps1 с задачей, промптом,
|
|
@@ -1046,6 +1211,8 @@ export async function writeWrapperCmd(
|
|
|
1046
1211
|
guards?: TaskGuards,
|
|
1047
1212
|
/** Путь к dist/core/guard-run.js (обязателен при guards). */
|
|
1048
1213
|
guardHelperFile?: string,
|
|
1214
|
+
/** PL-47: RELATIVE-пути, которые задача вправе изменить (из -Files). */
|
|
1215
|
+
gateAllowPaths?: string,
|
|
1049
1216
|
): Promise<string> {
|
|
1050
1217
|
await fs.mkdir(WRAPPER_DIR, { recursive: true });
|
|
1051
1218
|
const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
|
|
@@ -1110,6 +1277,8 @@ export async function writeWrapperCmd(
|
|
|
1110
1277
|
gateTimeoutSeconds: safeGateTimeout,
|
|
1111
1278
|
});
|
|
1112
1279
|
psArgs.push(`-GateSnapshotFile "${snapshotFile}"`);
|
|
1280
|
+
const safeAllow = (gateAllowPaths ?? "").replace(/[\r\n"]+/g, "").trim();
|
|
1281
|
+
if (safeAllow) psArgs.push(`-GateAllowPaths "${safeAllow}"`);
|
|
1113
1282
|
}
|
|
1114
1283
|
|
|
1115
1284
|
if (model?.trim()) {
|
|
@@ -5,9 +5,16 @@ import { pathToFileURL } from "node:url";
|
|
|
5
5
|
import { runTaskNow } from "./scheduler/run-now.js";
|
|
6
6
|
import { createSchedulerBackend } from "./scheduler/index.js";
|
|
7
7
|
import { notifyTaskCompletion } from "../notifications.js";
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
finishRun,
|
|
10
|
+
getLatestHistoryByTask,
|
|
11
|
+
normalizeErrorText,
|
|
12
|
+
recordRun,
|
|
13
|
+
startRun,
|
|
14
|
+
} from "../db/history-repo.js";
|
|
9
15
|
import { deleteSetting, decrementCounterSetting } from "../db/settings-repo.js";
|
|
10
16
|
import { getTask, listTasks } from "../db/tasks-repo.js";
|
|
17
|
+
import { extractLastRunLog } from "./mission.js";
|
|
11
18
|
import { rotateSessionIfNeeded } from "./session.js";
|
|
12
19
|
import type { TaskDefinition } from "../task-transfer.js";
|
|
13
20
|
import type { HistoryRecord } from "../history.js";
|
|
@@ -16,6 +23,7 @@ import {
|
|
|
16
23
|
finalizeMatrixIfComplete,
|
|
17
24
|
} from "./matrix.js";
|
|
18
25
|
import { appendStructuredLog } from "./structured-log.js";
|
|
26
|
+
import { collectOpenCodeUsage } from "./opencode-usage.js";
|
|
19
27
|
|
|
20
28
|
type Status = "success" | "error" | "timeout" | "skipped";
|
|
21
29
|
|
|
@@ -63,7 +71,9 @@ const LOG_TAIL_LINES = 500;
|
|
|
63
71
|
*/
|
|
64
72
|
function readLogTail(filePath: string, maxLines: number): string[] {
|
|
65
73
|
try {
|
|
66
|
-
|
|
74
|
+
// Токены/стоимость относятся к завершаемому запуску; старые прогоны
|
|
75
|
+
// в том же файле лога не должны портить оценку (QA-F.1).
|
|
76
|
+
const content = extractLastRunLog(fs.readFileSync(filePath, "utf8"));
|
|
67
77
|
const lines = content.split(/\r?\n/);
|
|
68
78
|
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
69
79
|
return lines.slice(-maxLines);
|
|
@@ -85,6 +95,11 @@ const TOKEN_PATTERNS: RegExp[] = [
|
|
|
85
95
|
const COST_PATTERNS: RegExp[] = [
|
|
86
96
|
new RegExp(USAGE_PREFIX + "(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)", "i"),
|
|
87
97
|
new RegExp(USAGE_PREFIX + "(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)", "i"),
|
|
98
|
+
// QA-F.1: OpenCode печатает costUsd=0.1 / cost=0.25 без валютного знака —
|
|
99
|
+
// старые шаблоны требовали `$` перед числом или `usd` после, поэтому
|
|
100
|
+
// стоимость терялась и в метриках/аналитике оставалась нулевой.
|
|
101
|
+
new RegExp(USAGE_PREFIX + "(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*\\$?\\s*([0-9]+(?:[.,][0-9]+)?)", "i"),
|
|
102
|
+
new RegExp(USAGE_PREFIX + "(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)", "i"),
|
|
88
103
|
];
|
|
89
104
|
|
|
90
105
|
function parseUsageValue(raw: string, suffix?: string): number | undefined {
|
|
@@ -142,6 +157,41 @@ export function parseUsageFromLog(logFile: string): UsageInfo {
|
|
|
142
157
|
return result;
|
|
143
158
|
}
|
|
144
159
|
|
|
160
|
+
/**
|
|
161
|
+
* PL-38: если обёртка не передала usage, а логи его не содержат, берём
|
|
162
|
+
* показания из собственной БД OpenCode за окно запуска задачи. Результат
|
|
163
|
+
* консервативный: уже найденные значения не перезаписываются, нули не подменяются.
|
|
164
|
+
*/
|
|
165
|
+
function resolveUsageFromOpenCodeDb(
|
|
166
|
+
taskName: string,
|
|
167
|
+
startedAtIso: string,
|
|
168
|
+
durationMs: number,
|
|
169
|
+
fallback: UsageInfo,
|
|
170
|
+
): UsageInfo {
|
|
171
|
+
if (fallback.tokens !== undefined && fallback.costUsd !== undefined) return fallback;
|
|
172
|
+
|
|
173
|
+
const definition = getTask(taskName);
|
|
174
|
+
const end = Date.now();
|
|
175
|
+
const parsedStart = Date.parse(startedAtIso);
|
|
176
|
+
const start = Number.isFinite(parsedStart) ? parsedStart : end - Math.max(0, durationMs);
|
|
177
|
+
// +-2 с покрывают рассинхрон часов обёртки и движка OpenCode.
|
|
178
|
+
const usage = collectOpenCodeUsage({
|
|
179
|
+
since: start - 2000,
|
|
180
|
+
until: end + 2000,
|
|
181
|
+
cwd: definition?.workingDirectory,
|
|
182
|
+
});
|
|
183
|
+
if (!usage || (usage.tokens <= 0 && usage.costUsd <= 0)) return fallback;
|
|
184
|
+
|
|
185
|
+
const resolved: UsageInfo = {
|
|
186
|
+
tokens: fallback.tokens ?? (usage.tokens > 0 ? usage.tokens : undefined),
|
|
187
|
+
costUsd: fallback.costUsd ?? (usage.costUsd > 0 ? usage.costUsd : undefined),
|
|
188
|
+
};
|
|
189
|
+
logRecorderEvent("usage.from_opencode_db", taskName, {
|
|
190
|
+
reason: `tokens=${usage.tokens} cost=${usage.costUsd} messages=${usage.messages}`,
|
|
191
|
+
});
|
|
192
|
+
return resolved;
|
|
193
|
+
}
|
|
194
|
+
|
|
145
195
|
/**
|
|
146
196
|
* Ищет настройку повторов задачи в БД.
|
|
147
197
|
* Возвращает 0, если повторы не настроены.
|
|
@@ -456,7 +506,7 @@ async function main() {
|
|
|
456
506
|
process.exit(1);
|
|
457
507
|
}
|
|
458
508
|
const durationMs = Number(fifth) || 0;
|
|
459
|
-
const error = sixth
|
|
509
|
+
const error = normalizeErrorText(sixth);
|
|
460
510
|
// 12-й аргумент — путь к лог-файлу задачи (добавлен в T-08 / D-08).
|
|
461
511
|
const logFile = twelfth;
|
|
462
512
|
const tokens = parseOptionalNumber(seventh);
|
|
@@ -474,6 +524,18 @@ async function main() {
|
|
|
474
524
|
costResolved = usage.costUsd;
|
|
475
525
|
}
|
|
476
526
|
}
|
|
527
|
+
// --finish не получает startedAt: восстанавливаем окно из длительности.
|
|
528
|
+
if (tokensResolved === undefined || costResolved === undefined) {
|
|
529
|
+
const approximatedStart = new Date(Date.now() - Math.max(0, durationMs)).toISOString();
|
|
530
|
+
const dbUsage = resolveUsageFromOpenCodeDb(
|
|
531
|
+
taskName,
|
|
532
|
+
approximatedStart,
|
|
533
|
+
durationMs,
|
|
534
|
+
{ tokens: tokensResolved, costUsd: costResolved },
|
|
535
|
+
);
|
|
536
|
+
tokensResolved = dbUsage.tokens;
|
|
537
|
+
costResolved = dbUsage.costUsd;
|
|
538
|
+
}
|
|
477
539
|
const model = ninth && ninth !== "-" ? ninth.trim() || undefined : undefined;
|
|
478
540
|
const preFlightStatus = parseHookStatus(tenth);
|
|
479
541
|
const postFlightStatus = parseHookStatus(eleventh);
|
|
@@ -521,7 +583,7 @@ async function main() {
|
|
|
521
583
|
|
|
522
584
|
const startedAt = third ?? new Date().toISOString();
|
|
523
585
|
const durationMs = Number(fourth) || 0;
|
|
524
|
-
const error = fifth
|
|
586
|
+
const error = normalizeErrorText(fifth);
|
|
525
587
|
|
|
526
588
|
// Токены и стоимость приходят из PowerShell-обёртки (ps-wrapper.ts).
|
|
527
589
|
// "-" означает «данных нет» (openCode не печатал usage в лог).
|
|
@@ -543,6 +605,14 @@ async function main() {
|
|
|
543
605
|
costResolved = usage.costUsd;
|
|
544
606
|
}
|
|
545
607
|
}
|
|
608
|
+
if (tokensResolved === undefined || costResolved === undefined) {
|
|
609
|
+
const dbUsage = resolveUsageFromOpenCodeDb(taskName, startedAt, durationMs, {
|
|
610
|
+
tokens: tokensResolved,
|
|
611
|
+
costUsd: costResolved,
|
|
612
|
+
});
|
|
613
|
+
tokensResolved = dbUsage.tokens;
|
|
614
|
+
costResolved = dbUsage.costUsd;
|
|
615
|
+
}
|
|
546
616
|
// Восьмой аргумент — модель; "-" означает, что модель не задана.
|
|
547
617
|
const model = eighth && eighth !== "-" ? eighth.trim() || undefined : undefined;
|
|
548
618
|
// Девятый и десятый — итоги pre/post-flight хуков.
|
|
@@ -662,9 +732,18 @@ async function handleCompletion(
|
|
|
662
732
|
}
|
|
663
733
|
|
|
664
734
|
if (st === "success") {
|
|
735
|
+
// PL-5.1: один и тот же следующий шаг может прийти и из chainTarget
|
|
736
|
+
// (nextTaskOnSuccess), и из DAG-зависимых (dependsOn). Запускаем каждое
|
|
737
|
+
// имя ровно один раз за завершение: Set по имени, без учёта регистра —
|
|
738
|
+
// именно так сравнивает имена selectDependentsToTrigger.
|
|
739
|
+
const triggered = new Set<string>();
|
|
740
|
+
const nameKey = (name: string): string => name.trim().toLowerCase();
|
|
741
|
+
|
|
665
742
|
// Успешный запуск сбрасывает счётчик повторов.
|
|
666
743
|
await deleteSetting(retryStateKey(taskName));
|
|
667
744
|
if (chainTarget) {
|
|
745
|
+
const key = nameKey(chainTarget);
|
|
746
|
+
triggered.add(key);
|
|
668
747
|
const started = await triggerTask(chainTarget);
|
|
669
748
|
if (started) {
|
|
670
749
|
logRecorderEvent("chain.triggered", taskName, { nextTask: chainTarget });
|
|
@@ -680,6 +759,17 @@ async function handleCompletion(
|
|
|
680
759
|
const definitions = listTasks();
|
|
681
760
|
const dependents = selectDependentsToTrigger(taskName, definitions, history);
|
|
682
761
|
for (const dependent of dependents) {
|
|
762
|
+
const key = nameKey(dependent);
|
|
763
|
+
if (triggered.has(key)) {
|
|
764
|
+
// Один шаг попал и в цепочку, и в DAG — второй triggerTask
|
|
765
|
+
// создал бы дублирующий запуск (наблюдалось 09:29:24Z).
|
|
766
|
+
logRecorderEvent("dag.dedup_skipped", taskName, {
|
|
767
|
+
reason: "already triggered via nextTaskOnSuccess",
|
|
768
|
+
nextTask: dependent,
|
|
769
|
+
});
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
triggered.add(key);
|
|
683
773
|
const started = await triggerTask(dependent);
|
|
684
774
|
if (started) {
|
|
685
775
|
logRecorderEvent("dag.triggered", taskName, { nextTask: dependent });
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QV-8: маркер дочернего прогона `opencode run`.
|
|
3
|
+
*
|
|
4
|
+
* Обёртки задач выставляют `AGENT_STEWARD_CHILD_RUN=1` перед запуском ИИ.
|
|
5
|
+
* Плагин читает маркер при загрузке и НЕ регистрирует инструменты
|
|
6
|
+
* планировщика, RPC, скилл и дашборд: дочерний агент не должен рекурсивно
|
|
7
|
+
* создавать задачи и не должен конкурировать с родительским дашбордом за порт.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const CHILD_RUN_ENV = "AGENT_STEWARD_CHILD_RUN";
|
|
11
|
+
|
|
12
|
+
const TRUTHY = new Set(["1", "true", "yes", "on"]);
|
|
13
|
+
|
|
14
|
+
/** True, когда текущий процесс — дочерний `opencode run` задачи планировщика. */
|
|
15
|
+
export function isChildRunMode(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
16
|
+
const raw = env[CHILD_RUN_ENV];
|
|
17
|
+
if (typeof raw !== "string") return false;
|
|
18
|
+
return TRUTHY.has(raw.trim().toLowerCase());
|
|
19
|
+
}
|
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { LOG_DIR, sanitizeName } from "../../types.js";
|
|
4
|
+
import { extractLastRunLog } from "../mission.js";
|
|
5
|
+
|
|
6
|
+
/** Codes returned by Windows/PowerShell while a log file is still held by the writer. */
|
|
7
|
+
export function isRetriableLogReadError(code: unknown): boolean {
|
|
8
|
+
return code === "EBUSY" || code === "EPERM" || code === "EACCES";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Retry fs.readFile while the writer still holds the log (emit_event / immediate get_task_logs race). */
|
|
12
|
+
export async function readLogWithRetry(
|
|
13
|
+
logPath: string,
|
|
14
|
+
attempts = 6,
|
|
15
|
+
delayMs = 50,
|
|
16
|
+
): Promise<string> {
|
|
17
|
+
let lastErr: unknown;
|
|
18
|
+
for (let i = 0; i < attempts; i++) {
|
|
19
|
+
try {
|
|
20
|
+
return await fs.readFile(logPath, "utf8");
|
|
21
|
+
} catch (err: unknown) {
|
|
22
|
+
lastErr = err;
|
|
23
|
+
if (
|
|
24
|
+
!isRetriableLogReadError((err as NodeJS.ErrnoException).code) ||
|
|
25
|
+
i === attempts - 1
|
|
26
|
+
) {
|
|
27
|
+
throw err;
|
|
28
|
+
}
|
|
29
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs * (i + 1)));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
throw lastErr;
|
|
33
|
+
}
|
|
4
34
|
|
|
5
35
|
/**
|
|
6
36
|
* Читает файл лога задачи и возвращает последние 50 строк.
|
|
@@ -15,7 +45,8 @@ export async function getTaskLogs(
|
|
|
15
45
|
const logPath = path.join(LOG_DIR, `${sanitizeName(name)}.log`);
|
|
16
46
|
try {
|
|
17
47
|
// PowerShell 5.1 пишет UTF-8 с BOM — убираем его, чтобы GUI не показывал мусор.
|
|
18
|
-
|
|
48
|
+
// Лог дописывается между запусками: показываем только последний прогон.
|
|
49
|
+
const content = extractLastRunLog(await readLogWithRetry(logPath));
|
|
19
50
|
const lines = content.split(/\r?\n/).filter((line) => line.trim());
|
|
20
51
|
if (lines.length === 0) {
|
|
21
52
|
return {
|