@rt-tools/agent-kit 0.37.1 → 0.38.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 +5 -5
- package/assets/checks/action-of.mjs +154 -0
- package/assets/checks/board-runs.github.mjs +40 -5
- package/assets/checks/check-board.github.mjs +38 -7
- package/assets/checks/check-state-next.mjs +22 -10
- package/assets/checks/check-turn-map.mjs +26 -6
- package/assets/checks/check-work-steps.mjs +4 -173
- package/assets/checks/decide.mjs +285 -0
- package/assets/checks/decision-table.json +21365 -0
- package/assets/checks/decision-table.mjs +495 -0
- package/assets/checks/epic-window.mjs +98 -0
- package/assets/checks/flow-condition.mjs +64 -0
- package/assets/checks/flow-data.mjs +136 -0
- package/assets/checks/flow-forecast.mjs +330 -0
- package/assets/checks/flow-guard-run.mjs +90 -0
- package/assets/checks/flow-guard.mjs +294 -0
- package/assets/checks/flow-model.mjs +271 -0
- package/assets/checks/flow-override.mjs +130 -0
- package/assets/checks/flow-plan.mjs +206 -0
- package/assets/checks/flow-scaffold.mjs +224 -0
- package/assets/checks/flow-step.mjs +365 -0
- package/assets/checks/flow-sync.mjs +296 -0
- package/assets/checks/flow-syntax.mjs +292 -0
- package/assets/checks/flow-verdict.mjs +112 -0
- package/assets/checks/merge-read.mjs +239 -0
- package/assets/checks/owner-nudges.mjs +389 -0
- package/assets/checks/push-inputs.mjs +59 -16
- package/assets/checks/record-count.mjs +410 -0
- package/assets/checks/record-recount.mjs +187 -0
- package/assets/checks/record-turn.mjs +155 -0
- package/assets/checks/task-flow-script.mjs +292 -0
- package/assets/checks/tree-assignment.mjs +26 -7
- package/assets/checks/work-result.mjs +281 -0
- package/assets/checks/work-steps-lib.mjs +205 -0
- package/assets/commands/night.md +6 -6
- package/assets/defaults/gate-map.sh +39 -12
- package/assets/defaults/merges.sh +48 -0
- package/assets/defaults/project.sh +6 -5
- package/assets/defaults/turn-map.md +21 -22
- package/assets/docs/GLOSSARY.md +5 -1
- package/assets/hooks/ask-judge.md +65 -0
- package/assets/hooks/browser-guard-device-id.sh +11 -9
- package/assets/hooks/browser-guard-no-asking.sh +12 -6
- package/assets/hooks/browser-guard-no-listing.sh +13 -7
- package/assets/hooks/browser-guard-no-other-drivers.sh +25 -17
- package/assets/hooks/browser-guard-require-select.sh +15 -15
- package/assets/hooks/commit-msg.sh +13 -3
- package/assets/hooks/conscience-guard.sh +9 -25
- package/assets/hooks/decide.sh +141 -0
- package/assets/hooks/deny-tail.sh +16 -11
- package/assets/hooks/dev-server-guard.sh +27 -20
- package/assets/hooks/dispatch.sh +47 -4
- package/assets/hooks/docs-guard.sh +31 -200
- package/assets/hooks/end-conversation-guard.sh +12 -21
- package/assets/hooks/epic-stop-guard.sh +54 -152
- package/assets/hooks/exam-guard.sh +32 -65
- package/assets/hooks/facts-docs.sh +221 -0
- package/assets/hooks/facts-flow.sh +173 -0
- package/assets/hooks/facts.sh +308 -0
- package/assets/hooks/flow-step-guard.sh +93 -0
- package/assets/hooks/git-guard-delivery-body.sh +4 -4
- package/assets/hooks/git-guard-delivery-conflict.sh +16 -10
- package/assets/hooks/git-guard-delivery-draft.sh +3 -3
- package/assets/hooks/git-guard-delivery-epic.sh +18 -9
- package/assets/hooks/git-guard-delivery-folder.sh +32 -7
- package/assets/hooks/git-guard-delivery-merge.sh +2 -2
- package/assets/hooks/git-guard-delivery-merged.sh +12 -1
- package/assets/hooks/git-guard-delivery-pipeline.sh +1 -1
- package/assets/hooks/git-guard-delivery-rerun.sh +32 -0
- package/assets/hooks/git-guard-delivery-signature.sh +82 -45
- package/assets/hooks/git-guard-delivery-task.sh +47 -0
- package/assets/hooks/git-guard-delivery.sh +112 -101
- package/assets/hooks/git-guard-discard.sh +8 -18
- package/assets/hooks/git-guard-main.sh +13 -19
- package/assets/hooks/git-guard-no-verify.sh +56 -16
- package/assets/hooks/git-guard-push-ahead.sh +15 -4
- package/assets/hooks/git-guard-push-marks.sh +53 -1
- package/assets/hooks/git-guard-push-tests.sh +30 -51
- package/assets/hooks/git-guard-tree-assignment.sh +7 -4
- package/assets/hooks/guard-note.sh +8 -6
- package/assets/hooks/handoff-entry-guard.sh +19 -38
- package/assets/hooks/handoff-write.sh +3 -1
- package/assets/hooks/hook-input.sh +0 -41
- package/assets/hooks/metric-marks.sh +19 -7
- package/assets/hooks/observe.sh +1 -1
- package/assets/hooks/override-write-guard.sh +27 -9
- package/assets/hooks/pre-push.sh +14 -10
- package/assets/hooks/prose-style-guard.sh +6 -19
- package/assets/hooks/pull-merges.sh +76 -0
- package/assets/hooks/push-set.sh +11 -4
- package/assets/hooks/qa-dataid-guard.sh +7 -17
- package/assets/hooks/record-turn.sh +52 -0
- package/assets/hooks/rerun-guard.sh +11 -16
- package/assets/hooks/reuse-first-guard.sh +7 -21
- package/assets/hooks/role-calls.sh +25 -3
- package/assets/hooks/rule-source-guard.sh +54 -21
- package/assets/hooks/skill-gate-rearm.sh +18 -5
- package/assets/hooks/skill-gate.sh +156 -20
- package/assets/hooks/skill-loaded.sh +18 -3
- package/assets/hooks/sql-guard-target.sh +2 -2
- package/assets/hooks/sql-guard-write.sh +12 -12
- package/assets/hooks/sql-guard.sh +58 -16
- package/assets/hooks/task-context-load.sh +3 -1
- package/assets/hooks/task-flow-context.sh +5 -18
- package/assets/hooks/task-flow-draft-guard.sh +25 -74
- package/assets/hooks/task-flow-guard.sh +28 -130
- package/assets/hooks/tree-assignment-guard.sh +25 -14
- package/assets/hooks/turn-entry-load.sh +3 -1
- package/assets/hooks/turn-exit-guard.sh +92 -452
- package/assets/hooks/turn-exit-role.sh +3 -1
- package/assets/hooks/turn-judge.md +103 -0
- package/assets/hooks/window-fill-guard.sh +22 -41
- package/assets/patterns/git-workflow-commit.azure.md +9 -155
- package/assets/patterns/git-workflow-commit.github.md +11 -269
- package/assets/patterns/git-workflow-commit.gitlab.md +9 -161
- package/assets/patterns/git-workflow-docker.md +8 -231
- package/assets/patterns/git-workflow-freshness.md +8 -56
- package/assets/patterns/git-workflow-merge.md +6 -176
- package/assets/patterns/git-workflow-migration.md +5 -75
- package/assets/patterns/git-workflow-pr-body.github.md +6 -159
- package/assets/patterns/git-workflow-pr-ready.md +9 -70
- package/assets/patterns/git-workflow-pr.azure.md +13 -285
- package/assets/patterns/git-workflow-pr.github.md +13 -251
- package/assets/patterns/git-workflow-pr.gitlab.md +13 -286
- package/assets/patterns/git-workflow-restart.md +5 -42
- package/assets/patterns/git-workflow-secrets.md +10 -76
- package/assets/patterns/git-workflow-stack.md +7 -207
- package/assets/patterns/status-report-table.github.md +1 -1
- package/assets/patterns/task-flow-archive.md +12 -233
- package/assets/patterns/task-flow-close.md +16 -292
- package/assets/patterns/task-flow-cycle.md +13 -39
- package/assets/patterns/task-flow-graph.needs-graph.md +8 -62
- package/assets/patterns/task-flow-handoff.md +13 -161
- package/assets/patterns/task-flow-resume.md +18 -218
- package/assets/patterns/task-flow-start.md +9 -247
- package/assets/patterns/turn-entry-map.md +2 -2
- package/assets/pitfalls/agent-kit-extend.md +200 -0
- package/assets/pitfalls/agent-kit.2.md +323 -0
- package/assets/pitfalls/angular-patterns.md +98 -0
- package/assets/pitfalls/browser-verification.md +265 -0
- package/assets/pitfalls/component-structure.md +98 -0
- package/assets/pitfalls/dependencies.md +92 -0
- package/assets/pitfalls/deploy-flow.azure.md +171 -0
- package/assets/pitfalls/deploy-flow.github.md +211 -0
- package/assets/pitfalls/deploy-flow.gitlab.md +173 -0
- package/assets/pitfalls/doc-style.2.md +286 -0
- package/assets/pitfalls/entity-conventions.needs-admin.md +96 -0
- package/assets/pitfalls/entity-models.md +89 -0
- package/assets/pitfalls/git-workflow-commit.azure.md +190 -0
- package/assets/pitfalls/git-workflow-commit.github.md +307 -0
- package/assets/pitfalls/git-workflow-commit.gitlab.md +196 -0
- package/assets/pitfalls/git-workflow-docker.md +275 -0
- package/assets/pitfalls/git-workflow-freshness.md +88 -0
- package/assets/pitfalls/git-workflow-hosting.azure.md +31 -0
- package/assets/pitfalls/git-workflow-hosting.github.md +32 -0
- package/assets/pitfalls/git-workflow-hosting.gitlab.md +31 -0
- package/assets/pitfalls/git-workflow-merge.md +220 -0
- package/assets/pitfalls/git-workflow-migration.md +103 -0
- package/assets/pitfalls/git-workflow-pr-body.github.md +185 -0
- package/assets/pitfalls/git-workflow-pr-ready.md +104 -0
- package/assets/pitfalls/git-workflow-pr.2.azure.md +172 -0
- package/assets/pitfalls/git-workflow-pr.2.github.md +184 -0
- package/assets/pitfalls/git-workflow-pr.2.gitlab.md +180 -0
- package/assets/pitfalls/git-workflow-pr.azure.md +159 -0
- package/assets/pitfalls/git-workflow-pr.github.md +107 -0
- package/assets/pitfalls/git-workflow-pr.gitlab.md +151 -0
- package/assets/pitfalls/git-workflow-push.azure.md +30 -0
- package/assets/pitfalls/git-workflow-push.github.md +30 -0
- package/assets/pitfalls/git-workflow-push.gitlab.md +30 -0
- package/assets/pitfalls/git-workflow-queue.azure.md +30 -0
- package/assets/pitfalls/git-workflow-queue.github.md +30 -0
- package/assets/pitfalls/git-workflow-queue.gitlab.md +30 -0
- package/assets/pitfalls/git-workflow-restart.md +72 -0
- package/assets/pitfalls/git-workflow-secrets.md +114 -0
- package/assets/pitfalls/git-workflow-stack.md +254 -0
- package/assets/pitfalls/git-workflow.2.azure.md +291 -0
- package/assets/pitfalls/git-workflow.2.github.md +294 -0
- package/assets/pitfalls/git-workflow.2.gitlab.md +278 -0
- package/assets/pitfalls/lib-layers.md +114 -0
- package/assets/pitfalls/lists.md +117 -0
- package/assets/pitfalls/navigation.md +94 -0
- package/assets/pitfalls/reuse-first.md +201 -0
- package/assets/pitfalls/spec-driven.2.md +318 -0
- package/assets/pitfalls/styling-bem.2.md +125 -0
- package/assets/pitfalls/task-flow-archive.md +264 -0
- package/assets/pitfalls/task-flow-close.2.md +165 -0
- package/assets/pitfalls/task-flow-close.md +167 -0
- package/assets/pitfalls/task-flow-cycle.md +73 -0
- package/assets/pitfalls/task-flow-graph.needs-graph.md +98 -0
- package/assets/pitfalls/task-flow-handoff.md +200 -0
- package/assets/pitfalls/task-flow-handover.md +30 -0
- package/assets/pitfalls/task-flow-owner.md +29 -0
- package/assets/pitfalls/task-flow-plan.md +29 -0
- package/assets/pitfalls/task-flow-resume.md +257 -0
- package/assets/pitfalls/task-flow-start.md +287 -0
- package/assets/pitfalls/task-flow.2.md +303 -0
- package/assets/pitfalls/task-flow.md +4 -4
- package/assets/pitfalls/testing.2.md +279 -0
- package/assets/pitfalls/turn-conduct.md +16 -17
- package/assets/pitfalls/typescript-conventions.md +161 -0
- package/assets/pitfalls/write-a-skill.md +128 -0
- package/assets/rules/angular-patterns.md +21 -86
- package/assets/rules/autonomous-work.md +2 -2
- package/assets/rules/browser-verification.md +28 -256
- package/assets/rules/component-structure.md +25 -87
- package/assets/rules/dependencies.md +20 -78
- package/assets/rules/deploy-flow.azure.md +26 -156
- package/assets/rules/deploy-flow.github.md +34 -200
- package/assets/rules/deploy-flow.gitlab.md +27 -159
- package/assets/rules/doc-style.md +32 -286
- package/assets/rules/entity-conventions.needs-admin.md +26 -82
- package/assets/rules/entity-models.md +14 -63
- package/assets/rules/git-workflow-hosting.azure.md +26 -0
- package/assets/rules/git-workflow-hosting.github.md +38 -0
- package/assets/rules/git-workflow-hosting.gitlab.md +27 -0
- package/assets/rules/git-workflow-push.azure.md +28 -0
- package/assets/rules/git-workflow-push.github.md +28 -0
- package/assets/rules/git-workflow-push.gitlab.md +28 -0
- package/assets/rules/git-workflow-queue.azure.md +23 -0
- package/assets/rules/git-workflow-queue.github.md +30 -0
- package/assets/rules/git-workflow-queue.gitlab.md +23 -0
- package/assets/rules/git-workflow.azure.md +21 -282
- package/assets/rules/git-workflow.github.md +24 -284
- package/assets/rules/git-workflow.gitlab.md +21 -269
- package/assets/rules/lib-layers.md +30 -103
- package/assets/rules/lists.md +21 -105
- package/assets/rules/navigation.md +10 -69
- package/assets/rules/reuse-first.md +20 -195
- package/assets/rules/spec-driven.md +35 -308
- package/assets/rules/styling-bem.md +20 -117
- package/assets/rules/task-flow-handover.md +24 -0
- package/assets/rules/task-flow-owner.md +34 -0
- package/assets/rules/task-flow-plan.md +38 -0
- package/assets/rules/task-flow.md +22 -300
- package/assets/rules/testing.md +32 -273
- package/assets/rules/turn-conduct.md +100 -104
- package/assets/rules/turn-entry.md +2 -2
- package/assets/rules/typescript-conventions.md +41 -147
- package/assets/samples/tasks/_template/plan.md +30 -6
- package/assets/samples/tasks/_template/progress.md +0 -1
- package/assets/skills/agent-kit-extend.md +25 -168
- package/assets/skills/agent-kit.md +27 -299
- package/assets/skills/write-a-skill.md +20 -106
- package/assets/task-flow/flow.js +188 -0
- package/assets/task-flow/flow.md +102 -0
- package/assets/task-flow/measure/agreement.mjs +24 -0
- package/assets/task-flow/measure/copy.mjs +22 -0
- package/assets/task-flow/measure/epic-of.mjs +50 -0
- package/assets/task-flow/measure/epic-text.mjs +35 -0
- package/assets/task-flow/measure/epic.mjs +114 -0
- package/assets/task-flow/measure/folder.mjs +16 -0
- package/assets/task-flow/measure/footprint.mjs +28 -0
- package/assets/task-flow/measure/grill.mjs +21 -0
- package/assets/task-flow/measure/host.mjs +8 -0
- package/assets/task-flow/measure/owner.mjs +20 -0
- package/assets/task-flow/measure/plan.mjs +27 -0
- package/assets/task-flow/measure/pr.mjs +20 -0
- package/assets/task-flow/measure/progress.mjs +50 -0
- package/assets/task-flow/measure/session.mjs +175 -0
- package/assets/task-flow/measure/task.mjs +23 -0
- package/assets/task-flow/measure/text.mjs +77 -0
- package/assets/task-flow/source/git.mjs +86 -0
- package/assets/task-flow/source/host.mjs +172 -0
- package/assets/task-flow/source/marks.mjs +56 -0
- package/assets/task-flow/source/owner.mjs +74 -0
- package/assets/task-flow/source/records.mjs +116 -0
- package/assets/task-flow/source/session.mjs +232 -0
- package/assets/task-flow/source/steps.mjs +28 -0
- package/assets/task-flow/source/tree.mjs +42 -0
- package/bin/agent-kit.d.ts.map +1 -1
- package/bin/agent-kit.js +30 -0
- package/bin/agent-kit.js.map +1 -1
- package/lib/agent-checks.d.ts +55 -0
- package/lib/agent-checks.d.ts.map +1 -0
- package/lib/agent-checks.js +209 -0
- package/lib/agent-checks.js.map +1 -0
- package/lib/assets.d.ts.map +1 -1
- package/lib/assets.js +7 -2
- package/lib/assets.js.map +1 -1
- package/lib/cargo.d.ts +29 -0
- package/lib/cargo.d.ts.map +1 -1
- package/lib/cargo.js +27 -1
- package/lib/cargo.js.map +1 -1
- package/lib/cascade.d.ts.map +1 -1
- package/lib/cascade.js +3 -1
- package/lib/cascade.js.map +1 -1
- package/lib/commands.d.ts.map +1 -1
- package/lib/commands.js +78 -2
- package/lib/commands.js.map +1 -1
- package/lib/config.d.ts +18 -0
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +18 -1
- package/lib/config.js.map +1 -1
- package/lib/epic-window-send.d.ts +74 -0
- package/lib/epic-window-send.d.ts.map +1 -0
- package/lib/epic-window-send.js +166 -0
- package/lib/epic-window-send.js.map +1 -0
- package/lib/hooks-map.d.ts +4 -0
- package/lib/hooks-map.d.ts.map +1 -1
- package/lib/hooks-map.js +2 -2
- package/lib/hooks-map.js.map +1 -1
- package/lib/integrity.d.ts +3 -0
- package/lib/integrity.d.ts.map +1 -1
- package/lib/integrity.js +7 -0
- package/lib/integrity.js.map +1 -1
- package/lib/metric-lines.d.ts +2 -1
- package/lib/metric-lines.d.ts.map +1 -1
- package/lib/metric-lines.js +49 -1
- package/lib/metric-lines.js.map +1 -1
- package/lib/metric-send-mark.d.ts +6 -3
- package/lib/metric-send-mark.d.ts.map +1 -1
- package/lib/metric-send-mark.js +15 -5
- package/lib/metric-send-mark.js.map +1 -1
- package/lib/metric-send.d.ts +6 -2
- package/lib/metric-send.d.ts.map +1 -1
- package/lib/metric-send.js +47 -13
- package/lib/metric-send.js.map +1 -1
- package/lib/metrics.d.ts +17 -0
- package/lib/metrics.d.ts.map +1 -1
- package/lib/metrics.js +26 -15
- package/lib/metrics.js.map +1 -1
- package/lib/observations.js +3 -3
- package/lib/observations.js.map +1 -1
- package/lib/outcomes.d.ts +5 -2
- package/lib/outcomes.d.ts.map +1 -1
- package/lib/outcomes.js +5 -4
- package/lib/outcomes.js.map +1 -1
- package/lib/push-gate.d.ts +13 -0
- package/lib/push-gate.d.ts.map +1 -1
- package/lib/push-gate.js +11 -7
- package/lib/push-gate.js.map +1 -1
- package/lib/push-set-usefulness.d.ts +78 -0
- package/lib/push-set-usefulness.d.ts.map +1 -0
- package/lib/push-set-usefulness.js +225 -0
- package/lib/push-set-usefulness.js.map +1 -0
- package/lib/sync.d.ts +10 -0
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +14 -1
- package/lib/sync.js.map +1 -1
- package/lib/work-result.d.ts +43 -0
- package/lib/work-result.d.ts.map +1 -0
- package/lib/work-result.js +39 -0
- package/lib/work-result.js.map +1 -0
- package/package.json +1 -1
- package/assets/hooks/claim-guard.sh +0 -212
- package/assets/hooks/grill-gate-ask.sh +0 -26
- package/assets/hooks/grill-gate-bypass.sh +0 -61
- package/assets/hooks/grill-gate-options.sh +0 -50
- package/assets/hooks/grill-gate.sh +0 -482
- package/assets/hooks/postmortem-guard.sh +0 -124
- package/assets/hooks/proposal-guard.sh +0 -154
- package/assets/hooks/stand-login-guard.sh +0 -107
- package/assets/hooks/turn-exit-epic.sh +0 -173
- package/assets/hooks/turn-exit-patterns.sh +0 -123
- package/assets/hooks/turn-exit-verdict.sh +0 -149
- package/assets/hooks/waiting-turn-guard.sh +0 -320
- package/assets/hooks/work-start-guard.sh +0 -175
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A step of the plan measured by its check — the engine command `step`.
|
|
3
|
+
*
|
|
4
|
+
* The check is taken from the commit that added the plan, not from the working copy: a plan edited
|
|
5
|
+
* after it is written would measure what was never approved. Every file of the task folder that the
|
|
6
|
+
* commit holds, except the progress, must still match it, otherwise the step is refused: a script of
|
|
7
|
+
* the folder edited after the plan would answer what the step needs. A command of the work itself is
|
|
8
|
+
* never a check, and an expected result in no form of `expect` is refused before anything runs. The
|
|
9
|
+
* command runs with a limit; past it the step does not match.
|
|
10
|
+
*
|
|
11
|
+
* A check is replaced only by a decision in the progress the owner allowed in the window on its edit:
|
|
12
|
+
*
|
|
13
|
+
* - **Проверка шага 2.4 заменена:** `<command>` → <expected>
|
|
14
|
+
*
|
|
15
|
+
* A matched step writes its mark: the branch, the step, the fingerprint of the plan, the head and the
|
|
16
|
+
* last line of the output. A step that does not match drops a mark left before, so a mark always
|
|
17
|
+
* says what the last measurement said.
|
|
18
|
+
*/
|
|
19
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
20
|
+
import { availableParallelism } from 'node:os';
|
|
21
|
+
import { createHash } from 'node:crypto';
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
23
|
+
|
|
24
|
+
import { dirname, join } from 'node:path';
|
|
25
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
26
|
+
|
|
27
|
+
import { compareExpected, isWriteCommand } from './flow-data.mjs';
|
|
28
|
+
|
|
29
|
+
// The sources of the description lie next to the engine where it is laid out, one level up in the package.
|
|
30
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
31
|
+
const RECORDS = [join(HERE, 'task-flow/source/records.mjs'), join(HERE, '../task-flow/source/records.mjs')].find((path) => existsSync(path));
|
|
32
|
+
const records = await import(pathToFileURL(RECORDS).href);
|
|
33
|
+
|
|
34
|
+
/** The record directories of this repository and the test of an approval mark, shared by the checks. */
|
|
35
|
+
export const openRecords = (root = process.cwd()) => records.openAt(root);
|
|
36
|
+
export const approvalFault = records.approvalFault;
|
|
37
|
+
|
|
38
|
+
/** The limit of one check, in milliseconds: past it the step does not match. */
|
|
39
|
+
export const STEP_LIMIT_MS = 540_000;
|
|
40
|
+
|
|
41
|
+
/** The progress changes every turn and is the one file of the folder not judged against the plan. */
|
|
42
|
+
const PROGRESS = 'progress.md';
|
|
43
|
+
|
|
44
|
+
/** A replacement of a step check in the progress. */
|
|
45
|
+
const REPLACEMENT = /^-\s+\*\*(?:Проверка шага|Check of step)\s+(\d+\.\d+)\s+(?:заменена|replaced):\*\*\s+`(.+)`\s+→\s+(.+?)(?:\s+·\s+(?:слово владельца|the owner's word):\s+«.+»)?\s*$/u;
|
|
46
|
+
|
|
47
|
+
/** A step the engine does not measure, with the reason. */
|
|
48
|
+
export class StepRefused extends Error {
|
|
49
|
+
constructor(message) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = 'StepRefused';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const lastLine = (output) =>
|
|
56
|
+
output
|
|
57
|
+
.split('\n')
|
|
58
|
+
.map((line) => line.trimEnd())
|
|
59
|
+
.filter((line) => line !== '')
|
|
60
|
+
.pop() ?? '';
|
|
61
|
+
|
|
62
|
+
const readFile = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null);
|
|
63
|
+
|
|
64
|
+
/** Runs a check: its exit code and output, or the mark that the limit ran out; `cwd` is where it runs. */
|
|
65
|
+
export function runCheck(command, limitMs = STEP_LIMIT_MS, cwd = undefined) {
|
|
66
|
+
const out = spawnSync('bash', ['-c', command], { cwd, encoding: 'utf8', timeout: limitMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024 });
|
|
67
|
+
const timedOut = out.error?.code === 'ETIMEDOUT';
|
|
68
|
+
return { code: timedOut ? null : out.status, output: out.stdout ?? '', errors: out.stderr ?? '', timedOut };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Runs a check without blocking: the same answer as `runCheck`, so that the checks of `--done` run side by side. */
|
|
72
|
+
export function runCheckAsync(command, limitMs = STEP_LIMIT_MS) {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
const child = spawn('bash', ['-c', command], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
75
|
+
let output = '';
|
|
76
|
+
let errors = '';
|
|
77
|
+
let timedOut = false;
|
|
78
|
+
const timer = setTimeout(() => {
|
|
79
|
+
timedOut = true;
|
|
80
|
+
child.kill('SIGKILL');
|
|
81
|
+
}, limitMs);
|
|
82
|
+
child.stdout.setEncoding('utf8');
|
|
83
|
+
child.stdout.on('data', (chunk) => (output += chunk));
|
|
84
|
+
child.stderr.setEncoding('utf8');
|
|
85
|
+
child.stderr.on('data', (chunk) => (errors += chunk));
|
|
86
|
+
child.on('close', (code) => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
resolve({ code: timedOut ? null : code, output, errors, timedOut });
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The plan of the checked-out branch as its commit wrote it: the commit that added the plan. A branch
|
|
95
|
+
* of `words.legacyBranches` takes the newest commit that changed it — its plan was approved, and
|
|
96
|
+
* edited by the owner's word, before the engine existed.
|
|
97
|
+
*/
|
|
98
|
+
export function planOfBranch(git, words = {}) {
|
|
99
|
+
const branch = git.branch();
|
|
100
|
+
const folder = `docs/tasks/${branch}`;
|
|
101
|
+
const path = `${folder}/plan.md`;
|
|
102
|
+
const legacy = (words.legacyBranches ?? []).includes(branch);
|
|
103
|
+
const sha = legacy
|
|
104
|
+
? ([...git.commits()].reverse().find((c) => c.added.includes(path) || c.modified.includes(path))?.sha ?? null)
|
|
105
|
+
: git.addedBy(path);
|
|
106
|
+
if (!sha) throw new StepRefused(`no commit of the branch added ${path}`);
|
|
107
|
+
const text = git.versionAt(path, sha);
|
|
108
|
+
return { branch, folder, sha, text, fingerprint: createHash('sha256').update(text).digest('hex').slice(0, 16) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The files of the task folder that differ from the commit of the plan; the progress is not judged. */
|
|
112
|
+
export function changedSincePlan(git, plan, read = readFile) {
|
|
113
|
+
return git
|
|
114
|
+
.filesAt(plan.folder, plan.sha)
|
|
115
|
+
.filter((path) => !path.endsWith(`/${PROGRESS}`))
|
|
116
|
+
.filter((path) => read(path) !== git.versionAt(path, plan.sha));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The check of a step after the decisions of the progress. A replacement line reaches the progress
|
|
121
|
+
* only through the owner's window on the edit (the guard answers `ask`), so the line itself is the
|
|
122
|
+
* owner's word: no quote is looked for. A quote of the older form is read and ignored. Of two lines
|
|
123
|
+
* for one step the later wins, here and in the rerun alike.
|
|
124
|
+
*/
|
|
125
|
+
export function replacedCheck(progressText, number, step) {
|
|
126
|
+
let last = null;
|
|
127
|
+
for (const line of (progressText ?? '').split('\n')) {
|
|
128
|
+
const m = line.match(REPLACEMENT);
|
|
129
|
+
if (m && m[1] === number) last = { command: m[2], expected: m[3], replaced: true };
|
|
130
|
+
}
|
|
131
|
+
return last ?? { command: step.command, expected: step.expected, replaced: false };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The progress text `text` with its replacement lines swapped for those of `latest`, the last
|
|
136
|
+
* version of the progress in the history. A replacement is the owner's decision about a check, not
|
|
137
|
+
* a part of the work the check measures: it holds on every version the rerun uses. A line the last
|
|
138
|
+
* version no longer carries stays away, and a step replaced twice keeps the later line.
|
|
139
|
+
*/
|
|
140
|
+
export function withReplacements(text, latest) {
|
|
141
|
+
const isReplacement = (line) => REPLACEMENT.test(line);
|
|
142
|
+
const kept = (text ?? '').split('\n').filter((line) => !isReplacement(line));
|
|
143
|
+
const lastOfStep = new Map();
|
|
144
|
+
for (const line of (latest ?? '').split('\n')) if (isReplacement(line)) lastOfStep.set(line.match(REPLACEMENT)[1], line);
|
|
145
|
+
const added = [...lastOfStep.values()];
|
|
146
|
+
if (added.length === 0) return kept.join('\n');
|
|
147
|
+
return `${kept.join('\n').replace(/\n*$/, '\n')}\n${added.join('\n')}\n`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The signs of a failed network in what a check printed. */
|
|
151
|
+
const NETWORK = /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|getaddrinfo|Could not resolve host|network is unreachable|Failed to connect/i;
|
|
152
|
+
|
|
153
|
+
/** What a run gave, in the words of the line: the code for the exit form, the last line otherwise. */
|
|
154
|
+
const gotOf = (run, form, limitMs, matched = true) => {
|
|
155
|
+
if (run.timedOut) return `the limit of ${limitMs / 1000} s ran out`;
|
|
156
|
+
const network = !matched && NETWORK.test(`${run.output}\n${run.errors ?? ''}`) ? ' — the cause is the network' : '';
|
|
157
|
+
if (form === 'exit') return `exit ${run.code}${network}`;
|
|
158
|
+
return (run.code === 0 ? lastLine(run.output) : `exit ${run.code}, ${lastLine(run.output)}`) + network;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/** The step ready to run: its plan, its check and the expected result, or a refusal before anything runs. */
|
|
162
|
+
function prepareStep({ git, steps }, model, number, read) {
|
|
163
|
+
const plan = planOfBranch(git, model.words);
|
|
164
|
+
const changed = changedSincePlan(git, plan, read);
|
|
165
|
+
if (changed.length > 0) throw new StepRefused(`the task folder differs from the commit of the plan: ${changed.join(', ')}`);
|
|
166
|
+
const planned = steps.ofPlan(plan.text).find((s) => s.number === number);
|
|
167
|
+
if (!planned) throw new StepRefused(`the plan names no step ${number}`);
|
|
168
|
+
const progress = `${plan.folder}/${PROGRESS}`;
|
|
169
|
+
const step = { number, ...replacedCheck(read(progress) ?? git.lastVersion(progress), number, planned) };
|
|
170
|
+
if (step.command === null) throw new StepRefused(`step ${number} has no check line`);
|
|
171
|
+
if (isWriteCommand(step.command, model.words)) throw new StepRefused(`the check of step ${number} is a command of the work: ${step.command}`);
|
|
172
|
+
if (compareExpected(model.expect, step.expected, 0, '') === null) throw new StepRefused(`the expected result of step ${number} is in no form: ${step.expected}`);
|
|
173
|
+
return { plan, step };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The progress with step `number` marked done and, when no step is current, the first one not begun
|
|
178
|
+
* made current. A progress that names no such step comes back as it was.
|
|
179
|
+
*/
|
|
180
|
+
export function markedProgress(text, number) {
|
|
181
|
+
const own = new RegExp(`^(\\s*-\\s+\\[)[ >x](\\]\\s+${number.replace('.', '\\.')}\\s)`);
|
|
182
|
+
const lines = text.split('\n');
|
|
183
|
+
const at = lines.findIndex((line) => own.test(line));
|
|
184
|
+
// A step already done is measured again, not marked again: the progress stays as it was.
|
|
185
|
+
if (at < 0 || /^\s*-\s+\[x\]/.test(lines[at])) return text;
|
|
186
|
+
lines[at] = lines[at].replace(own, '$1x$2');
|
|
187
|
+
if (!lines.some((line) => /^\s*-\s+\[>\]\s+\d+\.\d+\s/.test(line))) {
|
|
188
|
+
const next = lines.findIndex((line) => /^\s*-\s+\[ \]\s+\d+\.\d+\s/.test(line));
|
|
189
|
+
if (next >= 0) lines[next] = lines[next].replace('[ ]', '[>]');
|
|
190
|
+
}
|
|
191
|
+
return lines.join('\n');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The verdict of a run: the mark is written and the step marked done, or the mark is dropped; the result is returned. */
|
|
195
|
+
function settleStep({ git, marks }, model, { plan, step }, run, limitMs) {
|
|
196
|
+
const verdict = run.timedOut ? { form: null, matched: false } : compareExpected(model.expect, step.expected, run.code, run.output);
|
|
197
|
+
if (verdict.matched) {
|
|
198
|
+
marks.writeStep(plan.branch, step.number, { branch: plan.branch, step: step.number, plan: plan.fingerprint, head: git.head(), line: lastLine(run.output), replaced: step.replaced, matched: true });
|
|
199
|
+
// Only the engine marks a step done: the guard refuses a hand mark.
|
|
200
|
+
const progress = `${plan.folder}/${PROGRESS}`;
|
|
201
|
+
const text = readFile(progress);
|
|
202
|
+
if (text !== null) {
|
|
203
|
+
const marked = markedProgress(text, step.number);
|
|
204
|
+
if (marked !== text) writeFileSync(progress, marked);
|
|
205
|
+
}
|
|
206
|
+
} else marks.dropStep(plan.branch, step.number);
|
|
207
|
+
return { number: step.number, expected: step.expected, got: gotOf(run, verdict.form, limitMs, verdict.matched), matched: verdict.matched };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Measures one step of the plan: `{ number, expected, got, matched }`, and writes or drops its mark.
|
|
212
|
+
* `sources` holds `git`, `steps`, `marks` and `owner`; `model` gives the words and the forms of `expect`.
|
|
213
|
+
*/
|
|
214
|
+
export function measureStep(sources, model, number, limitMs = STEP_LIMIT_MS, read = readFile) {
|
|
215
|
+
const ready = prepareStep(sources, model, number, read);
|
|
216
|
+
return settleStep(sources, model, ready, runCheck(ready.step.command, limitMs), limitMs);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Measures the given steps side by side, at most `width` checks at once: the results in the order of
|
|
221
|
+
* `numbers`, a refused step as `{ number, refused }`. The limit holds for each check, as in `measureStep`.
|
|
222
|
+
*/
|
|
223
|
+
export async function measureSteps(sources, model, numbers, limitMs = STEP_LIMIT_MS, width = availableParallelism(), read = readFile) {
|
|
224
|
+
const results = new Array(numbers.length);
|
|
225
|
+
let next = 0;
|
|
226
|
+
const worker = async () => {
|
|
227
|
+
while (next < numbers.length) {
|
|
228
|
+
const index = next++;
|
|
229
|
+
const number = numbers[index];
|
|
230
|
+
try {
|
|
231
|
+
const ready = prepareStep(sources, model, number, read);
|
|
232
|
+
const run = await runCheckAsync(ready.step.command, limitMs);
|
|
233
|
+
results[index] = settleStep(sources, model, ready, run, limitMs);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (!(error instanceof StepRefused)) throw error;
|
|
236
|
+
results[index] = { number, refused: error.message };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(width, numbers.length)) }, worker));
|
|
241
|
+
return results;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The steps the progress marks done: the working copy, or the last version in the history. */
|
|
245
|
+
export function doneSteps({ git, steps }, model, read = readFile) {
|
|
246
|
+
const plan = planOfBranch(git, model.words);
|
|
247
|
+
const path = `${plan.folder}/${PROGRESS}`;
|
|
248
|
+
const text = read(path) ?? git.lastVersion(path) ?? '';
|
|
249
|
+
return steps.ofProgress(text).steps.filter((s) => s.mark === 'x').map((s) => s.number);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The line of one measured step; it always ends with the verdict. */
|
|
253
|
+
export const stepLine = (result) => `ожидалось ${result.expected} · получено ${result.got} · ${result.matched ? 'совпало' : 'не совпало'}`;
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The command `step <N.M>` or `step --done`: prints a line per step and returns the exit code — 0
|
|
257
|
+
* when every measured step matched, 1 when one did not or was refused. `--done` runs the checks side
|
|
258
|
+
* by side, prefixes each line with the number of its step and ends with the line
|
|
259
|
+
* `steps re-measured N, matched M`.
|
|
260
|
+
*/
|
|
261
|
+
export async function runStepCommand(sources, model, target, mode = '') {
|
|
262
|
+
if (mode === '--pr') return runBeforePull(sources, model);
|
|
263
|
+
if (target !== '--done') {
|
|
264
|
+
try {
|
|
265
|
+
const result = measureStep(sources, model, target);
|
|
266
|
+
console.log(stepLine(result));
|
|
267
|
+
return result.matched ? 0 : 1;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (!(error instanceof StepRefused)) throw error;
|
|
270
|
+
console.log(`step: ${error.message}`);
|
|
271
|
+
return 1;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
let numbers;
|
|
275
|
+
try {
|
|
276
|
+
numbers = doneSteps(sources, model);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (!(error instanceof StepRefused)) throw error;
|
|
279
|
+
console.log(`step: ${error.message}`);
|
|
280
|
+
return 1;
|
|
281
|
+
}
|
|
282
|
+
const results = await measureSteps(sources, model, numbers);
|
|
283
|
+
for (const result of results) console.log(`${result.number} ${result.refused ? `step: ${result.refused}` : stepLine(result)}`);
|
|
284
|
+
const matched = results.filter((result) => result.matched).length;
|
|
285
|
+
console.log(`steps re-measured ${results.length}, matched ${matched}`);
|
|
286
|
+
return matched === results.length ? 0 : 1;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The tracked files the working copy changed, as `git status` names them. */
|
|
290
|
+
const trackedChanges = () =>
|
|
291
|
+
(spawnSync('git', ['status', '--porcelain', '--untracked-files=no'], { encoding: 'utf8' }).stdout ?? '').split('\n').filter(Boolean).sort();
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* The rerun before a PR opens: every step the progress marks done is measured once more, whatever
|
|
295
|
+
* mark lies on disk. A taken-apart task folder is put back from the history for the run and removed
|
|
296
|
+
* after it; a check that leaves a tracked file changed does not match. A branch with no plan, or a
|
|
297
|
+
* plan with no checks, has nothing to measure. Returns 0 when every done step matched.
|
|
298
|
+
*/
|
|
299
|
+
export async function runBeforePull(sources, model) {
|
|
300
|
+
let plan;
|
|
301
|
+
try {
|
|
302
|
+
plan = planOfBranch(sources.git, model.words);
|
|
303
|
+
} catch (error) {
|
|
304
|
+
if (!(error instanceof StepRefused)) throw error;
|
|
305
|
+
console.log(`step: ${error.message} — nothing to measure before the PR`);
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
308
|
+
if (sources.steps.ofPlan(plan.text).every((s) => s.command === null)) {
|
|
309
|
+
console.log('step: the plan names no checks — nothing to measure before the PR');
|
|
310
|
+
return 0;
|
|
311
|
+
}
|
|
312
|
+
// A taken-apart folder: its last version comes back for the run and leaves after it.
|
|
313
|
+
const restored = [];
|
|
314
|
+
if (!existsSync(plan.folder)) {
|
|
315
|
+
const last = (spawnSync('git', ['log', '-1', '--format=%H', '--diff-filter=D', 'HEAD', '--', plan.folder], { encoding: 'utf8' }).stdout ?? '').trim();
|
|
316
|
+
const at = last ? `${last}^` : null;
|
|
317
|
+
for (const path of at ? sources.git.filesAt(plan.folder, at) : []) {
|
|
318
|
+
const text = sources.git.versionAt(path, at);
|
|
319
|
+
if (text === null) continue;
|
|
320
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
321
|
+
writeFileSync(path, text);
|
|
322
|
+
restored.push(path);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const before = trackedChanges();
|
|
326
|
+
try {
|
|
327
|
+
const numbers = doneSteps(sources, model);
|
|
328
|
+
// The suites shorten the limit; the work always runs with the step limit.
|
|
329
|
+
const limit = Number(process.env.RT_FLOW_STEP_LIMIT_MS) || STEP_LIMIT_MS;
|
|
330
|
+
// A restored folder brings the progress back as it stood when each step was measured — the
|
|
331
|
+
// version before the first commit that marks the step done: a check that reads the progress
|
|
332
|
+
// saw it so, while the last version has every step done.
|
|
333
|
+
const progressPath = `${plan.folder}/${PROGRESS}`;
|
|
334
|
+
const latest = restored.includes(progressPath) ? readFileSync(progressPath, 'utf8') : null;
|
|
335
|
+
const log = latest === null ? '' : (spawnSync('git', ['log', '--reverse', '--format=%H', 'HEAD', '--', progressPath], { encoding: 'utf8' }).stdout ?? '');
|
|
336
|
+
const versions = log.split('\n').filter(Boolean).map((sha) => sources.git.versionAt(progressPath, sha));
|
|
337
|
+
const groups = new Map();
|
|
338
|
+
for (const number of numbers) {
|
|
339
|
+
const done = new RegExp(`^\\s*-\\s+\\[x\\]\\s+${number.replace('.', '\\.')}\\s`, 'm');
|
|
340
|
+
const first = versions.findIndex((text) => text !== null && done.test(text));
|
|
341
|
+
const chosen = (first > 0 && versions[first - 1]) || latest;
|
|
342
|
+
const text = latest === null || chosen === latest ? chosen : withReplacements(chosen, latest);
|
|
343
|
+
groups.set(text, [...(groups.get(text) ?? []), number]);
|
|
344
|
+
}
|
|
345
|
+
const results = [];
|
|
346
|
+
for (const [text, group] of groups) {
|
|
347
|
+
if (text !== null) writeFileSync(progressPath, text);
|
|
348
|
+
results.push(...(await measureSteps(sources, model, group, limit)));
|
|
349
|
+
}
|
|
350
|
+
results.sort((a, b) => numbers.indexOf(a.number) - numbers.indexOf(b.number));
|
|
351
|
+
const changed = trackedChanges().filter((line) => !before.includes(line));
|
|
352
|
+
for (const result of results) console.log(`${result.number} ${result.refused ? `step: ${result.refused}` : stepLine(result)}`);
|
|
353
|
+
if (changed.length > 0) console.log(`step: the checks changed tracked files — ${changed.join(', ')}: a check measures, it does not edit`);
|
|
354
|
+
const matched = changed.length > 0 ? 0 : results.filter((result) => result.matched).length;
|
|
355
|
+
console.log(`steps re-measured ${results.length}, matched ${matched}`);
|
|
356
|
+
return matched === results.length && changed.length === 0 ? 0 : 1;
|
|
357
|
+
} catch (error) {
|
|
358
|
+
if (!(error instanceof StepRefused)) throw error;
|
|
359
|
+
console.log(`step: ${error.message}`);
|
|
360
|
+
return 1;
|
|
361
|
+
} finally {
|
|
362
|
+
for (const path of restored) rmSync(path, { force: true });
|
|
363
|
+
if (restored.length > 0) rmSync(plan.folder, { recursive: true, force: true });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* The generator of the texts the task flow description is told by. Five views are written from the
|
|
4
|
+
* description of the package, each between the markers `<!-- flow:<view> -->` and
|
|
5
|
+
* `<!-- /flow:<view> -->`, and `flow.md` next to the description is written whole:
|
|
6
|
+
*
|
|
7
|
+
* description `flow.md` — the whole description in tables;
|
|
8
|
+
* states the table «Work states» of the rule `task-flow`;
|
|
9
|
+
* map the states of the turn map;
|
|
10
|
+
* turn-end the release cases in the rule `turn-conduct`;
|
|
11
|
+
* expect the table of expected forms in the plan template.
|
|
12
|
+
*
|
|
13
|
+
* A text told by hand drifts from the scenario the engine measures, and nothing notices: so the
|
|
14
|
+
* text between the markers is the description's, and a hand edit there is refused by `--check`,
|
|
15
|
+
* which compares each file with its generation as text.
|
|
16
|
+
*
|
|
17
|
+
* In the package the five views are written into its sources. In a tree where the package is laid
|
|
18
|
+
* out the five are only compared: a laid-out file is rewritten by the layout, never here. The tree
|
|
19
|
+
* override, when it lies in the tree, is told by a sixth view `tree` — what it adds, replaces and
|
|
20
|
+
* removes, and the states of the merged scenario — in the companion `implementation.md` of the rule
|
|
21
|
+
* `task-flow`; the laid-out rule does not see the override and is not changed.
|
|
22
|
+
*
|
|
23
|
+
* Usage: node flow-sync.mjs [--check] [--flow <flow.js>] [--override <flow.js>] [--root <dir>].
|
|
24
|
+
* The description lies next to the generator as `task-flow/flow.js` where it is laid out, and as
|
|
25
|
+
* `../task-flow/flow.js` in the package. The root of the tree is `--root`, else the top of the git
|
|
26
|
+
* working copy, else the current directory; the layout is read from its `.claude/rt-kit.json`.
|
|
27
|
+
* `--check` prints `flow sync: <n> views match`, or a line per differing view and exits 1; without
|
|
28
|
+
* it every writable view is written and `flow sync: <k> of <n> views written` is printed.
|
|
29
|
+
*/
|
|
30
|
+
import { spawnSync } from 'node:child_process';
|
|
31
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
32
|
+
import { dirname, join, relative } from 'node:path';
|
|
33
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
34
|
+
|
|
35
|
+
import { FlowModelError, buildModel } from './flow-model.mjs';
|
|
36
|
+
import { OVERRIDE_PATH } from './flow-override.mjs';
|
|
37
|
+
import { FlowSyntaxError, Ref } from './flow-syntax.mjs';
|
|
38
|
+
|
|
39
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
40
|
+
|
|
41
|
+
/** What each way of comparison of an expected form means, for the plan template. */
|
|
42
|
+
const COMPARE_TEXT = {
|
|
43
|
+
exit: 'the command exits with the code of the first group; the output is not compared',
|
|
44
|
+
line: 'the code is 0 and the last non-empty line of the output equals the first group',
|
|
45
|
+
regex: 'the code is 0 and the last non-empty line matches the first group',
|
|
46
|
+
number: 'the code is 0, the last non-empty line is an integer, and its comparison by the first group with the second holds',
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** A code span that holds any text, backticks included. */
|
|
50
|
+
const code = (text) => (String(text).includes('`') ? `\`\` ${text} \`\`` : `\`${text}\``);
|
|
51
|
+
/** A table cell: a pipe would split it. */
|
|
52
|
+
const cell = (text) => String(text ?? '').replace(/\|/g, '\\|');
|
|
53
|
+
|
|
54
|
+
/** A condition in one line: a reference, or `all(…)`, `any(…)`, `not(…)` over its parts. */
|
|
55
|
+
export function conditionText(value) {
|
|
56
|
+
if (value instanceof Ref) return value.path.join('.');
|
|
57
|
+
const [op] = Object.keys(value);
|
|
58
|
+
if (op === 'not') return `not(${conditionText(value.not)})`;
|
|
59
|
+
return `${op}(${value[op].map(conditionText).join(', ')})`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const portsText = (ports) => {
|
|
63
|
+
const refs = Object.values(ports).map((ref) => code(ref.path.join('.')));
|
|
64
|
+
return refs.length > 0 ? refs.join(', ') : 'none';
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
function statesTable(model) {
|
|
68
|
+
return [
|
|
69
|
+
'| State | Exit | Mandatory action | Pattern |',
|
|
70
|
+
'| --- | --- | --- | --- |',
|
|
71
|
+
...model.states.map((s) => `| ${code(s.title)} | ${cell(code(conditionText(s.exit)))} | ${cell(s.action)} | ${s.pattern ? code(s.pattern) : ''} |`),
|
|
72
|
+
].join('\n');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function expectTable(model) {
|
|
76
|
+
return [
|
|
77
|
+
'| Form | Expected text | It matches when |',
|
|
78
|
+
'| --- | --- | --- |',
|
|
79
|
+
...Object.entries(model.expect).map(([key, f]) => `| ${code(key)} | ${cell(code(f.pattern))} | ${COMPARE_TEXT[f.compare]} |`),
|
|
80
|
+
].join('\n');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function releaseTable(model) {
|
|
84
|
+
return [
|
|
85
|
+
'| Order | Case | When | Log |',
|
|
86
|
+
'| --- | --- | --- | --- |',
|
|
87
|
+
...model.release.map((r) => `| ${r.order} | ${code(r.key)} | ${cell(code(conditionText(r.when)))} | ${cell(r.log)} |`),
|
|
88
|
+
].join('\n');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function componentTable(head, components) {
|
|
92
|
+
const rows = components.flatMap((c) => Object.entries(c.caps).map(([cap, ports]) => `| ${code(`${c.section}.${c.entry}.${cap}`)} | ${portsText(ports)} |`));
|
|
93
|
+
return [`| ${head} | Ports |`, '| --- | --- |', ...rows].join('\n');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function wordsTable(model) {
|
|
97
|
+
const rows = Object.entries(model.words).map(([key, value]) => `| ${code(key)} | ${cell(Array.isArray(value) ? value.join(', ') : code(value))} |`);
|
|
98
|
+
return ['| Key | Words |', '| --- | --- |', ...rows].join('\n');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The body of every view of the package description, by view name. */
|
|
102
|
+
export function packageViews(model) {
|
|
103
|
+
return {
|
|
104
|
+
description: [
|
|
105
|
+
'## States',
|
|
106
|
+
'',
|
|
107
|
+
statesTable(model),
|
|
108
|
+
'',
|
|
109
|
+
'## Release cases',
|
|
110
|
+
'',
|
|
111
|
+
'The engine asks the cases in this order, and a met case lets the turn end before the scenario does.',
|
|
112
|
+
'',
|
|
113
|
+
releaseTable(model),
|
|
114
|
+
'',
|
|
115
|
+
'## Measurers',
|
|
116
|
+
'',
|
|
117
|
+
componentTable('Measurer', model.measures),
|
|
118
|
+
'',
|
|
119
|
+
'## Sources',
|
|
120
|
+
'',
|
|
121
|
+
componentTable('Source', model.sources),
|
|
122
|
+
'',
|
|
123
|
+
'## Words',
|
|
124
|
+
'',
|
|
125
|
+
wordsTable(model),
|
|
126
|
+
'',
|
|
127
|
+
'## Expected forms',
|
|
128
|
+
'',
|
|
129
|
+
expectTable(model),
|
|
130
|
+
].join('\n'),
|
|
131
|
+
states: statesTable(model),
|
|
132
|
+
map: model.states.map((s) => `- ${code(s.title)} — ${s.action ?? ''}; leads ${code(s.pattern ?? '')}`).join('\n'),
|
|
133
|
+
'turn-end': [
|
|
134
|
+
'The engine lets a turn end before the scenario does when a case is met, asked in this order:',
|
|
135
|
+
'',
|
|
136
|
+
...model.release.map((r) => `- **${r.order}** · ${r.log ?? r.key} — ${code(conditionText(r.when))}`),
|
|
137
|
+
].join('\n'),
|
|
138
|
+
expect: expectTable(model),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The body of the view of the tree override: what it changes and the merged states. */
|
|
143
|
+
export function treeView(model, overridePath) {
|
|
144
|
+
const line = (c) => {
|
|
145
|
+
if (c.kind === 'removed') return `- removes ${code(c.key)} — ${c.reason}`;
|
|
146
|
+
return `- ${c.kind === 'added' ? 'adds' : 'replaces'} ${code(c.key)}${c.after ? ` after ${code(`state.${c.after}`)}` : ''}`;
|
|
147
|
+
};
|
|
148
|
+
return [
|
|
149
|
+
`The override ${code(overridePath)} changes the task flow of the package in this tree:`,
|
|
150
|
+
'',
|
|
151
|
+
...model.changes.map(line),
|
|
152
|
+
'',
|
|
153
|
+
'The states of the merged scenario:',
|
|
154
|
+
'',
|
|
155
|
+
statesTable(model),
|
|
156
|
+
].join('\n');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The whole text of `flow.md`. */
|
|
160
|
+
function flowMd(body) {
|
|
161
|
+
return [
|
|
162
|
+
'# The task flow',
|
|
163
|
+
'',
|
|
164
|
+
'Generated by `flow-sync.mjs` from `flow.js` next to it. `flow-sync.mjs --check` refuses a hand edit:',
|
|
165
|
+
'the description is edited, and the generator is run.',
|
|
166
|
+
'',
|
|
167
|
+
'<!-- flow:description -->',
|
|
168
|
+
body,
|
|
169
|
+
'<!-- /flow:description -->',
|
|
170
|
+
'',
|
|
171
|
+
].join('\n');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The text of a file with the view between its markers, or null when the markers are absent. */
|
|
175
|
+
export function withView(text, name, body) {
|
|
176
|
+
const open = `<!-- flow:${name} -->`;
|
|
177
|
+
const close = `<!-- /flow:${name} -->`;
|
|
178
|
+
const start = text.indexOf(open);
|
|
179
|
+
const end = text.indexOf(close);
|
|
180
|
+
if (start < 0 || end < start) return null;
|
|
181
|
+
return `${text.slice(0, start + open.length)}\n${body}\n${text.slice(end)}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The layout of the tree: where rules, defaults and samples lie. */
|
|
185
|
+
function layoutOf(root) {
|
|
186
|
+
const file = join(root, '.claude', 'rt-kit.json');
|
|
187
|
+
const layout = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')).layout ?? {}) : {};
|
|
188
|
+
return {
|
|
189
|
+
rules: layout.rules ?? '.claude/skills',
|
|
190
|
+
defaults: layout.defaults ?? '.claude/rt-kit/defaults',
|
|
191
|
+
samples: layout.samples ?? 'docs',
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The views to sync: `{ name, path, body, whole, writable }`. The description is in the package
|
|
197
|
+
* when the package sources lie next to its directory.
|
|
198
|
+
*/
|
|
199
|
+
export function viewsOf({ flow, override, root }) {
|
|
200
|
+
const flowDir = dirname(flow);
|
|
201
|
+
const assets = dirname(flowDir);
|
|
202
|
+
const inPackage = existsSync(join(assets, 'rules', 'task-flow.md'));
|
|
203
|
+
const layout = layoutOf(root);
|
|
204
|
+
const at = inPackage
|
|
205
|
+
? { states: join(assets, 'rules', 'task-flow.md'), map: join(assets, 'defaults', 'turn-map.md'), 'turn-end': join(assets, 'rules', 'turn-conduct.md'), expect: join(assets, 'samples', 'tasks', '_template', 'plan.md') }
|
|
206
|
+
: {
|
|
207
|
+
states: join(root, layout.rules, 'task-flow', 'SKILL.md'),
|
|
208
|
+
map: join(root, layout.defaults, 'turn-map.md'),
|
|
209
|
+
'turn-end': join(root, layout.rules, 'turn-conduct', 'SKILL.md'),
|
|
210
|
+
expect: join(root, layout.samples, 'tasks', '_template', 'plan.md'),
|
|
211
|
+
};
|
|
212
|
+
const bodies = packageViews(buildModel(flow));
|
|
213
|
+
const views = [{ name: 'description', path: join(flowDir, 'flow.md'), body: bodies.description, whole: true, writable: inPackage }];
|
|
214
|
+
for (const name of ['states', 'map', 'turn-end', 'expect']) views.push({ name, path: at[name], body: bodies[name], whole: false, writable: inPackage });
|
|
215
|
+
if (override) {
|
|
216
|
+
const merged = buildModel(flow, { override });
|
|
217
|
+
views.push({ name: 'tree', path: join(root, layout.rules, 'task-flow', 'implementation.md'), body: treeView(merged, relative(root, override)), whole: false, writable: true, append: true });
|
|
218
|
+
}
|
|
219
|
+
return { views, base: inPackage ? assets : root };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The text a view's file must have, or `{ reason }` when it cannot be made. */
|
|
223
|
+
function expected(view) {
|
|
224
|
+
if (view.whole) return { text: flowMd(view.body) };
|
|
225
|
+
const now = existsSync(view.path) ? readFileSync(view.path, 'utf8') : null;
|
|
226
|
+
if (now === null && !view.append) return { reason: 'the file is absent' };
|
|
227
|
+
const text = withView(now ?? '', view.name, view.body);
|
|
228
|
+
if (text !== null) return { text, now };
|
|
229
|
+
if (view.append) return { text: `${now ?? ''}${now && !now.endsWith('\n') ? '\n' : ''}\n<!-- flow:${view.name} -->\n${view.body}\n<!-- /flow:${view.name} -->\n`, now, unmarked: true };
|
|
230
|
+
return { reason: `it has no markers <!-- flow:${view.name} --> … <!-- /flow:${view.name} -->` };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Compares or writes the views. Returns the lines to print and the exit code. */
|
|
234
|
+
export function sync(options, { check }) {
|
|
235
|
+
const { views, base } = viewsOf(options);
|
|
236
|
+
const lines = [];
|
|
237
|
+
let differ = 0;
|
|
238
|
+
let written = 0;
|
|
239
|
+
for (const view of views) {
|
|
240
|
+
const where = relative(base, view.path);
|
|
241
|
+
const want = expected(view);
|
|
242
|
+
const now = existsSync(view.path) ? readFileSync(view.path, 'utf8') : null;
|
|
243
|
+
if (want.text !== undefined && want.text === now) continue;
|
|
244
|
+
if (check || !view.writable || want.text === undefined) {
|
|
245
|
+
differ += 1;
|
|
246
|
+
const reason = want.reason ?? (now === null ? 'the file is absent' : want.unmarked ? 'it has no markers yet' : 'it differs from its generation — a hand edit between the markers, or a description edited without a run');
|
|
247
|
+
const fix = view.writable ? 'run flow-sync.mjs' : 'the package writes it, and the layout brings it';
|
|
248
|
+
lines.push(`flow sync: ${view.name} in ${where}: ${reason}; ${fix}`);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
mkdirSync(dirname(view.path), { recursive: true });
|
|
252
|
+
writeFileSync(view.path, want.text);
|
|
253
|
+
written += 1;
|
|
254
|
+
lines.push(`wrote ${view.name} in ${where}`);
|
|
255
|
+
}
|
|
256
|
+
if (differ > 0) {
|
|
257
|
+
lines.push(`flow sync: ${differ} of ${views.length} views differ`);
|
|
258
|
+
return { lines, code: 1 };
|
|
259
|
+
}
|
|
260
|
+
lines.push(check ? `flow sync: ${views.length} views match` : `flow sync: ${written} of ${views.length} views written`);
|
|
261
|
+
return { lines, code: 0 };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Where the description lies: next to the laid-out generator, or in the package. */
|
|
265
|
+
function flowPath(given) {
|
|
266
|
+
if (given) return given;
|
|
267
|
+
const laid = join(HERE, 'task-flow', 'flow.js');
|
|
268
|
+
return existsSync(laid) ? laid : join(HERE, '..', 'task-flow', 'flow.js');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
272
|
+
const args = process.argv.slice(2);
|
|
273
|
+
const take = (flag) => {
|
|
274
|
+
const at = args.indexOf(flag);
|
|
275
|
+
return at >= 0 ? args.splice(at, 2)[1] : undefined;
|
|
276
|
+
};
|
|
277
|
+
const check = args.includes('--check');
|
|
278
|
+
const flow = flowPath(take('--flow'));
|
|
279
|
+
const given = take('--override');
|
|
280
|
+
const root = take('--root') ?? (spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout?.trim() || process.cwd());
|
|
281
|
+
if (args.some((a) => a !== '--check')) {
|
|
282
|
+
console.error('usage: node flow-sync.mjs [--check] [--flow <flow.js>] [--override <flow.js>] [--root <dir>]');
|
|
283
|
+
process.exit(2);
|
|
284
|
+
}
|
|
285
|
+
const override = given ?? (existsSync(join(root, OVERRIDE_PATH)) ? join(root, OVERRIDE_PATH) : undefined);
|
|
286
|
+
try {
|
|
287
|
+
const { lines, code: exit } = sync({ flow, override, root }, { check });
|
|
288
|
+
console.log(lines.join('\n'));
|
|
289
|
+
process.exit(exit);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error instanceof FlowSyntaxError) console.log(`flow syntax: ${error.message}`);
|
|
292
|
+
else if (error instanceof FlowModelError) console.log(`flow model: ${error.message}`);
|
|
293
|
+
else throw error;
|
|
294
|
+
process.exit(1);
|
|
295
|
+
}
|
|
296
|
+
}
|