@cbartens/bkit 5.5.0 → 6.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/.bkit/README.md +30 -20
- package/.bkit/core/.agents/docs.md +1 -0
- package/.bkit/core/.agents/rules.md +51 -26
- package/.bkit/core/.bkit/README.md +29 -19
- package/.bkit/core/.bkit/authoring.md +117 -0
- package/.bkit/core/.bkit/cloud.md +11 -11
- package/.bkit/core/.bkit/comparison.md +5 -5
- package/.bkit/core/.bkit/install.md +20 -20
- package/.bkit/core/.bkit/jsonl.md +202 -122
- package/.bkit/core/.bkit/lite.md +1 -1
- package/.bkit/core/.bkit/pipeline.md +49 -52
- package/.bkit/core/.bkit/prompts.md +106 -167
- package/.bkit/core/.bkit/providers.md +29 -32
- package/.bkit/core/.bkit/templates.md +44 -18
- package/.bkit/core/.bkit/trackers.md +60 -28
- package/.bkit/core/.bkit/workflows.md +399 -359
- package/.bkit/core/AGENTS.md +16 -22
- package/.bkit/core/docs/templates/bkit-audit-accessibility.md +14 -38
- package/.bkit/core/docs/templates/bkit-audit-adoption.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-agents.md +19 -43
- package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-analytics.md +14 -38
- package/.bkit/core/docs/templates/bkit-audit-annotations.md +11 -35
- package/.bkit/core/docs/templates/bkit-audit-app-performance.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-app-store.md +12 -36
- package/.bkit/core/docs/templates/bkit-audit-architecture.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-config.md +18 -42
- package/.bkit/core/docs/templates/bkit-audit-cost.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-coverage.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-database.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-dead-code.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-deferrals.md +15 -38
- package/.bkit/core/docs/templates/bkit-audit-dependencies.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-documentation.md +11 -35
- package/.bkit/core/docs/templates/bkit-audit-duplication.md +18 -42
- package/.bkit/core/docs/templates/bkit-audit-failures.md +13 -37
- package/.bkit/core/docs/templates/bkit-audit-flakes.md +12 -36
- package/.bkit/core/docs/templates/bkit-audit-gates.md +14 -38
- package/.bkit/core/docs/templates/bkit-audit-issues.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-llm.md +16 -40
- package/.bkit/core/docs/templates/bkit-audit-logs.md +14 -38
- package/.bkit/core/docs/templates/bkit-audit-models.md +12 -36
- package/.bkit/core/docs/templates/bkit-audit-privacy.md +12 -36
- package/.bkit/core/docs/templates/bkit-audit-prompts.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-red-team.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-reliability.md +15 -39
- package/.bkit/core/docs/templates/bkit-audit-repo.md +12 -36
- package/.bkit/core/docs/templates/bkit-audit-security.md +13 -37
- package/.bkit/core/docs/templates/bkit-audit-slop.md +14 -38
- package/.bkit/core/docs/templates/bkit-audit-testing.md +12 -36
- package/.bkit/core/docs/templates/bkit-audit-usability.md +16 -40
- package/.bkit/core/docs/templates/bkit-plan.md +97 -226
- package/.bkit/core/engine/checks/after/ci-yml.ts +39 -30
- package/.bkit/core/engine/checks/after/github.ts +101 -72
- package/.bkit/core/engine/checks/after/index.ts +10 -12
- package/.bkit/core/engine/checks/after/suppression.ts +8 -5
- package/.bkit/core/engine/checks/after/tools.ts +47 -92
- package/.bkit/core/engine/checks/before/env.ts +2 -2
- package/.bkit/core/engine/checks/before/files.ts +5 -4
- package/.bkit/core/engine/checks/before/index.ts +18 -1
- package/.bkit/core/engine/checks/before/repo.ts +168 -2
- package/.bkit/core/engine/checks/tips/catalogue.ts +16 -5
- package/.bkit/core/engine/checks/tips/detect.ts +34 -0
- package/.bkit/core/engine/checks/tips/index.ts +10 -7
- package/.bkit/core/engine/cli.ts +20 -53
- package/.bkit/core/engine/commands/analysis.ts +171 -140
- package/.bkit/core/engine/commands/ci/ci.ts +6 -6
- package/.bkit/core/engine/commands/comply.ts +77 -103
- package/.bkit/core/engine/commands/install/doctor.ts +2 -2
- package/.bkit/core/engine/commands/install/install.ts +57 -18
- package/.bkit/core/engine/commands/install/uninstall.ts +65 -28
- package/.bkit/core/engine/commands/land.ts +18 -12
- package/.bkit/core/engine/commands/lib.ts +79 -17
- package/.bkit/core/engine/commands/registry.ts +4 -0
- package/.bkit/core/engine/commands/setup/setup.ts +7 -7
- package/.bkit/core/engine/commands/stats.ts +204 -0
- package/.bkit/core/engine/commands/tips.ts +10 -5
- package/.bkit/core/engine/commands/workflow/branches.ts +741 -62
- package/.bkit/core/engine/commands/workflow/challenge.ts +673 -0
- package/.bkit/core/engine/commands/workflow/context.ts +853 -29
- package/.bkit/core/engine/commands/workflow/counters.ts +267 -84
- package/.bkit/core/engine/commands/workflow/decisions.ts +541 -0
- package/.bkit/core/engine/commands/workflow/disk.ts +2 -2
- package/.bkit/core/engine/commands/workflow/fids.ts +793 -33
- package/.bkit/core/engine/commands/workflow/issues.ts +427 -105
- package/.bkit/core/engine/commands/workflow/ledgers.ts +884 -27
- package/.bkit/core/engine/commands/workflow/locks.ts +26 -2
- package/.bkit/core/engine/commands/workflow/plan-blocks.ts +582 -0
- package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
- package/.bkit/core/engine/commands/workflow/prs.ts +166 -30
- package/.bkit/core/engine/commands/workflow/repo.ts +59 -7
- package/.bkit/core/engine/commands/workflow/roadmap.ts +16 -7
- package/.bkit/core/engine/commands/workflow/run-facts.ts +501 -0
- package/.bkit/core/engine/commands/workflow/runs.ts +179 -49
- package/.bkit/core/engine/commands/workflow/runtime.ts +22 -1
- package/.bkit/core/engine/commands/workflow/status.ts +142 -29
- package/.bkit/core/engine/commands/workflow/step-table.ts +339 -0
- package/.bkit/core/engine/commands/workflow/steps.ts +213 -88
- package/.bkit/core/engine/commands/workflow/summary.ts +398 -0
- package/.bkit/core/engine/commands/workflow/tests.ts +1013 -148
- package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
- package/.bkit/core/engine/commands/workflow/workflows.ts +984 -207
- package/.bkit/core/engine/commands/workflow/workstreams.ts +11 -5
- package/.bkit/core/engine/commands/workflow/worktrees.ts +276 -22
- package/.bkit/core/engine/install/manifest.ts +11 -9
- package/.bkit/core/engine/install/modules/cloud.ts +21 -13
- package/.bkit/core/engine/install/modules/core.ts +325 -7
- package/.bkit/core/engine/install/modules/opencode.ts +2 -2
- package/.bkit/core/engine/install/version-file.ts +6 -2
- package/.bkit/core/engine/ledgers/migrate.ts +92 -0
- package/.bkit/core/engine/ledgers/status.ts +92 -15
- package/.bkit/core/engine/ledgers/telemetry.ts +1261 -254
- package/.bkit/core/engine/render/hosts.ts +4 -0
- package/.bkit/core/engine/render/models.ts +12 -0
- package/.bkit/core/engine/shared/branches.ts +4 -1
- package/.bkit/core/engine/shared/egress.ts +7 -0
- package/.bkit/core/engine/shared/json.ts +25 -7
- package/.bkit/core/engine/shared/settings.ts +202 -33
- package/.bkit/core/engine/shared/text.ts +361 -0
- package/.bkit/core/engine/tools/grammar-density.ts +215 -0
- package/.bkit/core/engine/tools/instructions-sources.ts +834 -0
- package/.bkit/core/engine/tools/instructions.ts +1751 -0
- package/.bkit/core/hooks/gateguard-engine.js +24 -23
- package/.bkit/core/hooks/guardrails-shell.js +2 -3
- package/.bkit/core/hooks/guardrails-tiers.js +7 -1
- package/.bkit/core/hooks/readguard-engine.js +2 -2
- package/.bkit/core/prompts/bkit-audit-generate.md +62 -25
- package/.bkit/core/prompts/bkit-build-challenge-1.md +40 -17
- package/.bkit/core/prompts/bkit-build-challenge-2.md +44 -17
- package/.bkit/core/prompts/bkit-build-install-skills.md +26 -13
- package/.bkit/core/prompts/bkit-build-plan-convert.md +74 -0
- package/.bkit/core/prompts/bkit-build-plan-current.md +26 -13
- package/.bkit/core/prompts/bkit-build-plan-execute.md +74 -26
- package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +64 -23
- package/.bkit/core/prompts/bkit-build-plan-verify.md +57 -33
- package/.bkit/core/prompts/bkit-debug-abort-handover.md +30 -14
- package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +34 -14
- package/.bkit/core/prompts/bkit-debug-failure-remediate.md +34 -17
- package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +26 -13
- package/.bkit/core/prompts/bkit-debug-failure-soak.md +31 -16
- package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +21 -11
- package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +20 -11
- package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +20 -11
- package/.bkit/core/prompts/bkit-design-generate.md +33 -13
- package/.bkit/core/prompts/bkit-design-organise.md +25 -12
- package/.bkit/core/prompts/bkit-design-review-1.md +31 -15
- package/.bkit/core/prompts/bkit-design-review-2.md +28 -13
- package/.bkit/core/prompts/bkit-design-spike.md +30 -13
- package/.bkit/core/prompts/bkit-design-update.md +33 -19
- package/.bkit/core/prompts/bkit-plan-generate.md +75 -19
- package/.bkit/core/prompts/bkit-plan-review-1.md +50 -27
- package/.bkit/core/prompts/bkit-plan-review-2.md +59 -28
- package/.bkit/core/prompts/bkit-plan-scope-check.md +109 -0
- package/.bkit/core/prompts/bkit-plan-update.md +61 -24
- package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +27 -15
- package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +31 -16
- package/.bkit/core/prompts/bkit-ship-update-docs.md +30 -15
- package/.bkit/core/prompts/bkit-utility-compress-markdown.md +24 -14
- package/.bkit/core/prompts/bkit-utility-update-decisions.md +32 -14
- package/.bkit/core/prompts/bkit-utility-update-deferrals.md +29 -14
- package/.bkit/core/prompts/bkit-utility-update-documentation.md +28 -13
- package/.bkit/core/prompts/bkit-utility-update-failures.md +31 -14
- package/.bkit/core/prompts/bkit-utility-update-knowledge.md +33 -14
- package/.bkit/core/prompts/bkit-utility-update-roadmap.md +38 -17
- package/.bkit/core/prompts/bkit-utility-update-tracker.md +43 -20
- package/.bkit/core/workflows/bkit-auto.md +54 -46
- package/.bkit/core/workflows/bkit-build.md +577 -458
- package/.bkit/core/workflows/bkit-debug.md +348 -333
- package/.bkit/core/workflows/bkit-design.md +201 -237
- package/.bkit/core/workflows/bkit-plan.md +210 -321
- package/.bkit/core/workflows/bkit-ship.md +328 -278
- package/.bkit/shared/.bkit/.env.example +2 -2
- package/.bkit/shared/.claude/settings.json +11 -0
- package/.bkit/shared/.cursor/mcp.json +1 -1
- package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
- package/.bkit/shared/.gitattributes +1 -1
- package/.bkit/shared/.mcp.json +1 -1
- package/.bkit/shared/.opencode/opencode.json +11 -0
- package/.bkit/shared/CLAUDE.md +2 -2
- package/.bkit/shared/GEMINI.md +2 -2
- package/.bkit/shared/docs/architecture.md +1 -1
- package/.bkit/shared/docs/data-schema.md +1 -1
- package/.bkit/shared/docs/deployments.md +16 -28
- package/.bkit/shared/docs/design.md +1 -1
- package/.bkit/shared/docs/noise.md +1 -1
- package/.bkit/shared/docs/observability.md +2 -2
- package/.bkit/shared/docs/security.md +1 -1
- package/.bkit/shared/docs/setup.md +1 -1
- package/.bkit/shared/docs/technology.md +1 -1
- package/.bkit/shared/docs/testing.md +27 -10
- package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +1 -1
- package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +26 -5
- package/.bkit/templates/.github/workflows/bkit-ci.yml +22 -84
- package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
- package/.bkit/templates/.husky/pre-push +52 -13
- package/.bkit/templates/.prettierignore +7 -0
- package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +194 -0
- package/.bkit/templates/scripts/ci/check-capstone.mjs +2 -4
- package/.bkit/templates/scripts/ci/check-capstone.test.mjs +4 -23
- package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +104 -23
- package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +103 -6
- package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
- package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +3 -1
- package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +49 -29
- package/CHANGELOG.md +142 -0
- package/README.md +58 -34
- package/dist/checks/after/ci-yml.js +39 -29
- package/dist/checks/after/github.js +99 -72
- package/dist/checks/after/index.js +11 -13
- package/dist/checks/after/suppression.js +8 -5
- package/dist/checks/after/tools.js +40 -83
- package/dist/checks/before/env.js +2 -2
- package/dist/checks/before/files.js +5 -3
- package/dist/checks/before/index.js +15 -2
- package/dist/checks/before/repo.js +163 -2
- package/dist/checks/tips/catalogue.js +14 -5
- package/dist/checks/tips/detect.js +32 -0
- package/dist/checks/tips/index.js +7 -5
- package/dist/cli.js +19 -47
- package/dist/commands/analysis.js +109 -100
- package/dist/commands/ci/ci.js +6 -6
- package/dist/commands/comply.js +54 -91
- package/dist/commands/install/doctor.js +2 -2
- package/dist/commands/install/install.js +50 -19
- package/dist/commands/install/uninstall.js +59 -28
- package/dist/commands/land.js +16 -12
- package/dist/commands/lib.js +51 -16
- package/dist/commands/registry.js +4 -0
- package/dist/commands/setup/setup.js +7 -7
- package/dist/commands/stats.js +136 -0
- package/dist/commands/tips.js +7 -3
- package/dist/commands/workflow/branches.js +656 -56
- package/dist/commands/workflow/challenge.js +556 -0
- package/dist/commands/workflow/context.js +709 -30
- package/dist/commands/workflow/counters.js +208 -75
- package/dist/commands/workflow/decisions.js +441 -0
- package/dist/commands/workflow/disk.js +2 -2
- package/dist/commands/workflow/fids.js +689 -33
- package/dist/commands/workflow/issues.js +362 -99
- package/dist/commands/workflow/ledgers.js +762 -27
- package/dist/commands/workflow/locks.js +24 -2
- package/dist/commands/workflow/plan-blocks.js +437 -0
- package/dist/commands/workflow/plan-versions.js +22 -0
- package/dist/commands/workflow/prs.js +142 -32
- package/dist/commands/workflow/repo.js +52 -7
- package/dist/commands/workflow/roadmap.js +9 -7
- package/dist/commands/workflow/run-facts.js +426 -0
- package/dist/commands/workflow/runs.js +144 -43
- package/dist/commands/workflow/runtime.js +12 -1
- package/dist/commands/workflow/status.js +130 -29
- package/dist/commands/workflow/step-table.js +276 -0
- package/dist/commands/workflow/steps.js +171 -80
- package/dist/commands/workflow/summary.js +275 -0
- package/dist/commands/workflow/tests.js +834 -136
- package/dist/commands/workflow/tracker.js +983 -0
- package/dist/commands/workflow/workflows.js +834 -195
- package/dist/commands/workflow/workstreams.js +11 -5
- package/dist/commands/workflow/worktrees.js +221 -22
- package/dist/install/manifest.js +11 -9
- package/dist/install/modules/cloud.js +22 -13
- package/dist/install/modules/core.js +326 -7
- package/dist/install/modules/opencode.js +2 -2
- package/dist/install/version-file.js +6 -2
- package/dist/ledgers/migrate.js +81 -0
- package/dist/ledgers/status.js +61 -8
- package/dist/ledgers/telemetry.js +905 -124
- package/dist/render/hosts.js +4 -0
- package/dist/render/models.js +12 -0
- package/dist/shared/branches.js +3 -1
- package/dist/shared/egress.js +7 -0
- package/dist/shared/json.js +20 -7
- package/dist/shared/settings.js +147 -26
- package/dist/shared/text.js +333 -0
- package/dist/tools/grammar-density.js +183 -0
- package/dist/tools/instructions-sources.js +721 -0
- package/dist/tools/instructions.js +1579 -0
- package/package.json +114 -23
- package/.bkit/core/engine/commands/harvest.ts +0 -459
- package/.bkit/core/engine/tools/wording.ts +0 -748
- package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
- package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
- package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
- package/.bkit/core/prompts/bkit-build-summary.md +0 -94
- package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
- package/.bkit/core/prompts/bkit-design-summary.md +0 -107
- package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
- package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
- package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
- package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
- package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
- package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
- package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
- package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +0 -138
- package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +0 -181
- package/dist/commands/harvest.js +0 -353
- package/dist/tools/wording.js +0 -680
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
// bkit ledgers commit|union|only-bookkeeping — stage and commit bookkeeping
|
|
2
|
-
// an allow-list, never `git add -A
|
|
1
|
+
// bkit ledgers commit|union|only-bookkeeping|append|check — stage and commit bookkeeping
|
|
2
|
+
// by an allow-list, never `git add -A`; append validated rows with a minted `ts`;
|
|
3
|
+
// check that the ledger rows a plan names are on disk.
|
|
3
4
|
//
|
|
4
5
|
// The pathspec is built by `git ls-files` against quoted globs, so git does the
|
|
5
6
|
// matching and an unmatched glob is empty output, never a shell abort. Staging
|
|
@@ -10,8 +11,9 @@ import { spawnSync } from "node:child_process";
|
|
|
10
11
|
import * as fs from "node:fs";
|
|
11
12
|
import * as os from "node:os";
|
|
12
13
|
import * as path from "node:path";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
14
|
+
import { readBkitVersion } from "../../install/version-file.js";
|
|
15
|
+
import { APPEND_LEDGERS, SCHEMA, gitEnv, parse, mintTs, resolveRepoSlug, validate, writerProblem, } from "../../ledgers/telemetry.js";
|
|
16
|
+
import { CommandError, EXIT, isSharedBranch, parseJson, } from "../lib.js";
|
|
15
17
|
import { str } from "./status.js";
|
|
16
18
|
/** Root is not a directory or repo, git is too old, or a ref does not resolve. */
|
|
17
19
|
export const EXIT_ROOT = 3;
|
|
@@ -23,6 +25,8 @@ export const EXIT_COMMIT = 5;
|
|
|
23
25
|
export const EXIT_EMPTY = 6;
|
|
24
26
|
/** only-bookkeeping: a non-bookkeeping path changed, or from is not an ancestor of to. */
|
|
25
27
|
export const EXIT_NOT_BOOKKEEPING = 7;
|
|
28
|
+
/** append: a row was refused (supplied `ts`, wrong kind, invalid, unlisted writer). */
|
|
29
|
+
export const EXIT_ROW_REFUSED = 8;
|
|
26
30
|
const SCOPES = ["core", "full", "pr"];
|
|
27
31
|
const MODES = ["stage", "commit", "commit-allow-empty"];
|
|
28
32
|
/**
|
|
@@ -61,12 +65,13 @@ const UNION_PATHSPECS = [
|
|
|
61
65
|
":(exclude).bkit/issues.jsonl",
|
|
62
66
|
];
|
|
63
67
|
/** `git <args>` in `cwd`, never throwing and never trimming (NUL-delimited output). */
|
|
64
|
-
function gitRaw(cwd, args) {
|
|
68
|
+
function gitRaw(cwd, args, env = {}, input) {
|
|
65
69
|
const res = spawnSync("git", args, {
|
|
66
70
|
cwd,
|
|
67
71
|
encoding: "utf-8",
|
|
68
|
-
env: gitEnv(),
|
|
72
|
+
env: { ...gitEnv(), ...env },
|
|
69
73
|
maxBuffer: 1 << 28,
|
|
74
|
+
...(input === undefined ? {} : { input }),
|
|
70
75
|
});
|
|
71
76
|
// A spawn error is never a success: the child can exit 0 before ENOBUFS kills it.
|
|
72
77
|
const status = res.error && res.status === 0 ? 1 : res.status;
|
|
@@ -116,6 +121,398 @@ function dirtyTracked(root) {
|
|
|
116
121
|
.filter((l) => l !== "" && !l.startsWith("??"));
|
|
117
122
|
}
|
|
118
123
|
// ---------------------------------------------------------------------------
|
|
124
|
+
// Shared-checkout record — the one home
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
//
|
|
127
|
+
// An in-place run on `dev` shares its checkout with whatever else is dirty or
|
|
128
|
+
// committed there. At `worktrees setup` the run snapshots which paths were
|
|
129
|
+
// already dirty (and the HEAD it started from) into a per-clone file under the
|
|
130
|
+
// git dir, never committed. Every commit the run makes goes through
|
|
131
|
+
// `ownPathCommit`, which leaves those paths alone, and records its SHA so the
|
|
132
|
+
// push sends exactly the run's commits. Nothing else reads or writes the file.
|
|
133
|
+
/** Exit code: a path that was dirty before the run changed during it, so no commit was made. */
|
|
134
|
+
export const EXIT_FOREIGN_PATH = 10;
|
|
135
|
+
/** check: the plan has no `**Ledger rows:**` line, it is unfilled, or a key it names is on no ledger. */
|
|
136
|
+
export const EXIT_ROWS_MISSING = 11;
|
|
137
|
+
/** commit --scope=pr: the checkout is on `dev`, `main` or a detached HEAD, so nothing is committed. */
|
|
138
|
+
export const EXIT_SHARED_BRANCH = 12;
|
|
139
|
+
const RECORD_DIR = "bkit/shared-checkout";
|
|
140
|
+
const RECORD_FID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
141
|
+
/** The checkout's top: git status and pathspecs are relative to it, whatever `cwd` is. */
|
|
142
|
+
function topOf(cwd) {
|
|
143
|
+
const top = gitRaw(cwd, ["rev-parse", "--show-toplevel"]);
|
|
144
|
+
return top.status === 0 ? top.stdout.trim() : cwd;
|
|
145
|
+
}
|
|
146
|
+
/** `$(git rev-parse --git-path bkit/shared-checkout/{sub})`, absolute; null outside a repo. */
|
|
147
|
+
function recordPathOf(cwd, sub) {
|
|
148
|
+
const res = gitRaw(cwd, ["rev-parse", "--git-path", `${RECORD_DIR}/${sub}`]);
|
|
149
|
+
return res.status === 0 && res.stdout.trim() !== "" ? path.resolve(cwd, res.stdout.trim()) : null;
|
|
150
|
+
}
|
|
151
|
+
const recordFile = (cwd, fid) => RECORD_FID.test(fid) && !fid.includes("..") ? recordPathOf(cwd, `${fid}.json`) : null;
|
|
152
|
+
function asRecord(value) {
|
|
153
|
+
if (typeof value !== "object" || value === null)
|
|
154
|
+
return null;
|
|
155
|
+
const r = value;
|
|
156
|
+
if (typeof r.fid !== "string" ||
|
|
157
|
+
typeof r.branch !== "string" ||
|
|
158
|
+
typeof r.startSha !== "string" ||
|
|
159
|
+
typeof r.aheadAtStart !== "number" ||
|
|
160
|
+
!Array.isArray(r.paths) ||
|
|
161
|
+
!Array.isArray(r.commits))
|
|
162
|
+
return null;
|
|
163
|
+
return {
|
|
164
|
+
fid: r.fid,
|
|
165
|
+
branch: r.branch,
|
|
166
|
+
startSha: r.startSha,
|
|
167
|
+
originSha: typeof r.originSha === "string" ? r.originSha : null,
|
|
168
|
+
aheadAtStart: r.aheadAtStart,
|
|
169
|
+
paths: r.paths.filter((p) => typeof p?.path === "string"),
|
|
170
|
+
commits: r.commits.filter((c) => typeof c === "string"),
|
|
171
|
+
...(Array.isArray(r.pushed)
|
|
172
|
+
? { pushed: r.pushed.filter((c) => typeof c === "string") }
|
|
173
|
+
: {}),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/** The FID's record, or null when absent or unreadable. */
|
|
177
|
+
export function readRecord(cwd, fid) {
|
|
178
|
+
const file = recordFile(cwd, fid);
|
|
179
|
+
if (file === null || !fs.existsSync(file))
|
|
180
|
+
return null;
|
|
181
|
+
const parsed = parseJson(fs.readFileSync(file, "utf-8"));
|
|
182
|
+
return parsed.ok ? asRecord(parsed.value) : null;
|
|
183
|
+
}
|
|
184
|
+
/** Note run commits that now sit on origin/dev as replayed copies, so a later push skips them. */
|
|
185
|
+
export function markRecordPushed(cwd, fid, shas) {
|
|
186
|
+
const rec = readRecord(cwd, fid);
|
|
187
|
+
if (rec === null)
|
|
188
|
+
return;
|
|
189
|
+
writeRecord(cwd, { ...rec, pushed: [...new Set([...(rec.pushed ?? []), ...shas])] });
|
|
190
|
+
}
|
|
191
|
+
/** Every record in this clone. */
|
|
192
|
+
export function listRecords(cwd) {
|
|
193
|
+
const dir = recordPathOf(cwd, "");
|
|
194
|
+
if (dir === null || !fs.existsSync(dir))
|
|
195
|
+
return [];
|
|
196
|
+
return fs
|
|
197
|
+
.readdirSync(dir)
|
|
198
|
+
.filter((f) => f.endsWith(".json"))
|
|
199
|
+
.map((f) => readRecord(cwd, f.slice(0, -".json".length)))
|
|
200
|
+
.filter((r) => r !== null);
|
|
201
|
+
}
|
|
202
|
+
export function writeRecord(cwd, rec) {
|
|
203
|
+
const file = recordFile(cwd, rec.fid);
|
|
204
|
+
if (file === null)
|
|
205
|
+
throw new CommandError(EXIT_ROOT, `cannot place a record for "${rec.fid}"`);
|
|
206
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
207
|
+
fs.writeFileSync(file, `${JSON.stringify(rec, null, 2)}\n`);
|
|
208
|
+
}
|
|
209
|
+
/** A setup guard older than this is a crashed setup's leftover. */
|
|
210
|
+
const SETUP_GUARD_STALE_MS = 30_000;
|
|
211
|
+
/**
|
|
212
|
+
* Run `fn` as the only record-setup in this clone: an exclusive-create guard file
|
|
213
|
+
* next to the records makes the busy check and the record write one step. Returns
|
|
214
|
+
* null, without running `fn`, when another setup holds a fresh guard.
|
|
215
|
+
*/
|
|
216
|
+
export function withSetupGuard(cwd, fn) {
|
|
217
|
+
const guard = recordPathOf(cwd, ".setup.lock");
|
|
218
|
+
if (guard === null)
|
|
219
|
+
return { value: fn() };
|
|
220
|
+
fs.mkdirSync(path.dirname(guard), { recursive: true });
|
|
221
|
+
const take = () => {
|
|
222
|
+
try {
|
|
223
|
+
fs.closeSync(fs.openSync(guard, "wx"));
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
if (err.code === "EEXIST")
|
|
228
|
+
return false;
|
|
229
|
+
throw err;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
if (!take()) {
|
|
233
|
+
const age = fs.existsSync(guard) ? Date.now() - fs.statSync(guard).mtimeMs : Infinity;
|
|
234
|
+
if (age < SETUP_GUARD_STALE_MS)
|
|
235
|
+
return null;
|
|
236
|
+
fs.rmSync(guard, { force: true });
|
|
237
|
+
if (!take())
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
try {
|
|
241
|
+
return { value: fn() };
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
fs.rmSync(guard, { force: true });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** Remove the FID's record; false when there was none. */
|
|
248
|
+
export function removeRecord(cwd, fid) {
|
|
249
|
+
const file = recordFile(cwd, fid);
|
|
250
|
+
if (file === null || !fs.existsSync(file))
|
|
251
|
+
return false;
|
|
252
|
+
fs.rmSync(file, { force: true });
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
/** The FID's record, only while its branch is still the one checked out. */
|
|
256
|
+
export function activeRecord(cwd, fid) {
|
|
257
|
+
const rec = readRecord(cwd, fid);
|
|
258
|
+
if (rec === null)
|
|
259
|
+
return null;
|
|
260
|
+
const here = gitRaw(cwd, ["branch", "--show-current"]).stdout.trim();
|
|
261
|
+
return here === rec.branch ? rec : null;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The record of the run in place on `branch`, for a command that is not told
|
|
265
|
+
* its FID (the push). Setup keeps one live record per clone; if several are left
|
|
266
|
+
* over, the one written last wins.
|
|
267
|
+
*/
|
|
268
|
+
export function recordOnBranch(cwd, branch) {
|
|
269
|
+
const dir = recordPathOf(cwd, "");
|
|
270
|
+
const written = (r) => {
|
|
271
|
+
const file = recordFile(cwd, r.fid);
|
|
272
|
+
return file !== null && fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0;
|
|
273
|
+
};
|
|
274
|
+
const ours = listRecords(cwd).filter((r) => r.branch === branch);
|
|
275
|
+
if (dir === null || ours.length === 0)
|
|
276
|
+
return null;
|
|
277
|
+
return ours.reduce((a, b) => (written(b) > written(a) ? b : a));
|
|
278
|
+
}
|
|
279
|
+
/** Append a commit the run made; called only after the commit succeeded. */
|
|
280
|
+
export function appendRecordCommit(cwd, fid, sha) {
|
|
281
|
+
const rec = readRecord(cwd, fid);
|
|
282
|
+
if (rec === null || rec.commits.includes(sha))
|
|
283
|
+
return;
|
|
284
|
+
writeRecord(cwd, { ...rec, commits: [...rec.commits, sha] });
|
|
285
|
+
}
|
|
286
|
+
/** Paths git reports as changed or untracked, relative to the top, one per file. */
|
|
287
|
+
function dirtyPaths(top) {
|
|
288
|
+
const res = gitRaw(top, ["status", "--porcelain", "-z", "-uall", "--no-renames"]);
|
|
289
|
+
return nulList(res.stdout)
|
|
290
|
+
.filter((e) => e.length > 3 && !e.startsWith("!!"))
|
|
291
|
+
.map((e) => e.slice(3));
|
|
292
|
+
}
|
|
293
|
+
/** `git hash-object` of the working file; null when it is gone. */
|
|
294
|
+
function hashOf(top, rel) {
|
|
295
|
+
const abs = path.join(top, rel);
|
|
296
|
+
if (!fs.existsSync(abs))
|
|
297
|
+
return null;
|
|
298
|
+
if (!fs.statSync(abs).isFile())
|
|
299
|
+
return "not-a-file";
|
|
300
|
+
const res = gitRaw(top, ["hash-object", "--", rel]);
|
|
301
|
+
return res.status === 0 ? res.stdout.trim() : "unhashable";
|
|
302
|
+
}
|
|
303
|
+
/** A text's non-blank lines. */
|
|
304
|
+
const rowsOf = (text) => text.split("\n").filter((l) => l.trim() !== "");
|
|
305
|
+
/** Lines of `file` in `cwd`'s working copy that its HEAD blob lacks (compared trimmed). */
|
|
306
|
+
export function rowsHeadLacks(cwd, file) {
|
|
307
|
+
const head = new Set(rowsOf(gitRaw(cwd, ["show", `HEAD:${file}`]).stdout).map((l) => l.trim()));
|
|
308
|
+
return rowsOf(fs.readFileSync(path.join(cwd, file), "utf-8")).filter((l) => !head.has(l.trim()));
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Rows of `file` the run appended: lines HEAD lacks, and past the recorded line
|
|
312
|
+
* count when the run's record holds the file (rows before it are someone else's).
|
|
313
|
+
*/
|
|
314
|
+
export function runRows(cwd, file, rec) {
|
|
315
|
+
const was = rec?.paths.find((p) => p.path === file);
|
|
316
|
+
if (was?.lines === undefined)
|
|
317
|
+
return rowsHeadLacks(cwd, file);
|
|
318
|
+
const head = gitRaw(cwd, ["show", `HEAD:${file}`]);
|
|
319
|
+
const have = new Set(rowsOf(head.status === 0 ? head.stdout : "").map((l) => l.trim()));
|
|
320
|
+
const lines = fs.readFileSync(path.join(cwd, file), "utf-8").split("\n").slice(was.lines);
|
|
321
|
+
return rowsOf(lines.join("\n")).filter((l) => !have.has(l.trim()));
|
|
322
|
+
}
|
|
323
|
+
/** The record for a run starting now in `cwd` on `branch`. */
|
|
324
|
+
export function newRecord(cwd, fid, branch) {
|
|
325
|
+
const top = topOf(cwd);
|
|
326
|
+
const startSha = gitRaw(top, ["rev-parse", "HEAD"]).stdout.trim();
|
|
327
|
+
const origin = gitRaw(top, ["rev-parse", "-q", "--verify", `refs/remotes/origin/${branch}`]);
|
|
328
|
+
const originSha = origin.status === 0 ? origin.stdout.trim() : null;
|
|
329
|
+
const ahead = originSha === null
|
|
330
|
+
? 0
|
|
331
|
+
: Number(gitRaw(top, ["rev-list", "--count", `${originSha}..HEAD`]).stdout);
|
|
332
|
+
const paths = dirtyPaths(top).map((rel) => {
|
|
333
|
+
const hash = hashOf(top, rel);
|
|
334
|
+
const abs = path.join(top, rel);
|
|
335
|
+
const text = hash !== null && rel.endsWith(".jsonl") ? fs.readFileSync(abs, "utf-8") : null;
|
|
336
|
+
return text !== null && (text === "" || text.endsWith("\n"))
|
|
337
|
+
? { path: rel, hash, lines: fileLines(text).length }
|
|
338
|
+
: { path: rel, hash };
|
|
339
|
+
});
|
|
340
|
+
return { fid, branch, startSha, originSha, aheadAtStart: ahead, paths, commits: [] };
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* The paths that are the run's own: dirty now, minus every recorded path. A
|
|
344
|
+
* recorded append-only ledger contributes only the rows appended after the
|
|
345
|
+
* recorded line count that HEAD lacks. Any other recorded path whose content
|
|
346
|
+
* changed, or a ledger whose recorded lines changed, throws EXIT_FOREIGN_PATH.
|
|
347
|
+
* `among` limits which recorded paths count (a bookkeeping commit only commits
|
|
348
|
+
* its allow-list).
|
|
349
|
+
*/
|
|
350
|
+
export function ownSet(cwd, rec, among) {
|
|
351
|
+
const top = topOf(cwd);
|
|
352
|
+
const recorded = new Map(rec.paths.map((p) => [p.path, p]));
|
|
353
|
+
const out = { plain: [], ledgers: [] };
|
|
354
|
+
const foreign = [];
|
|
355
|
+
for (const rel of dirtyPaths(top)) {
|
|
356
|
+
const was = recorded.get(rel);
|
|
357
|
+
if (was === undefined) {
|
|
358
|
+
out.plain.push(rel);
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (among !== undefined && !among.includes(rel))
|
|
362
|
+
continue;
|
|
363
|
+
if (hashOf(top, rel) === was.hash)
|
|
364
|
+
continue;
|
|
365
|
+
if (was.lines === undefined) {
|
|
366
|
+
foreign.push(rel);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const text = fs.readFileSync(path.join(top, rel), "utf-8");
|
|
370
|
+
const lines = text.split("\n");
|
|
371
|
+
const prefix = `${lines.slice(0, was.lines).join("\n")}\n`;
|
|
372
|
+
// `--path` applies the same clean / eol filters `hashOf` hashed the file with.
|
|
373
|
+
const prefixHash = gitRaw(top, ["hash-object", `--path=${rel}`, "--stdin"], {}, prefix).stdout.trim();
|
|
374
|
+
if (was.lines > 0 && prefixHash !== was.hash) {
|
|
375
|
+
foreign.push(rel);
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const own = runRows(top, rel, rec);
|
|
379
|
+
if (own.length === 0)
|
|
380
|
+
continue;
|
|
381
|
+
const head = gitRaw(top, ["show", `HEAD:${rel}`]);
|
|
382
|
+
const base = head.status === 0 ? head.stdout : "";
|
|
383
|
+
const sep = base === "" || base.endsWith("\n") ? "" : "\n";
|
|
384
|
+
out.ledgers.push({ path: rel, text: `${base}${sep}${own.join("\n")}\n` });
|
|
385
|
+
}
|
|
386
|
+
if (foreign.length > 0) {
|
|
387
|
+
throw new CommandError(EXIT_FOREIGN_PATH, `refusing to commit: ${foreign.join(", ")} changed during the run but was already modified before it started — nothing committed; commit or revert ${foreign.length === 1 ? "it" : "them"} yourself, then re-run`);
|
|
388
|
+
}
|
|
389
|
+
return out;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Rebuild the real index entry of a ledger the user staged before the run: the
|
|
393
|
+
* new HEAD blob plus the staged rows HEAD lacks, so the user's next plain commit
|
|
394
|
+
* keeps the run's committed rows.
|
|
395
|
+
*/
|
|
396
|
+
function restageLedger(top, rel) {
|
|
397
|
+
const staged = gitRaw(top, ["show", `:${rel}`]);
|
|
398
|
+
const head = gitRaw(top, ["show", `HEAD:${rel}`]);
|
|
399
|
+
if (staged.status !== 0 || head.status !== 0)
|
|
400
|
+
return;
|
|
401
|
+
const have = new Set(rowsOf(head.stdout).map((l) => l.trim()));
|
|
402
|
+
const theirs = rowsOf(staged.stdout).filter((l) => !have.has(l.trim()));
|
|
403
|
+
if (theirs.length === 0) {
|
|
404
|
+
gitRaw(top, ["reset", "-q", "--", rel]);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const sep = head.stdout === "" || head.stdout.endsWith("\n") ? "" : "\n";
|
|
408
|
+
const blob = gitRaw(top, ["hash-object", "-w", "--stdin"], {}, `${head.stdout}${sep}${theirs.join("\n")}\n`);
|
|
409
|
+
if (blob.status !== 0)
|
|
410
|
+
return;
|
|
411
|
+
gitRaw(top, ["update-index", "--cacheinfo", `100644,${blob.stdout.trim()},${rel}`]);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Commit `set` and nothing else: foreign index entries stay staged and foreign
|
|
415
|
+
* files stay out. Plain files go through a pathspec commit; ledger rows, or an
|
|
416
|
+
* empty set, go through a temporary index read from HEAD. With `skipIfEmpty`, no
|
|
417
|
+
* change against HEAD makes no commit (`sha` null). The caller records the SHA.
|
|
418
|
+
*/
|
|
419
|
+
export function commitOwnSet(cwd, set, message, o = {}) {
|
|
420
|
+
const top = topOf(cwd);
|
|
421
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-own-"));
|
|
422
|
+
try {
|
|
423
|
+
const list = path.join(tmp, "list");
|
|
424
|
+
const all = [...set.plain, ...set.ledgers.map((l) => l.path)];
|
|
425
|
+
fs.writeFileSync(list, all.map((p) => `${p}\0`).join(""));
|
|
426
|
+
const stagedBefore = new Set(nulList(gitRaw(top, ["diff", "--cached", "--name-only", "-z"]).stdout));
|
|
427
|
+
const tail = ["-m", message];
|
|
428
|
+
let made;
|
|
429
|
+
if (set.ledgers.length === 0 && set.plain.length > 0) {
|
|
430
|
+
const add = gitRaw(top, ["add", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
|
|
431
|
+
if (add.status !== 0)
|
|
432
|
+
return { ok: false, error: `'git add' failed: ${add.stderr}` };
|
|
433
|
+
if (o.skipIfEmpty === true &&
|
|
434
|
+
gitRaw(top, ["diff", "--cached", "--quiet", "--", ...set.plain]).status === 0)
|
|
435
|
+
return { ok: true, sha: null };
|
|
436
|
+
made = gitRaw(top, [
|
|
437
|
+
"commit",
|
|
438
|
+
...(o.allowEmpty === true ? ["--allow-empty"] : []),
|
|
439
|
+
`--pathspec-from-file=${list}`,
|
|
440
|
+
"--pathspec-file-nul",
|
|
441
|
+
...tail,
|
|
442
|
+
]);
|
|
443
|
+
}
|
|
444
|
+
else {
|
|
445
|
+
const env = { GIT_INDEX_FILE: path.join(tmp, "index") };
|
|
446
|
+
if (gitRaw(top, ["rev-parse", "-q", "--verify", "HEAD"]).status === 0) {
|
|
447
|
+
const read = gitRaw(top, ["read-tree", "HEAD"], env);
|
|
448
|
+
if (read.status !== 0)
|
|
449
|
+
return { ok: false, error: `'git read-tree' failed: ${read.stderr}` };
|
|
450
|
+
}
|
|
451
|
+
if (set.plain.length > 0) {
|
|
452
|
+
const add = gitRaw(top, ["add", `--pathspec-from-file=${list}`, "--pathspec-file-nul"], env);
|
|
453
|
+
if (add.status !== 0)
|
|
454
|
+
return { ok: false, error: `'git add' failed: ${add.stderr}` };
|
|
455
|
+
}
|
|
456
|
+
for (const l of set.ledgers) {
|
|
457
|
+
const blob = gitRaw(top, ["hash-object", "-w", "--stdin"], env, l.text);
|
|
458
|
+
const upd = gitRaw(top, ["update-index", "--add", "--cacheinfo", `100644,${blob.stdout.trim()},${l.path}`], env);
|
|
459
|
+
if (blob.status !== 0 || upd.status !== 0) {
|
|
460
|
+
return { ok: false, error: `'git update-index' failed: ${upd.stderr || blob.stderr}` };
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (o.skipIfEmpty === true && gitRaw(top, ["diff", "--cached", "--quiet"], env).status === 0)
|
|
464
|
+
return { ok: true, sha: null };
|
|
465
|
+
made = gitRaw(top, ["commit", ...(o.allowEmpty === true ? ["--allow-empty"] : []), ...tail], env);
|
|
466
|
+
if (made.status === 0 && all.length > 0) {
|
|
467
|
+
// The real index still holds the pre-commit entries; bring the run's own
|
|
468
|
+
// (unstaged-by-anyone-else) paths level with the new HEAD.
|
|
469
|
+
const reset = all.filter((p) => !stagedBefore.has(p));
|
|
470
|
+
fs.writeFileSync(list, reset.map((p) => `${p}\0`).join(""));
|
|
471
|
+
if (reset.length > 0) {
|
|
472
|
+
gitRaw(top, ["reset", "-q", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
|
|
473
|
+
}
|
|
474
|
+
// A ledger the user had staged keeps their rows in the index, on top of the new HEAD's.
|
|
475
|
+
for (const l of set.ledgers)
|
|
476
|
+
if (stagedBefore.has(l.path))
|
|
477
|
+
restageLedger(top, l.path);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (made.status !== 0) {
|
|
481
|
+
// Leave the index as it was: unstage what this attempt staged, never another's entry.
|
|
482
|
+
const unstage = all.filter((p) => !stagedBefore.has(p));
|
|
483
|
+
fs.writeFileSync(list, unstage.map((p) => `${p}\0`).join(""));
|
|
484
|
+
if (unstage.length > 0)
|
|
485
|
+
gitRaw(top, ["reset", "-q", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
|
|
486
|
+
return { ok: false, error: made.stderr || made.stdout.trim() };
|
|
487
|
+
}
|
|
488
|
+
return { ok: true, sha: gitRaw(top, ["rev-parse", "HEAD"]).stdout.trim() };
|
|
489
|
+
}
|
|
490
|
+
finally {
|
|
491
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* The run's own-path commit: compute the own set from the record, commit it,
|
|
496
|
+
* append the SHA to the record. Throws EXIT_FOREIGN_PATH before committing.
|
|
497
|
+
*/
|
|
498
|
+
export function ownPathCommit(cwd, rec, message, o = {}) {
|
|
499
|
+
const made = commitOwnSet(cwd, ownSet(cwd, rec), message, o);
|
|
500
|
+
if (made.ok && made.sha !== null)
|
|
501
|
+
appendRecordCommit(cwd, rec.fid, made.sha);
|
|
502
|
+
return made;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* An empty commit of the run's own: nothing from the working tree or the real
|
|
506
|
+
* index goes in, so a path the user staged never lands in it. The SHA is
|
|
507
|
+
* appended to the record.
|
|
508
|
+
*/
|
|
509
|
+
export function retriggerCommit(cwd, rec, message) {
|
|
510
|
+
const made = commitOwnSet(cwd, { plain: [], ledgers: [] }, message, { allowEmpty: true });
|
|
511
|
+
if (made.ok && made.sha !== null)
|
|
512
|
+
appendRecordCommit(cwd, rec.fid, made.sha);
|
|
513
|
+
return made;
|
|
514
|
+
}
|
|
515
|
+
// ---------------------------------------------------------------------------
|
|
119
516
|
// Command
|
|
120
517
|
// ---------------------------------------------------------------------------
|
|
121
518
|
export const ledgersCommand = {
|
|
@@ -131,8 +528,7 @@ export const ledgersCommand = {
|
|
|
131
528
|
{
|
|
132
529
|
name: "scope",
|
|
133
530
|
type: "string",
|
|
134
|
-
|
|
135
|
-
help: "core (logs + ledgers) | full (+ docs ledgers, skills) | pr (+ top-level docs/*.md)",
|
|
531
|
+
help: "core (logs + ledgers) | full (+ docs ledgers, skills) | pr (+ top-level docs/*.md); not with --path",
|
|
136
532
|
},
|
|
137
533
|
{
|
|
138
534
|
name: "mode",
|
|
@@ -143,7 +539,12 @@ export const ledgersCommand = {
|
|
|
143
539
|
{
|
|
144
540
|
name: "stage-tracked-updates",
|
|
145
541
|
type: "boolean",
|
|
146
|
-
help: "run `git add -u` first (stages every tracked change)",
|
|
542
|
+
help: "run `git add -u` first (stages every tracked change; commit modes commit them too)",
|
|
543
|
+
},
|
|
544
|
+
{
|
|
545
|
+
name: "path",
|
|
546
|
+
type: "string",
|
|
547
|
+
help: "commit this one path alone, relative to --root (commit modes only; no --scope)",
|
|
147
548
|
},
|
|
148
549
|
{
|
|
149
550
|
name: "squash-of",
|
|
@@ -160,14 +561,17 @@ export const ledgersCommand = {
|
|
|
160
561
|
output: {
|
|
161
562
|
outcome: "committed | staged | nothing-to-commit | clean (no tracked changes, with --only-if-dirty-tracked)",
|
|
162
563
|
commit: "the new commit's sha, or null",
|
|
163
|
-
paths: "bookkeeping paths the allow-list matched",
|
|
564
|
+
paths: "bookkeeping paths the allow-list matched (the --path alone with --path)",
|
|
565
|
+
tracked: "tracked paths --stage-tracked-updates staged into the commit",
|
|
164
566
|
squashPaths: "paths the --squash-of ref brought in",
|
|
165
567
|
},
|
|
166
568
|
exitCodes: {
|
|
167
569
|
[EXIT_ROOT]: "root not a directory or git repo, git < 2.25, or --squash-of does not resolve",
|
|
168
570
|
[EXIT_STAGE]: "staging failed (git add / git add -u)",
|
|
169
571
|
[EXIT_COMMIT]: "git commit failed",
|
|
170
|
-
[EXIT_EMPTY]: "the allow-list matched nothing — refusing to commit the whole index",
|
|
572
|
+
[EXIT_EMPTY]: "the allow-list matched nothing — refusing to commit the whole index; or --path is outside the checkout",
|
|
573
|
+
[EXIT_FOREIGN_PATH]: "an in-place run's allow-listed path was already modified before the run and changed during it — nothing committed",
|
|
574
|
+
[EXIT_SHARED_BRANCH]: "--scope=pr commit on dev, main or a detached HEAD — refused, nothing committed",
|
|
171
575
|
},
|
|
172
576
|
run: (ctx) => commit(ctx),
|
|
173
577
|
},
|
|
@@ -204,14 +608,111 @@ export const ledgersCommand = {
|
|
|
204
608
|
},
|
|
205
609
|
run: (ctx) => onlyBookkeeping(ctx),
|
|
206
610
|
},
|
|
611
|
+
append: {
|
|
612
|
+
summary: "Append validated rows to one ledger, minting each row's ts at append time.",
|
|
613
|
+
flags: [
|
|
614
|
+
{ name: "root", type: "string", help: "checkout whose ledger to append to (default: cwd)" },
|
|
615
|
+
{
|
|
616
|
+
name: "ledger",
|
|
617
|
+
type: "string",
|
|
618
|
+
required: true,
|
|
619
|
+
help: Object.keys(APPEND_LEDGERS).join(" | "),
|
|
620
|
+
},
|
|
621
|
+
{
|
|
622
|
+
name: "rows",
|
|
623
|
+
type: "string",
|
|
624
|
+
required: true,
|
|
625
|
+
help: "file holding a JSON array of rows without schema, ts or bkit, or - for stdin",
|
|
626
|
+
},
|
|
627
|
+
],
|
|
628
|
+
output: {
|
|
629
|
+
ledger: "the ledger appended to",
|
|
630
|
+
file: "its path, relative to --root",
|
|
631
|
+
appended: "rows written",
|
|
632
|
+
keys: "each row's key, in order (null when a row has none)",
|
|
633
|
+
},
|
|
634
|
+
exitCodes: {
|
|
635
|
+
[EXIT_STAGE]: "mkdir or append failed",
|
|
636
|
+
[EXIT_ROW_REFUSED]: "a row carries ts, has the wrong kind, fails validation, or names a writer not listed for its kind — nothing written",
|
|
637
|
+
},
|
|
638
|
+
run: (ctx) => append(ctx),
|
|
639
|
+
},
|
|
640
|
+
check: {
|
|
641
|
+
summary: "Check that every decision / deferral key on a plan's `**Ledger rows:**` line is on disk.",
|
|
642
|
+
flags: [
|
|
643
|
+
{ name: "root", type: "string", help: "checkout whose ledgers to read (default: cwd)" },
|
|
644
|
+
{ name: "plan", type: "string", required: true, help: "plan file, relative to --root" },
|
|
645
|
+
],
|
|
646
|
+
output: {
|
|
647
|
+
plan: "the plan checked",
|
|
648
|
+
keys: "the keys its Ledger rows line names (empty for None)",
|
|
649
|
+
missing: "keys on neither docs/decisions.jsonl nor docs/deferrals.jsonl",
|
|
650
|
+
},
|
|
651
|
+
exitCodes: {
|
|
652
|
+
[EXIT_ROWS_MISSING]: "no `**Ledger rows:**` line, the line is unfilled, or a key it names has no row",
|
|
653
|
+
},
|
|
654
|
+
run: (ctx) => check(ctx),
|
|
655
|
+
},
|
|
207
656
|
},
|
|
208
657
|
};
|
|
658
|
+
/** Commit one named path alone: `git add` it, then `git commit -- <path>`. */
|
|
659
|
+
function commitOnePath(o, log) {
|
|
660
|
+
const { root, mode, message } = o;
|
|
661
|
+
const rel = o.path;
|
|
662
|
+
const abs = path.resolve(root, rel);
|
|
663
|
+
const inside = path.relative(root, abs);
|
|
664
|
+
if (inside === "" || inside.startsWith("..") || path.isAbsolute(inside)) {
|
|
665
|
+
throw new CommandError(EXIT_EMPTY, `--path is outside the checkout: ${rel}`);
|
|
666
|
+
}
|
|
667
|
+
const done = (outcome, sha) => ({
|
|
668
|
+
outcome,
|
|
669
|
+
commit: sha,
|
|
670
|
+
paths: [inside],
|
|
671
|
+
squashPaths: [],
|
|
672
|
+
tracked: [],
|
|
673
|
+
});
|
|
674
|
+
const add = gitRaw(root, ["add", "--", inside]);
|
|
675
|
+
if (add.status !== 0)
|
|
676
|
+
throw new CommandError(EXIT_STAGE, `'git add' failed: ${add.stderr}`);
|
|
677
|
+
if (mode === "commit" &&
|
|
678
|
+
gitRaw(root, ["diff", "--cached", "--quiet", "--", inside]).status === 0) {
|
|
679
|
+
log(`nothing to commit at ${inside}`);
|
|
680
|
+
return done("nothing-to-commit", null);
|
|
681
|
+
}
|
|
682
|
+
const made = gitRaw(root, [
|
|
683
|
+
"commit",
|
|
684
|
+
...(mode === "commit-allow-empty" ? ["--allow-empty"] : []),
|
|
685
|
+
"-m",
|
|
686
|
+
message,
|
|
687
|
+
"--",
|
|
688
|
+
inside,
|
|
689
|
+
]);
|
|
690
|
+
if (made.status !== 0) {
|
|
691
|
+
throw new CommandError(EXIT_COMMIT, `'git commit' failed: ${made.stderr || made.stdout.trim()}`);
|
|
692
|
+
}
|
|
693
|
+
const sha = gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim();
|
|
694
|
+
if (activeRecord(root, o.fid) !== null)
|
|
695
|
+
appendRecordCommit(root, o.fid, sha);
|
|
696
|
+
return done("committed", sha);
|
|
697
|
+
}
|
|
209
698
|
/**
|
|
210
699
|
* Stage (and commit) the bookkeeping allow-list for one feature. Throws a
|
|
211
700
|
* CommandError with EXIT_ROOT / EXIT_STAGE / EXIT_COMMIT / EXIT_EMPTY.
|
|
212
701
|
*/
|
|
213
702
|
export function commitBookkeeping(o, log) {
|
|
214
703
|
const { root, month, fid, scope, mode, message, squashOf } = o;
|
|
704
|
+
if (o.path !== undefined) {
|
|
705
|
+
if (mode === "stage" || !MODES.includes(mode)) {
|
|
706
|
+
throw new CommandError(EXIT.USAGE, "--path needs --mode=commit or commit-allow-empty");
|
|
707
|
+
}
|
|
708
|
+
if (o.stageTrackedUpdates === true || squashOf !== undefined || o.onlyIfDirtyTracked === true) {
|
|
709
|
+
throw new CommandError(EXIT.USAGE, "--path commits one path alone; drop --stage-tracked-updates, --squash-of and --only-if-dirty-tracked");
|
|
710
|
+
}
|
|
711
|
+
if (!message)
|
|
712
|
+
throw new CommandError(EXIT.USAGE, `--message is required for --mode=${mode}`);
|
|
713
|
+
requireRepo(root);
|
|
714
|
+
return commitOnePath(o, log);
|
|
715
|
+
}
|
|
215
716
|
if (!SCOPES.includes(scope)) {
|
|
216
717
|
throw new CommandError(EXIT.USAGE, `--scope must be core, full, or pr (got '${scope}')`);
|
|
217
718
|
}
|
|
@@ -224,6 +725,12 @@ export function commitBookkeeping(o, log) {
|
|
|
224
725
|
throw new CommandError(EXIT.USAGE, "--squash-of applies to commit modes only");
|
|
225
726
|
}
|
|
226
727
|
requireRepo(root);
|
|
728
|
+
if (scope === "pr" && mode !== "stage") {
|
|
729
|
+
const branch = gitRaw(root, ["branch", "--show-current"]).stdout.trim();
|
|
730
|
+
if (branch === "" || isSharedBranch(branch)) {
|
|
731
|
+
throw new CommandError(EXIT_SHARED_BRANCH, `--scope=pr commits a feature branch's bookkeeping: refusing to commit on '${branch || "detached HEAD"}'`);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
227
734
|
if (squashOf !== undefined &&
|
|
228
735
|
gitRaw(root, ["rev-parse", "-q", "--verify", `${squashOf}^{commit}`]).status !== 0) {
|
|
229
736
|
throw new CommandError(EXIT_ROOT, `--squash-of: unknown commit: ${squashOf}`);
|
|
@@ -233,15 +740,36 @@ export function commitBookkeeping(o, log) {
|
|
|
233
740
|
const dirty = dirtyTracked(root);
|
|
234
741
|
if (dirty.length === 0) {
|
|
235
742
|
log("no tracked file has uncommitted changes — nothing to commit");
|
|
236
|
-
return { outcome: "clean", commit: null, paths: [], squashPaths: [] };
|
|
743
|
+
return { outcome: "clean", commit: null, paths: [], squashPaths: [], tracked: [] };
|
|
237
744
|
}
|
|
238
745
|
for (const line of dirty)
|
|
239
746
|
log(line);
|
|
240
747
|
}
|
|
748
|
+
// An in-place run on a shared branch: recorded paths are someone else's.
|
|
749
|
+
const rec = squashOf === undefined ? activeRecord(root, fid) : null;
|
|
750
|
+
let tracked = [];
|
|
241
751
|
if (o.stageTrackedUpdates === true) {
|
|
242
|
-
|
|
752
|
+
// Throws EXIT_FOREIGN_PATH when any recorded path changed, before anything is staged.
|
|
753
|
+
if (rec !== null)
|
|
754
|
+
ownSet(root, rec);
|
|
755
|
+
const keepOut = (rec?.paths ?? []).map((p) => `:(exclude,literal)${p.path}`);
|
|
756
|
+
const res = gitRaw(root, ["add", "-u", ...(keepOut.length > 0 ? ["--", ".", ...keepOut] : [])]);
|
|
243
757
|
if (res.status !== 0)
|
|
244
758
|
throw new CommandError(EXIT_STAGE, `'git add -u' failed: ${res.stderr}`);
|
|
759
|
+
if (mode !== "stage") {
|
|
760
|
+
const cached = gitRaw(root, [
|
|
761
|
+
"diff",
|
|
762
|
+
"--cached",
|
|
763
|
+
"--name-only",
|
|
764
|
+
"-z",
|
|
765
|
+
"--no-renames",
|
|
766
|
+
...(keepOut.length > 0 ? ["--", ".", ...keepOut] : []),
|
|
767
|
+
]);
|
|
768
|
+
if (cached.status !== 0) {
|
|
769
|
+
throw new CommandError(EXIT_STAGE, `'git diff --cached' failed: ${cached.stderr}`);
|
|
770
|
+
}
|
|
771
|
+
tracked = nulList(cached.stdout);
|
|
772
|
+
}
|
|
245
773
|
}
|
|
246
774
|
const specs = bookPathspecs(month, fid, scope);
|
|
247
775
|
const listed = gitRaw(root, [
|
|
@@ -256,7 +784,14 @@ export function commitBookkeeping(o, log) {
|
|
|
256
784
|
if (listed.status !== 0) {
|
|
257
785
|
throw new CommandError(EXIT_ROOT, `'git ls-files' failed while building the pathspec: ${listed.stderr}`);
|
|
258
786
|
}
|
|
259
|
-
|
|
787
|
+
let paths = nulList(listed.stdout);
|
|
788
|
+
let ledgerRows = [];
|
|
789
|
+
if (rec !== null) {
|
|
790
|
+
// Throws EXIT_FOREIGN_PATH when a recorded path in the allow-list changed.
|
|
791
|
+
ledgerRows = ownSet(root, rec, paths).ledgers;
|
|
792
|
+
const recorded = new Set(rec.paths.map((p) => p.path));
|
|
793
|
+
paths = paths.filter((p) => !recorded.has(p));
|
|
794
|
+
}
|
|
260
795
|
let squashPaths = [];
|
|
261
796
|
if (squashOf !== undefined) {
|
|
262
797
|
const diff = gitRaw(root, ["diff", "--name-only", "-z", "--no-renames", `HEAD...${squashOf}`]);
|
|
@@ -265,33 +800,50 @@ export function commitBookkeeping(o, log) {
|
|
|
265
800
|
}
|
|
266
801
|
squashPaths = nulList(diff.stdout);
|
|
267
802
|
}
|
|
268
|
-
if (mode !== "stage" &&
|
|
803
|
+
if (mode !== "stage" &&
|
|
804
|
+
paths.length + squashPaths.length + ledgerRows.length + tracked.length === 0) {
|
|
269
805
|
// The pre-worktree commit records only bookkeeping; a dirty tree with none
|
|
270
806
|
// of it (a fresh consumer repo) has nothing of ours to commit, and stopping
|
|
271
807
|
// here never reaches `git commit`.
|
|
272
808
|
if (o.onlyIfDirtyTracked === true) {
|
|
273
809
|
log(`no bookkeeping under scope=${scope} in ${root} — nothing to commit`);
|
|
274
|
-
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths };
|
|
810
|
+
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
|
|
275
811
|
}
|
|
276
812
|
throw new CommandError(EXIT_EMPTY, `empty pathspec list — refusing to commit (nothing under scope=${scope} matched in ${root})`);
|
|
277
813
|
}
|
|
814
|
+
if (rec !== null && mode !== "stage" && ledgerRows.length > 0) {
|
|
815
|
+
const made = commitOwnSet(root, { plain: [...paths, ...tracked], ledgers: ledgerRows }, message, {
|
|
816
|
+
allowEmpty: mode === "commit-allow-empty",
|
|
817
|
+
skipIfEmpty: mode === "commit",
|
|
818
|
+
});
|
|
819
|
+
if (!made.ok)
|
|
820
|
+
throw new CommandError(EXIT_COMMIT, `'git commit' failed: ${made.error}`);
|
|
821
|
+
if (made.sha === null) {
|
|
822
|
+
log("nothing to commit");
|
|
823
|
+
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
|
|
824
|
+
}
|
|
825
|
+
appendRecordCommit(root, fid, made.sha);
|
|
826
|
+
return { outcome: "committed", commit: made.sha, paths, squashPaths, tracked };
|
|
827
|
+
}
|
|
278
828
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-ledgers-"));
|
|
279
829
|
try {
|
|
280
830
|
const bookList = path.join(tmp, "book");
|
|
281
831
|
const commitList = path.join(tmp, "commit");
|
|
282
832
|
fs.writeFileSync(bookList, paths.map((p) => `${p}\0`).join(""));
|
|
283
|
-
|
|
833
|
+
const commitPaths = [...new Set([...paths, ...squashPaths, ...tracked])];
|
|
834
|
+
fs.writeFileSync(commitList, commitPaths.map((p) => `${p}\0`).join(""));
|
|
284
835
|
const add = gitRaw(root, ["add", `--pathspec-from-file=${bookList}`, "--pathspec-file-nul"]);
|
|
285
836
|
if (add.status !== 0)
|
|
286
837
|
throw new CommandError(EXIT_STAGE, `'git add' failed: ${add.stderr}`);
|
|
287
838
|
if (mode === "stage") {
|
|
288
839
|
log(`staged (scope=${scope})`);
|
|
289
|
-
return { outcome: "staged", commit: null, paths, squashPaths };
|
|
840
|
+
return { outcome: "staged", commit: null, paths, squashPaths, tracked };
|
|
290
841
|
}
|
|
291
842
|
if (mode === "commit" &&
|
|
292
|
-
gitRaw(root, ["diff", "--cached", "--quiet", "--", ...specs, ...squashPaths])
|
|
843
|
+
gitRaw(root, ["diff", "--cached", "--quiet", "--", ...specs, ...squashPaths, ...tracked])
|
|
844
|
+
.status === 0) {
|
|
293
845
|
log("nothing to commit");
|
|
294
|
-
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths };
|
|
846
|
+
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
|
|
295
847
|
}
|
|
296
848
|
const made = gitRaw(root, [
|
|
297
849
|
"commit",
|
|
@@ -304,12 +856,10 @@ export function commitBookkeeping(o, log) {
|
|
|
304
856
|
if (made.status !== 0) {
|
|
305
857
|
throw new CommandError(EXIT_COMMIT, `'git commit' failed: ${made.stderr || made.stdout.trim()}`);
|
|
306
858
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
squashPaths,
|
|
312
|
-
};
|
|
859
|
+
const sha = gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim();
|
|
860
|
+
if (rec !== null)
|
|
861
|
+
appendRecordCommit(root, fid, sha);
|
|
862
|
+
return { outcome: "committed", commit: sha, paths, squashPaths, tracked };
|
|
313
863
|
}
|
|
314
864
|
finally {
|
|
315
865
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
@@ -322,12 +872,13 @@ function commit(ctx) {
|
|
|
322
872
|
root: rootOf(ctx),
|
|
323
873
|
month: required(ctx, "month"),
|
|
324
874
|
fid: required(ctx, "fid"),
|
|
325
|
-
scope: String(f.scope),
|
|
875
|
+
scope: String(f.scope ?? ""),
|
|
326
876
|
mode: String(f.mode),
|
|
327
877
|
message: str(f.message),
|
|
328
878
|
stageTrackedUpdates: f.stageTrackedUpdates === true,
|
|
329
879
|
squashOf: str(f.squashOf),
|
|
330
880
|
onlyIfDirtyTracked: f.onlyIfDirtyTracked === true,
|
|
881
|
+
path: str(f.path),
|
|
331
882
|
}, ctx.log),
|
|
332
883
|
});
|
|
333
884
|
return EXIT.OK;
|
|
@@ -391,6 +942,169 @@ function union(ctx) {
|
|
|
391
942
|
ctx.emit({ unioned: files.length, files });
|
|
392
943
|
return EXIT.OK;
|
|
393
944
|
}
|
|
945
|
+
/** The top section in its written order, then the row's own fields. */
|
|
946
|
+
const TOP_ORDER = ["schema", "ts", "kind", "key", "repo", "bkit", "by", "references"];
|
|
947
|
+
/**
|
|
948
|
+
* Append `rows` to one ledger. Every row is checked before any is written, so a
|
|
949
|
+
* refused row leaves the file byte-identical. Each row gets `schema` and a `ts`
|
|
950
|
+
* minted now (never supplied), `repo` when it lacks one and `bkit.version` from
|
|
951
|
+
* `.bkit/version`. Never reads back or rewrites existing rows. Throws a
|
|
952
|
+
* CommandError (USAGE / EXIT_ROW_REFUSED / EXIT_STAGE).
|
|
953
|
+
*/
|
|
954
|
+
export function appendLedgerRows(root, ledger, rows) {
|
|
955
|
+
if (!Object.hasOwn(APPEND_LEDGERS, ledger)) {
|
|
956
|
+
throw new CommandError(EXIT.USAGE, `--ledger must be one of ${Object.keys(APPEND_LEDGERS).join(", ")} (got '${ledger}')`);
|
|
957
|
+
}
|
|
958
|
+
const { file, kinds } = APPEND_LEDGERS[ledger];
|
|
959
|
+
const takes = kinds;
|
|
960
|
+
if (!Array.isArray(rows))
|
|
961
|
+
throw new CommandError(EXIT.USAGE, "--rows must hold a JSON array");
|
|
962
|
+
if (rows.length === 0)
|
|
963
|
+
throw new CommandError(EXIT.USAGE, "--rows holds no rows");
|
|
964
|
+
let repo;
|
|
965
|
+
let version;
|
|
966
|
+
let last;
|
|
967
|
+
const out = rows.map((raw, i) => {
|
|
968
|
+
const refuse = (why) => new CommandError(EXIT_ROW_REFUSED, `row ${i + 1}: ${why}`);
|
|
969
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
970
|
+
throw refuse("not a JSON object");
|
|
971
|
+
}
|
|
972
|
+
const r = raw;
|
|
973
|
+
if (Object.hasOwn(r, "ts"))
|
|
974
|
+
throw refuse("carries ts; ts is minted at append time");
|
|
975
|
+
if (Object.hasOwn(r, "schema"))
|
|
976
|
+
throw refuse("carries schema; it is set at append time");
|
|
977
|
+
if (!takes.includes(String(r["kind"]))) {
|
|
978
|
+
throw refuse(`kind must be ${takes.join(" | ")} in --ledger=${ledger} (got ${String(r["kind"])})`);
|
|
979
|
+
}
|
|
980
|
+
if (Object.hasOwn(r, "bkit"))
|
|
981
|
+
throw refuse("carries bkit; bkit.version is set at append time");
|
|
982
|
+
repo ??= resolveRepoSlug(root) || "unknown/repo";
|
|
983
|
+
version ??= readBkitVersion(path.join(root, ".bkit", "version"))?.pinnedVersion || "unknown";
|
|
984
|
+
last = mintTs(last);
|
|
985
|
+
const filled = {
|
|
986
|
+
repo,
|
|
987
|
+
...r,
|
|
988
|
+
schema: SCHEMA,
|
|
989
|
+
ts: last,
|
|
990
|
+
bkit: { version },
|
|
991
|
+
};
|
|
992
|
+
const row = {};
|
|
993
|
+
for (const k of TOP_ORDER)
|
|
994
|
+
if (filled[k] !== undefined)
|
|
995
|
+
row[k] = filled[k];
|
|
996
|
+
for (const [k, v] of Object.entries(filled))
|
|
997
|
+
if (!(k in row))
|
|
998
|
+
row[k] = v;
|
|
999
|
+
const v = validate(row);
|
|
1000
|
+
if (!v.ok)
|
|
1001
|
+
throw refuse(v.reason ?? "invalid");
|
|
1002
|
+
const who = writerProblem(row);
|
|
1003
|
+
if (who !== undefined)
|
|
1004
|
+
throw refuse(who);
|
|
1005
|
+
return row;
|
|
1006
|
+
});
|
|
1007
|
+
const abs = path.join(root, file);
|
|
1008
|
+
const made = mkdirp(path.dirname(abs));
|
|
1009
|
+
if (made)
|
|
1010
|
+
throw new CommandError(EXIT_STAGE, `mkdir failed for ${path.dirname(file)}: ${made}`);
|
|
1011
|
+
const block = out.map((r) => `${JSON.stringify(r)}\n`).join("");
|
|
1012
|
+
// A file missing its final newline would glue the first row onto its last one.
|
|
1013
|
+
const appendErr = appendText(abs, endsMidLine(abs) ? `\n${block}` : block);
|
|
1014
|
+
if (appendErr)
|
|
1015
|
+
throw new CommandError(EXIT_STAGE, `append failed: ${file} — ${appendErr}`);
|
|
1016
|
+
return {
|
|
1017
|
+
ledger: ledger,
|
|
1018
|
+
file,
|
|
1019
|
+
appended: out.length,
|
|
1020
|
+
keys: out.map((r) => (typeof r["key"] === "string" ? r["key"] : null)),
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
/** True when `abs` exists, is non-empty and its last byte is not a newline. */
|
|
1024
|
+
function endsMidLine(abs) {
|
|
1025
|
+
let fd;
|
|
1026
|
+
try {
|
|
1027
|
+
fd = fs.openSync(abs, "r");
|
|
1028
|
+
const size = fs.fstatSync(fd).size;
|
|
1029
|
+
if (size === 0)
|
|
1030
|
+
return false;
|
|
1031
|
+
const last = Buffer.alloc(1);
|
|
1032
|
+
fs.readSync(fd, last, 0, 1, size - 1);
|
|
1033
|
+
return last[0] !== 0x0a;
|
|
1034
|
+
}
|
|
1035
|
+
catch {
|
|
1036
|
+
// No file yet: the append creates it.
|
|
1037
|
+
return false;
|
|
1038
|
+
}
|
|
1039
|
+
finally {
|
|
1040
|
+
if (fd !== undefined)
|
|
1041
|
+
fs.closeSync(fd);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
function append(ctx) {
|
|
1045
|
+
const root = path.resolve(ctx.cwd, str(ctx.flags.root) ?? ".");
|
|
1046
|
+
const src = String(ctx.flags.rows);
|
|
1047
|
+
const read = readText(src === "-" ? 0 : path.resolve(ctx.cwd, src));
|
|
1048
|
+
if (!read.ok)
|
|
1049
|
+
throw new CommandError(EXIT.USAGE, `--rows unreadable: ${read.error}`);
|
|
1050
|
+
const text = read.text;
|
|
1051
|
+
if (text.trim() === "")
|
|
1052
|
+
throw new CommandError(EXIT.USAGE, "--rows holds no rows");
|
|
1053
|
+
const parsed = parseJson(text);
|
|
1054
|
+
if (!parsed.ok)
|
|
1055
|
+
throw new CommandError(EXIT.USAGE, "--rows is not JSON");
|
|
1056
|
+
const r = appendLedgerRows(root, String(ctx.flags.ledger), parsed.value);
|
|
1057
|
+
ctx.log(`appended ${r.appended} row(s) to ${r.file}`);
|
|
1058
|
+
ctx.emit({ ...r });
|
|
1059
|
+
return EXIT.OK;
|
|
1060
|
+
}
|
|
1061
|
+
const LEDGER_ROWS_LINE = /^\*\*Ledger rows:\*\*(.*)$/m;
|
|
1062
|
+
const CHECKED_LEDGERS = [APPEND_LEDGERS.decisions, APPEND_LEDGERS.deferrals];
|
|
1063
|
+
/**
|
|
1064
|
+
* Read the plan's `**Ledger rows:**` line — backticked keys, or `None` — and
|
|
1065
|
+
* return the keys no `decision` / `deferral` row carries. Throws EXIT_ROWS_MISSING
|
|
1066
|
+
* when the line is absent or still a placeholder.
|
|
1067
|
+
*/
|
|
1068
|
+
export function checkPlanRows(root, plan) {
|
|
1069
|
+
const abs = path.resolve(root, plan);
|
|
1070
|
+
if (!fs.existsSync(abs))
|
|
1071
|
+
throw new CommandError(EXIT.USAGE, `--plan not found: ${plan}`);
|
|
1072
|
+
const text = fs.readFileSync(abs, "utf-8");
|
|
1073
|
+
const line = LEDGER_ROWS_LINE.exec(text)?.[1]?.trim();
|
|
1074
|
+
if (line === undefined) {
|
|
1075
|
+
throw new CommandError(EXIT_ROWS_MISSING, `${plan} has no **Ledger rows:** line`);
|
|
1076
|
+
}
|
|
1077
|
+
const keys = [...line.matchAll(/`([^`]+)`/g)].map((m) => m[1] ?? "");
|
|
1078
|
+
if (keys.length === 0) {
|
|
1079
|
+
if (line.replace(/[."\s]/g, "") === "None")
|
|
1080
|
+
return { keys: [], missing: [] };
|
|
1081
|
+
throw new CommandError(EXIT_ROWS_MISSING, `${plan}: **Ledger rows:** is unfilled (${line})`);
|
|
1082
|
+
}
|
|
1083
|
+
const onDisk = new Set();
|
|
1084
|
+
for (const { file, kinds } of CHECKED_LEDGERS) {
|
|
1085
|
+
const abs = path.join(root, file);
|
|
1086
|
+
if (!fs.existsSync(abs))
|
|
1087
|
+
continue;
|
|
1088
|
+
for (const e of parse(fs.readFileSync(abs, "utf-8")).events) {
|
|
1089
|
+
const key = e.key;
|
|
1090
|
+
if (kinds.includes(e.kind) && typeof key === "string")
|
|
1091
|
+
onDisk.add(key);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return { keys, missing: keys.filter((k) => !onDisk.has(k)) };
|
|
1095
|
+
}
|
|
1096
|
+
function check(ctx) {
|
|
1097
|
+
const root = rootOf(ctx);
|
|
1098
|
+
const plan = String(ctx.flags.plan);
|
|
1099
|
+
const r = checkPlanRows(root, plan);
|
|
1100
|
+
ctx.emit({ plan, ...r });
|
|
1101
|
+
if (r.missing.length > 0) {
|
|
1102
|
+
ctx.log(`${plan}: no ledger row for ${r.missing.join(", ")}`);
|
|
1103
|
+
return EXIT_ROWS_MISSING;
|
|
1104
|
+
}
|
|
1105
|
+
ctx.log(`${plan}: ${r.keys.length} ledger row(s) on disk`);
|
|
1106
|
+
return EXIT.OK;
|
|
1107
|
+
}
|
|
394
1108
|
/** mkdir -p; the error text, or undefined on success. */
|
|
395
1109
|
function mkdirp(dir) {
|
|
396
1110
|
try {
|
|
@@ -402,6 +1116,27 @@ function mkdirp(dir) {
|
|
|
402
1116
|
return err.message;
|
|
403
1117
|
}
|
|
404
1118
|
}
|
|
1119
|
+
/** Append `text` to `file`; the error text, or undefined on success. */
|
|
1120
|
+
function appendText(file, text) {
|
|
1121
|
+
try {
|
|
1122
|
+
fs.appendFileSync(file, text);
|
|
1123
|
+
return undefined;
|
|
1124
|
+
}
|
|
1125
|
+
catch (err) {
|
|
1126
|
+
// Reported as the command's staging exit code, with the reason.
|
|
1127
|
+
return err.message;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
/** Read `file` (0 = stdin) as UTF-8; the text, or the error text. */
|
|
1131
|
+
function readText(file) {
|
|
1132
|
+
try {
|
|
1133
|
+
return { ok: true, text: fs.readFileSync(file, "utf-8") };
|
|
1134
|
+
}
|
|
1135
|
+
catch (err) {
|
|
1136
|
+
// Reported as a usage error, with the reason.
|
|
1137
|
+
return { ok: false, error: err.message };
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
405
1140
|
function copy(from, to) {
|
|
406
1141
|
try {
|
|
407
1142
|
fs.copyFileSync(from, to);
|