karajan-code 4.70.4 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +6 -14
- package/packages/hu-board/package.json +1 -1
- package/packages/hu-board/public/app.js +4 -18
- package/packages/hu-board/public/index.html +5 -2
- package/packages/hu-board/public/styles.css +26 -0
- package/packages/hu-board/public/utils/api.js +0 -74
- package/packages/hu-board/public/utils/board-tour.js +62 -0
- package/packages/hu-board/public/utils/board-view.js +49 -144
- package/packages/hu-board/public/utils/command-launcher.js +8 -70
- package/packages/hu-board/public/utils/formatters.js +10 -0
- package/packages/hu-board/public/utils/governance-view.js +13 -1
- package/packages/hu-board/public/utils/hu-actions.js +17 -68
- package/packages/hu-board/public/utils/init-listeners.js +7 -8
- package/packages/hu-board/public/utils/log-panel.js +3 -16
- package/packages/hu-board/public/utils/maggle-mode.js +2 -12
- package/packages/hu-board/public/utils/modals.js +7 -0
- package/packages/hu-board/public/utils/project-picker-view.js +1 -1
- package/packages/hu-board/public/utils/server-push.js +3 -22
- package/packages/hu-board/public/utils/shared-board-notice.js +33 -0
- package/packages/hu-board/public/utils/story-detail-view.js +5 -19
- package/packages/hu-board/src/cleanup-zombies.js +0 -1
- package/packages/hu-board/src/command-runner.js +36 -25
- package/packages/hu-board/src/db-connection.js +282 -0
- package/packages/hu-board/src/db-paths.js +113 -0
- package/packages/hu-board/src/db-queries.js +188 -0
- package/packages/hu-board/src/db-tombstones.js +51 -0
- package/packages/hu-board/src/db.js +28 -619
- package/packages/hu-board/src/ephemeral-cleaner.js +2 -3
- package/packages/hu-board/src/hu-zombie-reaper.js +5 -1
- package/packages/hu-board/src/plan-mutations.js +3 -153
- package/packages/hu-board/src/plans-service.js +55 -0
- package/packages/hu-board/src/routes/api/commands.js +122 -0
- package/packages/hu-board/src/routes/api/plans.js +55 -0
- package/packages/hu-board/src/routes/api/projects.js +267 -0
- package/packages/hu-board/src/routes/api/prompts.js +135 -0
- package/packages/hu-board/src/routes/api/sessions.js +95 -0
- package/packages/hu-board/src/routes/api/stories.js +183 -0
- package/packages/hu-board/src/routes/api/system.js +241 -0
- package/packages/hu-board/src/routes/api/tombstones.js +38 -0
- package/packages/hu-board/src/routes/api.js +24 -1371
- package/packages/hu-board/src/routes/governance.js +23 -1
- package/packages/hu-board/src/routes/lanes.js +40 -0
- package/packages/hu-board/src/routes/rag.js +4 -3
- package/packages/hu-board/src/server.js +20 -34
- package/packages/hu-board/src/sync-files.js +318 -0
- package/packages/hu-board/src/sync-project.js +99 -0
- package/packages/hu-board/src/sync.js +22 -566
- package/packages/hu-board/src/zombie-reaper.js +1 -1
- package/scripts/dual-publish.mjs +19 -3
- package/scripts/postinstall.js +15 -2
- package/scripts/verify-pack-mcp.mjs +11 -7
- package/scripts/verify-pack.mjs +4 -4
- package/src/audit/audit-history.js +3 -2
- package/src/audit/dead-exports.js +68 -59
- package/src/audit/deterministic-summary.js +33 -13
- package/src/audit/npm-signatures.js +41 -0
- package/src/audit/sbom.js +35 -0
- package/src/checks/agent-token.js +112 -0
- package/src/checks/dir-setup.js +34 -1
- package/src/checks/native-build.js +21 -39
- package/src/checks/runner.js +128 -142
- package/src/cli/advanced-commands.js +6 -6
- package/src/cli/register-meta.js +42 -82
- package/src/cli/register-pipeline.js +8 -143
- package/src/cli/register-plan.js +9 -100
- package/src/cli/retired-commands.js +49 -0
- package/src/cli.js +18 -5
- package/src/commands/agent-run.js +40 -26
- package/src/commands/audit.js +127 -124
- package/src/commands/board.js +5 -9
- package/src/commands/check.js +29 -16
- package/src/commands/doctor.js +2 -0
- package/src/commands/env.js +176 -150
- package/src/commands/go.js +71 -53
- package/src/commands/harden.js +90 -81
- package/src/commands/hu-start.js +52 -0
- package/src/commands/hu.js +288 -221
- package/src/commands/identity.js +111 -78
- package/src/commands/init-atril.js +47 -0
- package/src/commands/init.js +11 -40
- package/src/commands/install-tools.js +70 -85
- package/src/commands/main-guard.js +78 -0
- package/src/commands/policy.js +226 -184
- package/src/commands/qmd.js +27 -21
- package/src/commands/rag.js +75 -48
- package/src/commands/review-gate.js +421 -341
- package/src/commands/start.js +4 -5
- package/src/commands/steward.js +96 -47
- package/src/commands/tournament.js +46 -37
- package/src/commands/worktree.js +94 -25
- package/src/config/loader.js +34 -17
- package/src/config/secrets.js +36 -0
- package/src/config.js +1 -0
- package/src/environment/adr.js +16 -2
- package/src/git/karajan-label.js +20 -8
- package/src/guards/main-guard.js +54 -0
- package/src/harden/hook-templates.js +16 -1
- package/src/harden/sentinel/posttooluse.mjs +18 -6
- package/src/harden/sentinel/pretooluse-sentinel.mjs +64 -36
- package/src/harden/sentinel/sentinel-lib.mjs +129 -26
- package/src/harden/sentinel/sentinel-shell.mjs +5 -16
- package/src/harden/sentinel/sessionstart.mjs +3 -2
- package/src/harden/sentinel/stop.mjs +5 -4
- package/src/harden/workflow-templates.js +1 -1
- package/src/hu/board-lookup.js +29 -0
- package/src/hu/gh-identity.js +23 -0
- package/src/hu/github-board.js +4 -2
- package/src/hu/lane-prune.js +15 -7
- package/src/hu/lane-setup.js +65 -0
- package/src/hu/lanes.js +66 -0
- package/src/hu/team-board-mirror.js +3 -2
- package/src/infrastructure/command-runner.js +1 -1
- package/src/infrastructure/file-system-service.js +1 -1
- package/src/mcp/handlers/direct-handlers.js +2 -292
- package/src/mcp/handlers/hu-handlers.js +1 -35
- package/src/mcp/handlers/management-handlers.js +2 -42
- package/src/mcp/server-handlers.js +16 -22
- package/src/mcp/tools.js +1 -196
- package/src/plan/lane-plans.js +54 -0
- package/src/plan/plan-store.js +7 -4
- package/src/policy/add.js +26 -12
- package/src/policy/adr-number-check.js +31 -0
- package/src/prompts/audit.js +299 -339
- package/src/prompts/card-context.js +10 -5
- package/src/prompts/reviewer.js +5 -2
- package/src/rag/auto-update.js +56 -43
- package/src/rag/bootstrap-index.js +28 -54
- package/src/rag/migrate.js +1 -1
- package/src/rag/onnx-fallback.js +2 -2
- package/src/rag/pid-lease.js +70 -0
- package/src/rag/project-store.js +2 -12
- package/src/review/card-first.js +57 -46
- package/src/review/gate-gitignore.js +23 -4
- package/src/review/gate-hook.js +12 -4
- package/src/review/one-shot-review.js +45 -35
- package/src/review/publish-pr.js +14 -2
- package/src/review/repo-docs.js +73 -0
- package/src/review/repo-stack.js +59 -0
- package/src/review/reviewer-fallback.js +19 -4
- package/src/review/seal-commit.js +29 -0
- package/src/review/sonar-pregate.js +59 -44
- package/src/review/third-party-review.js +90 -16
- package/src/review/third-party-size.js +43 -0
- package/src/review/third-party-skills.js +54 -0
- package/src/review/verify-pr.js +1 -24
- package/src/roles/audit-role.js +106 -125
- package/src/skills/atril-skills.js +5 -4
- package/src/sonar/scanner.js +116 -101
- package/src/steward/invariants.js +5 -4
- package/src/steward/phantom-sweep.js +66 -0
- package/src/tournament/judge.js +60 -53
- package/src/utils/gh-account.js +37 -0
- package/src/utils/git.js +0 -13
- package/src/utils/home-migration.js +7 -1
- package/src/utils/main-checkout.js +53 -0
- package/src/utils/qmd-collection.js +3 -1
- package/src/utils/welcome.js +3 -3
- package/templates/{skills → atril/commands}/kj-architect.md +5 -0
- package/templates/{skills → atril/commands}/kj-audit.md +5 -0
- package/templates/{skills → atril/commands}/kj-board.md +5 -0
- package/templates/{skills → atril/commands}/kj-code.md +5 -0
- package/templates/{skills → atril/commands}/kj-csv-transform.md +5 -0
- package/templates/{skills → atril/commands}/kj-data-report.md +5 -0
- package/templates/{skills → atril/commands}/kj-discover.md +5 -0
- package/templates/{skills → atril/commands}/kj-rag-query.md +5 -0
- package/templates/{skills → atril/commands}/kj-review.md +5 -0
- package/templates/{skills → atril/commands}/kj-security.md +5 -0
- package/templates/{skills → atril/commands}/kj-sonar.md +5 -0
- package/templates/{skills → atril/commands}/kj-sql-analysis.md +5 -0
- package/templates/{skills → atril/commands}/kj-test.md +5 -0
- package/packages/hu-board/public/utils/run-launcher.js +0 -169
- package/packages/hu-board/src/run-tracker.js +0 -121
- package/src/activity-log.js +0 -59
- package/src/agents/host-agent.js +0 -38
- package/src/agents/model-registry.js +0 -142
- package/src/audit/plan-adherence.js +0 -224
- package/src/autonomy/arbiter-role.js +0 -71
- package/src/autonomy/arbiter.js +0 -22
- package/src/autonomy/decider.js +0 -18
- package/src/autonomy/decision-resolver.js +0 -58
- package/src/autonomy/outcome-report.js +0 -55
- package/src/autonomy/stage-ask.js +0 -30
- package/src/brain/decision-tracker.js +0 -125
- package/src/brain/decisor.js +0 -243
- package/src/brain/solomon-consult.js +0 -171
- package/src/brain/standby-scheduler.js +0 -8
- package/src/budget/comparison.js +0 -96
- package/src/canvas/parse-md.js +0 -238
- package/src/canvas/schema.js +0 -101
- package/src/canvas/to-flat.js +0 -85
- package/src/canvas/validate.js +0 -163
- package/src/ci/dispatch.js +0 -99
- package/src/ci/index.js +0 -3
- package/src/ci/pr-diff.js +0 -26
- package/src/cli/register-standby.js +0 -26
- package/src/commands/architect.js +0 -111
- package/src/commands/autorun.js +0 -49
- package/src/commands/researcher.js +0 -54
- package/src/commands/resume.js +0 -72
- package/src/commands/review.js +0 -89
- package/src/commands/run.js +0 -185
- package/src/commands/standby.js +0 -117
- package/src/commands/status.js +0 -36
- package/src/commands/triage.js +0 -78
- package/src/commands/undo.js +0 -62
- package/src/domains/domain-loader.js +0 -245
- package/src/domains/domain-registry.js +0 -140
- package/src/domains/domain-synthesizer.js +0 -129
- package/src/git/automation.js +0 -433
- package/src/git/coder-commit-guard.js +0 -40
- package/src/git/hu-automation.js +0 -243
- package/src/git/hu-snapshot.js +0 -10
- package/src/git/symlink-targets.js +0 -57
- package/src/golden/asserter.js +0 -92
- package/src/golden/loader.js +0 -52
- package/src/golden/runner.js +0 -92
- package/src/golden/schema.js +0 -41
- package/src/guards/duplicate-members.js +0 -86
- package/src/guards/intent-guard.js +0 -161
- package/src/guards/perf-guard.js +0 -126
- package/src/guards/policy-guard.js +0 -90
- package/src/guards/policy-resolver.js +0 -85
- package/src/guards/secret-redactor.js +0 -71
- package/src/hu/acceptance-runner.js +0 -138
- package/src/hu/lazy-planner.js +0 -109
- package/src/hu/parallel-executor.js +0 -94
- package/src/hu/routing-metrics.js +0 -17
- package/src/hu/split-validator.js +0 -143
- package/src/hu/splitting-detector.js +0 -158
- package/src/hu/splitting-generator.js +0 -175
- package/src/hu/store.js +0 -394
- package/src/infrastructure/mocks.js +0 -182
- package/src/mcp/handlers/run-handler.js +0 -318
- package/src/mcp/sovereignty-guard.js +0 -113
- package/src/mcp/tool-arg-normalizers.js +0 -16
- package/src/mutate/reviewer-signal.js +0 -76
- package/src/orchestrator/agent-fallback.js +0 -81
- package/src/orchestrator/brain-coordinator.js +0 -186
- package/src/orchestrator/ci-integration.js +0 -139
- package/src/orchestrator/config-init.js +0 -426
- package/src/orchestrator/direct-actions.js +0 -217
- package/src/orchestrator/drivers/error-recovery.js +0 -287
- package/src/orchestrator/drivers/init-context.js +0 -238
- package/src/orchestrator/drivers/iteration-loop.js +0 -382
- package/src/orchestrator/drivers/iteration-phases/coder-and-refactorer.js +0 -69
- package/src/orchestrator/drivers/iteration-phases/guards.js +0 -91
- package/src/orchestrator/drivers/iteration-phases/handle-approved.js +0 -29
- package/src/orchestrator/drivers/iteration-phases/quality-gates.js +0 -125
- package/src/orchestrator/drivers/iteration-phases/reviewer-gate.js +0 -62
- package/src/orchestrator/drivers/post-loop.js +0 -404
- package/src/orchestrator/drivers/pre-loop-phases/auto-hu-batch.js +0 -137
- package/src/orchestrator/drivers/pre-loop-phases/config-deprecations.js +0 -47
- package/src/orchestrator/drivers/pre-loop-phases/ensure-addyosmani-skills.js +0 -84
- package/src/orchestrator/drivers/pre-loop-phases/inject-loaded-plan.js +0 -393
- package/src/orchestrator/drivers/pre-loop.js +0 -524
- package/src/orchestrator/drivers/run-hu-batch.js +0 -468
- package/src/orchestrator/feedback-enrichment.js +0 -140
- package/src/orchestrator/feedback-queue.js +0 -151
- package/src/orchestrator/flow-control.js +0 -170
- package/src/orchestrator/flow-runner.js +0 -365
- package/src/orchestrator/fs-leak-detector.js +0 -228
- package/src/orchestrator/hu-scheduler.js +0 -114
- package/src/orchestrator/hu-sub-pipeline.js +0 -642
- package/src/orchestrator/iteration-gate.js +0 -73
- package/src/orchestrator/iteration-stages.js +0 -9
- package/src/orchestrator/parallel-limiter.js +0 -74
- package/src/orchestrator/pipeline-context.js +0 -72
- package/src/orchestrator/post-loop-stages.js +0 -468
- package/src/orchestrator/pre-loop-stages.js +0 -11
- package/src/orchestrator/preflight-checks.js +0 -487
- package/src/orchestrator/repair/repair-detector.js +0 -117
- package/src/orchestrator/repair/repair-runner.js +0 -142
- package/src/orchestrator/reviewer-fallback.js +0 -45
- package/src/orchestrator/role-output-compressor.js +0 -189
- package/src/orchestrator/session-journal.js +0 -308
- package/src/orchestrator/solomon-escalation.js +0 -331
- package/src/orchestrator/solomon-rules.js +0 -212
- package/src/orchestrator/stages/acceptance-coverage-stage.js +0 -47
- package/src/orchestrator/stages/architect-stage.js +0 -172
- package/src/orchestrator/stages/coder-stage.js +0 -506
- package/src/orchestrator/stages/domain-curator-stage.js +0 -82
- package/src/orchestrator/stages/format-stage.js +0 -61
- package/src/orchestrator/stages/hu-reviewer-phases/detect-and-apply-splits.js +0 -127
- package/src/orchestrator/stages/hu-reviewer-stage.js +0 -419
- package/src/orchestrator/stages/perf-stage.js +0 -140
- package/src/orchestrator/stages/planner-stage.js +0 -85
- package/src/orchestrator/stages/rag-context-stage.js +0 -80
- package/src/orchestrator/stages/rag-preload-decisor.js +0 -58
- package/src/orchestrator/stages/research-stage.js +0 -69
- package/src/orchestrator/stages/reviewer-stage.js +0 -431
- package/src/orchestrator/stages/sonar-stage.js +0 -439
- package/src/orchestrator/stages/stage-classes.js +0 -84
- package/src/orchestrator/stages/stage-executor.js +0 -155
- package/src/orchestrator/stages/suite-green-stage.js +0 -62
- package/src/orchestrator/stages/tdd-discipline-stage.js +0 -56
- package/src/orchestrator/stages/tool-judge-stage.js +0 -53
- package/src/orchestrator/stages/triage-stage.js +0 -172
- package/src/orchestrator/standby.js +0 -71
- package/src/orchestrator/verification-gate.js +0 -183
- package/src/orchestrator.js +0 -22
- package/src/plan/adr-generator.js +0 -170
- package/src/plan/adr-loader.js +0 -60
- package/src/plan/plan-executor.js +0 -100
- package/src/plan/plan-validation.js +0 -4
- package/src/prompts/acceptance-coverage.js +0 -32
- package/src/prompts/arbiter.js +0 -38
- package/src/prompts/architect.js +0 -103
- package/src/prompts/hu-reviewer.js +0 -244
- package/src/prompts/tool-correctness-judge.js +0 -31
- package/src/prompts/triage.js +0 -57
- package/src/rag/embedder.js +0 -2
- package/src/rag/embedders/_cloud-base.js +0 -2
- package/src/rag/embedders/cohere.js +0 -2
- package/src/rag/embedders/mistral.js +0 -2
- package/src/rag/embedders/onnx.js +0 -2
- package/src/rag/embedders/openai.js +0 -2
- package/src/rag/embedders/voyage.js +0 -2
- package/src/rag/rerank.js +0 -4
- package/src/rag/where-parser.js +0 -4
- package/src/repeat-detector.js +0 -88
- package/src/review/diff-generator.js +0 -112
- package/src/review/git-stash-helper.js +0 -104
- package/src/review/schema.js +0 -31
- package/src/review/scope-filter.js +0 -152
- package/src/review/snapshot-diff.js +0 -122
- package/src/review/tdd-discipline.js +0 -90
- package/src/review/tdd-policy.js +0 -69
- package/src/roles/acceptance-coverage-role.js +0 -78
- package/src/roles/architect-role.js +0 -77
- package/src/roles/coder-role.js +0 -113
- package/src/roles/commiter-role.js +0 -113
- package/src/roles/domain-curator-role.js +0 -134
- package/src/roles/hu-reviewer-role.js +0 -64
- package/src/roles/impeccable-role.js +0 -85
- package/src/roles/index.js +0 -18
- package/src/roles/karajan-brain-role.js +0 -134
- package/src/roles/perf-role.js +0 -122
- package/src/roles/planner-role.js +0 -151
- package/src/roles/refactorer-role.js +0 -30
- package/src/roles/repairer-role.js +0 -181
- package/src/roles/researcher-role.js +0 -70
- package/src/roles/reviewer-role.js +0 -115
- package/src/roles/security-role.js +0 -73
- package/src/roles/solomon-role.js +0 -271
- package/src/roles/sonar-role.js +0 -72
- package/src/roles/tester-role.js +0 -235
- package/src/roles/tool-correctness-judge-role.js +0 -78
- package/src/roles/triage-role.js +0 -99
- package/src/session/journal/decisions-writer.js +0 -200
- package/src/session/journal/iteration-logger.js +0 -194
- package/src/session/journal/summary-writer.js +0 -320
- package/src/session/journal/tree-writer.js +0 -164
- package/src/session/journal/write-all.js +0 -89
- package/src/session-cleanup.js +0 -116
- package/src/skills/semantic-detector.js +0 -167
- package/src/skills/skill-detector.js +0 -385
- package/src/sonar/cloud-scanner.js +0 -78
- package/src/tracker-bootstrap.js +0 -44
- package/src/types/index.js +0 -38
- package/src/types/policy.js +0 -43
- package/src/types/solomon.js +0 -87
- package/src/utils/async-lock.js +0 -31
- package/src/utils/budget.js +0 -229
- package/src/utils/cwd-confirm.js +0 -39
- package/src/utils/display/event-handlers.js +0 -403
- package/src/utils/display/formatters.js +0 -132
- package/src/utils/display/header.js +0 -47
- package/src/utils/display/session-summary.js +0 -118
- package/src/utils/display/solomon.js +0 -42
- package/src/utils/pricing.js +0 -29
- package/src/utils/quota-simulator.js +0 -56
- package/src/utils/role-assigner.js +0 -137
- package/src/utils/rtk-wrapper.js +0 -87
- package/src/utils/run-registry.js +0 -9
- package/src/utils/status-dashboard.js +0 -254
- package/src/utils/tool-call-extractor.js +0 -56
- package/src/webperf/devtools-detect.js +0 -112
- package/src/webperf/webperf-role-integration.js +0 -66
- package/templates/skills/kj-run.md +0 -73
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
// Structured feedback queue for inter-role communication.
|
|
2
|
-
// Replaces the flat session.last_reviewer_feedback string with typed messages.
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @typedef {Object} FeedbackEntry
|
|
6
|
-
* @property {string} source - "reviewer" | "tester" | "security" | "sonar" | "audit" | "brain"
|
|
7
|
-
* @property {string} severity - "critical" | "high" | "medium" | "low"
|
|
8
|
-
* @property {string} category - "security" | "correctness" | "tests" | "style" | "performance" | "other"
|
|
9
|
-
* @property {string} description
|
|
10
|
-
* @property {string} [file]
|
|
11
|
-
* @property {number} [line]
|
|
12
|
-
* @property {string} [suggestedFix]
|
|
13
|
-
* @property {string} [id]
|
|
14
|
-
* @property {number} [iteration] - when this feedback was added
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
const SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
|
|
18
|
-
const CATEGORY_ORDER = { security: 0, correctness: 1, tests: 2, performance: 3, style: 4, other: 5 };
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Create a new empty feedback queue.
|
|
22
|
-
*/
|
|
23
|
-
export function createQueue() {
|
|
24
|
-
return { entries: [] };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Add a feedback entry to the queue.
|
|
29
|
-
*/
|
|
30
|
-
export function addEntry(queue, entry) {
|
|
31
|
-
if (!entry || !entry.description) return queue;
|
|
32
|
-
const normalized = {
|
|
33
|
-
source: entry.source || "unknown",
|
|
34
|
-
severity: entry.severity || "medium",
|
|
35
|
-
category: entry.category || "other",
|
|
36
|
-
description: entry.description,
|
|
37
|
-
file: entry.file || null,
|
|
38
|
-
line: entry.line || null,
|
|
39
|
-
suggestedFix: entry.suggestedFix || null,
|
|
40
|
-
id: entry.id || null,
|
|
41
|
-
iteration: entry.iteration || 0
|
|
42
|
-
};
|
|
43
|
-
queue.entries.push(normalized);
|
|
44
|
-
return queue;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Add multiple entries at once.
|
|
49
|
-
*/
|
|
50
|
-
export function addEntries(queue, entries) {
|
|
51
|
-
for (const e of entries || []) addEntry(queue, e);
|
|
52
|
-
return queue;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Deduplicate entries with the same description + source (keep the most severe).
|
|
57
|
-
*/
|
|
58
|
-
export function deduplicate(queue) {
|
|
59
|
-
const seen = new Map();
|
|
60
|
-
for (const e of queue.entries) {
|
|
61
|
-
const key = `${e.source}::${e.description}`;
|
|
62
|
-
const existing = seen.get(key);
|
|
63
|
-
if (!existing || SEVERITY_ORDER[e.severity] < SEVERITY_ORDER[existing.severity]) {
|
|
64
|
-
seen.set(key, e);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
queue.entries = [...seen.values()];
|
|
68
|
-
return queue;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Sort entries by priority: category first (security > correctness > ...), then severity.
|
|
73
|
-
*/
|
|
74
|
-
export function prioritize(queue) {
|
|
75
|
-
queue.entries.sort((a, b) => {
|
|
76
|
-
const catDiff = (CATEGORY_ORDER[a.category] ?? 5) - (CATEGORY_ORDER[b.category] ?? 5);
|
|
77
|
-
if (catDiff !== 0) return catDiff;
|
|
78
|
-
return (SEVERITY_ORDER[a.severity] ?? 2) - (SEVERITY_ORDER[b.severity] ?? 2);
|
|
79
|
-
});
|
|
80
|
-
return queue;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Format queue as a numbered list for the coder prompt.
|
|
85
|
-
*/
|
|
86
|
-
export function formatForCoder(queue) {
|
|
87
|
-
if (!queue.entries.length) return "";
|
|
88
|
-
|
|
89
|
-
const lines = [];
|
|
90
|
-
queue.entries.forEach((e, i) => {
|
|
91
|
-
const loc = e.file ? ` (${e.file}${e.line ? `:${e.line}` : ""})` : "";
|
|
92
|
-
const tag = `[${e.source}:${e.severity}:${e.category}]`;
|
|
93
|
-
lines.push(`${i + 1}. ${tag}${loc} ${e.description}`);
|
|
94
|
-
if (e.suggestedFix) lines.push(` Fix: ${e.suggestedFix}`);
|
|
95
|
-
});
|
|
96
|
-
return lines.join("\n");
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Filter entries by category.
|
|
101
|
-
*/
|
|
102
|
-
export function filterByCategory(queue, category) {
|
|
103
|
-
return { entries: queue.entries.filter(e => e.category === category) };
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Check if queue has any critical/high severity entries.
|
|
108
|
-
*/
|
|
109
|
-
export function hasBlockingIssues(queue) {
|
|
110
|
-
return queue.entries.some(e => e.severity === "critical" || e.severity === "high");
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Get count of entries by category.
|
|
115
|
-
*/
|
|
116
|
-
export function countByCategory(queue) {
|
|
117
|
-
const counts = {};
|
|
118
|
-
for (const e of queue.entries) {
|
|
119
|
-
counts[e.category] = (counts[e.category] || 0) + 1;
|
|
120
|
-
}
|
|
121
|
-
return counts;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Clear the queue (after coder addresses the feedback).
|
|
126
|
-
*/
|
|
127
|
-
export function clear(queue) {
|
|
128
|
-
queue.entries = [];
|
|
129
|
-
return queue;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Serialize queue for persistence in session.
|
|
134
|
-
*/
|
|
135
|
-
export function serialize(queue) {
|
|
136
|
-
return JSON.stringify(queue);
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* Deserialize queue from session.
|
|
141
|
-
*/
|
|
142
|
-
export function deserialize(str) {
|
|
143
|
-
if (!str) return createQueue();
|
|
144
|
-
try {
|
|
145
|
-
const parsed = JSON.parse(str);
|
|
146
|
-
return { entries: Array.isArray(parsed.entries) ? parsed.entries : [] };
|
|
147
|
-
} catch {
|
|
148
|
-
return createQueue();
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Session flow control — checkpoints, timeouts, budget checks.
|
|
3
|
-
* Extracted from orchestrator.js — session management, not orchestration.
|
|
4
|
-
*/
|
|
5
|
-
import { markSessionStatus, addCheckpoint } from "../session/store.js";
|
|
6
|
-
import { setRetryCount } from "../session/mutators.js";
|
|
7
|
-
import { emitProgress, makeEvent } from "../utils/events.js";
|
|
8
|
-
import { msg, getLang } from "../utils/messages.js";
|
|
9
|
-
|
|
10
|
-
function detectCheckpointProgress(session, lastCheckpointSnapshot) {
|
|
11
|
-
if (!lastCheckpointSnapshot) return true; // First checkpoint — assume progress
|
|
12
|
-
const currentIteration = session.reviewer_retry_count ?? 0;
|
|
13
|
-
const currentStages = Object.keys(session.resolved_policies || {}).length;
|
|
14
|
-
const currentCheckpoints = (session.checkpoints || []).length;
|
|
15
|
-
|
|
16
|
-
const iterationAdvanced = currentIteration !== lastCheckpointSnapshot.iteration;
|
|
17
|
-
const stagesChanged = currentStages !== lastCheckpointSnapshot.stagesCount;
|
|
18
|
-
const checkpointsChanged = currentCheckpoints !== lastCheckpointSnapshot.checkpointsCount;
|
|
19
|
-
|
|
20
|
-
return iterationAdvanced || stagesChanged || checkpointsChanged;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function takeCheckpointSnapshot(session) {
|
|
24
|
-
return {
|
|
25
|
-
iteration: session.reviewer_retry_count ?? 0,
|
|
26
|
-
stagesCount: Object.keys(session.resolved_policies || {}).length,
|
|
27
|
-
checkpointsCount: (session.checkpoints || []).length
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Determine if checkpoint should auto-continue without asking the user.
|
|
33
|
-
* Exported for testing.
|
|
34
|
-
*/
|
|
35
|
-
export function shouldAutoContinueCheckpoint(session, hasProgress) {
|
|
36
|
-
if (hasProgress) {
|
|
37
|
-
setRetryCount(session, "checkpoint_stall", 0);
|
|
38
|
-
return { autoContinue: true, reason: "progress_detected" };
|
|
39
|
-
}
|
|
40
|
-
const wasRateLimited = (session.standby_retry_count || 0) > 0;
|
|
41
|
-
const consecutiveStalls = (session._checkpoint_stall_count || 0) + 1;
|
|
42
|
-
setRetryCount(session, "checkpoint_stall", consecutiveStalls);
|
|
43
|
-
if (wasRateLimited && consecutiveStalls < 3) {
|
|
44
|
-
return { autoContinue: true, reason: "recoverable_stall" };
|
|
45
|
-
}
|
|
46
|
-
return { autoContinue: false, reason: consecutiveStalls >= 3 ? "max_stalls_reached" : "no_progress" };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export async function handleCheckpoint({ checkpointDisabled, askQuestion, lastCheckpointAt, checkpointIntervalMs, elapsedMinutes, i, config, budgetTracker, stageResults, emitter, eventBase, session, budgetSummary, lastCheckpointSnapshot }) {
|
|
50
|
-
if (checkpointDisabled || !askQuestion || (Date.now() - lastCheckpointAt) < checkpointIntervalMs) {
|
|
51
|
-
return { action: "continue_loop", checkpointDisabled, lastCheckpointAt, lastCheckpointSnapshot };
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const elapsedStr = elapsedMinutes.toFixed(1);
|
|
55
|
-
const stagesCompleted = Object.keys(stageResults).join(", ") || "none";
|
|
56
|
-
|
|
57
|
-
const hasProgress = detectCheckpointProgress(session, lastCheckpointSnapshot);
|
|
58
|
-
const newSnapshot = takeCheckpointSnapshot(session);
|
|
59
|
-
const decision = shouldAutoContinueCheckpoint(session, hasProgress);
|
|
60
|
-
|
|
61
|
-
if (decision.autoContinue) {
|
|
62
|
-
emitProgress(
|
|
63
|
-
emitter,
|
|
64
|
-
makeEvent("session:checkpoint", { ...eventBase, iteration: i, stage: "checkpoint" }, {
|
|
65
|
-
message: `Checkpoint: ${decision.reason === "progress_detected" ? "progress detected" : "stall caused by rate limit/cooldown"}, auto-continuing (${elapsedStr} min elapsed)`,
|
|
66
|
-
detail: { elapsed_minutes: Number(elapsedStr), iterations_done: i - 1, stages: stagesCompleted, auto_continued: true, reason: decision.reason }
|
|
67
|
-
})
|
|
68
|
-
);
|
|
69
|
-
return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now(), lastCheckpointSnapshot: newSnapshot };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const iterInfo = `${i - 1}/${config.max_iterations} iterations completed`;
|
|
73
|
-
const budgetInfo = budgetTracker.total().cost_usd > 0 ? ` | Budget: $${budgetTracker.total().cost_usd.toFixed(2)}` : "";
|
|
74
|
-
const checkpointMsg = `Checkpoint — ${elapsedStr} min elapsed | ${iterInfo}${budgetInfo} | Stages completed: ${stagesCompleted}. No progress since last checkpoint. What would you like to do?`;
|
|
75
|
-
|
|
76
|
-
emitProgress(
|
|
77
|
-
emitter,
|
|
78
|
-
makeEvent("session:checkpoint", { ...eventBase, iteration: i, stage: "checkpoint" }, {
|
|
79
|
-
message: `Interactive checkpoint at ${elapsedStr} min (stalled)`,
|
|
80
|
-
detail: { elapsed_minutes: Number(elapsedStr), iterations_done: i - 1, stages: stagesCompleted, auto_continued: false }
|
|
81
|
-
})
|
|
82
|
-
);
|
|
83
|
-
|
|
84
|
-
const lang = getLang(config);
|
|
85
|
-
const answer = await askQuestion(
|
|
86
|
-
`${checkpointMsg}\n\n${msg("checkpoint_options", lang)}`
|
|
87
|
-
);
|
|
88
|
-
|
|
89
|
-
await addCheckpoint(session, { stage: "interactive-checkpoint", elapsed_minutes: Number(elapsedStr), answer });
|
|
90
|
-
|
|
91
|
-
const trimmedAnswer = (answer || "").trim();
|
|
92
|
-
const isExplicitStop = trimmedAnswer === "4" || trimmedAnswer.toLowerCase().startsWith("stop");
|
|
93
|
-
|
|
94
|
-
if (isExplicitStop) {
|
|
95
|
-
await markSessionStatus(session, "stopped");
|
|
96
|
-
emitProgress(
|
|
97
|
-
emitter,
|
|
98
|
-
makeEvent("session:end", { ...eventBase, iteration: i, stage: "user-stop" }, {
|
|
99
|
-
status: "stopped",
|
|
100
|
-
message: "Session stopped by user at checkpoint",
|
|
101
|
-
detail: { approved: false, reason: "user_stopped", elapsed_minutes: Number(elapsedStr), budget: budgetSummary() }
|
|
102
|
-
})
|
|
103
|
-
);
|
|
104
|
-
return { action: "stop", result: { approved: false, sessionId: session.id, reason: "user_stopped", elapsed_minutes: Number(elapsedStr) } };
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const parsed = parseCheckpointAnswer({ trimmedAnswer, checkpointDisabled, config });
|
|
108
|
-
parsed.lastCheckpointSnapshot = newSnapshot;
|
|
109
|
-
return parsed;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
export function parseCheckpointAnswer({ trimmedAnswer, checkpointDisabled, config }) {
|
|
113
|
-
if (!trimmedAnswer) {
|
|
114
|
-
return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
|
|
115
|
-
}
|
|
116
|
-
if (trimmedAnswer === "2" || trimmedAnswer.toLowerCase().startsWith("continue until")) {
|
|
117
|
-
return { action: "continue_loop", checkpointDisabled: true, lastCheckpointAt: Date.now() };
|
|
118
|
-
}
|
|
119
|
-
if (trimmedAnswer === "1" || trimmedAnswer.toLowerCase().includes("5 m")) {
|
|
120
|
-
return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
|
|
121
|
-
}
|
|
122
|
-
const customMinutes = Number.parseInt(trimmedAnswer.replaceAll(/\D/g, ""), 10);
|
|
123
|
-
if (customMinutes > 0) {
|
|
124
|
-
config.session.checkpoint_interval_minutes = customMinutes;
|
|
125
|
-
return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
|
|
126
|
-
}
|
|
127
|
-
return { action: "continue_loop", checkpointDisabled, lastCheckpointAt: Date.now() };
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export async function checkSessionTimeout({ askQuestion, elapsedMinutes, config, session, emitter, eventBase, i, budgetSummary }) {
|
|
131
|
-
// Enforce the wall-clock when no human is watching the checkpoint: either a
|
|
132
|
-
// non-interactive run (no askQuestion) OR an autonomous one — where askQuestion
|
|
133
|
-
// is the auto-continue wrapper (truthy) but nobody is there to stop a runaway.
|
|
134
|
-
// Interactive runs keep skipping it (the human decides at the checkpoint).
|
|
135
|
-
// KJC-TSK-0575 (AUTO-D): without this, autonomous runs had NO wall-clock cap.
|
|
136
|
-
const unattended = !askQuestion || askQuestion.unattended === true;
|
|
137
|
-
if (!unattended || elapsedMinutes <= config.session.max_total_minutes) return;
|
|
138
|
-
|
|
139
|
-
await markSessionStatus(session, "failed");
|
|
140
|
-
emitProgress(
|
|
141
|
-
emitter,
|
|
142
|
-
makeEvent("session:end", { ...eventBase, iteration: i, stage: "timeout" }, {
|
|
143
|
-
status: "fail",
|
|
144
|
-
message: "Session timed out",
|
|
145
|
-
detail: { approved: false, reason: "timeout", budget: budgetSummary() }
|
|
146
|
-
})
|
|
147
|
-
);
|
|
148
|
-
throw new Error("Session timed out");
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export async function checkBudgetExceeded({ budgetTracker, config, session, emitter, eventBase, i, budgetLimit, budgetSummary }) {
|
|
152
|
-
if (!budgetTracker.isOverBudget(config?.max_budget_usd)) return;
|
|
153
|
-
|
|
154
|
-
await markSessionStatus(session, "failed");
|
|
155
|
-
const totalCost = budgetTracker.total().cost_usd;
|
|
156
|
-
const limit = Number(budgetLimit ?? config?.max_budget_usd);
|
|
157
|
-
const message =
|
|
158
|
-
`Budget exceeded: $${totalCost.toFixed(2)} > $${limit.toFixed(2)}. ` +
|
|
159
|
-
`Continue consciously with \`kj resume ${session.id}\`, or raise the cap ` +
|
|
160
|
-
`(max_budget_usd in .karajan/kj.config.yml; null removes it).`;
|
|
161
|
-
emitProgress(
|
|
162
|
-
emitter,
|
|
163
|
-
makeEvent("session:end", { ...eventBase, iteration: i, stage: "budget" }, {
|
|
164
|
-
status: "fail",
|
|
165
|
-
message,
|
|
166
|
-
detail: { approved: false, reason: "budget_exceeded", budget: budgetSummary(), max_budget_usd: budgetLimit }
|
|
167
|
-
})
|
|
168
|
-
);
|
|
169
|
-
throw new Error(message);
|
|
170
|
-
}
|
|
@@ -1,365 +0,0 @@
|
|
|
1
|
-
// Post-TSK-0335 flow-runner.js is a thin orchestrator: runFlow + resumeFlow.
|
|
2
|
-
// Heavy lifting lives under src/orchestrator/drivers/. Imports here reflect
|
|
3
|
-
// only what the two top-level entry points still need directly:
|
|
4
|
-
// • session/store.js — load/save/resume/checkpoint for resumeFlow
|
|
5
|
-
// • utils/events.js — session:start / session:end / init_error events
|
|
6
|
-
// • solomon-escalation.js — init-error fallback (pre-loop failures)
|
|
7
|
-
// • hu-sub-pipeline.js — branch: if HU batch → sub-pipeline, else loop
|
|
8
|
-
// • config-init.js — dry-run handling, pipeline flag resolution,
|
|
9
|
-
// product-context loader
|
|
10
|
-
// • config/test-harness.js — defensive testHarness resolution for callers
|
|
11
|
-
// that bypass loadConfig (orchestrator tests)
|
|
12
|
-
// • skills/skill-detector.js — cleanupAutoInstalledSkills on session end
|
|
13
|
-
// • drivers/* — the extracted pipeline phases
|
|
14
|
-
import {
|
|
15
|
-
loadSession,
|
|
16
|
-
markSessionStatus,
|
|
17
|
-
resumeSessionWithAnswer,
|
|
18
|
-
saveSession,
|
|
19
|
-
} from "../session/store.js";
|
|
20
|
-
// TSK-0337: session mutations go through the mutators module. Every
|
|
21
|
-
// `session.x = y` outside src/session/ should route through one of these
|
|
22
|
-
// so grepping the mutator name locates every writer in seconds. See
|
|
23
|
-
// tests/architecture/session-write-boundary.test.js for the invariant.
|
|
24
|
-
import {
|
|
25
|
-
setStatus, setReviewerFeedback, resetAllRetryCounters,
|
|
26
|
-
setSonarIssueSignature, setReviewerIssueSignature,
|
|
27
|
-
setSonarRepeatCount, setReviewerRepeatCount,
|
|
28
|
-
setBudget,
|
|
29
|
-
} from "../session/mutators.js";
|
|
30
|
-
import { emitProgress, makeEvent } from "../utils/events.js";
|
|
31
|
-
import {
|
|
32
|
-
resolvePipelineFlags, handleDryRun,
|
|
33
|
-
} from "./config-init.js";
|
|
34
|
-
import { resolveTestHarness } from "../config/test-harness.js";
|
|
35
|
-
import { cleanupAutoInstalledSkills } from "../skills/skill-detector.js";
|
|
36
|
-
import { withRunContext } from "../utils/run-context.js";
|
|
37
|
-
import { ensureTrackerRegistered } from "../tracker-bootstrap.js";
|
|
38
|
-
|
|
39
|
-
// Drivers extracted from this god-module in TSK-0335 (Oleada 3 of the v2.7.4
|
|
40
|
-
// audit refactor). Each driver covers one phase of the pipeline; flow-runner
|
|
41
|
-
// keeps only the top-level runFlow/resumeFlow orchestration.
|
|
42
|
-
// • drivers/init-context.js — build the PipelineContext (pre-loop setup)
|
|
43
|
-
// • drivers/iteration-loop.js — the coder→reviewer iteration body
|
|
44
|
-
// • drivers/post-loop.js — writeHistoryRecord called from resumeFlow
|
|
45
|
-
import { initFlowContext } from "./drivers/init-context.js";
|
|
46
|
-
import { runIterationLoop } from "./drivers/iteration-loop.js";
|
|
47
|
-
import { writeHistoryRecord } from "./drivers/post-loop.js";
|
|
48
|
-
import { runHuBatch } from "./drivers/run-hu-batch.js";
|
|
49
|
-
// Analysis-only path (taskType=audit/doc/infra) skips coder iterations
|
|
50
|
-
// and runs security + audit directly. These three were called without
|
|
51
|
-
// imports until ESLint surfaced it — same class of latent bug as the
|
|
52
|
-
// `saveSession` ReferenceError that took the demo down on 2026-04-27.
|
|
53
|
-
import { generateDiff } from "../review/diff-generator.js";
|
|
54
|
-
import { runSecurityStage, runFinalAuditStage } from "./post-loop-stages.js";
|
|
55
|
-
|
|
56
|
-
// Public re-exports (loadProductContext, shouldAutoContinueCheckpoint,
|
|
57
|
-
// parseCheckpointAnswer) live in src/orchestrator.js (the barrel).
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
// PG card "In Progress" logic moved to src/planning-game/pipeline-adapter.js → initPgAdapter()
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Boundary guard: make sure the session's terminal status reflects what
|
|
65
|
-
* actually happened, even if some inner exit path forgot to call
|
|
66
|
-
* `markSessionStatus`. KJC-BUG-0037 (N1 dogfooding 2026-05-07): runs
|
|
67
|
-
* that took the Brain "max_iterations approved" / "Solomon-after-error
|
|
68
|
-
* approved" / "Brain solomon-approved" exits returned `{approved:true}`
|
|
69
|
-
* upstream but left `session.status = "running"` on disk indefinitely.
|
|
70
|
-
* `kj status` then showed "Pipeline RUNNING" forever and the HU Board
|
|
71
|
-
* carried a perma-zombie.
|
|
72
|
-
*
|
|
73
|
-
* Maps the result shape to a terminal status:
|
|
74
|
-
* approved → "approved"
|
|
75
|
-
* paused → "paused"
|
|
76
|
-
* cancelled → "cancelled"
|
|
77
|
-
* hibernated → "hibernated"
|
|
78
|
-
* anything else → "failed"
|
|
79
|
-
*
|
|
80
|
-
* Idempotent: only writes when the current status is still "running"
|
|
81
|
-
* (or unset). If an inner path already sealed it correctly, this is a
|
|
82
|
-
* no-op.
|
|
83
|
-
*
|
|
84
|
-
* Safe-by-default: never throws. A failure here must not block the
|
|
85
|
-
* top-level result from being returned to the caller.
|
|
86
|
-
*
|
|
87
|
-
* @param {object} session
|
|
88
|
-
* @param {object} [result]
|
|
89
|
-
*/
|
|
90
|
-
export async function sealSessionStatusIfStillRunning(session, result) {
|
|
91
|
-
try {
|
|
92
|
-
if (!session) return;
|
|
93
|
-
const current = session.status;
|
|
94
|
-
if (current && current !== "running") return;
|
|
95
|
-
let target = "failed";
|
|
96
|
-
if (result?.approved === true) target = "approved";
|
|
97
|
-
else if (result?.paused === true) target = "paused";
|
|
98
|
-
else if (result?.cancelled === true) target = "cancelled";
|
|
99
|
-
// A run hibernated on a provider quota cap is NOT a failure — it is
|
|
100
|
-
// suspended and resumable via `kj standby resume`. Sealing it as
|
|
101
|
-
// `failed` would let the HU-zombie reaper treat it as dead work.
|
|
102
|
-
else if (result?.hibernated === true) target = "hibernated";
|
|
103
|
-
await markSessionStatus(session, target);
|
|
104
|
-
} catch { /* non-blocking */ }
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export async function runFlow(opts) {
|
|
108
|
-
// TSK-0338: isolate per-run state (git/diff runner, projectDir, snapshot)
|
|
109
|
-
// inside an AsyncLocalStorage scope. Two concurrent `runFlow` invocations
|
|
110
|
-
// (MCP multi-client) no longer contaminate each other's module state.
|
|
111
|
-
// initFlowContext writes into this store (see drivers/init-context.js).
|
|
112
|
-
return withRunContext({}, () => _runFlowInner(opts));
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
async function _runFlowInner({ task, config, logger, flags = {}, emitter = null, askQuestion = null, pgTaskId = null, pgProject = null, preexisting = null }) {
|
|
116
|
-
// Defensive test-harness resolution for callers that bypass loadConfig()
|
|
117
|
-
// (orchestrator unit tests that build raw config objects). Production
|
|
118
|
-
// callers go through src/config/loader.js → loadConfig which already
|
|
119
|
-
// runs resolveTestHarness() once. When config.testHarness is missing we
|
|
120
|
-
// resolve it here using the same contract: explicit field → globalThis →
|
|
121
|
-
// prod defaults. Idempotent — no-op when already present.
|
|
122
|
-
if (config && !config.testHarness) {
|
|
123
|
-
config.testHarness = resolveTestHarness(config.testHarness);
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// TSK-0339: delegate tracker registration to the neutral bootstrap
|
|
127
|
-
// module so `src/orchestrator/` never imports a tracker directly.
|
|
128
|
-
// Idempotent — no-op if the adapter is already registered (which is the
|
|
129
|
-
// steady state once the real `src/bootstrap.js::ensureBootstrap` has
|
|
130
|
-
// run; orchestrator unit tests that skip bootstrap benefit from this
|
|
131
|
-
// lazy fallback).
|
|
132
|
-
await ensureTrackerRegistered(config);
|
|
133
|
-
|
|
134
|
-
// Auto-GC: prune orphan plans and old finalised state so `~/.kj/` and
|
|
135
|
-
// `~/.karajan/` don't accumulate forever. Silent unless something was
|
|
136
|
-
// removed; stderr one-liner on cleanup. Skipped in test env.
|
|
137
|
-
if (!process.env.VITEST && process.env.NODE_ENV !== "test") {
|
|
138
|
-
try {
|
|
139
|
-
const { runAutoGC, summarizeGC } = await import("../utils/garbage-collector.js");
|
|
140
|
-
const gcResult = await runAutoGC();
|
|
141
|
-
const summary = summarizeGC(gcResult);
|
|
142
|
-
if (summary) process.stderr.write(`${summary}\n`);
|
|
143
|
-
} catch (err) {
|
|
144
|
-
logger?.warn?.(`Auto-GC failed (non-blocking): ${err.message}`);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
const pipelineFlags = resolvePipelineFlags(config);
|
|
149
|
-
|
|
150
|
-
if (flags.dryRun) {
|
|
151
|
-
return handleDryRun({ task, config, flags, emitter, pipelineFlags });
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
let ctx;
|
|
155
|
-
try {
|
|
156
|
-
ctx = await initFlowContext({ task, config, logger, emitter, askQuestion, pgTaskId, pgProject, flags, preexisting });
|
|
157
|
-
} catch (initError) {
|
|
158
|
-
// Pre-loop / preflight failures are CONFIG problems, not pipeline
|
|
159
|
-
// disputes. Pre-v2.7.5 we escalated them to Solomon, which:
|
|
160
|
-
// 1. Spent tokens on something an LLM can't actually fix (e.g.
|
|
161
|
-
// "port 9000 occupied", "docker not installed", "node version
|
|
162
|
-
// too old"). Solomon's job is to mediate between coder and
|
|
163
|
-
// reviewer, not to rewrite the user's environment.
|
|
164
|
-
// 2. Often failed to parse its own output ("Failed to parse
|
|
165
|
-
// Solomon output: no JSON found") and then asked the user a
|
|
166
|
-
// garbled multi-line "Conflict: init_error" prompt — useless
|
|
167
|
-
// when the run was launched by the board's ▶ Run plan with
|
|
168
|
-
// stdio=ignore, since there's nobody to answer it.
|
|
169
|
-
//
|
|
170
|
-
// New behaviour: print the error verbatim with the actionable fix
|
|
171
|
-
// (the preflight check already attached one), emit init_error
|
|
172
|
-
// through the event channel for tooling, and bail with a non-zero
|
|
173
|
-
// exit. The user gets one clear message and a fix; nothing tries to
|
|
174
|
-
// be cleverer than that.
|
|
175
|
-
logger.error(`Initialization failed: ${initError.message}`);
|
|
176
|
-
if (initError.fix) logger.error(` Fix: ${initError.fix}`);
|
|
177
|
-
emitProgress(emitter, makeEvent("init:failed", {
|
|
178
|
-
sessionId: "init-error", iteration: 0, stage: "init", startedAt: Date.now()
|
|
179
|
-
}, {
|
|
180
|
-
status: "fail",
|
|
181
|
-
message: `Initialization failed: ${initError.message}`,
|
|
182
|
-
detail: { error: initError.message, fix: initError.fix || null }
|
|
183
|
-
}));
|
|
184
|
-
throw initError;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
try {
|
|
188
|
-
// --- Analysis-only flow: skip coder/reviewer when coderRequired === false ---
|
|
189
|
-
if (ctx.pipelineFlags.coderRequired === false) {
|
|
190
|
-
logger.info("Analysis-only task — skipping coder/reviewer iteration loop");
|
|
191
|
-
emitProgress(emitter, makeEvent("pipeline:analysis-only", { ...ctx.eventBase, stage: "analysis" }, {
|
|
192
|
-
message: "Analysis-only task — running security and audit stages only",
|
|
193
|
-
detail: { taskType: ctx.session.resolved_policies?.taskType, coderRequired: false }
|
|
194
|
-
}));
|
|
195
|
-
|
|
196
|
-
const analysisStageResults = ctx.stageResults;
|
|
197
|
-
const postLoopDiff = await generateDiff({ baseRef: ctx.session.session_start_sha });
|
|
198
|
-
|
|
199
|
-
if (ctx.pipelineFlags.securityEnabled) {
|
|
200
|
-
const securityResult = await runSecurityStage({
|
|
201
|
-
config: ctx.config, logger, emitter, eventBase: ctx.eventBase, session: ctx.session,
|
|
202
|
-
coderRole: ctx.coderRole, trackBudget: ctx.trackBudget,
|
|
203
|
-
iteration: 1, task: ctx.plannedTask, diff: postLoopDiff, askQuestion, brainCtx: ctx.brainCtx
|
|
204
|
-
});
|
|
205
|
-
if (securityResult.stageResult) analysisStageResults.security = securityResult.stageResult;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const auditResult = await runFinalAuditStage({
|
|
209
|
-
config: ctx.config, logger, emitter, eventBase: ctx.eventBase, session: ctx.session,
|
|
210
|
-
coderRole: ctx.coderRole, trackBudget: ctx.trackBudget,
|
|
211
|
-
iteration: 1, task: ctx.plannedTask, diff: postLoopDiff
|
|
212
|
-
});
|
|
213
|
-
if (auditResult.stageResult) analysisStageResults.audit = auditResult.stageResult;
|
|
214
|
-
|
|
215
|
-
setBudget(ctx.session, ctx.budgetSummary());
|
|
216
|
-
await markSessionStatus(ctx.session, "approved");
|
|
217
|
-
|
|
218
|
-
const analysisResult = {
|
|
219
|
-
approved: true,
|
|
220
|
-
sessionId: ctx.session.id,
|
|
221
|
-
analysisOnly: true,
|
|
222
|
-
stages: analysisStageResults,
|
|
223
|
-
budget: ctx.budgetSummary()
|
|
224
|
-
};
|
|
225
|
-
await writeHistoryRecord({ sessionId: ctx.session.id, task, result: analysisResult, logger });
|
|
226
|
-
|
|
227
|
-
emitProgress(emitter, makeEvent("session:end", { ...ctx.eventBase, stage: "done" }, {
|
|
228
|
-
message: "Analysis-only session completed",
|
|
229
|
-
detail: analysisResult
|
|
230
|
-
}));
|
|
231
|
-
|
|
232
|
-
return analysisResult;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
// --- HU Sub-Pipeline: extracted to drivers/run-hu-batch.js (PR-L) ---
|
|
236
|
-
// 244 LOC of needsSubPipeline check + per-HU iteration with
|
|
237
|
-
// policies + acceptance-tests gate + Sonar + tester translation.
|
|
238
|
-
const huBatch = await runHuBatch({ ctx, task, askQuestion, emitter, logger });
|
|
239
|
-
if (huBatch.handled) {
|
|
240
|
-
await sealSessionStatusIfStillRunning(ctx.session, huBatch.result);
|
|
241
|
-
return huBatch.result;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// --- Standard single-task pipeline (1 HU or no HU reviewer) ---
|
|
245
|
-
const result = await runIterationLoop(ctx, { task: ctx.plannedTask, askQuestion, emitter, logger });
|
|
246
|
-
await writeHistoryRecord({ sessionId: ctx.session.id, task, result, logger });
|
|
247
|
-
await sealSessionStatusIfStillRunning(ctx.session, result);
|
|
248
|
-
return result;
|
|
249
|
-
} finally {
|
|
250
|
-
// --- Journal: best-effort write for non-approved endings (KJC-BUG-0084) ---
|
|
251
|
-
// finalizeApprovedSession writes the journal on the happy path and sets
|
|
252
|
-
// session._journalWritten. Every other terminal ending (sonar_repeat
|
|
253
|
-
// stall, stage_error, thrown stage, budget exceeded) used to leave only
|
|
254
|
-
// triage.md behind — losing the Cache hits table, budget breakdown and
|
|
255
|
-
// commits exactly on the runs where the post-mortem matters most.
|
|
256
|
-
// Paused sessions are skipped: they resume later and the eventual
|
|
257
|
-
// finalize overwrites the journal with the real outcome.
|
|
258
|
-
try {
|
|
259
|
-
const s = ctx.session;
|
|
260
|
-
if (s && s._journalDir && !s._journalWritten && s.status !== "paused") {
|
|
261
|
-
const { writeSessionJournal } = await import("../session/journal/write-all.js");
|
|
262
|
-
const badge = s.status && s.status !== "running" ? s.status.toUpperCase() : "FAILED";
|
|
263
|
-
await writeSessionJournal({
|
|
264
|
-
session: s, logger,
|
|
265
|
-
result: badge,
|
|
266
|
-
iterations: s._journalIterations?.length || 0,
|
|
267
|
-
budget: typeof ctx.budgetSummary === "function" ? ctx.budgetSummary() : null,
|
|
268
|
-
stages: ctx.stageResults || {},
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
} catch (err) {
|
|
272
|
-
logger.warn(`Final journal write failed (non-blocking): ${err.message}`);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// --- Cleanup auto-installed skills ---
|
|
276
|
-
const autoSkills = ctx.session?.autoInstalledSkills;
|
|
277
|
-
if (autoSkills && autoSkills.length > 0) {
|
|
278
|
-
const cleanProjectDir = ctx.config?.projectDir || process.cwd();
|
|
279
|
-
try {
|
|
280
|
-
const cleanupResult = await cleanupAutoInstalledSkills(autoSkills, cleanProjectDir);
|
|
281
|
-
if (cleanupResult.removed.length > 0) {
|
|
282
|
-
logger.info(`Cleaned up ${cleanupResult.removed.length} auto-installed skill(s): ${cleanupResult.removed.join(", ")}`);
|
|
283
|
-
}
|
|
284
|
-
} catch (err) {
|
|
285
|
-
logger.warn(`Skill cleanup failed (non-blocking): ${err.message}`);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
// --- Telemetry: anonymous pipeline_complete event (non-blocking) ---
|
|
290
|
-
try {
|
|
291
|
-
const { sendTelemetryEvent, computeCachedPct } = await import("../utils/telemetry.js");
|
|
292
|
-
const durationS = Math.round((Date.now() - ctx.startedAt) / 1000);
|
|
293
|
-
const sessionStatus = ctx.session?.status || "unknown";
|
|
294
|
-
// Φ0-H (KJC-TSK-0526): aggregate cache-hit ratios per role so we
|
|
295
|
-
// can see on the fleet how much each provider's cache is buying.
|
|
296
|
-
let cachedPct = { cached_pct_coder: null, cached_pct_reviewer: null, cached_pct_total: null };
|
|
297
|
-
try {
|
|
298
|
-
const budgetSummary = ctx.budgetTracker?.summary?.();
|
|
299
|
-
if (budgetSummary) cachedPct = computeCachedPct(budgetSummary);
|
|
300
|
-
} catch { /* non-blocking — telemetry must never break runs */ }
|
|
301
|
-
sendTelemetryEvent("pipeline_complete", {
|
|
302
|
-
mode: config.review_mode,
|
|
303
|
-
agent: ctx.coderRole?.provider || config.coder,
|
|
304
|
-
duration_s: durationS,
|
|
305
|
-
success: sessionStatus === "approved",
|
|
306
|
-
taskType: ctx.session?.resolved_policies?.taskType || null,
|
|
307
|
-
...cachedPct
|
|
308
|
-
}, config).catch(() => {});
|
|
309
|
-
} catch { /* non-blocking */ }
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
export async function resumeFlow({ sessionId, answer, config, logger, flags = {}, emitter = null, askQuestion = null }) {
|
|
314
|
-
const session = answer
|
|
315
|
-
? await resumeSessionWithAnswer(sessionId, answer)
|
|
316
|
-
: await loadSession(sessionId);
|
|
317
|
-
|
|
318
|
-
if (session.status === "paused" && !answer) {
|
|
319
|
-
logger.info(`Session ${sessionId} is paused. Provide --answer to resume.`);
|
|
320
|
-
return session;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
// Allow resuming "stopped" sessions (checkpoint stop) and "failed" sessions
|
|
324
|
-
const resumableStatuses = new Set(["running", "stopped", "failed"]);
|
|
325
|
-
if (!resumableStatuses.has(session.status)) {
|
|
326
|
-
logger.info(`Session ${sessionId} has status ${session.status} — not resumable`);
|
|
327
|
-
return session;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// Mark as running again for stopped/failed sessions
|
|
331
|
-
if (session.status !== "running") {
|
|
332
|
-
logger.info(`Resuming ${session.status} session ${sessionId}`);
|
|
333
|
-
setStatus(session, "running");
|
|
334
|
-
await saveSession(session);
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
// Session was paused and now resumed with answer - re-run the flow
|
|
338
|
-
const task = session.task;
|
|
339
|
-
const sessionConfig = config || session.config_snapshot;
|
|
340
|
-
if (!sessionConfig) {
|
|
341
|
-
throw new Error("No config available to resume session");
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
logger.info(`Resuming session ${sessionId} with answer: ${answer}`);
|
|
345
|
-
|
|
346
|
-
// Inject the answer as additional feedback for the coder
|
|
347
|
-
if (session.paused_state?.context?.lastFeedback) {
|
|
348
|
-
setReviewerFeedback(session, `Previous feedback: ${session.paused_state.context.lastFeedback}\nUser guidance: ${answer}`);
|
|
349
|
-
}
|
|
350
|
-
resetAllRetryCounters(session);
|
|
351
|
-
setSonarIssueSignature(session, null);
|
|
352
|
-
setSonarRepeatCount(session, 0);
|
|
353
|
-
setReviewerIssueSignature(session, null);
|
|
354
|
-
setReviewerRepeatCount(session, 0);
|
|
355
|
-
await saveSession(session);
|
|
356
|
-
|
|
357
|
-
// Re-run the flow with the existing session context
|
|
358
|
-
try {
|
|
359
|
-
// KJC-BUG-0412: what was pending is what was pending when THIS session started.
|
|
360
|
-
return await runFlow({ task, config: sessionConfig, logger, flags, emitter, askQuestion, preexisting: session.git_preexisting ?? null });
|
|
361
|
-
} catch (err) {
|
|
362
|
-
await markSessionStatus(session, "failed");
|
|
363
|
-
throw err;
|
|
364
|
-
}
|
|
365
|
-
}
|