@hassangameryt/freeflow 0.5.0 → 0.6.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +148 -154
- package/capabilities/cognitive-routing/SKILL.md +229 -0
- package/capabilities/context-virtualization/SKILL.md +103 -0
- package/capabilities/conversation-history/SKILL.md +53 -0
- package/command-surface.json +6 -13
- package/hooks/freeflow-runtime-context.mjs +35 -91
- package/hooks/tests/check-runtime-context-hook.sh +56 -39
- package/package.json +24 -16
- package/pi-extension/dist/cognitive-routing/commands.js +96 -0
- package/pi-extension/dist/cognitive-routing/config.js +236 -0
- package/pi-extension/dist/cognitive-routing/controller.js +862 -0
- package/pi-extension/dist/cognitive-routing/history.js +439 -0
- package/pi-extension/dist/cognitive-routing/host.js +126 -0
- package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
- package/pi-extension/dist/cognitive-routing/tool.js +211 -0
- package/pi-extension/dist/cognitive-routing/types.js +6 -0
- package/pi-extension/dist/context-virtualization/commands.js +89 -0
- package/pi-extension/dist/context-virtualization/projector.js +42 -0
- package/pi-extension/dist/context-virtualization/runtime.js +356 -0
- package/pi-extension/dist/context-virtualization/state.js +57 -0
- package/pi-extension/dist/context-virtualization/types.js +10 -0
- package/pi-extension/dist/conversation-history/passages.js +66 -0
- package/pi-extension/dist/conversation-history/ranking.js +105 -0
- package/pi-extension/dist/conversation-history/runtime.js +226 -0
- package/pi-extension/dist/conversation-history/search.js +56 -0
- package/pi-extension/dist/conversation-history/types.js +1 -0
- package/pi-extension/dist/freeflow-context/resolver.js +120 -0
- package/pi-extension/dist/freeflow-context/runtime.js +80 -0
- package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
- package/pi-extension/dist/freeflow-context/tool.js +308 -0
- package/pi-extension/dist/freeflow-context/types.js +12 -0
- package/pi-extension/dist/freeflow-context/visibility.js +28 -0
- package/pi-extension/dist/index.js +516 -98
- package/pi-extension/dist/runtime/runtime-context.js +318 -271
- package/pi-extension/dist/runtime/runtime-identity.js +5 -0
- package/pi-extension/dist/settings/settings-tui.js +78 -0
- package/pi-extension/dist/settings/settings-ui.js +593 -563
- package/pi-extension/dist/ui/text-component.js +57 -0
- package/pi-extension/src/cognitive-routing/commands.ts +119 -0
- package/pi-extension/src/cognitive-routing/config.ts +307 -0
- package/pi-extension/src/cognitive-routing/controller.ts +1118 -0
- package/pi-extension/src/cognitive-routing/history.ts +638 -0
- package/pi-extension/src/cognitive-routing/host.ts +172 -0
- package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
- package/pi-extension/src/cognitive-routing/tool.ts +272 -0
- package/pi-extension/src/cognitive-routing/types.ts +89 -0
- package/pi-extension/src/context-virtualization/commands.ts +111 -0
- package/pi-extension/src/context-virtualization/projector.ts +62 -0
- package/pi-extension/src/context-virtualization/runtime.ts +406 -0
- package/pi-extension/src/context-virtualization/state.ts +79 -0
- package/pi-extension/src/context-virtualization/types.ts +92 -0
- package/pi-extension/src/conversation-history/passages.ts +81 -0
- package/pi-extension/src/conversation-history/ranking.ts +155 -0
- package/pi-extension/src/conversation-history/runtime.ts +250 -0
- package/pi-extension/src/conversation-history/search.ts +79 -0
- package/pi-extension/src/conversation-history/types.ts +31 -0
- package/pi-extension/src/freeflow-context/resolver.ts +139 -0
- package/pi-extension/src/freeflow-context/runtime.ts +100 -0
- package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
- package/pi-extension/src/freeflow-context/tool.ts +360 -0
- package/pi-extension/src/freeflow-context/types.ts +70 -0
- package/pi-extension/src/freeflow-context/visibility.ts +53 -0
- package/pi-extension/src/index.ts +553 -101
- package/pi-extension/src/runtime/runtime-context.ts +339 -281
- package/pi-extension/src/runtime/runtime-identity.ts +8 -0
- package/pi-extension/src/settings/settings-tui.ts +93 -0
- package/pi-extension/src/settings/settings-ui.ts +700 -613
- package/pi-extension/src/ui/text-component.ts +66 -0
- package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
- package/pi-extension/tests/cognitive-routing/controller.test.js +1099 -0
- package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1071 -0
- package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
- package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
- package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
- package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +236 -0
- package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
- package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
- package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
- package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
- package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
- package/pi-extension/tests/conversation-history/search.test.js +97 -0
- package/pi-extension/tests/integration/pi-extension.test.js +927 -2048
- package/pi-extension/tests/integration/prompt-architecture.test.js +305 -0
- package/runtime/prompts/cognitive-routing.md +9 -0
- package/runtime/prompts/context-virtualization.md +3 -0
- package/runtime/prompts/conversation-history.md +3 -0
- package/runtime/prompts/core.md +13 -0
- package/runtime/prompts/interaction-contract.md +7 -0
- package/runtime/prompts/skills.md +65 -0
- package/skills/action-selection/SKILL.md +91 -0
- package/skills/bypass/SKILL.md +3 -2
- package/skills/commit-work/SKILL.md +1 -1
- package/skills/commit-work/references/staging-decisions.md +1 -1
- package/skills/decision-gate/SKILL.md +1 -1
- package/skills/design-for-depth/SKILL.md +14 -33
- package/skills/design-for-depth/references/design-pressure-signals.md +1 -1
- package/skills/design-for-depth/references/interface-design-loop.md +1 -1
- package/skills/design-for-depth/references/software-design-philosophy.md +1 -1
- package/skills/diagnose-failure/SKILL.md +20 -14
- package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +1 -3
- package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +1 -1
- package/skills/discuss/SKILL.md +34 -22
- package/skills/discuss/references/discussion-continuity.md +71 -0
- package/skills/evaluate-skill/SKILL.md +5 -5
- package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +42 -2
- package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
- package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
- package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
- package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
- package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
- package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
- package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
- package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
- package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
- package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
- package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
- package/skills/execute-work/SKILL.md +18 -15
- package/skills/execute-work/references/code-practices.md +1 -1
- package/skills/execute-work/references/execute-work-edges.md +42 -0
- package/skills/finish-branch/SKILL.md +2 -2
- package/skills/finish-branch/references/integration-options.md +1 -1
- package/skills/handoff/SKILL.md +3 -3
- package/skills/launch-work/SKILL.md +1 -1
- package/skills/launch-work/references/launch-readiness.md +2 -2
- package/skills/migration-work/SKILL.md +2 -2
- package/skills/migration-work/references/migration-lifecycle.md +1 -1
- package/skills/mode-contract/SKILL.md +4 -4
- package/skills/release-work/SKILL.md +1 -1
- package/skills/release-work/references/release-evidence.md +1 -1
- package/skills/review-artifact/SKILL.md +28 -26
- package/skills/review-work/SKILL.md +28 -26
- package/skills/review-work/references/{reviewer-prompt.md → independent-work-reviewer-contract.md} +1 -1
- package/skills/review-work/references/security-risk-lens.md +1 -1
- package/skills/setup-freeflow/SKILL.md +3 -1
- package/skills/setup-freeflow/references/activation-contract.md +2 -2
- package/skills/setup-freeflow/references/host-setup.md +2 -2
- package/skills/simplify-code/SKILL.md +1 -1
- package/skills/simplify-code/references/simplification-patterns.md +1 -1
- package/skills/tdd/SKILL.md +18 -38
- package/skills/tdd/references/test-design.md +2 -2
- package/skills/track-work/SKILL.md +362 -58
- package/skills/track-work/scripts/lib/codec.mjs +570 -0
- package/skills/track-work/scripts/lib/commands.mjs +568 -0
- package/skills/track-work/scripts/lib/contract.mjs +303 -0
- package/skills/track-work/scripts/lib/model.mjs +506 -0
- package/skills/track-work/scripts/lib/operations.mjs +965 -0
- package/skills/track-work/scripts/lib/record-store.mjs +264 -0
- package/skills/track-work/scripts/lib/result.mjs +37 -0
- package/skills/track-work/scripts/lib/rewrites.mjs +740 -0
- package/skills/track-work/scripts/lib/schema.mjs +277 -0
- package/skills/track-work/scripts/lib/source-inventory.mjs +162 -0
- package/skills/track-work/scripts/lib/views.mjs +443 -0
- package/skills/track-work/scripts/lib/workspace.mjs +134 -0
- package/skills/track-work/scripts/working-record.mjs +122 -0
- package/skills/verify-work/SKILL.md +14 -2
- package/skills/verify-work/references/browser-runtime-evidence.md +1 -1
- package/skills/verify-work/references/integration-evidence.md +1 -1
- package/skills/verify-work/references/performance-evidence.md +1 -1
- package/skills/workflow/SKILL.md +105 -53
- package/skills/workflow/references/domain-skill-composition.md +22 -42
- package/skills/write-plan/SKILL.md +1 -1
- package/skills/write-skill/SKILL.md +3 -2
- package/skills/write-skill/references/progressive-disclosure.md +17 -3
- package/capabilities/output-router/SKILL.md +0 -206
- package/capabilities/output-router/references/safety-policy.md +0 -40
- package/capabilities/output-router/references/setup.md +0 -110
- package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
- package/pi-extension/dist/output-router/native-safety-net.js +0 -216
- package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
- package/pi-extension/dist/output-router/renderers.js +0 -1023
- package/pi-extension/dist/output-router/router-tools.js +0 -554
- package/pi-extension/dist/output-router/schemas.js +0 -383
- package/pi-extension/dist/output-router/status.js +0 -744
- package/pi-extension/dist/output-router/utils.js +0 -502
- package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
- package/pi-extension/src/output-router/native-safety-net.ts +0 -248
- package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
- package/pi-extension/src/output-router/renderers.ts +0 -1108
- package/pi-extension/src/output-router/router-tools.ts +0 -579
- package/pi-extension/src/output-router/schemas.ts +0 -387
- package/pi-extension/src/output-router/status.ts +0 -791
- package/pi-extension/src/output-router/utils.ts +0 -554
- package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
- package/pi-extension/tests/output-router/search.test.js +0 -722
- package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
- package/router/dist/benchmarks/benchmark-harness.js +0 -92
- package/router/dist/benchmarks/benchmarks.d.ts +0 -109
- package/router/dist/benchmarks/benchmarks.js +0 -979
- package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
- package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
- package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
- package/router/dist/benchmarks/command-benchmarks.js +0 -698
- package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
- package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
- package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
- package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
- package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
- package/router/dist/benchmarks/context-saving-baseline.js +0 -470
- package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
- package/router/dist/benchmarks/index-benchmarks.js +0 -862
- package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
- package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
- package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
- package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
- package/router/dist/config/config.d.ts +0 -103
- package/router/dist/config/config.js +0 -632
- package/router/dist/config/router-contract.d.ts +0 -10
- package/router/dist/config/router-contract.js +0 -54
- package/router/dist/config/schema.d.ts +0 -27
- package/router/dist/config/schema.js +0 -648
- package/router/dist/config/types.d.ts +0 -573
- package/router/dist/config/types.js +0 -41
- package/router/dist/evidence/bounded-evidence.d.ts +0 -40
- package/router/dist/evidence/bounded-evidence.js +0 -323
- package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
- package/router/dist/evidence/evidence-range-selector.js +0 -232
- package/router/dist/evidence/evidence-search.d.ts +0 -27
- package/router/dist/evidence/evidence-search.js +0 -490
- package/router/dist/evidence/evidence.d.ts +0 -38
- package/router/dist/evidence/evidence.js +0 -200
- package/router/dist/evidence/failure-contracts.d.ts +0 -37
- package/router/dist/evidence/failure-contracts.js +0 -166
- package/router/dist/evidence/line-ranges.d.ts +0 -24
- package/router/dist/evidence/line-ranges.js +0 -22
- package/router/dist/experiments/local-index.d.ts +0 -64
- package/router/dist/experiments/local-index.js +0 -581
- package/router/dist/index.d.ts +0 -30
- package/router/dist/index.js +0 -32
- package/router/dist/local/local-traversal.d.ts +0 -18
- package/router/dist/local/local-traversal.js +0 -334
- package/router/dist/processing/engine.d.ts +0 -132
- package/router/dist/processing/engine.js +0 -533
- package/router/dist/processing/reducers.d.ts +0 -280
- package/router/dist/processing/reducers.js +0 -1673
- package/router/dist/processing/renderers.d.ts +0 -31
- package/router/dist/processing/renderers.js +0 -195
- package/router/dist/processing/scripts.d.ts +0 -91
- package/router/dist/processing/scripts.js +0 -386
- package/router/dist/repo/repo-traversal.d.ts +0 -18
- package/router/dist/repo/repo-traversal.js +0 -245
- package/router/dist/routing/observed-reducers.d.ts +0 -41
- package/router/dist/routing/observed-reducers.js +0 -661
- package/router/dist/routing/observed-routing.d.ts +0 -26
- package/router/dist/routing/observed-routing.js +0 -378
- package/router/dist/routing/parsers.d.ts +0 -16
- package/router/dist/routing/parsers.js +0 -521
- package/router/dist/routing/run-filters.d.ts +0 -60
- package/router/dist/routing/run-filters.js +0 -238
- package/router/dist/routing/run-reducers.d.ts +0 -49
- package/router/dist/routing/run-reducers.js +0 -122
- package/router/dist/sandbox/adapter-roots.d.ts +0 -46
- package/router/dist/sandbox/adapter-roots.js +0 -66
- package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
- package/router/dist/sandbox/eryx-python-adapter.js +0 -868
- package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
- package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
- package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
- package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
- package/router/dist/sandbox/script-sandbox.d.ts +0 -134
- package/router/dist/sandbox/script-sandbox.js +0 -337
- package/router/dist/setup/script-transform-adapters.d.ts +0 -32
- package/router/dist/setup/script-transform-adapters.js +0 -278
- package/router/dist/tools/batch.d.ts +0 -33
- package/router/dist/tools/batch.js +0 -586
- package/router/dist/tools/run.d.ts +0 -62
- package/router/dist/tools/run.js +0 -1304
- package/router/dist/tools/search.d.ts +0 -66
- package/router/dist/tools/search.js +0 -1364
- package/router/dist/transform/engine.d.ts +0 -168
- package/router/dist/transform/engine.js +0 -2072
- package/router/dist/vault/vault-index.d.ts +0 -125
- package/router/dist/vault/vault-index.js +0 -416
- package/router/dist/vault/vault.d.ts +0 -138
- package/router/dist/vault/vault.js +0 -630
- package/runtime/interaction-contract.md +0 -16
- package/skills/discuss/references/checkpoints.md +0 -66
- package/skills/execute-work/references/execution-loop.md +0 -77
- package/skills/track-work/references/working-record-schema.md +0 -378
- package/skills/workflow/references/workflow-loop.md +0 -92
- /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
- /package/skills/review-artifact/references/{reviewer-prompt.md → independent-artifact-reviewer-contract.md} +0 -0
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { CommittedResultError, commitText, loadRecord, requireV2, withMutationLock } from "./record-store.mjs";
|
|
5
|
+
import { parseRecord, renderRecord } from "./codec.mjs";
|
|
6
|
+
import { sourceEntities, sourceUnitOwners, sourceUnits } from "./source-inventory.mjs";
|
|
7
|
+
import {
|
|
8
|
+
WorkingRecordError,
|
|
9
|
+
changedSemanticPaths,
|
|
10
|
+
clone,
|
|
11
|
+
fail,
|
|
12
|
+
failureInjection,
|
|
13
|
+
isoNow,
|
|
14
|
+
sha256,
|
|
15
|
+
validateModel,
|
|
16
|
+
} from "./model.mjs";
|
|
17
|
+
import { assertNoSymlinkPath, displayPath, exists, taskRoot } from "./workspace.mjs";
|
|
18
|
+
import { baseEnvelope, recordMetadata } from "./result.mjs";
|
|
19
|
+
|
|
20
|
+
const MIGRATION_DISPOSITIONS = new Set(["verbatim", "represented", "projection-only", "formatting-normalized"]);
|
|
21
|
+
const MIGRATION_KEYS = new Set([
|
|
22
|
+
"authoritySource",
|
|
23
|
+
"reason",
|
|
24
|
+
"candidateText",
|
|
25
|
+
"coverage",
|
|
26
|
+
"expectedSha",
|
|
27
|
+
"expectedSha256",
|
|
28
|
+
"dryRun",
|
|
29
|
+
]);
|
|
30
|
+
const COMPRESSION_KEYS = new Set([
|
|
31
|
+
"authoritySource",
|
|
32
|
+
"reason",
|
|
33
|
+
"preservation",
|
|
34
|
+
"scope",
|
|
35
|
+
"candidateText",
|
|
36
|
+
"expectedSha",
|
|
37
|
+
"expectedSha256",
|
|
38
|
+
"dryRun",
|
|
39
|
+
]);
|
|
40
|
+
const COVERAGE_KEYS = new Set([
|
|
41
|
+
"unitId",
|
|
42
|
+
"startByte",
|
|
43
|
+
"endByte",
|
|
44
|
+
"sourceSha256",
|
|
45
|
+
"kind",
|
|
46
|
+
"line",
|
|
47
|
+
"disposition",
|
|
48
|
+
"targetPaths",
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
function assertKnownKeys(value, allowed, path) {
|
|
52
|
+
for (const key of Object.keys(value))
|
|
53
|
+
if (!allowed.has(key)) fail("unknown-input-field", `Unknown input field: ${key}`, { path: `${path}.${key}` });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function requiredString(value, name) {
|
|
57
|
+
if (typeof value !== "string" || !value.trim())
|
|
58
|
+
fail("missing-rewrite-declaration", `${name} is required`, { path: name });
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function candidateFromText(candidateText, recordPath) {
|
|
63
|
+
if (typeof candidateText !== "string" || !candidateText.length)
|
|
64
|
+
fail("missing-candidate", "candidateText must contain the complete schema-v2 candidate");
|
|
65
|
+
let parsed;
|
|
66
|
+
try {
|
|
67
|
+
parsed = parseRecord(candidateText, recordPath);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error instanceof WorkingRecordError) {
|
|
70
|
+
fail("candidate-validation-failure", "Candidate could not be parsed", {
|
|
71
|
+
cause: error.message,
|
|
72
|
+
...(error.details ?? {}),
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
if (parsed.kind !== "v2") fail("candidate-validation-failure", "Rewrite candidates must be schema v2");
|
|
78
|
+
const validation = validateModel(parsed.data);
|
|
79
|
+
if (validation.length) fail("candidate-validation-failure", "Candidate failed schema validation", { validation });
|
|
80
|
+
return clone(parsed.data);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function semanticPathValue(data, path) {
|
|
84
|
+
if (typeof path !== "string" || !path) return undefined;
|
|
85
|
+
const matcher = /([^.[\]]+)(?:\[([^\]]+)\])?/g;
|
|
86
|
+
let current = data;
|
|
87
|
+
let consumed = 0;
|
|
88
|
+
let match;
|
|
89
|
+
while ((match = matcher.exec(path))) {
|
|
90
|
+
if (match.index !== consumed) return undefined;
|
|
91
|
+
const key = match[1];
|
|
92
|
+
if (!current || typeof current !== "object" || !Object.hasOwn(current, key)) return undefined;
|
|
93
|
+
current = current[key];
|
|
94
|
+
if (match[2] !== undefined) {
|
|
95
|
+
if (!Array.isArray(current)) return undefined;
|
|
96
|
+
const selector = /^(id|title)=(.+)$/.exec(match[2]);
|
|
97
|
+
if (!selector) return undefined;
|
|
98
|
+
let expected = selector[2];
|
|
99
|
+
if (expected.startsWith('"')) {
|
|
100
|
+
try {
|
|
101
|
+
expected = JSON.parse(expected);
|
|
102
|
+
} catch {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
current = current.find((item) => String(item?.[selector[1]]) === String(expected));
|
|
107
|
+
if (!current) return undefined;
|
|
108
|
+
}
|
|
109
|
+
consumed = matcher.lastIndex;
|
|
110
|
+
if (path[consumed] === ".") consumed += 1;
|
|
111
|
+
}
|
|
112
|
+
return consumed === path.length ? current : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function valueContainsPayload(value, payload) {
|
|
116
|
+
if (typeof value === "string") return value.includes(payload);
|
|
117
|
+
if (Array.isArray(value)) return value.some((item) => valueContainsPayload(item, payload));
|
|
118
|
+
if (value && typeof value === "object")
|
|
119
|
+
return Object.values(value).some((item) => valueContainsPayload(item, payload));
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function sourcePayload(unit, owners) {
|
|
124
|
+
const text = unit.text.trim();
|
|
125
|
+
if (!text || text === "None" || /^(?:Schema|Last updated):/.test(text)) return null;
|
|
126
|
+
if (/^#{1,6}[ \t]+/.test(text)) {
|
|
127
|
+
const owner = owners.get(unit.unitId);
|
|
128
|
+
if (owner?.structural && owner.recognized) return null;
|
|
129
|
+
return text.replace(/^#{1,6}[ \t]+/, "").trim() || null;
|
|
130
|
+
}
|
|
131
|
+
const field = /^(?:-\s+)?[^:]+:\s*(.*)$/.exec(text);
|
|
132
|
+
let payload = (field ? field[1] : text).trim();
|
|
133
|
+
if (payload.startsWith("- ")) payload = payload.slice(2).trim();
|
|
134
|
+
return payload || null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function formattingOnlySourceUnit(unit, owners) {
|
|
138
|
+
const trimmed = unit.text.trim();
|
|
139
|
+
return !trimmed || Boolean(owners.get(unit.unitId)?.structural && owners.get(unit.unitId)?.recognized);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function validateCoverage(text, coverage, candidateText, candidate) {
|
|
143
|
+
if (!Array.isArray(coverage) || coverage.length === 0)
|
|
144
|
+
fail("missing-coverage", "Migration requires a complete non-empty coverage ledger", { path: "coverage" });
|
|
145
|
+
const inventory = sourceUnits(text);
|
|
146
|
+
const owners = sourceUnitOwners(text);
|
|
147
|
+
const candidateInventory = sourceUnits(candidateText);
|
|
148
|
+
const byId = new Map(inventory.map((unit) => [unit.unitId, unit]));
|
|
149
|
+
const consumedCandidateUnits = new Set();
|
|
150
|
+
const seen = new Set();
|
|
151
|
+
const normalized = [];
|
|
152
|
+
for (let index = 0; index < coverage.length; index += 1) {
|
|
153
|
+
const entry = coverage[index];
|
|
154
|
+
const path = `coverage[${index}]`;
|
|
155
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
156
|
+
fail("invalid-coverage", "Coverage entries must be objects", { path });
|
|
157
|
+
assertKnownKeys(entry, COVERAGE_KEYS, path);
|
|
158
|
+
const unit = byId.get(entry.unitId);
|
|
159
|
+
if (!unit) fail("invalid-coverage", `Unknown source unit: ${entry.unitId}`, { path });
|
|
160
|
+
if (seen.has(entry.unitId))
|
|
161
|
+
fail("overlapping-coverage", `Source unit is covered more than once: ${entry.unitId}`, { path });
|
|
162
|
+
seen.add(entry.unitId);
|
|
163
|
+
if (entry.startByte !== unit.startByte || entry.endByte !== unit.endByte)
|
|
164
|
+
fail("stale-coverage", `Source boundaries do not match ${entry.unitId}`, { path });
|
|
165
|
+
if (entry.sourceSha256 !== unit.sourceSha256 || entry.kind !== unit.kind || entry.line !== unit.line)
|
|
166
|
+
fail("stale-coverage", `Source descriptor does not match ${entry.unitId}`, { path });
|
|
167
|
+
if (!MIGRATION_DISPOSITIONS.has(entry.disposition))
|
|
168
|
+
fail("invalid-migration-disposition", `Unsupported migration disposition: ${entry.disposition}`, { path });
|
|
169
|
+
if (entry.disposition === "formatting-normalized" && !formattingOnlySourceUnit(unit, owners))
|
|
170
|
+
fail("invalid-formatting-normalization", `${unit.unitId} contains semantic content`, { path });
|
|
171
|
+
const targetPaths = entry.targetPaths ?? [];
|
|
172
|
+
if (!Array.isArray(targetPaths) || targetPaths.some((target) => typeof target !== "string" || !target))
|
|
173
|
+
fail("invalid-coverage", "targetPaths must be an array of non-empty strings", { path: `${path}.targetPaths` });
|
|
174
|
+
if (entry.disposition !== "verbatim" && entry.disposition !== "formatting-normalized") {
|
|
175
|
+
const sourceOwner = owners.get(unit.unitId)?.owner;
|
|
176
|
+
if (!sourceOwner) fail("unmapped-source", `${unit.unitId} has no deterministic semantic owner`, { path });
|
|
177
|
+
if (
|
|
178
|
+
!targetPaths.some(
|
|
179
|
+
(target) =>
|
|
180
|
+
target === sourceOwner || target.startsWith(`${sourceOwner}.`) || target.startsWith(`${sourceOwner}[`),
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
fail("invalid-migration-target", `${unit.unitId} targets a different semantic owner`, {
|
|
184
|
+
path,
|
|
185
|
+
sourceOwner,
|
|
186
|
+
targetPaths,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
for (const target of targetPaths)
|
|
190
|
+
if (semanticPathValue(candidate, target) === undefined)
|
|
191
|
+
fail("unmapped-source", `Candidate does not contain migration target path: ${target}`, { path });
|
|
192
|
+
const payload =
|
|
193
|
+
entry.disposition === "verbatim" || entry.disposition === "formatting-normalized"
|
|
194
|
+
? null
|
|
195
|
+
: sourcePayload(unit, owners);
|
|
196
|
+
if (payload && !targetPaths.some((target) => valueContainsPayload(semanticPathValue(candidate, target), payload)))
|
|
197
|
+
fail("invalid-migration-representation", `${unit.unitId} is not represented by its target values`, {
|
|
198
|
+
path,
|
|
199
|
+
payload,
|
|
200
|
+
targetPaths,
|
|
201
|
+
});
|
|
202
|
+
if (entry.disposition === "verbatim") {
|
|
203
|
+
const candidateIndex = candidateInventory.findIndex(
|
|
204
|
+
(candidateUnit, candidateUnitIndex) =>
|
|
205
|
+
!consumedCandidateUnits.has(candidateUnitIndex) && candidateUnit.text === unit.text,
|
|
206
|
+
);
|
|
207
|
+
if (candidateIndex < 0)
|
|
208
|
+
fail("unrepresented-source", `${unit.unitId} is declared verbatim but is absent from the candidate`, { path });
|
|
209
|
+
consumedCandidateUnits.add(candidateIndex);
|
|
210
|
+
} else {
|
|
211
|
+
if (!targetPaths.length)
|
|
212
|
+
fail("unmapped-source", `${unit.unitId} requires targetPaths for ${entry.disposition}`, { path });
|
|
213
|
+
if (
|
|
214
|
+
entry.disposition === "projection-only" &&
|
|
215
|
+
targetPaths.some((target) => !/^current(Context|Work)(\.|$)/.test(target))
|
|
216
|
+
)
|
|
217
|
+
fail("invalid-coverage", "projection-only targets must belong to currentContext or currentWork", { path });
|
|
218
|
+
}
|
|
219
|
+
normalized.push({
|
|
220
|
+
unitId: unit.unitId,
|
|
221
|
+
startByte: unit.startByte,
|
|
222
|
+
endByte: unit.endByte,
|
|
223
|
+
sourceSha256: unit.sourceSha256,
|
|
224
|
+
kind: unit.kind,
|
|
225
|
+
disposition: entry.disposition,
|
|
226
|
+
...(targetPaths.length ? { targetPaths: [...targetPaths] } : {}),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
if (seen.size !== inventory.length) {
|
|
230
|
+
const missing = inventory.filter((unit) => !seen.has(unit.unitId)).map((unit) => unit.unitId);
|
|
231
|
+
fail("unmapped-source", "Every source unit requires exactly one migration disposition", { missing });
|
|
232
|
+
}
|
|
233
|
+
return normalized.sort((left, right) => left.startByte - right.startByte);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function collectIds(data) {
|
|
237
|
+
const ids = [];
|
|
238
|
+
const add = (value) => {
|
|
239
|
+
if (typeof value === "string" && value) ids.push(value);
|
|
240
|
+
};
|
|
241
|
+
add(data.currentWork?.currentSlice?.id);
|
|
242
|
+
for (const collection of [data.history?.decisions, data.history?.checkpoints, data.history?.slices])
|
|
243
|
+
for (const item of collection ?? []) add(item.id);
|
|
244
|
+
return ids;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function candidateEntityKeys(data) {
|
|
248
|
+
return [
|
|
249
|
+
...(data.proposals ?? []).map((item) => `proposal:${item.title}`),
|
|
250
|
+
...(data.history?.decisions ?? []).map((item) => `decision:${item.id}|${item.title}`),
|
|
251
|
+
...(data.history?.checkpoints ?? []).map((item) =>
|
|
252
|
+
item.id ? `checkpoint:${item.id}|${item.title}` : `checkpoint:${item.title}`,
|
|
253
|
+
),
|
|
254
|
+
...(data.history?.slices ?? []).map((item) => `slice:${item.id}|${item.title}`),
|
|
255
|
+
...(data.notes ?? []).map((item) => `note:${item.title}`),
|
|
256
|
+
];
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function assertSourceEntityInvariants(sourceText, candidate) {
|
|
260
|
+
const remaining = new Map();
|
|
261
|
+
for (const key of candidateEntityKeys(candidate)) remaining.set(key, (remaining.get(key) ?? 0) + 1);
|
|
262
|
+
const missing = [];
|
|
263
|
+
for (const { key } of sourceEntities(sourceText)) {
|
|
264
|
+
const count = remaining.get(key) ?? 0;
|
|
265
|
+
if (count) remaining.set(key, count - 1);
|
|
266
|
+
else missing.push(key);
|
|
267
|
+
}
|
|
268
|
+
if (missing.length) fail("protected-invariant", "Migration cannot remove recognized source entities", { missing });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function assertMigrationInvariants(source, candidate) {
|
|
272
|
+
assertSourceEntityInvariants(source.raw ?? "", candidate);
|
|
273
|
+
if (source.data.taskName && source.data.taskName !== "Unknown task" && candidate.taskName !== source.data.taskName)
|
|
274
|
+
fail("protected-invariant", "Migration cannot change the task name", { path: "taskName" });
|
|
275
|
+
if (source.data.taskState && candidate.taskState !== source.data.taskState)
|
|
276
|
+
fail("protected-invariant", "Migration cannot change task state", { path: "taskState" });
|
|
277
|
+
const sourceSlice = source.data.currentWork?.currentSlice;
|
|
278
|
+
const candidateSlice = candidate.currentWork?.currentSlice;
|
|
279
|
+
if (sourceSlice?.id) {
|
|
280
|
+
if (!candidateSlice || candidateSlice.id !== sourceSlice.id)
|
|
281
|
+
fail("protected-invariant", "Migration cannot change the existing Current Slice identity", {
|
|
282
|
+
path: "currentWork.currentSlice.id",
|
|
283
|
+
});
|
|
284
|
+
for (const field of ["state", "type"]) {
|
|
285
|
+
if (sourceSlice[field] && candidateSlice[field] !== sourceSlice[field])
|
|
286
|
+
fail("protected-invariant", `Migration cannot change Current Slice ${field}`, {
|
|
287
|
+
path: `currentWork.currentSlice.${field}`,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const sourceIds = collectIds(source.data);
|
|
292
|
+
const candidateIds = new Set(collectIds(candidate));
|
|
293
|
+
const missing = sourceIds.filter((id) => !candidateIds.has(id));
|
|
294
|
+
if (missing.length) fail("protected-invariant", "Migration cannot remove existing entity IDs", { missing });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function entitySignature(data) {
|
|
298
|
+
return {
|
|
299
|
+
proposals: (data.proposals ?? []).map((item) => item.title),
|
|
300
|
+
decisions: (data.history?.decisions ?? []).map((item) => `${item.id}|${item.title}`),
|
|
301
|
+
checkpoints: (data.history?.checkpoints ?? []).map((item) => (item.id ? `${item.id}|${item.title}` : item.title)),
|
|
302
|
+
slices: (data.history?.slices ?? []).map((item) => `${item.id}|${item.title}`),
|
|
303
|
+
notes: (data.notes ?? []).map((item) => item.title),
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function collectKeyValues(value, keyPattern, result = []) {
|
|
308
|
+
if (Array.isArray(value)) {
|
|
309
|
+
for (const item of value) collectKeyValues(item, keyPattern, result);
|
|
310
|
+
return result;
|
|
311
|
+
}
|
|
312
|
+
if (!value || typeof value !== "object") return result;
|
|
313
|
+
for (const [key, child] of Object.entries(value)) {
|
|
314
|
+
if (keyPattern.test(key)) result.push(clone(child));
|
|
315
|
+
collectKeyValues(child, keyPattern, result);
|
|
316
|
+
}
|
|
317
|
+
return result;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function protectedProjection(data) {
|
|
321
|
+
return {
|
|
322
|
+
taskState: data.taskState,
|
|
323
|
+
currentSlice: data.currentWork?.currentSlice
|
|
324
|
+
? {
|
|
325
|
+
id: data.currentWork.currentSlice.id,
|
|
326
|
+
state: data.currentWork.currentSlice.state,
|
|
327
|
+
type: data.currentWork.currentSlice.type,
|
|
328
|
+
authoritySource: data.currentWork.currentSlice.authoritySource,
|
|
329
|
+
reasonAndScope: data.currentWork.currentSlice.reasonAndScope,
|
|
330
|
+
expectedEvidence: data.currentWork.currentSlice.expectedEvidence,
|
|
331
|
+
stopCondition: data.currentWork.currentSlice.stopCondition,
|
|
332
|
+
blocker: data.currentWork.currentSlice.blocker,
|
|
333
|
+
resumeWhen: data.currentWork.currentSlice.resumeWhen,
|
|
334
|
+
startingState: data.currentWork.currentSlice.startingState,
|
|
335
|
+
acceptedExtensions: data.currentWork.currentSlice.acceptedExtensions,
|
|
336
|
+
dependencies: data.currentWork.currentSlice.dependencies,
|
|
337
|
+
selectedCheckpoints: data.currentWork.currentSlice.selectedCheckpoints,
|
|
338
|
+
pendingBoundaries: data.currentWork.currentSlice.pendingBoundaries,
|
|
339
|
+
pendingReviews: data.currentWork.currentSlice.pendingReviews,
|
|
340
|
+
}
|
|
341
|
+
: null,
|
|
342
|
+
entitySignature: entitySignature(data),
|
|
343
|
+
proposalBoundaries: (data.proposals ?? []).map((proposal) => ({
|
|
344
|
+
title: proposal.title,
|
|
345
|
+
dependencies: proposal.dependencies,
|
|
346
|
+
selectedCheckpoints: proposal.selectedCheckpoints,
|
|
347
|
+
})),
|
|
348
|
+
historicalBoundaries: (data.history?.slices ?? []).map((slice) => ({
|
|
349
|
+
id: slice.id,
|
|
350
|
+
acceptedExtensions: slice.acceptedExtensions,
|
|
351
|
+
dependencies: slice.dependencies,
|
|
352
|
+
selectedCheckpoints: slice.selectedCheckpoints,
|
|
353
|
+
pendingBoundaries: slice.pendingBoundaries,
|
|
354
|
+
pendingReviews: slice.pendingReviews,
|
|
355
|
+
abandonmentReason: slice.abandonmentReason,
|
|
356
|
+
})),
|
|
357
|
+
authoritySources: collectKeyValues(data, /^authoritySource$/),
|
|
358
|
+
blockers: collectKeyValues(data, /^(blocker|resumeWhen)$/),
|
|
359
|
+
pending: [data.currentWork?.upcomingCheckpoints ?? [], ...collectKeyValues(data, /pending/i)],
|
|
360
|
+
decisionLinks: (data.history?.decisions ?? []).map((item) => ({
|
|
361
|
+
id: item.id,
|
|
362
|
+
state: item.state,
|
|
363
|
+
supersedes: item.supersedes,
|
|
364
|
+
supersededBy: item.supersededBy,
|
|
365
|
+
})),
|
|
366
|
+
decisionContent: (data.history?.decisions ?? []).map((item) => ({
|
|
367
|
+
id: item.id,
|
|
368
|
+
title: item.title,
|
|
369
|
+
decision: item.decision,
|
|
370
|
+
rationale: item.rationale,
|
|
371
|
+
consequences: item.consequences,
|
|
372
|
+
revisitWhen: item.revisitWhen,
|
|
373
|
+
})),
|
|
374
|
+
checkpointContent: (data.history?.checkpoints ?? []).map((item) => ({
|
|
375
|
+
id: item.id,
|
|
376
|
+
title: item.title,
|
|
377
|
+
type: item.type,
|
|
378
|
+
selectedBy: item.selectedBy,
|
|
379
|
+
condition: item.condition,
|
|
380
|
+
result: item.result,
|
|
381
|
+
judgment: item.judgment,
|
|
382
|
+
effect: item.effect,
|
|
383
|
+
})),
|
|
384
|
+
evidence: collectKeyValues(data, /^(evidence|expectedEvidence)$/),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function sameJson(left, right) {
|
|
389
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function scopeAllows(path, scope) {
|
|
393
|
+
return scope.some((prefix) => path === prefix || path.startsWith(`${prefix}.`) || path.startsWith(`${prefix}[`));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function validateCompression(before, candidate, scope) {
|
|
397
|
+
const beforeComparable = clone(before);
|
|
398
|
+
const candidateComparable = clone(candidate);
|
|
399
|
+
beforeComparable.lastUpdated = candidateComparable.lastUpdated = before.lastUpdated;
|
|
400
|
+
const changedPaths = changedSemanticPaths(beforeComparable, candidateComparable);
|
|
401
|
+
const outOfScope = changedPaths.filter((path) => !scopeAllows(path, scope));
|
|
402
|
+
if (outOfScope.length)
|
|
403
|
+
fail("rewrite-out-of-scope", "Candidate changes fall outside the declared compression scope", { outOfScope });
|
|
404
|
+
const beforeProtected = protectedProjection(beforeComparable);
|
|
405
|
+
const afterProtected = protectedProjection(candidateComparable);
|
|
406
|
+
if (!sameJson(beforeProtected, afterProtected)) {
|
|
407
|
+
fail(
|
|
408
|
+
"protected-invariant",
|
|
409
|
+
"Compression changed protected task, lifecycle, authority, blocker, boundary, decision, or evidence state",
|
|
410
|
+
{
|
|
411
|
+
protectedBefore: beforeProtected,
|
|
412
|
+
protectedAfter: afterProtected,
|
|
413
|
+
},
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
return changedPaths;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function removedSemanticPaths(before, after, path = "") {
|
|
420
|
+
if (before === undefined || after === undefined)
|
|
421
|
+
return before !== undefined && after === undefined ? [path || "$"] : [];
|
|
422
|
+
if (before === null || after === null || typeof before !== "object" || typeof after !== "object") return [];
|
|
423
|
+
if (Array.isArray(before) || Array.isArray(after)) {
|
|
424
|
+
if (!Array.isArray(before) || !Array.isArray(after)) return [path || "$"];
|
|
425
|
+
const afterIds = new Set(after.map((item) => item?.id ?? item?.title));
|
|
426
|
+
return before.flatMap((item, index) => {
|
|
427
|
+
const hasId = item?.id !== undefined;
|
|
428
|
+
const identity = hasId ? item.id : item?.title;
|
|
429
|
+
if (identity !== undefined && !afterIds.has(identity))
|
|
430
|
+
return [`${path}[${hasId ? "id" : "title"}=${JSON.stringify(identity)}]`];
|
|
431
|
+
return removedSemanticPaths(item, after[index], `${path}[${index}]`);
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
const paths = [];
|
|
435
|
+
for (const key of Object.keys(before)) {
|
|
436
|
+
const childPath = path ? `${path}.${key}` : key;
|
|
437
|
+
paths.push(...removedSemanticPaths(before[key], after[key], childPath));
|
|
438
|
+
}
|
|
439
|
+
return paths;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function canonicalDescriptor(value) {
|
|
443
|
+
return JSON.stringify(value);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
async function writeImmutable(path, content, code, root) {
|
|
447
|
+
await assertNoSymlinkPath(dirname(path), taskRoot(root));
|
|
448
|
+
if (await exists(path)) {
|
|
449
|
+
const existing = await readFile(path, "utf8");
|
|
450
|
+
if (existing !== content)
|
|
451
|
+
fail("rewrite-evidence-conflict", `Immutable rewrite evidence conflicts at ${path}`, { path });
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
if (failureInjection(code)) fail(`${code}-failure`, `Injected ${code} failure`);
|
|
455
|
+
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
456
|
+
let committed = false;
|
|
457
|
+
try {
|
|
458
|
+
await writeFile(temporaryPath, content, { encoding: "utf8", flag: "wx" });
|
|
459
|
+
await rename(temporaryPath, path);
|
|
460
|
+
committed = true;
|
|
461
|
+
return true;
|
|
462
|
+
} finally {
|
|
463
|
+
if (!committed) await unlink(temporaryPath).catch(() => undefined);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async function ensureSnapshot(root, recordPath, loaded, descriptor) {
|
|
468
|
+
const snapshotRoot = join(dirname(recordPath), "snapshots", loaded.rawSha);
|
|
469
|
+
const operationKey = sha256(canonicalDescriptor(descriptor));
|
|
470
|
+
const operationRoot = join(snapshotRoot, "operations");
|
|
471
|
+
await assertNoSymlinkPath(join(dirname(recordPath), "snapshots"), taskRoot(root));
|
|
472
|
+
await mkdir(operationRoot, { recursive: true });
|
|
473
|
+
await assertNoSymlinkPath(snapshotRoot, taskRoot(root));
|
|
474
|
+
await assertNoSymlinkPath(operationRoot, taskRoot(root));
|
|
475
|
+
const source = {
|
|
476
|
+
sourceSha256: loaded.rawSha,
|
|
477
|
+
byteCount: Buffer.byteLength(loaded.text, "utf8"),
|
|
478
|
+
sourceKind: loaded.kind,
|
|
479
|
+
schemaVersion: loaded.data?.schemaVersion ?? null,
|
|
480
|
+
recordPath: displayPath(root, recordPath),
|
|
481
|
+
};
|
|
482
|
+
await writeImmutable(join(snapshotRoot, "record.md"), loaded.text, "snapshot-write", root);
|
|
483
|
+
await writeImmutable(
|
|
484
|
+
join(snapshotRoot, "source.json"),
|
|
485
|
+
`${JSON.stringify(source, null, 2)}\n`,
|
|
486
|
+
"snapshot-write",
|
|
487
|
+
root,
|
|
488
|
+
);
|
|
489
|
+
const manifest = {
|
|
490
|
+
...descriptor,
|
|
491
|
+
operationKey,
|
|
492
|
+
snapshotPath: displayPath(root, snapshotRoot),
|
|
493
|
+
};
|
|
494
|
+
await writeImmutable(
|
|
495
|
+
join(operationRoot, `${operationKey}.json`),
|
|
496
|
+
`${JSON.stringify(manifest, null, 2)}\n`,
|
|
497
|
+
"manifest-write",
|
|
498
|
+
root,
|
|
499
|
+
);
|
|
500
|
+
return {
|
|
501
|
+
operationKey,
|
|
502
|
+
snapshotPath: displayPath(root, snapshotRoot),
|
|
503
|
+
manifestPath: displayPath(root, join(operationRoot, `${operationKey}.json`)),
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function rewriteMetadata(root, recordPath, data, sha, confirmation = "confirmed", unavailable = []) {
|
|
508
|
+
return recordMetadata(root, recordPath, data, sha, confirmation, unavailable);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function expectedSha(options, input) {
|
|
512
|
+
return options["--expected-sha"] ?? options["--expected-sha256"] ?? input.expectedSha256 ?? input.expectedSha;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function dryRun(options, input) {
|
|
516
|
+
return options["--dry-run"] === true || input.dryRun === true;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function rewriteResult(
|
|
520
|
+
command,
|
|
521
|
+
root,
|
|
522
|
+
recordPath,
|
|
523
|
+
loaded,
|
|
524
|
+
candidate,
|
|
525
|
+
candidateSha,
|
|
526
|
+
details,
|
|
527
|
+
status,
|
|
528
|
+
recordConfirmation = "candidate",
|
|
529
|
+
) {
|
|
530
|
+
const envelope = baseEnvelope(
|
|
531
|
+
command,
|
|
532
|
+
command,
|
|
533
|
+
rewriteMetadata(root, recordPath, candidate, candidateSha, recordConfirmation),
|
|
534
|
+
);
|
|
535
|
+
envelope.status = status;
|
|
536
|
+
envelope.beforeSha256 = loaded.rawSha;
|
|
537
|
+
envelope.afterSha256 = status === "updated" ? candidateSha : loaded.rawSha;
|
|
538
|
+
envelope.sourceKind = loaded.kind;
|
|
539
|
+
envelope.sourceSha256 = loaded.rawSha;
|
|
540
|
+
envelope.candidateSha256 = candidateSha;
|
|
541
|
+
Object.assign(envelope, details);
|
|
542
|
+
return envelope;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function buildRewrite(command, recordPath, loaded, input) {
|
|
546
|
+
if (command === "migrate") {
|
|
547
|
+
assertKnownKeys(input, MIGRATION_KEYS, "input");
|
|
548
|
+
if (loaded.kind === "v2") fail("migration-source-not-legacy", "migrate accepts only legacy or unsupported records");
|
|
549
|
+
const authoritySource = requiredString(input.authoritySource, "authoritySource");
|
|
550
|
+
const reason = requiredString(input.reason, "reason");
|
|
551
|
+
const candidate = candidateFromText(input.candidateText, recordPath);
|
|
552
|
+
assertMigrationInvariants(loaded, candidate);
|
|
553
|
+
candidate.lastUpdated = isoNow();
|
|
554
|
+
const candidateText = renderRecord(candidate);
|
|
555
|
+
const coverage = validateCoverage(loaded.text, input.coverage, candidateText, candidate);
|
|
556
|
+
const candidateSha = sha256(candidateText);
|
|
557
|
+
const changedPaths = [...new Set(coverage.flatMap((entry) => entry.targetPaths ?? []))];
|
|
558
|
+
const descriptor = {
|
|
559
|
+
operation: "migrate",
|
|
560
|
+
sourceSha256: loaded.rawSha,
|
|
561
|
+
candidateSha256: candidateSha,
|
|
562
|
+
authoritySource,
|
|
563
|
+
reason,
|
|
564
|
+
changedPaths: changedPaths.length ? changedPaths : ["record"],
|
|
565
|
+
removedPaths: [],
|
|
566
|
+
coverage,
|
|
567
|
+
};
|
|
568
|
+
return {
|
|
569
|
+
candidate,
|
|
570
|
+
candidateText,
|
|
571
|
+
candidateSha,
|
|
572
|
+
changedPaths: descriptor.changedPaths,
|
|
573
|
+
removedPaths: [],
|
|
574
|
+
descriptor,
|
|
575
|
+
coverage,
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
assertKnownKeys(input, COMPRESSION_KEYS, "input");
|
|
580
|
+
if (loaded.kind !== "v2")
|
|
581
|
+
fail("compression-source-not-v2", "compress requires a valid schema-v2 record; migrate first");
|
|
582
|
+
requireV2(loaded);
|
|
583
|
+
const authoritySource = requiredString(input.authoritySource, "authoritySource");
|
|
584
|
+
const reason = requiredString(input.reason, "reason");
|
|
585
|
+
const preservation = requiredString(input.preservation, "preservation");
|
|
586
|
+
if (
|
|
587
|
+
!Array.isArray(input.scope) ||
|
|
588
|
+
input.scope.length === 0 ||
|
|
589
|
+
input.scope.some((item) => typeof item !== "string" || !item)
|
|
590
|
+
)
|
|
591
|
+
fail("missing-compression-scope", "compress requires a non-empty scope array of semantic paths", { path: "scope" });
|
|
592
|
+
const scope = [...new Set(input.scope)];
|
|
593
|
+
const candidate = candidateFromText(input.candidateText, recordPath);
|
|
594
|
+
candidate.lastUpdated = isoNow();
|
|
595
|
+
const changedPaths = validateCompression(loaded.data, candidate, scope);
|
|
596
|
+
if (!changedPaths.length) {
|
|
597
|
+
return {
|
|
598
|
+
candidate: loaded.data,
|
|
599
|
+
candidateText: loaded.text,
|
|
600
|
+
candidateSha: loaded.rawSha,
|
|
601
|
+
changedPaths: [],
|
|
602
|
+
removedPaths: [],
|
|
603
|
+
descriptor: null,
|
|
604
|
+
scope,
|
|
605
|
+
preservation,
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
const candidateText = renderRecord(candidate);
|
|
609
|
+
const candidateSha = sha256(candidateText);
|
|
610
|
+
const removed = removedSemanticPaths(loaded.data, candidate);
|
|
611
|
+
const descriptor = {
|
|
612
|
+
operation: "compress",
|
|
613
|
+
sourceSha256: loaded.rawSha,
|
|
614
|
+
candidateSha256: candidateSha,
|
|
615
|
+
scope,
|
|
616
|
+
authoritySource,
|
|
617
|
+
reason,
|
|
618
|
+
preservation,
|
|
619
|
+
changedPaths,
|
|
620
|
+
removedPaths: removed,
|
|
621
|
+
};
|
|
622
|
+
return {
|
|
623
|
+
candidate,
|
|
624
|
+
candidateText,
|
|
625
|
+
candidateSha,
|
|
626
|
+
changedPaths,
|
|
627
|
+
removedPaths: removed,
|
|
628
|
+
descriptor,
|
|
629
|
+
scope,
|
|
630
|
+
preservation,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export async function rewriteExisting(root, command, recordPath, input, options) {
|
|
635
|
+
const expected = expectedSha(options, input);
|
|
636
|
+
if (!expected) fail("missing-expected-sha", "Existing-record rewrites require --expected-sha or expectedSha256");
|
|
637
|
+
const isDryRun = dryRun(options, input);
|
|
638
|
+
await assertNoSymlinkPath(recordPath, taskRoot(root));
|
|
639
|
+
return withMutationLock(recordPath, { dryRun: isDryRun }, async () => {
|
|
640
|
+
const loaded = await loadRecord(root, recordPath);
|
|
641
|
+
if (loaded.rawSha !== expected)
|
|
642
|
+
fail("stale-sha", "Expected SHA-256 does not match the current record", {
|
|
643
|
+
expectedSha256: expected,
|
|
644
|
+
actualSha256: loaded.rawSha,
|
|
645
|
+
});
|
|
646
|
+
const built = buildRewrite(command, recordPath, loaded, input);
|
|
647
|
+
if (!built.changedPaths.length && command === "compress") {
|
|
648
|
+
const envelope = rewriteResult(
|
|
649
|
+
command,
|
|
650
|
+
root,
|
|
651
|
+
recordPath,
|
|
652
|
+
loaded,
|
|
653
|
+
loaded.data,
|
|
654
|
+
loaded.rawSha,
|
|
655
|
+
{
|
|
656
|
+
changedPaths: [],
|
|
657
|
+
removedPaths: [],
|
|
658
|
+
scope: built.scope,
|
|
659
|
+
},
|
|
660
|
+
isDryRun ? "dry-run" : "no-change",
|
|
661
|
+
"confirmed",
|
|
662
|
+
);
|
|
663
|
+
if (isDryRun) envelope.prospective = { wouldChange: false, candidateSha256: loaded.rawSha };
|
|
664
|
+
return envelope;
|
|
665
|
+
}
|
|
666
|
+
let evidence = null;
|
|
667
|
+
if (built.descriptor && !isDryRun) evidence = await ensureSnapshot(root, recordPath, loaded, built.descriptor);
|
|
668
|
+
const details = {
|
|
669
|
+
changedPaths: built.changedPaths,
|
|
670
|
+
removedPaths: built.removedPaths,
|
|
671
|
+
...(built.coverage ? { coverage: built.coverage } : {}),
|
|
672
|
+
...(built.scope ? { scope: built.scope } : {}),
|
|
673
|
+
...(evidence ? { snapshot: evidence, operationKey: evidence.operationKey } : {}),
|
|
674
|
+
};
|
|
675
|
+
if (isDryRun) {
|
|
676
|
+
const envelope = rewriteResult(
|
|
677
|
+
command,
|
|
678
|
+
root,
|
|
679
|
+
recordPath,
|
|
680
|
+
loaded,
|
|
681
|
+
built.candidate,
|
|
682
|
+
built.candidateSha,
|
|
683
|
+
details,
|
|
684
|
+
"dry-run",
|
|
685
|
+
);
|
|
686
|
+
envelope.beforeSha256 = loaded.rawSha;
|
|
687
|
+
envelope.afterSha256 = loaded.rawSha;
|
|
688
|
+
envelope.prospective = {
|
|
689
|
+
wouldChange: true,
|
|
690
|
+
candidateSha256: built.candidateSha,
|
|
691
|
+
sourceSnapshotSha256: loaded.rawSha,
|
|
692
|
+
operationKey: built.descriptor ? sha256(canonicalDescriptor(built.descriptor)) : null,
|
|
693
|
+
};
|
|
694
|
+
return envelope;
|
|
695
|
+
}
|
|
696
|
+
try {
|
|
697
|
+
const committed = await commitText(recordPath, built.candidateText, built.candidate);
|
|
698
|
+
const envelope = rewriteResult(
|
|
699
|
+
command,
|
|
700
|
+
root,
|
|
701
|
+
recordPath,
|
|
702
|
+
loaded,
|
|
703
|
+
committed.data,
|
|
704
|
+
committed.sha256,
|
|
705
|
+
details,
|
|
706
|
+
"updated",
|
|
707
|
+
);
|
|
708
|
+
envelope.afterSha256 = committed.sha256;
|
|
709
|
+
return envelope;
|
|
710
|
+
} catch (error) {
|
|
711
|
+
if (error instanceof WorkingRecordError && error.committed) {
|
|
712
|
+
const envelope = rewriteResult(
|
|
713
|
+
command,
|
|
714
|
+
root,
|
|
715
|
+
recordPath,
|
|
716
|
+
loaded,
|
|
717
|
+
error.candidate?.data ?? built.candidate,
|
|
718
|
+
error.candidate?.sha256 ?? built.candidateSha,
|
|
719
|
+
details,
|
|
720
|
+
"committed-unconfirmed",
|
|
721
|
+
"candidate",
|
|
722
|
+
);
|
|
723
|
+
envelope.afterSha256 = null;
|
|
724
|
+
envelope.errors = [{ code: error.code, message: error.message, ...(error.details ?? {}) }];
|
|
725
|
+
envelope.recovery = {
|
|
726
|
+
required: true,
|
|
727
|
+
discardExpectedSha: true,
|
|
728
|
+
steps: [
|
|
729
|
+
"fresh read of the actual record path",
|
|
730
|
+
"validate",
|
|
731
|
+
"inspect when available",
|
|
732
|
+
"establish confirmed task projection before another rewrite",
|
|
733
|
+
],
|
|
734
|
+
};
|
|
735
|
+
throw new CommittedResultError(envelope);
|
|
736
|
+
}
|
|
737
|
+
throw error;
|
|
738
|
+
}
|
|
739
|
+
});
|
|
740
|
+
}
|