@cbartens/bkit 5.5.1 → 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 +35 -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 +19 -18
- 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 +91 -167
- package/.bkit/core/.bkit/providers.md +29 -32
- package/.bkit/core/.bkit/templates.md +12 -11
- package/.bkit/core/.bkit/trackers.md +51 -28
- package/.bkit/core/.bkit/workflows.md +394 -355
- 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 -29
- package/.bkit/core/engine/checks/after/github.ts +95 -17
- package/.bkit/core/engine/checks/after/index.ts +10 -7
- package/.bkit/core/engine/checks/after/suppression.ts +8 -5
- package/.bkit/core/engine/checks/after/tools.ts +46 -91
- 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 +6 -6
- 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 +407 -64
- 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 +58 -8
- 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 +185 -8
- 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 +250 -3
- 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 +157 -20
- 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 +29 -15
- 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 +32 -14
- 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 +72 -18
- 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 +29 -14
- 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 +27 -12
- 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 +41 -18
- 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 +11 -11
- 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 +16 -7
- 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 +1 -1
- package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
- package/.bkit/templates/.husky/pre-push +4 -4
- package/.bkit/templates/.prettierignore +7 -0
- package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
- package/CHANGELOG.md +112 -0
- package/README.md +50 -35
- package/dist/checks/after/ci-yml.js +39 -28
- package/dist/checks/after/github.js +91 -17
- package/dist/checks/after/index.js +11 -8
- package/dist/checks/after/suppression.js +8 -5
- package/dist/checks/after/tools.js +39 -82
- 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 +4 -4
- 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 +343 -59
- 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 -8
- 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 +147 -9
- package/dist/install/manifest.js +11 -9
- package/dist/install/modules/cloud.js +22 -13
- package/dist/install/modules/core.js +247 -3
- 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 +125 -17
- 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 +113 -24
- 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/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
|
|
@@ -12,8 +13,27 @@ import * as fs from "node:fs";
|
|
|
12
13
|
import * as os from "node:os";
|
|
13
14
|
import * as path from "node:path";
|
|
14
15
|
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
16
|
+
import { readBkitVersion } from "../../install/version-file.js";
|
|
17
|
+
import {
|
|
18
|
+
APPEND_LEDGERS,
|
|
19
|
+
SCHEMA,
|
|
20
|
+
gitEnv,
|
|
21
|
+
parse,
|
|
22
|
+
mintTs,
|
|
23
|
+
resolveRepoSlug,
|
|
24
|
+
validate,
|
|
25
|
+
writerProblem,
|
|
26
|
+
type AppendLedger,
|
|
27
|
+
} from "../../ledgers/telemetry.js";
|
|
28
|
+
import {
|
|
29
|
+
CommandError,
|
|
30
|
+
EXIT,
|
|
31
|
+
isSharedBranch,
|
|
32
|
+
parseJson,
|
|
33
|
+
type CommandSpec,
|
|
34
|
+
type FlagSpec,
|
|
35
|
+
type RunContext,
|
|
36
|
+
} from "../lib.js";
|
|
17
37
|
import { str } from "./status.js";
|
|
18
38
|
|
|
19
39
|
/** Root is not a directory or repo, git is too old, or a ref does not resolve. */
|
|
@@ -26,6 +46,8 @@ export const EXIT_COMMIT = 5;
|
|
|
26
46
|
export const EXIT_EMPTY = 6;
|
|
27
47
|
/** only-bookkeeping: a non-bookkeeping path changed, or from is not an ancestor of to. */
|
|
28
48
|
export const EXIT_NOT_BOOKKEEPING = 7;
|
|
49
|
+
/** append: a row was refused (supplied `ts`, wrong kind, invalid, unlisted writer). */
|
|
50
|
+
export const EXIT_ROW_REFUSED = 8;
|
|
29
51
|
|
|
30
52
|
const SCOPES = ["core", "full", "pr"] as const;
|
|
31
53
|
export type Scope = (typeof SCOPES)[number];
|
|
@@ -84,12 +106,18 @@ interface GitResult {
|
|
|
84
106
|
}
|
|
85
107
|
|
|
86
108
|
/** `git <args>` in `cwd`, never throwing and never trimming (NUL-delimited output). */
|
|
87
|
-
function gitRaw(
|
|
109
|
+
function gitRaw(
|
|
110
|
+
cwd: string,
|
|
111
|
+
args: string[],
|
|
112
|
+
env: NodeJS.ProcessEnv = {},
|
|
113
|
+
input?: string,
|
|
114
|
+
): GitResult {
|
|
88
115
|
const res = spawnSync("git", args, {
|
|
89
116
|
cwd,
|
|
90
117
|
encoding: "utf-8",
|
|
91
|
-
env: gitEnv(),
|
|
118
|
+
env: { ...gitEnv(), ...env },
|
|
92
119
|
maxBuffer: 1 << 28,
|
|
120
|
+
...(input === undefined ? {} : { input }),
|
|
93
121
|
});
|
|
94
122
|
// A spawn error is never a success: the child can exit 0 before ENOBUFS kills it.
|
|
95
123
|
const status = res.error && res.status === 0 ? 1 : res.status;
|
|
@@ -152,6 +180,472 @@ function dirtyTracked(root: string): string[] {
|
|
|
152
180
|
.filter((l) => l !== "" && !l.startsWith("??"));
|
|
153
181
|
}
|
|
154
182
|
|
|
183
|
+
// ---------------------------------------------------------------------------
|
|
184
|
+
// Shared-checkout record — the one home
|
|
185
|
+
// ---------------------------------------------------------------------------
|
|
186
|
+
//
|
|
187
|
+
// An in-place run on `dev` shares its checkout with whatever else is dirty or
|
|
188
|
+
// committed there. At `worktrees setup` the run snapshots which paths were
|
|
189
|
+
// already dirty (and the HEAD it started from) into a per-clone file under the
|
|
190
|
+
// git dir, never committed. Every commit the run makes goes through
|
|
191
|
+
// `ownPathCommit`, which leaves those paths alone, and records its SHA so the
|
|
192
|
+
// push sends exactly the run's commits. Nothing else reads or writes the file.
|
|
193
|
+
|
|
194
|
+
/** Exit code: a path that was dirty before the run changed during it, so no commit was made. */
|
|
195
|
+
export const EXIT_FOREIGN_PATH = 10;
|
|
196
|
+
|
|
197
|
+
/** check: the plan has no `**Ledger rows:**` line, it is unfilled, or a key it names is on no ledger. */
|
|
198
|
+
export const EXIT_ROWS_MISSING = 11;
|
|
199
|
+
|
|
200
|
+
/** commit --scope=pr: the checkout is on `dev`, `main` or a detached HEAD, so nothing is committed. */
|
|
201
|
+
export const EXIT_SHARED_BRANCH = 12;
|
|
202
|
+
|
|
203
|
+
/** A path dirty at the run's start: its content hash (null when deleted) and, for an append-only ledger, its line count. */
|
|
204
|
+
export interface RecordedPath {
|
|
205
|
+
path: string;
|
|
206
|
+
hash: string | null;
|
|
207
|
+
lines?: number;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export interface SharedCheckoutRecord {
|
|
211
|
+
fid: string;
|
|
212
|
+
branch: string;
|
|
213
|
+
startSha: string;
|
|
214
|
+
originSha: string | null;
|
|
215
|
+
aheadAtStart: number;
|
|
216
|
+
paths: RecordedPath[];
|
|
217
|
+
/** SHAs of the commits the run made, in order. */
|
|
218
|
+
commits: string[];
|
|
219
|
+
/** Run commits already landed on origin/dev as replayed copies (different SHAs there). */
|
|
220
|
+
pushed?: string[];
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const RECORD_DIR = "bkit/shared-checkout";
|
|
224
|
+
const RECORD_FID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
225
|
+
|
|
226
|
+
/** The checkout's top: git status and pathspecs are relative to it, whatever `cwd` is. */
|
|
227
|
+
function topOf(cwd: string): string {
|
|
228
|
+
const top = gitRaw(cwd, ["rev-parse", "--show-toplevel"]);
|
|
229
|
+
return top.status === 0 ? top.stdout.trim() : cwd;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** `$(git rev-parse --git-path bkit/shared-checkout/{sub})`, absolute; null outside a repo. */
|
|
233
|
+
function recordPathOf(cwd: string, sub: string): string | null {
|
|
234
|
+
const res = gitRaw(cwd, ["rev-parse", "--git-path", `${RECORD_DIR}/${sub}`]);
|
|
235
|
+
return res.status === 0 && res.stdout.trim() !== "" ? path.resolve(cwd, res.stdout.trim()) : null;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const recordFile = (cwd: string, fid: string): string | null =>
|
|
239
|
+
RECORD_FID.test(fid) && !fid.includes("..") ? recordPathOf(cwd, `${fid}.json`) : null;
|
|
240
|
+
|
|
241
|
+
function asRecord(value: unknown): SharedCheckoutRecord | null {
|
|
242
|
+
if (typeof value !== "object" || value === null) return null;
|
|
243
|
+
const r = value as Record<string, unknown>;
|
|
244
|
+
if (
|
|
245
|
+
typeof r.fid !== "string" ||
|
|
246
|
+
typeof r.branch !== "string" ||
|
|
247
|
+
typeof r.startSha !== "string" ||
|
|
248
|
+
typeof r.aheadAtStart !== "number" ||
|
|
249
|
+
!Array.isArray(r.paths) ||
|
|
250
|
+
!Array.isArray(r.commits)
|
|
251
|
+
)
|
|
252
|
+
return null;
|
|
253
|
+
return {
|
|
254
|
+
fid: r.fid,
|
|
255
|
+
branch: r.branch,
|
|
256
|
+
startSha: r.startSha,
|
|
257
|
+
originSha: typeof r.originSha === "string" ? r.originSha : null,
|
|
258
|
+
aheadAtStart: r.aheadAtStart,
|
|
259
|
+
paths: (r.paths as RecordedPath[]).filter((p) => typeof p?.path === "string"),
|
|
260
|
+
commits: (r.commits as unknown[]).filter((c): c is string => typeof c === "string"),
|
|
261
|
+
...(Array.isArray(r.pushed)
|
|
262
|
+
? { pushed: (r.pushed as unknown[]).filter((c): c is string => typeof c === "string") }
|
|
263
|
+
: {}),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** The FID's record, or null when absent or unreadable. */
|
|
268
|
+
export function readRecord(cwd: string, fid: string): SharedCheckoutRecord | null {
|
|
269
|
+
const file = recordFile(cwd, fid);
|
|
270
|
+
if (file === null || !fs.existsSync(file)) return null;
|
|
271
|
+
const parsed = parseJson(fs.readFileSync(file, "utf-8"));
|
|
272
|
+
return parsed.ok ? asRecord(parsed.value) : null;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Note run commits that now sit on origin/dev as replayed copies, so a later push skips them. */
|
|
276
|
+
export function markRecordPushed(cwd: string, fid: string, shas: string[]): void {
|
|
277
|
+
const rec = readRecord(cwd, fid);
|
|
278
|
+
if (rec === null) return;
|
|
279
|
+
writeRecord(cwd, { ...rec, pushed: [...new Set([...(rec.pushed ?? []), ...shas])] });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Every record in this clone. */
|
|
283
|
+
export function listRecords(cwd: string): SharedCheckoutRecord[] {
|
|
284
|
+
const dir = recordPathOf(cwd, "");
|
|
285
|
+
if (dir === null || !fs.existsSync(dir)) return [];
|
|
286
|
+
return fs
|
|
287
|
+
.readdirSync(dir)
|
|
288
|
+
.filter((f) => f.endsWith(".json"))
|
|
289
|
+
.map((f) => readRecord(cwd, f.slice(0, -".json".length)))
|
|
290
|
+
.filter((r): r is SharedCheckoutRecord => r !== null);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function writeRecord(cwd: string, rec: SharedCheckoutRecord): void {
|
|
294
|
+
const file = recordFile(cwd, rec.fid);
|
|
295
|
+
if (file === null) throw new CommandError(EXIT_ROOT, `cannot place a record for "${rec.fid}"`);
|
|
296
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
297
|
+
fs.writeFileSync(file, `${JSON.stringify(rec, null, 2)}\n`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** A setup guard older than this is a crashed setup's leftover. */
|
|
301
|
+
const SETUP_GUARD_STALE_MS = 30_000;
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Run `fn` as the only record-setup in this clone: an exclusive-create guard file
|
|
305
|
+
* next to the records makes the busy check and the record write one step. Returns
|
|
306
|
+
* null, without running `fn`, when another setup holds a fresh guard.
|
|
307
|
+
*/
|
|
308
|
+
export function withSetupGuard<T>(cwd: string, fn: () => T): { value: T } | null {
|
|
309
|
+
const guard = recordPathOf(cwd, ".setup.lock");
|
|
310
|
+
if (guard === null) return { value: fn() };
|
|
311
|
+
fs.mkdirSync(path.dirname(guard), { recursive: true });
|
|
312
|
+
const take = (): boolean => {
|
|
313
|
+
try {
|
|
314
|
+
fs.closeSync(fs.openSync(guard, "wx"));
|
|
315
|
+
return true;
|
|
316
|
+
} catch (err) {
|
|
317
|
+
if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
|
|
318
|
+
throw err;
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
if (!take()) {
|
|
322
|
+
const age = fs.existsSync(guard) ? Date.now() - fs.statSync(guard).mtimeMs : Infinity;
|
|
323
|
+
if (age < SETUP_GUARD_STALE_MS) return null;
|
|
324
|
+
fs.rmSync(guard, { force: true });
|
|
325
|
+
if (!take()) return null;
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
return { value: fn() };
|
|
329
|
+
} finally {
|
|
330
|
+
fs.rmSync(guard, { force: true });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Remove the FID's record; false when there was none. */
|
|
335
|
+
export function removeRecord(cwd: string, fid: string): boolean {
|
|
336
|
+
const file = recordFile(cwd, fid);
|
|
337
|
+
if (file === null || !fs.existsSync(file)) return false;
|
|
338
|
+
fs.rmSync(file, { force: true });
|
|
339
|
+
return true;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** The FID's record, only while its branch is still the one checked out. */
|
|
343
|
+
export function activeRecord(cwd: string, fid: string): SharedCheckoutRecord | null {
|
|
344
|
+
const rec = readRecord(cwd, fid);
|
|
345
|
+
if (rec === null) return null;
|
|
346
|
+
const here = gitRaw(cwd, ["branch", "--show-current"]).stdout.trim();
|
|
347
|
+
return here === rec.branch ? rec : null;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The record of the run in place on `branch`, for a command that is not told
|
|
352
|
+
* its FID (the push). Setup keeps one live record per clone; if several are left
|
|
353
|
+
* over, the one written last wins.
|
|
354
|
+
*/
|
|
355
|
+
export function recordOnBranch(cwd: string, branch: string): SharedCheckoutRecord | null {
|
|
356
|
+
const dir = recordPathOf(cwd, "");
|
|
357
|
+
const written = (r: SharedCheckoutRecord) => {
|
|
358
|
+
const file = recordFile(cwd, r.fid);
|
|
359
|
+
return file !== null && fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0;
|
|
360
|
+
};
|
|
361
|
+
const ours = listRecords(cwd).filter((r) => r.branch === branch);
|
|
362
|
+
if (dir === null || ours.length === 0) return null;
|
|
363
|
+
return ours.reduce((a, b) => (written(b) > written(a) ? b : a));
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Append a commit the run made; called only after the commit succeeded. */
|
|
367
|
+
export function appendRecordCommit(cwd: string, fid: string, sha: string): void {
|
|
368
|
+
const rec = readRecord(cwd, fid);
|
|
369
|
+
if (rec === null || rec.commits.includes(sha)) return;
|
|
370
|
+
writeRecord(cwd, { ...rec, commits: [...rec.commits, sha] });
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Paths git reports as changed or untracked, relative to the top, one per file. */
|
|
374
|
+
function dirtyPaths(top: string): string[] {
|
|
375
|
+
const res = gitRaw(top, ["status", "--porcelain", "-z", "-uall", "--no-renames"]);
|
|
376
|
+
return nulList(res.stdout)
|
|
377
|
+
.filter((e) => e.length > 3 && !e.startsWith("!!"))
|
|
378
|
+
.map((e) => e.slice(3));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** `git hash-object` of the working file; null when it is gone. */
|
|
382
|
+
function hashOf(top: string, rel: string): string | null {
|
|
383
|
+
const abs = path.join(top, rel);
|
|
384
|
+
if (!fs.existsSync(abs)) return null;
|
|
385
|
+
if (!fs.statSync(abs).isFile()) return "not-a-file";
|
|
386
|
+
const res = gitRaw(top, ["hash-object", "--", rel]);
|
|
387
|
+
return res.status === 0 ? res.stdout.trim() : "unhashable";
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** A text's non-blank lines. */
|
|
391
|
+
const rowsOf = (text: string) => text.split("\n").filter((l) => l.trim() !== "");
|
|
392
|
+
|
|
393
|
+
/** Lines of `file` in `cwd`'s working copy that its HEAD blob lacks (compared trimmed). */
|
|
394
|
+
export function rowsHeadLacks(cwd: string, file: string): string[] {
|
|
395
|
+
const head = new Set(rowsOf(gitRaw(cwd, ["show", `HEAD:${file}`]).stdout).map((l) => l.trim()));
|
|
396
|
+
return rowsOf(fs.readFileSync(path.join(cwd, file), "utf-8")).filter((l) => !head.has(l.trim()));
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Rows of `file` the run appended: lines HEAD lacks, and past the recorded line
|
|
401
|
+
* count when the run's record holds the file (rows before it are someone else's).
|
|
402
|
+
*/
|
|
403
|
+
export function runRows(cwd: string, file: string, rec: SharedCheckoutRecord | null): string[] {
|
|
404
|
+
const was = rec?.paths.find((p) => p.path === file);
|
|
405
|
+
if (was?.lines === undefined) return rowsHeadLacks(cwd, file);
|
|
406
|
+
const head = gitRaw(cwd, ["show", `HEAD:${file}`]);
|
|
407
|
+
const have = new Set(rowsOf(head.status === 0 ? head.stdout : "").map((l) => l.trim()));
|
|
408
|
+
const lines = fs.readFileSync(path.join(cwd, file), "utf-8").split("\n").slice(was.lines);
|
|
409
|
+
return rowsOf(lines.join("\n")).filter((l) => !have.has(l.trim()));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** The record for a run starting now in `cwd` on `branch`. */
|
|
413
|
+
export function newRecord(cwd: string, fid: string, branch: string): SharedCheckoutRecord {
|
|
414
|
+
const top = topOf(cwd);
|
|
415
|
+
const startSha = gitRaw(top, ["rev-parse", "HEAD"]).stdout.trim();
|
|
416
|
+
const origin = gitRaw(top, ["rev-parse", "-q", "--verify", `refs/remotes/origin/${branch}`]);
|
|
417
|
+
const originSha = origin.status === 0 ? origin.stdout.trim() : null;
|
|
418
|
+
const ahead =
|
|
419
|
+
originSha === null
|
|
420
|
+
? 0
|
|
421
|
+
: Number(gitRaw(top, ["rev-list", "--count", `${originSha}..HEAD`]).stdout);
|
|
422
|
+
const paths = dirtyPaths(top).map((rel): RecordedPath => {
|
|
423
|
+
const hash = hashOf(top, rel);
|
|
424
|
+
const abs = path.join(top, rel);
|
|
425
|
+
const text = hash !== null && rel.endsWith(".jsonl") ? fs.readFileSync(abs, "utf-8") : null;
|
|
426
|
+
return text !== null && (text === "" || text.endsWith("\n"))
|
|
427
|
+
? { path: rel, hash, lines: fileLines(text).length }
|
|
428
|
+
: { path: rel, hash };
|
|
429
|
+
});
|
|
430
|
+
return { fid, branch, startSha, originSha, aheadAtStart: ahead, paths, commits: [] };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** What a run may commit now: whole files, and recorded ledgers cut down to the run's rows. */
|
|
434
|
+
export interface OwnSet {
|
|
435
|
+
plain: string[];
|
|
436
|
+
ledgers: Array<{ path: string; text: string }>;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* The paths that are the run's own: dirty now, minus every recorded path. A
|
|
441
|
+
* recorded append-only ledger contributes only the rows appended after the
|
|
442
|
+
* recorded line count that HEAD lacks. Any other recorded path whose content
|
|
443
|
+
* changed, or a ledger whose recorded lines changed, throws EXIT_FOREIGN_PATH.
|
|
444
|
+
* `among` limits which recorded paths count (a bookkeeping commit only commits
|
|
445
|
+
* its allow-list).
|
|
446
|
+
*/
|
|
447
|
+
export function ownSet(cwd: string, rec: SharedCheckoutRecord, among?: string[]): OwnSet {
|
|
448
|
+
const top = topOf(cwd);
|
|
449
|
+
const recorded = new Map(rec.paths.map((p) => [p.path, p]));
|
|
450
|
+
const out: OwnSet = { plain: [], ledgers: [] };
|
|
451
|
+
const foreign: string[] = [];
|
|
452
|
+
for (const rel of dirtyPaths(top)) {
|
|
453
|
+
const was = recorded.get(rel);
|
|
454
|
+
if (was === undefined) {
|
|
455
|
+
out.plain.push(rel);
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
if (among !== undefined && !among.includes(rel)) continue;
|
|
459
|
+
if (hashOf(top, rel) === was.hash) continue;
|
|
460
|
+
if (was.lines === undefined) {
|
|
461
|
+
foreign.push(rel);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const text = fs.readFileSync(path.join(top, rel), "utf-8");
|
|
465
|
+
const lines = text.split("\n");
|
|
466
|
+
const prefix = `${lines.slice(0, was.lines).join("\n")}\n`;
|
|
467
|
+
// `--path` applies the same clean / eol filters `hashOf` hashed the file with.
|
|
468
|
+
const prefixHash = gitRaw(
|
|
469
|
+
top,
|
|
470
|
+
["hash-object", `--path=${rel}`, "--stdin"],
|
|
471
|
+
{},
|
|
472
|
+
prefix,
|
|
473
|
+
).stdout.trim();
|
|
474
|
+
if (was.lines > 0 && prefixHash !== was.hash) {
|
|
475
|
+
foreign.push(rel);
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
const own = runRows(top, rel, rec);
|
|
479
|
+
if (own.length === 0) continue;
|
|
480
|
+
const head = gitRaw(top, ["show", `HEAD:${rel}`]);
|
|
481
|
+
const base = head.status === 0 ? head.stdout : "";
|
|
482
|
+
const sep = base === "" || base.endsWith("\n") ? "" : "\n";
|
|
483
|
+
out.ledgers.push({ path: rel, text: `${base}${sep}${own.join("\n")}\n` });
|
|
484
|
+
}
|
|
485
|
+
if (foreign.length > 0) {
|
|
486
|
+
throw new CommandError(
|
|
487
|
+
EXIT_FOREIGN_PATH,
|
|
488
|
+
`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`,
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
return out;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export type OwnCommit = { ok: true; sha: string | null } | { ok: false; error: string };
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Rebuild the real index entry of a ledger the user staged before the run: the
|
|
498
|
+
* new HEAD blob plus the staged rows HEAD lacks, so the user's next plain commit
|
|
499
|
+
* keeps the run's committed rows.
|
|
500
|
+
*/
|
|
501
|
+
function restageLedger(top: string, rel: string): void {
|
|
502
|
+
const staged = gitRaw(top, ["show", `:${rel}`]);
|
|
503
|
+
const head = gitRaw(top, ["show", `HEAD:${rel}`]);
|
|
504
|
+
if (staged.status !== 0 || head.status !== 0) return;
|
|
505
|
+
const have = new Set(rowsOf(head.stdout).map((l) => l.trim()));
|
|
506
|
+
const theirs = rowsOf(staged.stdout).filter((l) => !have.has(l.trim()));
|
|
507
|
+
if (theirs.length === 0) {
|
|
508
|
+
gitRaw(top, ["reset", "-q", "--", rel]);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const sep = head.stdout === "" || head.stdout.endsWith("\n") ? "" : "\n";
|
|
512
|
+
const blob = gitRaw(
|
|
513
|
+
top,
|
|
514
|
+
["hash-object", "-w", "--stdin"],
|
|
515
|
+
{},
|
|
516
|
+
`${head.stdout}${sep}${theirs.join("\n")}\n`,
|
|
517
|
+
);
|
|
518
|
+
if (blob.status !== 0) return;
|
|
519
|
+
gitRaw(top, ["update-index", "--cacheinfo", `100644,${blob.stdout.trim()},${rel}`]);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Commit `set` and nothing else: foreign index entries stay staged and foreign
|
|
524
|
+
* files stay out. Plain files go through a pathspec commit; ledger rows, or an
|
|
525
|
+
* empty set, go through a temporary index read from HEAD. With `skipIfEmpty`, no
|
|
526
|
+
* change against HEAD makes no commit (`sha` null). The caller records the SHA.
|
|
527
|
+
*/
|
|
528
|
+
export function commitOwnSet(
|
|
529
|
+
cwd: string,
|
|
530
|
+
set: OwnSet,
|
|
531
|
+
message: string,
|
|
532
|
+
o: { allowEmpty?: boolean; skipIfEmpty?: boolean } = {},
|
|
533
|
+
): OwnCommit {
|
|
534
|
+
const top = topOf(cwd);
|
|
535
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-own-"));
|
|
536
|
+
try {
|
|
537
|
+
const list = path.join(tmp, "list");
|
|
538
|
+
const all = [...set.plain, ...set.ledgers.map((l) => l.path)];
|
|
539
|
+
fs.writeFileSync(list, all.map((p) => `${p}\0`).join(""));
|
|
540
|
+
const stagedBefore = new Set(
|
|
541
|
+
nulList(gitRaw(top, ["diff", "--cached", "--name-only", "-z"]).stdout),
|
|
542
|
+
);
|
|
543
|
+
const tail = ["-m", message];
|
|
544
|
+
let made: GitResult;
|
|
545
|
+
if (set.ledgers.length === 0 && set.plain.length > 0) {
|
|
546
|
+
const add = gitRaw(top, ["add", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
|
|
547
|
+
if (add.status !== 0) return { ok: false, error: `'git add' failed: ${add.stderr}` };
|
|
548
|
+
if (
|
|
549
|
+
o.skipIfEmpty === true &&
|
|
550
|
+
gitRaw(top, ["diff", "--cached", "--quiet", "--", ...set.plain]).status === 0
|
|
551
|
+
)
|
|
552
|
+
return { ok: true, sha: null };
|
|
553
|
+
made = gitRaw(top, [
|
|
554
|
+
"commit",
|
|
555
|
+
...(o.allowEmpty === true ? ["--allow-empty"] : []),
|
|
556
|
+
`--pathspec-from-file=${list}`,
|
|
557
|
+
"--pathspec-file-nul",
|
|
558
|
+
...tail,
|
|
559
|
+
]);
|
|
560
|
+
} else {
|
|
561
|
+
const env = { GIT_INDEX_FILE: path.join(tmp, "index") };
|
|
562
|
+
if (gitRaw(top, ["rev-parse", "-q", "--verify", "HEAD"]).status === 0) {
|
|
563
|
+
const read = gitRaw(top, ["read-tree", "HEAD"], env);
|
|
564
|
+
if (read.status !== 0)
|
|
565
|
+
return { ok: false, error: `'git read-tree' failed: ${read.stderr}` };
|
|
566
|
+
}
|
|
567
|
+
if (set.plain.length > 0) {
|
|
568
|
+
const add = gitRaw(
|
|
569
|
+
top,
|
|
570
|
+
["add", `--pathspec-from-file=${list}`, "--pathspec-file-nul"],
|
|
571
|
+
env,
|
|
572
|
+
);
|
|
573
|
+
if (add.status !== 0) return { ok: false, error: `'git add' failed: ${add.stderr}` };
|
|
574
|
+
}
|
|
575
|
+
for (const l of set.ledgers) {
|
|
576
|
+
const blob = gitRaw(top, ["hash-object", "-w", "--stdin"], env, l.text);
|
|
577
|
+
const upd = gitRaw(
|
|
578
|
+
top,
|
|
579
|
+
["update-index", "--add", "--cacheinfo", `100644,${blob.stdout.trim()},${l.path}`],
|
|
580
|
+
env,
|
|
581
|
+
);
|
|
582
|
+
if (blob.status !== 0 || upd.status !== 0) {
|
|
583
|
+
return { ok: false, error: `'git update-index' failed: ${upd.stderr || blob.stderr}` };
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
if (o.skipIfEmpty === true && gitRaw(top, ["diff", "--cached", "--quiet"], env).status === 0)
|
|
587
|
+
return { ok: true, sha: null };
|
|
588
|
+
made = gitRaw(
|
|
589
|
+
top,
|
|
590
|
+
["commit", ...(o.allowEmpty === true ? ["--allow-empty"] : []), ...tail],
|
|
591
|
+
env,
|
|
592
|
+
);
|
|
593
|
+
if (made.status === 0 && all.length > 0) {
|
|
594
|
+
// The real index still holds the pre-commit entries; bring the run's own
|
|
595
|
+
// (unstaged-by-anyone-else) paths level with the new HEAD.
|
|
596
|
+
const reset = all.filter((p) => !stagedBefore.has(p));
|
|
597
|
+
fs.writeFileSync(list, reset.map((p) => `${p}\0`).join(""));
|
|
598
|
+
if (reset.length > 0) {
|
|
599
|
+
gitRaw(top, ["reset", "-q", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
|
|
600
|
+
}
|
|
601
|
+
// A ledger the user had staged keeps their rows in the index, on top of the new HEAD's.
|
|
602
|
+
for (const l of set.ledgers) if (stagedBefore.has(l.path)) restageLedger(top, l.path);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (made.status !== 0) {
|
|
606
|
+
// Leave the index as it was: unstage what this attempt staged, never another's entry.
|
|
607
|
+
const unstage = all.filter((p) => !stagedBefore.has(p));
|
|
608
|
+
fs.writeFileSync(list, unstage.map((p) => `${p}\0`).join(""));
|
|
609
|
+
if (unstage.length > 0)
|
|
610
|
+
gitRaw(top, ["reset", "-q", `--pathspec-from-file=${list}`, "--pathspec-file-nul"]);
|
|
611
|
+
return { ok: false, error: made.stderr || made.stdout.trim() };
|
|
612
|
+
}
|
|
613
|
+
return { ok: true, sha: gitRaw(top, ["rev-parse", "HEAD"]).stdout.trim() };
|
|
614
|
+
} finally {
|
|
615
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* The run's own-path commit: compute the own set from the record, commit it,
|
|
621
|
+
* append the SHA to the record. Throws EXIT_FOREIGN_PATH before committing.
|
|
622
|
+
*/
|
|
623
|
+
export function ownPathCommit(
|
|
624
|
+
cwd: string,
|
|
625
|
+
rec: SharedCheckoutRecord,
|
|
626
|
+
message: string,
|
|
627
|
+
o: { allowEmpty?: boolean } = {},
|
|
628
|
+
): OwnCommit {
|
|
629
|
+
const made = commitOwnSet(cwd, ownSet(cwd, rec), message, o);
|
|
630
|
+
if (made.ok && made.sha !== null) appendRecordCommit(cwd, rec.fid, made.sha);
|
|
631
|
+
return made;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* An empty commit of the run's own: nothing from the working tree or the real
|
|
636
|
+
* index goes in, so a path the user staged never lands in it. The SHA is
|
|
637
|
+
* appended to the record.
|
|
638
|
+
*/
|
|
639
|
+
export function retriggerCommit(
|
|
640
|
+
cwd: string,
|
|
641
|
+
rec: SharedCheckoutRecord,
|
|
642
|
+
message: string,
|
|
643
|
+
): OwnCommit {
|
|
644
|
+
const made = commitOwnSet(cwd, { plain: [], ledgers: [] }, message, { allowEmpty: true });
|
|
645
|
+
if (made.ok && made.sha !== null) appendRecordCommit(cwd, rec.fid, made.sha);
|
|
646
|
+
return made;
|
|
647
|
+
}
|
|
648
|
+
|
|
155
649
|
// ---------------------------------------------------------------------------
|
|
156
650
|
// Command
|
|
157
651
|
// ---------------------------------------------------------------------------
|
|
@@ -170,8 +664,7 @@ export const ledgersCommand: CommandSpec = {
|
|
|
170
664
|
{
|
|
171
665
|
name: "scope",
|
|
172
666
|
type: "string",
|
|
173
|
-
|
|
174
|
-
help: "core (logs + ledgers) | full (+ docs ledgers, skills) | pr (+ top-level docs/*.md)",
|
|
667
|
+
help: "core (logs + ledgers) | full (+ docs ledgers, skills) | pr (+ top-level docs/*.md); not with --path",
|
|
175
668
|
},
|
|
176
669
|
{
|
|
177
670
|
name: "mode",
|
|
@@ -182,7 +675,12 @@ export const ledgersCommand: CommandSpec = {
|
|
|
182
675
|
{
|
|
183
676
|
name: "stage-tracked-updates",
|
|
184
677
|
type: "boolean",
|
|
185
|
-
help: "run `git add -u` first (stages every tracked change)",
|
|
678
|
+
help: "run `git add -u` first (stages every tracked change; commit modes commit them too)",
|
|
679
|
+
},
|
|
680
|
+
{
|
|
681
|
+
name: "path",
|
|
682
|
+
type: "string",
|
|
683
|
+
help: "commit this one path alone, relative to --root (commit modes only; no --scope)",
|
|
186
684
|
},
|
|
187
685
|
{
|
|
188
686
|
name: "squash-of",
|
|
@@ -200,7 +698,8 @@ export const ledgersCommand: CommandSpec = {
|
|
|
200
698
|
outcome:
|
|
201
699
|
"committed | staged | nothing-to-commit | clean (no tracked changes, with --only-if-dirty-tracked)",
|
|
202
700
|
commit: "the new commit's sha, or null",
|
|
203
|
-
paths: "bookkeeping paths the allow-list matched",
|
|
701
|
+
paths: "bookkeeping paths the allow-list matched (the --path alone with --path)",
|
|
702
|
+
tracked: "tracked paths --stage-tracked-updates staged into the commit",
|
|
204
703
|
squashPaths: "paths the --squash-of ref brought in",
|
|
205
704
|
},
|
|
206
705
|
exitCodes: {
|
|
@@ -208,7 +707,12 @@ export const ledgersCommand: CommandSpec = {
|
|
|
208
707
|
"root not a directory or git repo, git < 2.25, or --squash-of does not resolve",
|
|
209
708
|
[EXIT_STAGE]: "staging failed (git add / git add -u)",
|
|
210
709
|
[EXIT_COMMIT]: "git commit failed",
|
|
211
|
-
[EXIT_EMPTY]:
|
|
710
|
+
[EXIT_EMPTY]:
|
|
711
|
+
"the allow-list matched nothing — refusing to commit the whole index; or --path is outside the checkout",
|
|
712
|
+
[EXIT_FOREIGN_PATH]:
|
|
713
|
+
"an in-place run's allow-listed path was already modified before the run and changed during it — nothing committed",
|
|
714
|
+
[EXIT_SHARED_BRANCH]:
|
|
715
|
+
"--scope=pr commit on dev, main or a detached HEAD — refused, nothing committed",
|
|
212
716
|
},
|
|
213
717
|
run: (ctx) => commit(ctx),
|
|
214
718
|
},
|
|
@@ -246,6 +750,54 @@ export const ledgersCommand: CommandSpec = {
|
|
|
246
750
|
},
|
|
247
751
|
run: (ctx) => onlyBookkeeping(ctx),
|
|
248
752
|
},
|
|
753
|
+
append: {
|
|
754
|
+
summary: "Append validated rows to one ledger, minting each row's ts at append time.",
|
|
755
|
+
flags: [
|
|
756
|
+
{ name: "root", type: "string", help: "checkout whose ledger to append to (default: cwd)" },
|
|
757
|
+
{
|
|
758
|
+
name: "ledger",
|
|
759
|
+
type: "string",
|
|
760
|
+
required: true,
|
|
761
|
+
help: Object.keys(APPEND_LEDGERS).join(" | "),
|
|
762
|
+
},
|
|
763
|
+
{
|
|
764
|
+
name: "rows",
|
|
765
|
+
type: "string",
|
|
766
|
+
required: true,
|
|
767
|
+
help: "file holding a JSON array of rows without schema, ts or bkit, or - for stdin",
|
|
768
|
+
},
|
|
769
|
+
],
|
|
770
|
+
output: {
|
|
771
|
+
ledger: "the ledger appended to",
|
|
772
|
+
file: "its path, relative to --root",
|
|
773
|
+
appended: "rows written",
|
|
774
|
+
keys: "each row's key, in order (null when a row has none)",
|
|
775
|
+
},
|
|
776
|
+
exitCodes: {
|
|
777
|
+
[EXIT_STAGE]: "mkdir or append failed",
|
|
778
|
+
[EXIT_ROW_REFUSED]:
|
|
779
|
+
"a row carries ts, has the wrong kind, fails validation, or names a writer not listed for its kind — nothing written",
|
|
780
|
+
},
|
|
781
|
+
run: (ctx) => append(ctx),
|
|
782
|
+
},
|
|
783
|
+
check: {
|
|
784
|
+
summary:
|
|
785
|
+
"Check that every decision / deferral key on a plan's `**Ledger rows:**` line is on disk.",
|
|
786
|
+
flags: [
|
|
787
|
+
{ name: "root", type: "string", help: "checkout whose ledgers to read (default: cwd)" },
|
|
788
|
+
{ name: "plan", type: "string", required: true, help: "plan file, relative to --root" },
|
|
789
|
+
],
|
|
790
|
+
output: {
|
|
791
|
+
plan: "the plan checked",
|
|
792
|
+
keys: "the keys its Ledger rows line names (empty for None)",
|
|
793
|
+
missing: "keys on neither docs/decisions.jsonl nor docs/deferrals.jsonl",
|
|
794
|
+
},
|
|
795
|
+
exitCodes: {
|
|
796
|
+
[EXIT_ROWS_MISSING]:
|
|
797
|
+
"no `**Ledger rows:**` line, the line is unfilled, or a key it names has no row",
|
|
798
|
+
},
|
|
799
|
+
run: (ctx) => check(ctx),
|
|
800
|
+
},
|
|
249
801
|
},
|
|
250
802
|
};
|
|
251
803
|
|
|
@@ -260,6 +812,8 @@ export interface BookkeepingCommit {
|
|
|
260
812
|
stageTrackedUpdates?: boolean;
|
|
261
813
|
squashOf?: string;
|
|
262
814
|
onlyIfDirtyTracked?: boolean;
|
|
815
|
+
/** Commit this one path alone (commit modes only). */
|
|
816
|
+
path?: string;
|
|
263
817
|
}
|
|
264
818
|
|
|
265
819
|
export interface BookkeepingResult {
|
|
@@ -267,6 +821,51 @@ export interface BookkeepingResult {
|
|
|
267
821
|
commit: string | null;
|
|
268
822
|
paths: string[];
|
|
269
823
|
squashPaths: string[];
|
|
824
|
+
tracked: string[];
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Commit one named path alone: `git add` it, then `git commit -- <path>`. */
|
|
828
|
+
function commitOnePath(o: BookkeepingCommit, log: (m: string) => void): BookkeepingResult {
|
|
829
|
+
const { root, mode, message } = o;
|
|
830
|
+
const rel = o.path!;
|
|
831
|
+
const abs = path.resolve(root, rel);
|
|
832
|
+
const inside = path.relative(root, abs);
|
|
833
|
+
if (inside === "" || inside.startsWith("..") || path.isAbsolute(inside)) {
|
|
834
|
+
throw new CommandError(EXIT_EMPTY, `--path is outside the checkout: ${rel}`);
|
|
835
|
+
}
|
|
836
|
+
const done = (outcome: BookkeepingResult["outcome"], sha: string | null): BookkeepingResult => ({
|
|
837
|
+
outcome,
|
|
838
|
+
commit: sha,
|
|
839
|
+
paths: [inside],
|
|
840
|
+
squashPaths: [],
|
|
841
|
+
tracked: [],
|
|
842
|
+
});
|
|
843
|
+
const add = gitRaw(root, ["add", "--", inside]);
|
|
844
|
+
if (add.status !== 0) throw new CommandError(EXIT_STAGE, `'git add' failed: ${add.stderr}`);
|
|
845
|
+
if (
|
|
846
|
+
mode === "commit" &&
|
|
847
|
+
gitRaw(root, ["diff", "--cached", "--quiet", "--", inside]).status === 0
|
|
848
|
+
) {
|
|
849
|
+
log(`nothing to commit at ${inside}`);
|
|
850
|
+
return done("nothing-to-commit", null);
|
|
851
|
+
}
|
|
852
|
+
const made = gitRaw(root, [
|
|
853
|
+
"commit",
|
|
854
|
+
...(mode === "commit-allow-empty" ? ["--allow-empty"] : []),
|
|
855
|
+
"-m",
|
|
856
|
+
message!,
|
|
857
|
+
"--",
|
|
858
|
+
inside,
|
|
859
|
+
]);
|
|
860
|
+
if (made.status !== 0) {
|
|
861
|
+
throw new CommandError(
|
|
862
|
+
EXIT_COMMIT,
|
|
863
|
+
`'git commit' failed: ${made.stderr || made.stdout.trim()}`,
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
const sha = gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim();
|
|
867
|
+
if (activeRecord(root, o.fid) !== null) appendRecordCommit(root, o.fid, sha);
|
|
868
|
+
return done("committed", sha);
|
|
270
869
|
}
|
|
271
870
|
|
|
272
871
|
/**
|
|
@@ -278,6 +877,20 @@ export function commitBookkeeping(
|
|
|
278
877
|
log: (m: string) => void,
|
|
279
878
|
): BookkeepingResult {
|
|
280
879
|
const { root, month, fid, scope, mode, message, squashOf } = o;
|
|
880
|
+
if (o.path !== undefined) {
|
|
881
|
+
if (mode === "stage" || !MODES.includes(mode)) {
|
|
882
|
+
throw new CommandError(EXIT.USAGE, "--path needs --mode=commit or commit-allow-empty");
|
|
883
|
+
}
|
|
884
|
+
if (o.stageTrackedUpdates === true || squashOf !== undefined || o.onlyIfDirtyTracked === true) {
|
|
885
|
+
throw new CommandError(
|
|
886
|
+
EXIT.USAGE,
|
|
887
|
+
"--path commits one path alone; drop --stage-tracked-updates, --squash-of and --only-if-dirty-tracked",
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
if (!message) throw new CommandError(EXIT.USAGE, `--message is required for --mode=${mode}`);
|
|
891
|
+
requireRepo(root);
|
|
892
|
+
return commitOnePath(o, log);
|
|
893
|
+
}
|
|
281
894
|
if (!SCOPES.includes(scope)) {
|
|
282
895
|
throw new CommandError(EXIT.USAGE, `--scope must be core, full, or pr (got '${scope}')`);
|
|
283
896
|
}
|
|
@@ -294,6 +907,15 @@ export function commitBookkeeping(
|
|
|
294
907
|
}
|
|
295
908
|
|
|
296
909
|
requireRepo(root);
|
|
910
|
+
if (scope === "pr" && mode !== "stage") {
|
|
911
|
+
const branch = gitRaw(root, ["branch", "--show-current"]).stdout.trim();
|
|
912
|
+
if (branch === "" || isSharedBranch(branch)) {
|
|
913
|
+
throw new CommandError(
|
|
914
|
+
EXIT_SHARED_BRANCH,
|
|
915
|
+
`--scope=pr commits a feature branch's bookkeeping: refusing to commit on '${branch || "detached HEAD"}'`,
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
297
919
|
if (
|
|
298
920
|
squashOf !== undefined &&
|
|
299
921
|
gitRaw(root, ["rev-parse", "-q", "--verify", `${squashOf}^{commit}`]).status !== 0
|
|
@@ -306,14 +928,34 @@ export function commitBookkeeping(
|
|
|
306
928
|
const dirty = dirtyTracked(root);
|
|
307
929
|
if (dirty.length === 0) {
|
|
308
930
|
log("no tracked file has uncommitted changes — nothing to commit");
|
|
309
|
-
return { outcome: "clean", commit: null, paths: [], squashPaths: [] };
|
|
931
|
+
return { outcome: "clean", commit: null, paths: [], squashPaths: [], tracked: [] };
|
|
310
932
|
}
|
|
311
933
|
for (const line of dirty) log(line);
|
|
312
934
|
}
|
|
313
935
|
|
|
936
|
+
// An in-place run on a shared branch: recorded paths are someone else's.
|
|
937
|
+
const rec = squashOf === undefined ? activeRecord(root, fid) : null;
|
|
938
|
+
let tracked: string[] = [];
|
|
314
939
|
if (o.stageTrackedUpdates === true) {
|
|
315
|
-
|
|
940
|
+
// Throws EXIT_FOREIGN_PATH when any recorded path changed, before anything is staged.
|
|
941
|
+
if (rec !== null) ownSet(root, rec);
|
|
942
|
+
const keepOut = (rec?.paths ?? []).map((p) => `:(exclude,literal)${p.path}`);
|
|
943
|
+
const res = gitRaw(root, ["add", "-u", ...(keepOut.length > 0 ? ["--", ".", ...keepOut] : [])]);
|
|
316
944
|
if (res.status !== 0) throw new CommandError(EXIT_STAGE, `'git add -u' failed: ${res.stderr}`);
|
|
945
|
+
if (mode !== "stage") {
|
|
946
|
+
const cached = gitRaw(root, [
|
|
947
|
+
"diff",
|
|
948
|
+
"--cached",
|
|
949
|
+
"--name-only",
|
|
950
|
+
"-z",
|
|
951
|
+
"--no-renames",
|
|
952
|
+
...(keepOut.length > 0 ? ["--", ".", ...keepOut] : []),
|
|
953
|
+
]);
|
|
954
|
+
if (cached.status !== 0) {
|
|
955
|
+
throw new CommandError(EXIT_STAGE, `'git diff --cached' failed: ${cached.stderr}`);
|
|
956
|
+
}
|
|
957
|
+
tracked = nulList(cached.stdout);
|
|
958
|
+
}
|
|
317
959
|
}
|
|
318
960
|
|
|
319
961
|
const specs = bookPathspecs(month, fid, scope);
|
|
@@ -332,7 +974,14 @@ export function commitBookkeeping(
|
|
|
332
974
|
`'git ls-files' failed while building the pathspec: ${listed.stderr}`,
|
|
333
975
|
);
|
|
334
976
|
}
|
|
335
|
-
|
|
977
|
+
let paths = nulList(listed.stdout);
|
|
978
|
+
let ledgerRows: OwnSet["ledgers"] = [];
|
|
979
|
+
if (rec !== null) {
|
|
980
|
+
// Throws EXIT_FOREIGN_PATH when a recorded path in the allow-list changed.
|
|
981
|
+
ledgerRows = ownSet(root, rec, paths).ledgers;
|
|
982
|
+
const recorded = new Set(rec.paths.map((p) => p.path));
|
|
983
|
+
paths = paths.filter((p) => !recorded.has(p));
|
|
984
|
+
}
|
|
336
985
|
let squashPaths: string[] = [];
|
|
337
986
|
if (squashOf !== undefined) {
|
|
338
987
|
const diff = gitRaw(root, ["diff", "--name-only", "-z", "--no-renames", `HEAD...${squashOf}`]);
|
|
@@ -345,13 +994,16 @@ export function commitBookkeeping(
|
|
|
345
994
|
squashPaths = nulList(diff.stdout);
|
|
346
995
|
}
|
|
347
996
|
|
|
348
|
-
if (
|
|
997
|
+
if (
|
|
998
|
+
mode !== "stage" &&
|
|
999
|
+
paths.length + squashPaths.length + ledgerRows.length + tracked.length === 0
|
|
1000
|
+
) {
|
|
349
1001
|
// The pre-worktree commit records only bookkeeping; a dirty tree with none
|
|
350
1002
|
// of it (a fresh consumer repo) has nothing of ours to commit, and stopping
|
|
351
1003
|
// here never reaches `git commit`.
|
|
352
1004
|
if (o.onlyIfDirtyTracked === true) {
|
|
353
1005
|
log(`no bookkeeping under scope=${scope} in ${root} — nothing to commit`);
|
|
354
|
-
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths };
|
|
1006
|
+
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
|
|
355
1007
|
}
|
|
356
1008
|
throw new CommandError(
|
|
357
1009
|
EXIT_EMPTY,
|
|
@@ -359,26 +1011,47 @@ export function commitBookkeeping(
|
|
|
359
1011
|
);
|
|
360
1012
|
}
|
|
361
1013
|
|
|
1014
|
+
if (rec !== null && mode !== "stage" && ledgerRows.length > 0) {
|
|
1015
|
+
const made = commitOwnSet(
|
|
1016
|
+
root,
|
|
1017
|
+
{ plain: [...paths, ...tracked], ledgers: ledgerRows },
|
|
1018
|
+
message!,
|
|
1019
|
+
{
|
|
1020
|
+
allowEmpty: mode === "commit-allow-empty",
|
|
1021
|
+
skipIfEmpty: mode === "commit",
|
|
1022
|
+
},
|
|
1023
|
+
);
|
|
1024
|
+
if (!made.ok) throw new CommandError(EXIT_COMMIT, `'git commit' failed: ${made.error}`);
|
|
1025
|
+
if (made.sha === null) {
|
|
1026
|
+
log("nothing to commit");
|
|
1027
|
+
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
|
|
1028
|
+
}
|
|
1029
|
+
appendRecordCommit(root, fid, made.sha);
|
|
1030
|
+
return { outcome: "committed", commit: made.sha, paths, squashPaths, tracked };
|
|
1031
|
+
}
|
|
1032
|
+
|
|
362
1033
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-ledgers-"));
|
|
363
1034
|
try {
|
|
364
1035
|
const bookList = path.join(tmp, "book");
|
|
365
1036
|
const commitList = path.join(tmp, "commit");
|
|
366
1037
|
fs.writeFileSync(bookList, paths.map((p) => `${p}\0`).join(""));
|
|
367
|
-
|
|
1038
|
+
const commitPaths = [...new Set([...paths, ...squashPaths, ...tracked])];
|
|
1039
|
+
fs.writeFileSync(commitList, commitPaths.map((p) => `${p}\0`).join(""));
|
|
368
1040
|
|
|
369
1041
|
const add = gitRaw(root, ["add", `--pathspec-from-file=${bookList}`, "--pathspec-file-nul"]);
|
|
370
1042
|
if (add.status !== 0) throw new CommandError(EXIT_STAGE, `'git add' failed: ${add.stderr}`);
|
|
371
1043
|
|
|
372
1044
|
if (mode === "stage") {
|
|
373
1045
|
log(`staged (scope=${scope})`);
|
|
374
|
-
return { outcome: "staged", commit: null, paths, squashPaths };
|
|
1046
|
+
return { outcome: "staged", commit: null, paths, squashPaths, tracked };
|
|
375
1047
|
}
|
|
376
1048
|
if (
|
|
377
1049
|
mode === "commit" &&
|
|
378
|
-
gitRaw(root, ["diff", "--cached", "--quiet", "--", ...specs, ...squashPaths])
|
|
1050
|
+
gitRaw(root, ["diff", "--cached", "--quiet", "--", ...specs, ...squashPaths, ...tracked])
|
|
1051
|
+
.status === 0
|
|
379
1052
|
) {
|
|
380
1053
|
log("nothing to commit");
|
|
381
|
-
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths };
|
|
1054
|
+
return { outcome: "nothing-to-commit", commit: null, paths, squashPaths, tracked };
|
|
382
1055
|
}
|
|
383
1056
|
const made = gitRaw(root, [
|
|
384
1057
|
"commit",
|
|
@@ -394,12 +1067,9 @@ export function commitBookkeeping(
|
|
|
394
1067
|
`'git commit' failed: ${made.stderr || made.stdout.trim()}`,
|
|
395
1068
|
);
|
|
396
1069
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
paths,
|
|
401
|
-
squashPaths,
|
|
402
|
-
};
|
|
1070
|
+
const sha = gitRaw(root, ["rev-parse", "HEAD"]).stdout.trim();
|
|
1071
|
+
if (rec !== null) appendRecordCommit(root, fid, sha);
|
|
1072
|
+
return { outcome: "committed", commit: sha, paths, squashPaths, tracked };
|
|
403
1073
|
} finally {
|
|
404
1074
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
405
1075
|
}
|
|
@@ -413,12 +1083,13 @@ function commit(ctx: RunContext): number {
|
|
|
413
1083
|
root: rootOf(ctx),
|
|
414
1084
|
month: required(ctx, "month"),
|
|
415
1085
|
fid: required(ctx, "fid"),
|
|
416
|
-
scope: String(f.scope) as Scope,
|
|
1086
|
+
scope: String(f.scope ?? "") as Scope,
|
|
417
1087
|
mode: String(f.mode) as BookkeepingCommit["mode"],
|
|
418
1088
|
message: str(f.message),
|
|
419
1089
|
stageTrackedUpdates: f.stageTrackedUpdates === true,
|
|
420
1090
|
squashOf: str(f.squashOf),
|
|
421
1091
|
onlyIfDirtyTracked: f.onlyIfDirtyTracked === true,
|
|
1092
|
+
path: str(f.path),
|
|
422
1093
|
},
|
|
423
1094
|
ctx.log,
|
|
424
1095
|
),
|
|
@@ -483,6 +1154,171 @@ function union(ctx: RunContext): number {
|
|
|
483
1154
|
return EXIT.OK;
|
|
484
1155
|
}
|
|
485
1156
|
|
|
1157
|
+
export interface AppendResult {
|
|
1158
|
+
ledger: AppendLedger;
|
|
1159
|
+
file: string;
|
|
1160
|
+
appended: number;
|
|
1161
|
+
keys: Array<string | null>;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/** The top section in its written order, then the row's own fields. */
|
|
1165
|
+
const TOP_ORDER = ["schema", "ts", "kind", "key", "repo", "bkit", "by", "references"];
|
|
1166
|
+
|
|
1167
|
+
/**
|
|
1168
|
+
* Append `rows` to one ledger. Every row is checked before any is written, so a
|
|
1169
|
+
* refused row leaves the file byte-identical. Each row gets `schema` and a `ts`
|
|
1170
|
+
* minted now (never supplied), `repo` when it lacks one and `bkit.version` from
|
|
1171
|
+
* `.bkit/version`. Never reads back or rewrites existing rows. Throws a
|
|
1172
|
+
* CommandError (USAGE / EXIT_ROW_REFUSED / EXIT_STAGE).
|
|
1173
|
+
*/
|
|
1174
|
+
export function appendLedgerRows(root: string, ledger: string, rows: unknown): AppendResult {
|
|
1175
|
+
if (!Object.hasOwn(APPEND_LEDGERS, ledger)) {
|
|
1176
|
+
throw new CommandError(
|
|
1177
|
+
EXIT.USAGE,
|
|
1178
|
+
`--ledger must be one of ${Object.keys(APPEND_LEDGERS).join(", ")} (got '${ledger}')`,
|
|
1179
|
+
);
|
|
1180
|
+
}
|
|
1181
|
+
const { file, kinds } = APPEND_LEDGERS[ledger as AppendLedger];
|
|
1182
|
+
const takes: readonly string[] = kinds;
|
|
1183
|
+
if (!Array.isArray(rows)) throw new CommandError(EXIT.USAGE, "--rows must hold a JSON array");
|
|
1184
|
+
if (rows.length === 0) throw new CommandError(EXIT.USAGE, "--rows holds no rows");
|
|
1185
|
+
|
|
1186
|
+
let repo: string | undefined;
|
|
1187
|
+
let version: string | undefined;
|
|
1188
|
+
let last: number | undefined;
|
|
1189
|
+
const out: Array<Record<string, unknown>> = rows.map((raw, i) => {
|
|
1190
|
+
const refuse = (why: string) => new CommandError(EXIT_ROW_REFUSED, `row ${i + 1}: ${why}`);
|
|
1191
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
1192
|
+
throw refuse("not a JSON object");
|
|
1193
|
+
}
|
|
1194
|
+
const r = raw as Record<string, unknown>;
|
|
1195
|
+
if (Object.hasOwn(r, "ts")) throw refuse("carries ts; ts is minted at append time");
|
|
1196
|
+
if (Object.hasOwn(r, "schema")) throw refuse("carries schema; it is set at append time");
|
|
1197
|
+
if (!takes.includes(String(r["kind"]))) {
|
|
1198
|
+
throw refuse(
|
|
1199
|
+
`kind must be ${takes.join(" | ")} in --ledger=${ledger} (got ${String(r["kind"])})`,
|
|
1200
|
+
);
|
|
1201
|
+
}
|
|
1202
|
+
if (Object.hasOwn(r, "bkit")) throw refuse("carries bkit; bkit.version is set at append time");
|
|
1203
|
+
repo ??= resolveRepoSlug(root) || "unknown/repo";
|
|
1204
|
+
version ??= readBkitVersion(path.join(root, ".bkit", "version"))?.pinnedVersion || "unknown";
|
|
1205
|
+
last = mintTs(last);
|
|
1206
|
+
const filled: Record<string, unknown> = {
|
|
1207
|
+
repo,
|
|
1208
|
+
...r,
|
|
1209
|
+
schema: SCHEMA,
|
|
1210
|
+
ts: last,
|
|
1211
|
+
bkit: { version },
|
|
1212
|
+
};
|
|
1213
|
+
const row: Record<string, unknown> = {};
|
|
1214
|
+
for (const k of TOP_ORDER) if (filled[k] !== undefined) row[k] = filled[k];
|
|
1215
|
+
for (const [k, v] of Object.entries(filled)) if (!(k in row)) row[k] = v;
|
|
1216
|
+
const v = validate(row);
|
|
1217
|
+
if (!v.ok) throw refuse(v.reason ?? "invalid");
|
|
1218
|
+
const who = writerProblem(row);
|
|
1219
|
+
if (who !== undefined) throw refuse(who);
|
|
1220
|
+
return row;
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
const abs = path.join(root, file);
|
|
1224
|
+
const made = mkdirp(path.dirname(abs));
|
|
1225
|
+
if (made) throw new CommandError(EXIT_STAGE, `mkdir failed for ${path.dirname(file)}: ${made}`);
|
|
1226
|
+
const block = out.map((r) => `${JSON.stringify(r)}\n`).join("");
|
|
1227
|
+
// A file missing its final newline would glue the first row onto its last one.
|
|
1228
|
+
const appendErr = appendText(abs, endsMidLine(abs) ? `\n${block}` : block);
|
|
1229
|
+
if (appendErr) throw new CommandError(EXIT_STAGE, `append failed: ${file} — ${appendErr}`);
|
|
1230
|
+
return {
|
|
1231
|
+
ledger: ledger as AppendLedger,
|
|
1232
|
+
file,
|
|
1233
|
+
appended: out.length,
|
|
1234
|
+
keys: out.map((r) => (typeof r["key"] === "string" ? r["key"] : null)),
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/** True when `abs` exists, is non-empty and its last byte is not a newline. */
|
|
1239
|
+
function endsMidLine(abs: string): boolean {
|
|
1240
|
+
let fd: number | undefined;
|
|
1241
|
+
try {
|
|
1242
|
+
fd = fs.openSync(abs, "r");
|
|
1243
|
+
const size = fs.fstatSync(fd).size;
|
|
1244
|
+
if (size === 0) return false;
|
|
1245
|
+
const last = Buffer.alloc(1);
|
|
1246
|
+
fs.readSync(fd, last, 0, 1, size - 1);
|
|
1247
|
+
return last[0] !== 0x0a;
|
|
1248
|
+
} catch {
|
|
1249
|
+
// No file yet: the append creates it.
|
|
1250
|
+
return false;
|
|
1251
|
+
} finally {
|
|
1252
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
function append(ctx: RunContext): number {
|
|
1257
|
+
const root = path.resolve(ctx.cwd, str(ctx.flags.root) ?? ".");
|
|
1258
|
+
const src = String(ctx.flags.rows);
|
|
1259
|
+
const read = readText(src === "-" ? 0 : path.resolve(ctx.cwd, src));
|
|
1260
|
+
if (!read.ok) throw new CommandError(EXIT.USAGE, `--rows unreadable: ${read.error}`);
|
|
1261
|
+
const text = read.text;
|
|
1262
|
+
if (text.trim() === "") throw new CommandError(EXIT.USAGE, "--rows holds no rows");
|
|
1263
|
+
const parsed = parseJson(text);
|
|
1264
|
+
if (!parsed.ok) throw new CommandError(EXIT.USAGE, "--rows is not JSON");
|
|
1265
|
+
const r = appendLedgerRows(root, String(ctx.flags.ledger), parsed.value);
|
|
1266
|
+
ctx.log(`appended ${r.appended} row(s) to ${r.file}`);
|
|
1267
|
+
ctx.emit({ ...r });
|
|
1268
|
+
return EXIT.OK;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
const LEDGER_ROWS_LINE = /^\*\*Ledger rows:\*\*(.*)$/m;
|
|
1272
|
+
const CHECKED_LEDGERS = [APPEND_LEDGERS.decisions, APPEND_LEDGERS.deferrals];
|
|
1273
|
+
|
|
1274
|
+
export interface PlanRowsResult {
|
|
1275
|
+
keys: string[];
|
|
1276
|
+
missing: string[];
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/**
|
|
1280
|
+
* Read the plan's `**Ledger rows:**` line — backticked keys, or `None` — and
|
|
1281
|
+
* return the keys no `decision` / `deferral` row carries. Throws EXIT_ROWS_MISSING
|
|
1282
|
+
* when the line is absent or still a placeholder.
|
|
1283
|
+
*/
|
|
1284
|
+
export function checkPlanRows(root: string, plan: string): PlanRowsResult {
|
|
1285
|
+
const abs = path.resolve(root, plan);
|
|
1286
|
+
if (!fs.existsSync(abs)) throw new CommandError(EXIT.USAGE, `--plan not found: ${plan}`);
|
|
1287
|
+
const text = fs.readFileSync(abs, "utf-8");
|
|
1288
|
+
const line = LEDGER_ROWS_LINE.exec(text)?.[1]?.trim();
|
|
1289
|
+
if (line === undefined) {
|
|
1290
|
+
throw new CommandError(EXIT_ROWS_MISSING, `${plan} has no **Ledger rows:** line`);
|
|
1291
|
+
}
|
|
1292
|
+
const keys = [...line.matchAll(/`([^`]+)`/g)].map((m) => m[1] ?? "");
|
|
1293
|
+
if (keys.length === 0) {
|
|
1294
|
+
if (line.replace(/[."\s]/g, "") === "None") return { keys: [], missing: [] };
|
|
1295
|
+
throw new CommandError(EXIT_ROWS_MISSING, `${plan}: **Ledger rows:** is unfilled (${line})`);
|
|
1296
|
+
}
|
|
1297
|
+
const onDisk = new Set<string>();
|
|
1298
|
+
for (const { file, kinds } of CHECKED_LEDGERS) {
|
|
1299
|
+
const abs = path.join(root, file);
|
|
1300
|
+
if (!fs.existsSync(abs)) continue;
|
|
1301
|
+
for (const e of parse(fs.readFileSync(abs, "utf-8")).events) {
|
|
1302
|
+
const key = (e as { key?: unknown }).key;
|
|
1303
|
+
if ((kinds as readonly string[]).includes(e.kind) && typeof key === "string") onDisk.add(key);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
return { keys, missing: keys.filter((k) => !onDisk.has(k)) };
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
function check(ctx: RunContext): number {
|
|
1310
|
+
const root = rootOf(ctx);
|
|
1311
|
+
const plan = String(ctx.flags.plan);
|
|
1312
|
+
const r = checkPlanRows(root, plan);
|
|
1313
|
+
ctx.emit({ plan, ...r });
|
|
1314
|
+
if (r.missing.length > 0) {
|
|
1315
|
+
ctx.log(`${plan}: no ledger row for ${r.missing.join(", ")}`);
|
|
1316
|
+
return EXIT_ROWS_MISSING;
|
|
1317
|
+
}
|
|
1318
|
+
ctx.log(`${plan}: ${r.keys.length} ledger row(s) on disk`);
|
|
1319
|
+
return EXIT.OK;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
486
1322
|
/** mkdir -p; the error text, or undefined on success. */
|
|
487
1323
|
function mkdirp(dir: string): string | undefined {
|
|
488
1324
|
try {
|
|
@@ -494,6 +1330,27 @@ function mkdirp(dir: string): string | undefined {
|
|
|
494
1330
|
}
|
|
495
1331
|
}
|
|
496
1332
|
|
|
1333
|
+
/** Append `text` to `file`; the error text, or undefined on success. */
|
|
1334
|
+
function appendText(file: string, text: string): string | undefined {
|
|
1335
|
+
try {
|
|
1336
|
+
fs.appendFileSync(file, text);
|
|
1337
|
+
return undefined;
|
|
1338
|
+
} catch (err) {
|
|
1339
|
+
// Reported as the command's staging exit code, with the reason.
|
|
1340
|
+
return (err as Error).message;
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/** Read `file` (0 = stdin) as UTF-8; the text, or the error text. */
|
|
1345
|
+
function readText(file: string | 0): { ok: true; text: string } | { ok: false; error: string } {
|
|
1346
|
+
try {
|
|
1347
|
+
return { ok: true, text: fs.readFileSync(file, "utf-8") };
|
|
1348
|
+
} catch (err) {
|
|
1349
|
+
// Reported as a usage error, with the reason.
|
|
1350
|
+
return { ok: false, error: (err as Error).message };
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
497
1354
|
function copy(from: string, to: string): string | undefined {
|
|
498
1355
|
try {
|
|
499
1356
|
fs.copyFileSync(from, to);
|