@ornexus/neocortex 4.61.5 → 4.62.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/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +31 -34
- package/install.sh +1 -1
- package/package.json +5 -2
- package/packages/client/dist/adapters/adapter-registry.js +1 -108
- package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
- package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
- package/packages/client/dist/adapters/codex-adapter.js +2 -80
- package/packages/client/dist/adapters/cursor-adapter.js +4 -115
- package/packages/client/dist/adapters/gemini-adapter.js +2 -71
- package/packages/client/dist/adapters/grok-adapter.js +2 -42
- package/packages/client/dist/adapters/index.js +1 -22
- package/packages/client/dist/adapters/platform-detector.js +1 -220
- package/packages/client/dist/adapters/target-adapter.js +0 -12
- package/packages/client/dist/adapters/vscode-adapter.js +2 -72
- package/packages/client/dist/agent/refresh-stubs.js +2 -443
- package/packages/client/dist/agent/update-agent-yaml.js +1 -102
- package/packages/client/dist/agent/update-description.d.ts +8 -1
- package/packages/client/dist/agent/update-description.js +2 -260
- package/packages/client/dist/cache/crypto-utils.js +1 -78
- package/packages/client/dist/cache/encrypted-cache.js +1 -338
- package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
- package/packages/client/dist/cache/index.js +1 -13
- package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
- package/packages/client/dist/checkpoint/index.js +1 -11
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
- package/packages/client/dist/cli.js +5 -364
- package/packages/client/dist/commands/activate.js +8 -394
- package/packages/client/dist/commands/architecture-answers.js +7 -274
- package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
- package/packages/client/dist/commands/architecture-root-binding.js +1 -51
- package/packages/client/dist/commands/cache-status.js +2 -112
- package/packages/client/dist/commands/config.js +1 -88
- package/packages/client/dist/commands/doctor.js +2 -635
- package/packages/client/dist/commands/invoke.d.ts +17 -0
- package/packages/client/dist/commands/invoke.js +148 -7822
- package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
- package/packages/client/dist/commands/legacy-story-branch.js +1 -96
- package/packages/client/dist/commands/legacy-story-pr.js +1 -276
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
- package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
- package/packages/client/dist/commands/mutation-qa-git.js +1 -41
- package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
- package/packages/client/dist/commands/mutation-qa-run.js +3 -219
- package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
- package/packages/client/dist/commands/mutation-qa.js +1 -220
- package/packages/client/dist/commands/native-agent.js +2 -136
- package/packages/client/dist/commands/planning-diagnosis.js +1 -43
- package/packages/client/dist/commands/planning-generation.js +1 -53
- package/packages/client/dist/commands/planning-memory.js +1 -40
- package/packages/client/dist/commands/planning-research.js +1 -42
- package/packages/client/dist/commands/private-session.js +1 -75
- package/packages/client/dist/commands/property-qa.js +1 -139
- package/packages/client/dist/commands/qa-control.js +1 -16
- package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
- package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
- package/packages/client/dist/commands/qa-scan-capture.js +5 -663
- package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
- package/packages/client/dist/commands/qa-scan-review.js +5 -826
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
- package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
- package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
- package/packages/client/dist/commands/refactor-characterization.js +21 -671
- package/packages/client/dist/commands/refactor-commit.js +13 -399
- package/packages/client/dist/commands/refactor-control.js +3 -142
- package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
- package/packages/client/dist/commands/refactor-review.js +5 -283
- package/packages/client/dist/commands/refactor-root.js +7 -588
- package/packages/client/dist/commands/refresh-memory.js +3 -174
- package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
- package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
- package/packages/client/dist/commands/story-checkpoint.js +1 -203
- package/packages/client/dist/commands/story-worktree.js +5 -258
- package/packages/client/dist/config/host-auth-broker.js +1 -60
- package/packages/client/dist/config/host-auth-reference.js +1 -93
- package/packages/client/dist/config/profile-directory.js +1 -13
- package/packages/client/dist/config/resolver-selection.js +1 -278
- package/packages/client/dist/config/secure-config.js +12 -281
- package/packages/client/dist/config.js +2 -224
- package/packages/client/dist/constants.js +1 -25
- package/packages/client/dist/context/context-collector.js +2 -222
- package/packages/client/dist/context/context-sanitizer.js +1 -145
- package/packages/client/dist/continuity/autonomous-governance.js +1 -285
- package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
- package/packages/client/dist/continuity/invoke-hooks.js +1 -129
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
- package/packages/client/dist/continuity/native-agent-store.js +1 -69
- package/packages/client/dist/continuity/native-agent-types.js +1 -105
- package/packages/client/dist/continuity/outbox.js +1 -117
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
- package/packages/client/dist/continuity/sqlite-store.js +81 -2612
- package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
- package/packages/client/dist/errors/error-messages.js +2 -258
- package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
- package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
- package/packages/client/dist/evidence/collector.js +1 -347
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +0 -2
- package/packages/client/dist/fs/atomic-state-replace.js +1 -152
- package/packages/client/dist/generated/command-registry.generated.js +1 -4076
- package/packages/client/dist/generated/public-projections.generated.js +1 -149
- package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +94 -9
- package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -1592
- package/packages/client/dist/git/epic-operational-state.js +2 -672
- package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
- package/packages/client/dist/git/git-lifecycle-store.d.ts +88 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -2529
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
- package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
- package/packages/client/dist/git/legacy-story-pr.js +70 -3538
- package/packages/client/dist/git/neocortex-trailers.js +2 -53
- package/packages/client/dist/git/release-gate-env.d.ts +62 -0
- package/packages/client/dist/git/release-gate-env.js +1 -0
- package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
- package/packages/client/dist/git/secure-filesystem-boundary.js +20 -186
- package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
- package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -603
- package/packages/client/dist/git/story-worktree-manager.js +3 -843
- package/packages/client/dist/git/story-worktree-paths.js +1 -150
- package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
- package/packages/client/dist/git/story-write-set-extension.js +1 -0
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
- package/packages/client/dist/i18n/first-run.js +2 -60
- package/packages/client/dist/index.js +1 -50
- package/packages/client/dist/invocation/invoke-input.js +1 -24
- package/packages/client/dist/license/host-auth-recovery.js +1 -401
- package/packages/client/dist/license/index.js +1 -5
- package/packages/client/dist/license/license-client.js +1 -337
- package/packages/client/dist/machine/fingerprint.js +2 -163
- package/packages/client/dist/machine/index.js +1 -5
- package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
- package/packages/client/dist/memory/project-memory-writer.js +41 -1117
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
- package/packages/client/dist/migrations/project-identity-capability.js +1 -50
- package/packages/client/dist/migrations/project-identity.js +7 -493
- package/packages/client/dist/migrations/state-json.js +4 -393
- package/packages/client/dist/policy/architecture-policy.js +2 -184
- package/packages/client/dist/policy/index.js +1 -7
- package/packages/client/dist/policy/shared-policy-types.js +0 -38
- package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
- package/packages/client/dist/private-execution/clean-baseline.js +2 -279
- package/packages/client/dist/private-execution/codex-executor.js +4 -574
- package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
- package/packages/client/dist/private-execution/delivery.js +13 -410
- package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
- package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
- package/packages/client/dist/private-execution/implementation-validation.js +2 -106
- package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
- package/packages/client/dist/private-execution/isolated-session.js +5 -725
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
- package/packages/client/dist/private-execution/pact-test-source.js +1 -258
- package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
- package/packages/client/dist/private-execution/pact-write-set.js +1 -172
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
- package/packages/client/dist/private-execution/private-report-store.js +1 -42
- package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
- package/packages/client/dist/private-execution/property-test-choices.js +3 -147
- package/packages/client/dist/private-execution/property-test-plan.js +7 -271
- package/packages/client/dist/private-execution/property-test-review.js +4 -258
- package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
- package/packages/client/dist/private-execution/property-test-source.js +1 -139
- package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
- package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
- package/packages/client/dist/private-execution/root-memory-request.js +1 -29
- package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
- package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
- package/packages/client/dist/private-execution/session-lease.js +1 -63
- package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
- package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
- package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
- package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
- package/packages/client/dist/private-execution/ux-write-set.js +2 -191
- package/packages/client/dist/registry/registry-reconciliation.js +1 -234
- package/packages/client/dist/resilience/circuit-breaker.js +1 -170
- package/packages/client/dist/resilience/degradation-manager.js +1 -164
- package/packages/client/dist/resilience/freshness-indicator.js +1 -100
- package/packages/client/dist/resilience/index.js +1 -8
- package/packages/client/dist/resilience/recovery-detector.js +1 -74
- package/packages/client/dist/resolvers/asset-resolver.js +0 -13
- package/packages/client/dist/resolvers/local-resolver.js +8 -255
- package/packages/client/dist/resolvers/remote-resolver.js +1 -233
- package/packages/client/dist/runner/binary.js +1 -404
- package/packages/client/dist/runner/cli.js +17 -1571
- package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
- package/packages/client/dist/runner/headless/adapters.js +1 -49
- package/packages/client/dist/runner/headless/background-root.js +1 -85
- package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
- package/packages/client/dist/runner/headless/child-env.js +1 -0
- package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
- package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
- package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
- package/packages/client/dist/runner/headless/managed-profile.js +1 -149
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
- package/packages/client/dist/runner/headless/resolver.js +1 -231
- package/packages/client/dist/runner/headless/run-yolo.js +1 -886
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
- package/packages/client/dist/runner/headless/types.js +2 -575
- package/packages/client/dist/runner/host-capacity.js +1 -59
- package/packages/client/dist/runner/local-console.js +13 -396
- package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
- package/packages/client/dist/runner/project-identity.js +1 -106
- package/packages/client/dist/runner/scheduler.js +7 -995
- package/packages/client/dist/runner-cli.js +2 -18
- package/packages/client/dist/state/invocation-shape.js +1 -13
- package/packages/client/dist/state/project-state-snapshot.js +1 -1754
- package/packages/client/dist/state/state-json-repair.js +3 -785
- package/packages/client/dist/state/structural-dag-projection.js +1 -118
- package/packages/client/dist/telemetry/index.js +1 -5
- package/packages/client/dist/telemetry/offline-queue.js +1 -131
- package/packages/client/dist/tier/index.js +1 -5
- package/packages/client/dist/tier/tier-aware-client.js +1 -405
- package/packages/client/dist/types/index.js +1 -38
- package/packages/client/dist/version.js +1 -27
- package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
- package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
- package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
- package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
- package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
- package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
- package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
- package/packages/client/dist/yoloop/discovery-hook.js +2 -300
- package/packages/client/dist/yoloop/index.js +1 -8
- package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
- package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
- package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
- package/packages/client/dist/yoloop/target-normalization.js +1 -180
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
- package/packages/shared/dist/frontmatter-context-contract.js +164 -52
- package/packages/shared/dist/project-manifest-projection.js +199 -0
- package/packages/shared/dist/project-validation-commands.js +14 -6
- package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
- package/packages/shared/dist/yolo/spec-envelope.js +33 -7
- package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
- package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/install-antigravity.sh +13 -4
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +5 -5
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/lib/managed-config-merge.js +77 -1
- package/targets-stubs/lib/managed-profile.sh +7 -0
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/install-vscode.sh +21 -0
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,588 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
const MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
9
|
-
const MAX_PATHS = 256;
|
|
10
|
-
function digest(bytes) {
|
|
11
|
-
return createHash('sha256').update(bytes).digest('hex');
|
|
12
|
-
}
|
|
13
|
-
export function privateRefactorDirectory(root) {
|
|
14
|
-
const commonRaw = mutationQaGit(root, ['rev-parse', '--git-common-dir']).toString('utf8').trim();
|
|
15
|
-
const common = isAbsolute(commonRaw) ? resolve(commonRaw) : resolve(root, commonRaw);
|
|
16
|
-
if (realpathSync(common) !== common || lstatSync(common).isSymbolicLink()
|
|
17
|
-
|| lstatSync(common).uid !== process.getuid?.())
|
|
18
|
-
throw new Error('refactor-root-store-unverified');
|
|
19
|
-
const directory = join(common, 'neocortex-refactor');
|
|
20
|
-
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
21
|
-
const stat = lstatSync(directory);
|
|
22
|
-
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
23
|
-
|| (stat.mode & 0o077) !== 0)
|
|
24
|
-
throw new Error('refactor-root-store-unverified');
|
|
25
|
-
return directory;
|
|
26
|
-
}
|
|
27
|
-
function pathIsSafe(path) {
|
|
28
|
-
if (!path || path.length > 512 || isAbsolute(path) || path.includes('\\')
|
|
29
|
-
|| /[\u0000-\u001f\u007f:*?\[\]]/.test(path) || path.normalize('NFC') !== path)
|
|
30
|
-
return false;
|
|
31
|
-
const parts = path.split('/');
|
|
32
|
-
return !parts.some((part) => !part || part === '.' || part === '..'
|
|
33
|
-
|| ['.git', '.neocortex', 'node_modules'].includes(part.toLowerCase()));
|
|
34
|
-
}
|
|
35
|
-
export function exactCommittedRefactorFile(root, path) {
|
|
36
|
-
if (!pathIsSafe(path))
|
|
37
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
38
|
-
const physicalPath = join(root, path);
|
|
39
|
-
const stat = lstatSync(physicalPath);
|
|
40
|
-
if (realpathSync(physicalPath) !== physicalPath || !stat.isFile() || stat.isSymbolicLink()
|
|
41
|
-
|| stat.size === 0 || stat.size > MAX_FILE_BYTES)
|
|
42
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
43
|
-
const bytes = readFileSync(physicalPath);
|
|
44
|
-
if (bytes.length === 0 || bytes.length > MAX_FILE_BYTES) {
|
|
45
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
46
|
-
}
|
|
47
|
-
new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
48
|
-
if (bytes.includes(0))
|
|
49
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
50
|
-
const committed = mutationQaGit(root, ['show', `HEAD:${path}`]);
|
|
51
|
-
if (!bytes.equals(committed))
|
|
52
|
-
throw new Error('refactor-root-source-dirty');
|
|
53
|
-
return Object.freeze({ sha256: digest(bytes), mode: stat.mode & 0o777 });
|
|
54
|
-
}
|
|
55
|
-
function ignoredByGit(root, path) {
|
|
56
|
-
try {
|
|
57
|
-
mutationQaGit(root, ['check-ignore', '--no-index', '-q', '--', path]);
|
|
58
|
-
return true;
|
|
59
|
-
}
|
|
60
|
-
catch (error) {
|
|
61
|
-
if (error.status === 1)
|
|
62
|
-
return false;
|
|
63
|
-
throw error;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
/** A new test/document path is explicit, absent, untracked and not ignored. */
|
|
67
|
-
function exactNewPath(root, path) {
|
|
68
|
-
if (!pathIsSafe(path))
|
|
69
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
70
|
-
const physicalPath = join(root, path);
|
|
71
|
-
const parent = dirname(physicalPath);
|
|
72
|
-
const parentStat = lstatSync(parent);
|
|
73
|
-
if (!parentStat.isDirectory() || parentStat.isSymbolicLink() || realpathSync(parent) !== parent
|
|
74
|
-
|| mutationQaGit(root, ['ls-files', '--stage', '-z', '--', path]).length > 0
|
|
75
|
-
|| ignoredByGit(root, path))
|
|
76
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
77
|
-
try {
|
|
78
|
-
lstatSync(physicalPath);
|
|
79
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
80
|
-
}
|
|
81
|
-
catch (error) {
|
|
82
|
-
if (error.code !== 'ENOENT')
|
|
83
|
-
throw error;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
function indexDigest(root) {
|
|
87
|
-
return digest(mutationQaGit(root, ['ls-files', '--stage', '-z']));
|
|
88
|
-
}
|
|
89
|
-
function names(root, args) {
|
|
90
|
-
const bytes = mutationQaGit(root, args);
|
|
91
|
-
const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
92
|
-
return decoded.split('\0').filter(Boolean);
|
|
93
|
-
}
|
|
94
|
-
function requireNormalIndex(root) {
|
|
95
|
-
const entries = names(root, ['ls-files', '-v', '-z']);
|
|
96
|
-
if (entries.some((entry) => !entry.startsWith('H '))) {
|
|
97
|
-
throw new Error('refactor-root-index-unverified');
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
/** Preserve pre-existing visible and ignored Neocortex controls without copying them to a model. */
|
|
101
|
-
export function refactorSidecarDigest(root) {
|
|
102
|
-
const rows = [];
|
|
103
|
-
const seen = new Set();
|
|
104
|
-
let totalBytes = 0;
|
|
105
|
-
const entries = names(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
|
|
106
|
-
entries.push(...names(root, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z', '--', '.neocortex/'])
|
|
107
|
-
.map(path => `!! ${path}`));
|
|
108
|
-
for (const entry of entries) {
|
|
109
|
-
if (entry.length < 4 || entry[2] !== ' ')
|
|
110
|
-
throw new Error('refactor-root-sidecar-unverified');
|
|
111
|
-
const path = entry.slice(3);
|
|
112
|
-
if (!path.startsWith('.neocortex/'))
|
|
113
|
-
continue;
|
|
114
|
-
if (seen.has(path) || path.includes('\\') || /[\u0000-\u001f\u007f]/.test(path)
|
|
115
|
-
|| path.split('/').some((part) => !part || part === '.' || part === '..')) {
|
|
116
|
-
throw new Error('refactor-root-sidecar-unverified');
|
|
117
|
-
}
|
|
118
|
-
seen.add(path);
|
|
119
|
-
const physicalPath = join(root, path);
|
|
120
|
-
const stat = lstatSync(physicalPath);
|
|
121
|
-
if (realpathSync(physicalPath) !== physicalPath || !stat.isFile() || stat.isSymbolicLink()
|
|
122
|
-
|| stat.nlink !== 1 || stat.size > 64 * 1024 * 1024)
|
|
123
|
-
throw new Error('refactor-root-sidecar-unverified');
|
|
124
|
-
totalBytes += stat.size;
|
|
125
|
-
if (totalBytes > 128 * 1024 * 1024)
|
|
126
|
-
throw new Error('refactor-root-sidecar-unverified');
|
|
127
|
-
const fd = openSync(physicalPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
128
|
-
try {
|
|
129
|
-
const buffer = Buffer.alloc(stat.size + 1);
|
|
130
|
-
let length = 0;
|
|
131
|
-
while (length < buffer.length) {
|
|
132
|
-
const count = readSync(fd, buffer, length, buffer.length - length, length);
|
|
133
|
-
if (!count)
|
|
134
|
-
break;
|
|
135
|
-
length += count;
|
|
136
|
-
}
|
|
137
|
-
const after = fstatSync(fd), current = lstatSync(physicalPath);
|
|
138
|
-
if (length !== stat.size || realpathSync(physicalPath) !== physicalPath
|
|
139
|
-
|| [after, current].some(value => value.dev !== stat.dev || value.ino !== stat.ino
|
|
140
|
-
|| value.size !== stat.size || value.mtimeMs !== stat.mtimeMs || value.ctimeMs !== stat.ctimeMs
|
|
141
|
-
|| value.mode !== stat.mode || value.nlink !== 1))
|
|
142
|
-
throw new Error('refactor-root-sidecar-unverified');
|
|
143
|
-
rows.push({ status: entry.slice(0, 2), path, sha256: digest(buffer.subarray(0, length)), mode: stat.mode & 0o777 });
|
|
144
|
-
}
|
|
145
|
-
finally {
|
|
146
|
-
closeSync(fd);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
rows.sort((a, b) => Buffer.from(a.path).compare(Buffer.from(b.path)));
|
|
150
|
-
return digest(JSON.stringify(rows));
|
|
151
|
-
}
|
|
152
|
-
function orderedPaths(paths) {
|
|
153
|
-
return [...paths].sort((a, b) => Buffer.from(a).compare(Buffer.from(b)));
|
|
154
|
-
}
|
|
155
|
-
function writeSetDigest(record) {
|
|
156
|
-
const files = record.files.map((file) => file.path);
|
|
157
|
-
return digest(JSON.stringify(record.schemaVersion === 1
|
|
158
|
-
? files : { files, newFiles: record.newFiles.map((file) => file.path) }));
|
|
159
|
-
}
|
|
160
|
-
function admissionPath(root, sha256) {
|
|
161
|
-
if (!SHA256.test(sha256))
|
|
162
|
-
throw new Error('refactor-root-admission-invalid');
|
|
163
|
-
return join(privateRefactorDirectory(root), `admission-${sha256}.json`);
|
|
164
|
-
}
|
|
165
|
-
export function readPrivateRefactorAdmission(root, sha256) {
|
|
166
|
-
const path = admissionPath(root, sha256);
|
|
167
|
-
const stat = lstatSync(path);
|
|
168
|
-
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
169
|
-
|| (stat.mode & 0o077) !== 0 || stat.size < 100 || stat.size > 512 * 1024) {
|
|
170
|
-
throw new Error('refactor-root-admission-invalid');
|
|
171
|
-
}
|
|
172
|
-
const raw = readFileSync(path);
|
|
173
|
-
if (raw.length > 512 * 1024)
|
|
174
|
-
throw new Error('refactor-root-admission-invalid');
|
|
175
|
-
let parsed;
|
|
176
|
-
try {
|
|
177
|
-
parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
|
|
178
|
-
}
|
|
179
|
-
catch {
|
|
180
|
-
throw new Error('refactor-root-admission-invalid');
|
|
181
|
-
}
|
|
182
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
183
|
-
throw new Error('refactor-root-admission-invalid');
|
|
184
|
-
}
|
|
185
|
-
const record = parsed;
|
|
186
|
-
const v2 = record.schemaVersion === 2;
|
|
187
|
-
const keys = ['schemaVersion', 'kind', 'storyId', 'sourceHead', 'storySha256',
|
|
188
|
-
'planSha256', 'indexSha256', 'sidecarSha256', 'files', 'admissionSha256'];
|
|
189
|
-
if (v2)
|
|
190
|
-
keys.push('newFiles');
|
|
191
|
-
if (Object.keys(record).sort().join('\0') !== keys.sort().join('\0')
|
|
192
|
-
|| ![1, 2].includes(record.schemaVersion)
|
|
193
|
-
|| record.kind !== 'private-root-refactor-admission'
|
|
194
|
-
|| typeof record.storyId !== 'string' || !STORY_ID.test(record.storyId)
|
|
195
|
-
|| typeof record.sourceHead !== 'string' || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(record.sourceHead)
|
|
196
|
-
|| typeof record.storySha256 !== 'string' || !SHA256.test(record.storySha256)
|
|
197
|
-
|| typeof record.planSha256 !== 'string' || !SHA256.test(record.planSha256)
|
|
198
|
-
|| typeof record.indexSha256 !== 'string' || !SHA256.test(record.indexSha256)
|
|
199
|
-
|| typeof record.sidecarSha256 !== 'string' || !SHA256.test(record.sidecarSha256)
|
|
200
|
-
|| record.admissionSha256 !== sha256 || !Array.isArray(record.files)
|
|
201
|
-
|| record.files.length > MAX_PATHS
|
|
202
|
-
|| (v2 ? !Array.isArray(record.newFiles) || record.newFiles.length < 1
|
|
203
|
-
|| record.files.length + record.newFiles.length > MAX_PATHS
|
|
204
|
-
: record.files.length < 1)) {
|
|
205
|
-
throw new Error('refactor-root-admission-invalid');
|
|
206
|
-
}
|
|
207
|
-
if (digest(`root-refactor-story-scope-v1\0${record.sourceHead}\0${record.storyId}\0${record.storySha256}`)
|
|
208
|
-
!== record.planSha256)
|
|
209
|
-
throw new Error('refactor-root-admission-invalid');
|
|
210
|
-
const files = record.files;
|
|
211
|
-
if (files.some((file) => !file || typeof file !== 'object' || Array.isArray(file)
|
|
212
|
-
|| Object.keys(file).sort().join('\0') !== ['mode', 'path', 'sha256'].join('\0')
|
|
213
|
-
|| typeof file.path !== 'string'
|
|
214
|
-
|| !pathIsSafe(file.path)
|
|
215
|
-
|| typeof file.sha256 !== 'string'
|
|
216
|
-
|| !SHA256.test(file.sha256)
|
|
217
|
-
|| !Number.isSafeInteger(file.mode)
|
|
218
|
-
|| file.mode < 0
|
|
219
|
-
|| file.mode > 0o777)) {
|
|
220
|
-
throw new Error('refactor-root-admission-invalid');
|
|
221
|
-
}
|
|
222
|
-
const ordered = files.map((file) => file.path);
|
|
223
|
-
if (new Set(ordered).size !== ordered.length
|
|
224
|
-
|| ordered.join('\0') !== orderedPaths(ordered).join('\0')) {
|
|
225
|
-
throw new Error('refactor-root-admission-invalid');
|
|
226
|
-
}
|
|
227
|
-
if (v2) {
|
|
228
|
-
const newFiles = record.newFiles;
|
|
229
|
-
if (newFiles.some((file) => !file || typeof file !== 'object' || Array.isArray(file)
|
|
230
|
-
|| Object.keys(file).join('\0') !== 'path'
|
|
231
|
-
|| typeof file.path !== 'string'
|
|
232
|
-
|| !pathIsSafe(file.path))) {
|
|
233
|
-
throw new Error('refactor-root-admission-invalid');
|
|
234
|
-
}
|
|
235
|
-
const newPaths = newFiles.map((file) => file.path);
|
|
236
|
-
if (new Set([...ordered, ...newPaths]).size !== ordered.length + newPaths.length
|
|
237
|
-
|| newPaths.join('\0') !== orderedPaths(newPaths).join('\0')
|
|
238
|
-
|| [...ordered, ...newPaths].includes(`docs/stories/${record.storyId}.story.md`)) {
|
|
239
|
-
throw new Error('refactor-root-admission-invalid');
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
const { admissionSha256: _digest, ...body } = record;
|
|
243
|
-
if (digest(JSON.stringify(body)) !== sha256 || !raw.equals(Buffer.from(`${JSON.stringify(record)}\n`))) {
|
|
244
|
-
throw new Error('refactor-root-admission-invalid');
|
|
245
|
-
}
|
|
246
|
-
return record;
|
|
247
|
-
}
|
|
248
|
-
export function admitRootRefactor(projectRoot, storyId, planSha256, paths, authorizeRootEdit, newPaths = []) {
|
|
249
|
-
if (!authorizeRootEdit)
|
|
250
|
-
throw new Error('refactor-root-authorization-required');
|
|
251
|
-
if (!SHA256.test(planSha256) || paths.length + newPaths.length < 1
|
|
252
|
-
|| paths.length + newPaths.length > MAX_PATHS) {
|
|
253
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
254
|
-
}
|
|
255
|
-
const root = resolve(projectRoot);
|
|
256
|
-
try {
|
|
257
|
-
const plan = planRootRefactor(root, storyId);
|
|
258
|
-
if (plan.planSha256 !== planSha256)
|
|
259
|
-
throw new Error('refactor-root-plan-stale');
|
|
260
|
-
requireNormalIndex(root);
|
|
261
|
-
const beforeIndex = indexDigest(root);
|
|
262
|
-
const beforeSidecar = refactorSidecarDigest(root);
|
|
263
|
-
const ordered = orderedPaths(paths);
|
|
264
|
-
const orderedNew = orderedPaths(newPaths);
|
|
265
|
-
if (new Set([...ordered, ...orderedNew]).size !== ordered.length + orderedNew.length
|
|
266
|
-
|| [...ordered, ...orderedNew].includes(`docs/stories/${storyId}.story.md`)) {
|
|
267
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
268
|
-
}
|
|
269
|
-
const files = ordered.map((path) => Object.freeze({ path, ...exactCommittedRefactorFile(root, path) }));
|
|
270
|
-
const newFiles = orderedNew.map((path) => { exactNewPath(root, path); return Object.freeze({ path }); });
|
|
271
|
-
if (indexDigest(root) !== beforeIndex || refactorSidecarDigest(root) !== beforeSidecar
|
|
272
|
-
|| planRootRefactor(root, storyId).planSha256 !== planSha256) {
|
|
273
|
-
throw new Error('refactor-root-source-dirty');
|
|
274
|
-
}
|
|
275
|
-
for (const file of newFiles)
|
|
276
|
-
exactNewPath(root, file.path);
|
|
277
|
-
const base = { kind: 'private-root-refactor-admission',
|
|
278
|
-
storyId, sourceHead: plan.sourceHead, storySha256: plan.storySha256,
|
|
279
|
-
planSha256, indexSha256: beforeIndex, sidecarSha256: beforeSidecar, files };
|
|
280
|
-
const body = newFiles.length > 0
|
|
281
|
-
? { schemaVersion: 2, ...base, newFiles }
|
|
282
|
-
: { schemaVersion: 1, ...base };
|
|
283
|
-
const admissionSha256 = digest(JSON.stringify(body));
|
|
284
|
-
const record = { ...body, admissionSha256 };
|
|
285
|
-
const path = admissionPath(root, admissionSha256);
|
|
286
|
-
const bytes = Buffer.from(`${JSON.stringify(record)}\n`);
|
|
287
|
-
if (existsSync(path)) {
|
|
288
|
-
readPrivateRefactorAdmission(root, admissionSha256);
|
|
289
|
-
}
|
|
290
|
-
else {
|
|
291
|
-
const handle = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL
|
|
292
|
-
| (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
293
|
-
try {
|
|
294
|
-
writeFileSync(handle, bytes);
|
|
295
|
-
fsyncSync(handle);
|
|
296
|
-
}
|
|
297
|
-
finally {
|
|
298
|
-
closeSync(handle);
|
|
299
|
-
}
|
|
300
|
-
const directoryHandle = openSync(privateRefactorDirectory(root), constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
|
|
301
|
-
try {
|
|
302
|
-
fsyncSync(directoryHandle);
|
|
303
|
-
}
|
|
304
|
-
finally {
|
|
305
|
-
closeSync(directoryHandle);
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
readPrivateRefactorAdmission(root, admissionSha256);
|
|
309
|
-
if (indexDigest(root) !== beforeIndex || refactorSidecarDigest(root) !== beforeSidecar
|
|
310
|
-
|| planRootRefactor(root, storyId).planSha256 !== planSha256) {
|
|
311
|
-
throw new Error('refactor-root-source-dirty');
|
|
312
|
-
}
|
|
313
|
-
for (const file of newFiles)
|
|
314
|
-
exactNewPath(root, file.path);
|
|
315
|
-
const receipt = { kind: 'root-refactor-write-set-admission',
|
|
316
|
-
storyId, sourceHead: plan.sourceHead, planSha256,
|
|
317
|
-
writeSetSha256: writeSetDigest(record), admissionSha256,
|
|
318
|
-
fileCount: files.length, rootEditPrepared: true, privateChildAuthorized: false,
|
|
319
|
-
gitCommitAuthorized: false, publicSafe: true };
|
|
320
|
-
return record.schemaVersion === 2
|
|
321
|
-
? Object.freeze({ schemaVersion: 2, ...receipt, newFileCount: newFiles.length })
|
|
322
|
-
: Object.freeze({ schemaVersion: 1, ...receipt });
|
|
323
|
-
}
|
|
324
|
-
catch (error) {
|
|
325
|
-
if (error instanceof Error && error.message.startsWith('refactor-root-'))
|
|
326
|
-
throw error;
|
|
327
|
-
throw new Error('refactor-root-write-set-invalid');
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
function physicalNewFile(root, path) {
|
|
331
|
-
if (!pathIsSafe(path) || ignoredByGit(root, path)
|
|
332
|
-
|| mutationQaGit(root, ['ls-files', '--stage', '-z', '--', path]).length > 0) {
|
|
333
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
334
|
-
}
|
|
335
|
-
const physicalPath = join(root, path);
|
|
336
|
-
const parent = dirname(physicalPath);
|
|
337
|
-
if (!lstatSync(parent).isDirectory() || realpathSync(parent) !== parent) {
|
|
338
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
339
|
-
}
|
|
340
|
-
const stat = lstatSync(physicalPath);
|
|
341
|
-
if (realpathSync(physicalPath) !== physicalPath || !stat.isFile() || stat.isSymbolicLink()
|
|
342
|
-
|| stat.size === 0 || stat.size > MAX_FILE_BYTES
|
|
343
|
-
|| (stat.mode & 0o113) !== 0)
|
|
344
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
345
|
-
const bytes = readFileSync(physicalPath);
|
|
346
|
-
if (bytes.length === 0 || bytes.length > MAX_FILE_BYTES || bytes.includes(0)) {
|
|
347
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
348
|
-
}
|
|
349
|
-
new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
350
|
-
return digest(bytes);
|
|
351
|
-
}
|
|
352
|
-
export function verifyRootRefactor(projectRoot, admissionSha256) {
|
|
353
|
-
return verifyRefactorDelta(projectRoot, admissionSha256, false).receipt;
|
|
354
|
-
}
|
|
355
|
-
/** Private characterization preparation only. Full review/commit still requires
|
|
356
|
-
* every admitted new file. Missing Markdown cannot authorize QA or Git effects.
|
|
357
|
-
*/
|
|
358
|
-
export function verifyRootRefactorForCharacterization(projectRoot, admissionSha256) {
|
|
359
|
-
return verifyRefactorDelta(projectRoot, admissionSha256, true);
|
|
360
|
-
}
|
|
361
|
-
function verifyRefactorDelta(projectRoot, admissionSha256, allowPendingDocumentation) {
|
|
362
|
-
const root = resolve(projectRoot);
|
|
363
|
-
try {
|
|
364
|
-
const record = readPrivateRefactorAdmission(root, admissionSha256);
|
|
365
|
-
const head = mutationQaGit(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim();
|
|
366
|
-
if (head !== record.sourceHead || indexDigest(root) !== record.indexSha256
|
|
367
|
-
|| refactorSidecarDigest(root) !== record.sidecarSha256) {
|
|
368
|
-
throw new Error('refactor-root-baseline-stale');
|
|
369
|
-
}
|
|
370
|
-
requireNormalIndex(root);
|
|
371
|
-
const storyPath = join(root, 'docs', 'stories', `${record.storyId}.story.md`);
|
|
372
|
-
const storyStat = lstatSync(storyPath);
|
|
373
|
-
if (!storyStat.isFile() || storyStat.isSymbolicLink() || realpathSync(storyPath) !== storyPath
|
|
374
|
-
|| digest(readFileSync(storyPath)) !== record.storySha256
|
|
375
|
-
|| digest(mutationQaGit(root, ['show', `HEAD:docs/stories/${record.storyId}.story.md`]))
|
|
376
|
-
!== record.storySha256) {
|
|
377
|
-
throw new Error('refactor-root-baseline-stale');
|
|
378
|
-
}
|
|
379
|
-
const changed = names(root, ['diff', '--name-only', '-z', '--no-ext-diff', '--no-textconv'])
|
|
380
|
-
.filter((path) => !path.startsWith('.neocortex/'));
|
|
381
|
-
const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z'])
|
|
382
|
-
.filter((path) => !path.startsWith('.neocortex/'));
|
|
383
|
-
const admitted = new Set(record.files.map((file) => file.path));
|
|
384
|
-
const admittedNew = record.schemaVersion === 2 ? record.newFiles.map((file) => file.path) : [];
|
|
385
|
-
const pendingDocumentationPaths = [];
|
|
386
|
-
if (allowPendingDocumentation)
|
|
387
|
-
for (const path of admittedNew) {
|
|
388
|
-
if (!path.endsWith('.md'))
|
|
389
|
-
continue;
|
|
390
|
-
try {
|
|
391
|
-
lstatSync(join(root, path));
|
|
392
|
-
}
|
|
393
|
-
catch (error) {
|
|
394
|
-
if (error.code !== 'ENOENT')
|
|
395
|
-
throw error;
|
|
396
|
-
exactNewPath(root, path);
|
|
397
|
-
pendingDocumentationPaths.push(path);
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
const materializedNew = admittedNew.filter(path => !pendingDocumentationPaths.includes(path));
|
|
401
|
-
const newSet = new Set(admittedNew);
|
|
402
|
-
if (changed.length + untracked.length === 0 || untracked.length !== materializedNew.length
|
|
403
|
-
|| changed.some((path) => !admitted.has(path))
|
|
404
|
-
|| untracked.some((path) => !newSet.has(path))) {
|
|
405
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
406
|
-
}
|
|
407
|
-
let changedFileCount = 0;
|
|
408
|
-
const currentDigests = [];
|
|
409
|
-
for (const file of record.files) {
|
|
410
|
-
const physicalPath = join(root, file.path);
|
|
411
|
-
if (digest(mutationQaGit(root, ['show', `HEAD:${file.path}`])) !== file.sha256) {
|
|
412
|
-
throw new Error('refactor-root-admission-invalid');
|
|
413
|
-
}
|
|
414
|
-
const stat = lstatSync(physicalPath);
|
|
415
|
-
if (realpathSync(physicalPath) !== physicalPath || !stat.isFile() || stat.isSymbolicLink()
|
|
416
|
-
|| stat.size === 0 || stat.size > MAX_FILE_BYTES || (stat.mode & 0o777) !== file.mode) {
|
|
417
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
418
|
-
}
|
|
419
|
-
const bytes = readFileSync(physicalPath);
|
|
420
|
-
if (bytes.length === 0 || bytes.length > MAX_FILE_BYTES) {
|
|
421
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
422
|
-
}
|
|
423
|
-
new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
424
|
-
if (bytes.includes(0))
|
|
425
|
-
throw new Error('refactor-root-delta-outside-admission');
|
|
426
|
-
const current = digest(bytes);
|
|
427
|
-
currentDigests.push(current);
|
|
428
|
-
if (current !== file.sha256)
|
|
429
|
-
changedFileCount++;
|
|
430
|
-
}
|
|
431
|
-
const newDigests = materializedNew.map((path) => physicalNewFile(root, path));
|
|
432
|
-
changedFileCount += newDigests.length;
|
|
433
|
-
const finalChanged = names(root, ['diff', '--name-only', '-z', '--no-ext-diff', '--no-textconv'])
|
|
434
|
-
.filter((path) => !path.startsWith('.neocortex/'));
|
|
435
|
-
const finalUntracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z'])
|
|
436
|
-
.filter((path) => !path.startsWith('.neocortex/'));
|
|
437
|
-
requireNormalIndex(root);
|
|
438
|
-
if (changedFileCount === 0 || changedFileCount !== changed.length + untracked.length
|
|
439
|
-
|| finalChanged.join('\0') !== changed.join('\0')
|
|
440
|
-
|| finalUntracked.join('\0') !== untracked.join('\0')
|
|
441
|
-
|| record.files.some((file, index) => {
|
|
442
|
-
const path = join(root, file.path);
|
|
443
|
-
const stat = lstatSync(path);
|
|
444
|
-
if (realpathSync(path) !== path || !stat.isFile() || stat.isSymbolicLink()
|
|
445
|
-
|| stat.size > MAX_FILE_BYTES || (stat.mode & 0o777) !== file.mode)
|
|
446
|
-
return true;
|
|
447
|
-
const bytes = readFileSync(path);
|
|
448
|
-
return bytes.length > MAX_FILE_BYTES || digest(bytes) !== currentDigests[index];
|
|
449
|
-
})
|
|
450
|
-
|| materializedNew.some((path, index) => physicalNewFile(root, path) !== newDigests[index])
|
|
451
|
-
|| indexDigest(root) !== record.indexSha256
|
|
452
|
-
|| refactorSidecarDigest(root) !== record.sidecarSha256
|
|
453
|
-
|| mutationQaGit(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim() !== head) {
|
|
454
|
-
throw new Error('refactor-root-baseline-stale');
|
|
455
|
-
}
|
|
456
|
-
for (const path of pendingDocumentationPaths)
|
|
457
|
-
exactNewPath(root, path);
|
|
458
|
-
const receipt = { kind: 'root-refactor-delta-containment',
|
|
459
|
-
storyId: record.storyId, sourceHead: record.sourceHead,
|
|
460
|
-
planSha256: record.planSha256, admissionSha256,
|
|
461
|
-
writeSetSha256: writeSetDigest(record),
|
|
462
|
-
changedFileCount, rootEditContained: true, qaAccepted: false,
|
|
463
|
-
gitCommitAuthorized: false, publicSafe: true };
|
|
464
|
-
const fullReceipt = record.schemaVersion === 2
|
|
465
|
-
? Object.freeze({ schemaVersion: 2, ...receipt, newFileCount: materializedNew.length })
|
|
466
|
-
: Object.freeze({ schemaVersion: 1, ...receipt });
|
|
467
|
-
return Object.freeze({ receipt: fullReceipt,
|
|
468
|
-
pendingDocumentationPaths: Object.freeze(pendingDocumentationPaths) });
|
|
469
|
-
}
|
|
470
|
-
catch (error) {
|
|
471
|
-
if (error instanceof Error && error.message.startsWith('refactor-root-'))
|
|
472
|
-
throw error;
|
|
473
|
-
throw new Error('refactor-root-delta-unverified');
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
export function planRootRefactor(projectRoot, storyId) {
|
|
477
|
-
if (!STORY_ID.test(storyId))
|
|
478
|
-
throw new Error('refactor-root-story-invalid');
|
|
479
|
-
const root = resolve(projectRoot);
|
|
480
|
-
try {
|
|
481
|
-
if (realpathSync(root) !== root || !lstatSync(root).isDirectory()) {
|
|
482
|
-
throw new Error('refactor-root-source-unverified');
|
|
483
|
-
}
|
|
484
|
-
const top = mutationQaGit(root, ['rev-parse', '--show-toplevel']).toString('utf8').trim();
|
|
485
|
-
if (top !== root)
|
|
486
|
-
throw new Error('refactor-root-source-unverified');
|
|
487
|
-
const status = mutationQaGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
|
|
488
|
-
.toString('utf8').split('\0').filter(Boolean);
|
|
489
|
-
if (status.some((entry) => !/^.{2} \.neocortex\//.test(entry))) {
|
|
490
|
-
throw new Error('refactor-root-source-dirty');
|
|
491
|
-
}
|
|
492
|
-
const sourceHead = mutationQaGit(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim();
|
|
493
|
-
if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(sourceHead)) {
|
|
494
|
-
throw new Error('refactor-root-source-unverified');
|
|
495
|
-
}
|
|
496
|
-
const relativePath = `docs/stories/${storyId}.story.md`;
|
|
497
|
-
const physicalPath = join(root, relativePath);
|
|
498
|
-
const stat = lstatSync(physicalPath);
|
|
499
|
-
if (realpathSync(physicalPath) !== physicalPath || !stat.isFile() || stat.isSymbolicLink()
|
|
500
|
-
|| stat.size === 0 || stat.size > 1024 * 1024) {
|
|
501
|
-
throw new Error('refactor-root-story-unverified');
|
|
502
|
-
}
|
|
503
|
-
const physical = readFileSync(physicalPath);
|
|
504
|
-
const committed = mutationQaGit(root, ['show', `HEAD:${relativePath}`]);
|
|
505
|
-
if (!physical.equals(committed))
|
|
506
|
-
throw new Error('refactor-root-story-unverified');
|
|
507
|
-
const storySha256 = digest(physical);
|
|
508
|
-
const planSha256 = digest(`root-refactor-story-scope-v1\0${sourceHead}\0${storyId}\0${storySha256}`);
|
|
509
|
-
return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-story-scope', storyId,
|
|
510
|
-
sourceHead, storySha256, planSha256, candidateWriteSetRequired: true,
|
|
511
|
-
characterizationRequired: true, executionAuthorized: false,
|
|
512
|
-
gitAuthority: 'ROOT_ONLY', graphExecution: 'NOT_RUN', publicSafe: true });
|
|
513
|
-
}
|
|
514
|
-
catch (error) {
|
|
515
|
-
if (error instanceof Error && error.message.startsWith('refactor-root-'))
|
|
516
|
-
throw error;
|
|
517
|
-
throw new Error('refactor-root-source-unverified');
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
export function refactorRootCliHandler(args) {
|
|
521
|
-
let action = '';
|
|
522
|
-
let projectRoot = '';
|
|
523
|
-
let storyId = '';
|
|
524
|
-
let planSha256 = '';
|
|
525
|
-
let admissionSha256 = '';
|
|
526
|
-
let authorizeRootEdit = false;
|
|
527
|
-
const paths = [];
|
|
528
|
-
const newPaths = [];
|
|
529
|
-
let format = 'plain';
|
|
530
|
-
try {
|
|
531
|
-
const tokens = [...args];
|
|
532
|
-
action = tokens.shift() ?? '';
|
|
533
|
-
for (let index = 0; index < tokens.length; index++) {
|
|
534
|
-
const token = tokens[index];
|
|
535
|
-
const next = () => {
|
|
536
|
-
const value = tokens[++index];
|
|
537
|
-
if (!value || value.startsWith('--'))
|
|
538
|
-
throw new Error('refactor-root-arguments-invalid');
|
|
539
|
-
return value;
|
|
540
|
-
};
|
|
541
|
-
if (token === '--project-root')
|
|
542
|
-
projectRoot = next();
|
|
543
|
-
else if (token === '--story')
|
|
544
|
-
storyId = next();
|
|
545
|
-
else if (token === '--plan-sha')
|
|
546
|
-
planSha256 = next();
|
|
547
|
-
else if (token === '--admission-sha')
|
|
548
|
-
admissionSha256 = next();
|
|
549
|
-
else if (token === '--path')
|
|
550
|
-
paths.push(next());
|
|
551
|
-
else if (token === '--new-path')
|
|
552
|
-
newPaths.push(next());
|
|
553
|
-
else if (token === '--authorize-root-edit')
|
|
554
|
-
authorizeRootEdit = true;
|
|
555
|
-
else if (token === '--format')
|
|
556
|
-
format = next();
|
|
557
|
-
else
|
|
558
|
-
throw new Error('refactor-root-arguments-invalid');
|
|
559
|
-
}
|
|
560
|
-
if (!projectRoot || !['plain', 'json'].includes(format)) {
|
|
561
|
-
throw new Error('refactor-root-arguments-invalid');
|
|
562
|
-
}
|
|
563
|
-
if (action === 'plan' && storyId && !planSha256 && !admissionSha256
|
|
564
|
-
&& paths.length === 0 && newPaths.length === 0 && !authorizeRootEdit) {
|
|
565
|
-
const plan = planRootRefactor(projectRoot, storyId);
|
|
566
|
-
process.stdout.write(`${JSON.stringify({ ok: true, plan })}\n`);
|
|
567
|
-
}
|
|
568
|
-
else if (action === 'admit' && storyId && planSha256 && !admissionSha256
|
|
569
|
-
&& paths.length + newPaths.length > 0) {
|
|
570
|
-
const admission = admitRootRefactor(projectRoot, storyId, planSha256, paths, authorizeRootEdit, newPaths);
|
|
571
|
-
process.stdout.write(`${JSON.stringify({ ok: true, admission })}\n`);
|
|
572
|
-
}
|
|
573
|
-
else if (action === 'verify' && !storyId && !planSha256 && admissionSha256
|
|
574
|
-
&& paths.length === 0 && newPaths.length === 0 && !authorizeRootEdit) {
|
|
575
|
-
const containment = verifyRootRefactor(projectRoot, admissionSha256);
|
|
576
|
-
process.stdout.write(`${JSON.stringify({ ok: true, containment })}\n`);
|
|
577
|
-
}
|
|
578
|
-
else
|
|
579
|
-
throw new Error('refactor-root-arguments-invalid');
|
|
580
|
-
return 0;
|
|
581
|
-
}
|
|
582
|
-
catch (error) {
|
|
583
|
-
const reasonCode = error instanceof Error && /^refactor-root-[a-z-]+$/.test(error.message)
|
|
584
|
-
? error.message : 'refactor-root-source-unverified';
|
|
585
|
-
process.stdout.write(`${JSON.stringify({ ok: false, reasonCode })}\n`);
|
|
586
|
-
return 1;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
1
|
+
import{createHash as se}from"node:crypto";import{closeSync as q,constants as j,existsSync as ne,fstatSync as ae,fsyncSync as G,lstatSync as p,mkdirSync as ce,openSync as I,readFileSync as A,readSync as fe,realpathSync as v,writeFileSync as de}from"node:fs";import{dirname as U,isAbsolute as Q,join as b,resolve as L}from"node:path";import{mutationQaGit as E}from"./mutation-qa-git.js";const K=/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/,F=/^[a-f0-9]{64}$/,N=8*1024*1024,Y=256;function g(s){return se("sha256").update(s).digest("hex")}function Z(s){const o=E(s,["rev-parse","--git-common-dir"]).toString("utf8").trim(),t=Q(o)?L(o):L(s,o);if(v(t)!==t||p(t).isSymbolicLink()||p(t).uid!==process.getuid?.())throw new Error("refactor-root-store-unverified");const r=b(t,"neocortex-refactor");ce(r,{recursive:!0,mode:448});const i=p(r);if(!i.isDirectory()||i.isSymbolicLink()||i.uid!==process.getuid?.()||(i.mode&63)!==0)throw new Error("refactor-root-store-unverified");return r}function C(s){return!s||s.length>512||Q(s)||s.includes("\\")||/[\u0000-\u001f\u007f:*?\[\]]/.test(s)||s.normalize("NFC")!==s?!1:!s.split("/").some(t=>!t||t==="."||t===".."||[".git",".neocortex","node_modules"].includes(t.toLowerCase()))}function le(s,o){if(!C(o))throw new Error("refactor-root-write-set-invalid");const t=b(s,o),r=p(t);if(v(t)!==t||!r.isFile()||r.isSymbolicLink()||r.size===0||r.size>N)throw new Error("refactor-root-write-set-invalid");const i=A(t);if(i.length===0||i.length>N)throw new Error("refactor-root-write-set-invalid");if(new TextDecoder("utf-8",{fatal:!0}).decode(i),i.includes(0))throw new Error("refactor-root-write-set-invalid");const n=E(s,["show",`HEAD:${o}`]);if(!i.equals(n))throw new Error("refactor-root-source-dirty");return Object.freeze({sha256:g(i),mode:r.mode&511})}function ee(s,o){try{return E(s,["check-ignore","--no-index","-q","--",o]),!0}catch(t){if(t.status===1)return!1;throw t}}function P(s,o){if(!C(o))throw new Error("refactor-root-write-set-invalid");const t=b(s,o),r=U(t),i=p(r);if(!i.isDirectory()||i.isSymbolicLink()||v(r)!==r||E(s,["ls-files","--stage","-z","--",o]).length>0||ee(s,o))throw new Error("refactor-root-write-set-invalid");try{throw p(t),new Error("refactor-root-write-set-invalid")}catch(n){if(n.code!=="ENOENT")throw n}}function _(s){return g(E(s,["ls-files","--stage","-z"]))}function D(s,o){const t=E(s,o);return new TextDecoder("utf-8",{fatal:!0}).decode(t).split("\0").filter(Boolean)}function M(s){if(D(s,["ls-files","-v","-z"]).some(t=>!t.startsWith("H ")))throw new Error("refactor-root-index-unverified")}function W(s){const o=[],t=new Set;let r=0;const i=D(s,["status","--porcelain=v1","-z","--untracked-files=all"]);i.push(...D(s,["ls-files","--others","--ignored","--exclude-standard","-z","--",".neocortex/"]).map(n=>`!! ${n}`));for(const n of i){if(n.length<4||n[2]!==" ")throw new Error("refactor-root-sidecar-unverified");const e=n.slice(3);if(!e.startsWith(".neocortex/"))continue;if(t.has(e)||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e)||e.split("/").some(l=>!l||l==="."||l===".."))throw new Error("refactor-root-sidecar-unverified");t.add(e);const d=b(s,e),f=p(d);if(v(d)!==d||!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>64*1024*1024)throw new Error("refactor-root-sidecar-unverified");if(r+=f.size,r>128*1024*1024)throw new Error("refactor-root-sidecar-unverified");const w=I(d,j.O_RDONLY|j.O_NOFOLLOW);try{const l=Buffer.alloc(f.size+1);let h=0;for(;h<l.length;){const u=fe(w,l,h,l.length-h,h);if(!u)break;h+=u}const m=ae(w),c=p(d);if(h!==f.size||v(d)!==d||[m,c].some(u=>u.dev!==f.dev||u.ino!==f.ino||u.size!==f.size||u.mtimeMs!==f.mtimeMs||u.ctimeMs!==f.ctimeMs||u.mode!==f.mode||u.nlink!==1))throw new Error("refactor-root-sidecar-unverified");o.push({status:n.slice(0,2),path:e,sha256:g(l.subarray(0,h)),mode:f.mode&511})}finally{q(w)}}return o.sort((n,e)=>Buffer.from(n.path).compare(Buffer.from(e.path))),g(JSON.stringify(o))}function V(s){return[...s].sort((o,t)=>Buffer.from(o).compare(Buffer.from(t)))}function te(s){const o=s.files.map(t=>t.path);return g(JSON.stringify(s.schemaVersion===1?o:{files:o,newFiles:s.newFiles.map(t=>t.path)}))}function re(s,o){if(!F.test(o))throw new Error("refactor-root-admission-invalid");return b(Z(s),`admission-${o}.json`)}function X(s,o){const t=re(s,o),r=p(t);if(!r.isFile()||r.isSymbolicLink()||r.uid!==process.getuid?.()||(r.mode&63)!==0||r.size<100||r.size>512*1024)throw new Error("refactor-root-admission-invalid");const i=A(t);if(i.length>512*1024)throw new Error("refactor-root-admission-invalid");let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error("refactor-root-admission-invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("refactor-root-admission-invalid");const e=n,d=e.schemaVersion===2,f=["schemaVersion","kind","storyId","sourceHead","storySha256","planSha256","indexSha256","sidecarSha256","files","admissionSha256"];if(d&&f.push("newFiles"),Object.keys(e).sort().join("\0")!==f.sort().join("\0")||![1,2].includes(e.schemaVersion)||e.kind!=="private-root-refactor-admission"||typeof e.storyId!="string"||!K.test(e.storyId)||typeof e.sourceHead!="string"||!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(e.sourceHead)||typeof e.storySha256!="string"||!F.test(e.storySha256)||typeof e.planSha256!="string"||!F.test(e.planSha256)||typeof e.indexSha256!="string"||!F.test(e.indexSha256)||typeof e.sidecarSha256!="string"||!F.test(e.sidecarSha256)||e.admissionSha256!==o||!Array.isArray(e.files)||e.files.length>Y||(d?!Array.isArray(e.newFiles)||e.newFiles.length<1||e.files.length+e.newFiles.length>Y:e.files.length<1))throw new Error("refactor-root-admission-invalid");if(g(`root-refactor-story-scope-v1\0${e.sourceHead}\0${e.storyId}\0${e.storySha256}`)!==e.planSha256)throw new Error("refactor-root-admission-invalid");const w=e.files;if(w.some(c=>!c||typeof c!="object"||Array.isArray(c)||Object.keys(c).sort().join("\0")!==["mode","path","sha256"].join("\0")||typeof c.path!="string"||!C(c.path)||typeof c.sha256!="string"||!F.test(c.sha256)||!Number.isSafeInteger(c.mode)||c.mode<0||c.mode>511))throw new Error("refactor-root-admission-invalid");const l=w.map(c=>c.path);if(new Set(l).size!==l.length||l.join("\0")!==V(l).join("\0"))throw new Error("refactor-root-admission-invalid");if(d){const c=e.newFiles;if(c.some(y=>!y||typeof y!="object"||Array.isArray(y)||Object.keys(y).join("\0")!=="path"||typeof y.path!="string"||!C(y.path)))throw new Error("refactor-root-admission-invalid");const u=c.map(y=>y.path);if(new Set([...l,...u]).size!==l.length+u.length||u.join("\0")!==V(u).join("\0")||[...l,...u].includes(`docs/stories/${e.storyId}.story.md`))throw new Error("refactor-root-admission-invalid")}const{admissionSha256:h,...m}=e;if(g(JSON.stringify(m))!==o||!i.equals(Buffer.from(`${JSON.stringify(e)}
|
|
2
|
+
`)))throw new Error("refactor-root-admission-invalid");return e}function he(s,o,t,r,i,n=[]){if(!i)throw new Error("refactor-root-authorization-required");if(!F.test(t)||r.length+n.length<1||r.length+n.length>Y)throw new Error("refactor-root-write-set-invalid");const e=L(s);try{const d=B(e,o);if(d.planSha256!==t)throw new Error("refactor-root-plan-stale");M(e);const f=_(e),w=W(e),l=V(r),h=V(n);if(new Set([...l,...h]).size!==l.length+h.length||[...l,...h].includes(`docs/stories/${o}.story.md`))throw new Error("refactor-root-write-set-invalid");const m=l.map(S=>Object.freeze({path:S,...le(e,S)})),c=h.map(S=>(P(e,S),Object.freeze({path:S})));if(_(e)!==f||W(e)!==w||B(e,o).planSha256!==t)throw new Error("refactor-root-source-dirty");for(const S of c)P(e,S.path);const u={kind:"private-root-refactor-admission",storyId:o,sourceHead:d.sourceHead,storySha256:d.storySha256,planSha256:t,indexSha256:f,sidecarSha256:w,files:m},y=c.length>0?{schemaVersion:2,...u,newFiles:c}:{schemaVersion:1,...u},k=g(JSON.stringify(y)),R={...y,admissionSha256:k},T=re(e,k),J=Buffer.from(`${JSON.stringify(R)}
|
|
3
|
+
`);if(ne(T))X(e,k);else{const S=I(T,j.O_WRONLY|j.O_CREAT|j.O_EXCL|(j.O_NOFOLLOW??0),384);try{de(S,J),G(S)}finally{q(S)}const a=I(Z(e),j.O_RDONLY|(j.O_DIRECTORY??0));try{G(a)}finally{q(a)}}if(X(e,k),_(e)!==f||W(e)!==w||B(e,o).planSha256!==t)throw new Error("refactor-root-source-dirty");for(const S of c)P(e,S.path);const $={kind:"root-refactor-write-set-admission",storyId:o,sourceHead:d.sourceHead,planSha256:t,writeSetSha256:te(R),admissionSha256:k,fileCount:m.length,rootEditPrepared:!0,privateChildAuthorized:!1,gitCommitAuthorized:!1,publicSafe:!0};return R.schemaVersion===2?Object.freeze({schemaVersion:2,...$,newFileCount:c.length}):Object.freeze({schemaVersion:1,...$})}catch(d){throw d instanceof Error&&d.message.startsWith("refactor-root-")?d:new Error("refactor-root-write-set-invalid")}}function oe(s,o){if(!C(o)||ee(s,o)||E(s,["ls-files","--stage","-z","--",o]).length>0)throw new Error("refactor-root-delta-outside-admission");const t=b(s,o),r=U(t);if(!p(r).isDirectory()||v(r)!==r)throw new Error("refactor-root-delta-outside-admission");const i=p(t);if(v(t)!==t||!i.isFile()||i.isSymbolicLink()||i.size===0||i.size>N||(i.mode&75)!==0)throw new Error("refactor-root-delta-outside-admission");const n=A(t);if(n.length===0||n.length>N||n.includes(0))throw new Error("refactor-root-delta-outside-admission");return new TextDecoder("utf-8",{fatal:!0}).decode(n),g(n)}function ue(s,o){return ie(s,o,!1).receipt}function ge(s,o){return ie(s,o,!0)}function ie(s,o,t){const r=L(s);try{const i=X(r,o),n=E(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(n!==i.sourceHead||_(r)!==i.indexSha256||W(r)!==i.sidecarSha256)throw new Error("refactor-root-baseline-stale");M(r);const e=b(r,"docs","stories",`${i.storyId}.story.md`),d=p(e);if(!d.isFile()||d.isSymbolicLink()||v(e)!==e||g(A(e))!==i.storySha256||g(E(r,["show",`HEAD:docs/stories/${i.storyId}.story.md`]))!==i.storySha256)throw new Error("refactor-root-baseline-stale");const f=D(r,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(a=>!a.startsWith(".neocortex/")),w=D(r,["ls-files","--others","--exclude-standard","-z"]).filter(a=>!a.startsWith(".neocortex/")),l=new Set(i.files.map(a=>a.path)),h=i.schemaVersion===2?i.newFiles.map(a=>a.path):[],m=[];if(t){for(const a of h)if(a.endsWith(".md"))try{p(b(r,a))}catch(z){if(z.code!=="ENOENT")throw z;P(r,a),m.push(a)}}const c=h.filter(a=>!m.includes(a)),u=new Set(h);if(f.length+w.length===0||w.length!==c.length||f.some(a=>!l.has(a))||w.some(a=>!u.has(a)))throw new Error("refactor-root-delta-outside-admission");let y=0;const k=[];for(const a of i.files){const z=b(r,a.path);if(g(E(r,["show",`HEAD:${a.path}`]))!==a.sha256)throw new Error("refactor-root-admission-invalid");const x=p(z);if(v(z)!==z||!x.isFile()||x.isSymbolicLink()||x.size===0||x.size>N||(x.mode&511)!==a.mode)throw new Error("refactor-root-delta-outside-admission");const O=A(z);if(O.length===0||O.length>N)throw new Error("refactor-root-delta-outside-admission");if(new TextDecoder("utf-8",{fatal:!0}).decode(O),O.includes(0))throw new Error("refactor-root-delta-outside-admission");const H=g(O);k.push(H),H!==a.sha256&&y++}const R=c.map(a=>oe(r,a));y+=R.length;const T=D(r,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]).filter(a=>!a.startsWith(".neocortex/")),J=D(r,["ls-files","--others","--exclude-standard","-z"]).filter(a=>!a.startsWith(".neocortex/"));if(M(r),y===0||y!==f.length+w.length||T.join("\0")!==f.join("\0")||J.join("\0")!==w.join("\0")||i.files.some((a,z)=>{const x=b(r,a.path),O=p(x);if(v(x)!==x||!O.isFile()||O.isSymbolicLink()||O.size>N||(O.mode&511)!==a.mode)return!0;const H=A(x);return H.length>N||g(H)!==k[z]})||c.some((a,z)=>oe(r,a)!==R[z])||_(r)!==i.indexSha256||W(r)!==i.sidecarSha256||E(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim()!==n)throw new Error("refactor-root-baseline-stale");for(const a of m)P(r,a);const $={kind:"root-refactor-delta-containment",storyId:i.storyId,sourceHead:i.sourceHead,planSha256:i.planSha256,admissionSha256:o,writeSetSha256:te(i),changedFileCount:y,rootEditContained:!0,qaAccepted:!1,gitCommitAuthorized:!1,publicSafe:!0},S=i.schemaVersion===2?Object.freeze({schemaVersion:2,...$,newFileCount:c.length}):Object.freeze({schemaVersion:1,...$});return Object.freeze({receipt:S,pendingDocumentationPaths:Object.freeze(m)})}catch(i){throw i instanceof Error&&i.message.startsWith("refactor-root-")?i:new Error("refactor-root-delta-unverified")}}function B(s,o){if(!K.test(o))throw new Error("refactor-root-story-invalid");const t=L(s);try{if(v(t)!==t||!p(t).isDirectory())throw new Error("refactor-root-source-unverified");if(E(t,["rev-parse","--show-toplevel"]).toString("utf8").trim()!==t)throw new Error("refactor-root-source-unverified");if(E(t,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(c=>!/^.{2} \.neocortex\//.test(c)))throw new Error("refactor-root-source-dirty");const n=E(t,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(n))throw new Error("refactor-root-source-unverified");const e=`docs/stories/${o}.story.md`,d=b(t,e),f=p(d);if(v(d)!==d||!f.isFile()||f.isSymbolicLink()||f.size===0||f.size>1024*1024)throw new Error("refactor-root-story-unverified");const w=A(d),l=E(t,["show",`HEAD:${e}`]);if(!w.equals(l))throw new Error("refactor-root-story-unverified");const h=g(w),m=g(`root-refactor-story-scope-v1\0${n}\0${o}\0${h}`);return Object.freeze({schemaVersion:1,kind:"root-refactor-story-scope",storyId:o,sourceHead:n,storySha256:h,planSha256:m,candidateWriteSetRequired:!0,characterizationRequired:!0,executionAuthorized:!1,gitAuthority:"ROOT_ONLY",graphExecution:"NOT_RUN",publicSafe:!0})}catch(r){throw r instanceof Error&&r.message.startsWith("refactor-root-")?r:new Error("refactor-root-source-unverified")}}function Se(s){let o="",t="",r="",i="",n="",e=!1;const d=[],f=[];let w="plain";try{const l=[...s];o=l.shift()??"";for(let h=0;h<l.length;h++){const m=l[h],c=()=>{const u=l[++h];if(!u||u.startsWith("--"))throw new Error("refactor-root-arguments-invalid");return u};if(m==="--project-root")t=c();else if(m==="--story")r=c();else if(m==="--plan-sha")i=c();else if(m==="--admission-sha")n=c();else if(m==="--path")d.push(c());else if(m==="--new-path")f.push(c());else if(m==="--authorize-root-edit")e=!0;else if(m==="--format")w=c();else throw new Error("refactor-root-arguments-invalid")}if(!t||!["plain","json"].includes(w))throw new Error("refactor-root-arguments-invalid");if(o==="plan"&&r&&!i&&!n&&d.length===0&&f.length===0&&!e){const h=B(t,r);process.stdout.write(`${JSON.stringify({ok:!0,plan:h})}
|
|
4
|
+
`)}else if(o==="admit"&&r&&i&&!n&&d.length+f.length>0){const h=he(t,r,i,d,e,f);process.stdout.write(`${JSON.stringify({ok:!0,admission:h})}
|
|
5
|
+
`)}else if(o==="verify"&&!r&&!i&&n&&d.length===0&&f.length===0&&!e){const h=ue(t,n);process.stdout.write(`${JSON.stringify({ok:!0,containment:h})}
|
|
6
|
+
`)}else throw new Error("refactor-root-arguments-invalid");return 0}catch(l){const h=l instanceof Error&&/^refactor-root-[a-z-]+$/.test(l.message)?l.message:"refactor-root-source-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:h})}
|
|
7
|
+
`),1}}export{he as admitRootRefactor,le as exactCommittedRefactorFile,B as planRootRefactor,Z as privateRefactorDirectory,X as readPrivateRefactorAdmission,Se as refactorRootCliHandler,W as refactorSidecarDigest,ue as verifyRootRefactor,ge as verifyRootRefactorForCharacterization};
|