@ornexus/neocortex 4.60.71 → 4.60.73
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 +1211 -1217
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +108 -1
- package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
- package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
- package/packages/client/dist/adapters/codex-adapter.js +80 -2
- package/packages/client/dist/adapters/cursor-adapter.js +115 -4
- package/packages/client/dist/adapters/gemini-adapter.js +71 -2
- package/packages/client/dist/adapters/grok-adapter.js +42 -2
- package/packages/client/dist/adapters/index.js +22 -1
- package/packages/client/dist/adapters/platform-detector.js +212 -1
- package/packages/client/dist/adapters/target-adapter.js +12 -0
- package/packages/client/dist/adapters/vscode-adapter.js +72 -2
- package/packages/client/dist/agent/refresh-stubs.js +417 -2
- package/packages/client/dist/agent/update-agent-yaml.js +102 -1
- package/packages/client/dist/agent/update-description.js +251 -1
- package/packages/client/dist/cache/crypto-utils.js +78 -1
- package/packages/client/dist/cache/encrypted-cache.js +108 -1
- package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
- package/packages/client/dist/cache/index.js +13 -1
- package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
- package/packages/client/dist/checkpoint/index.js +11 -1
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
- package/packages/client/dist/cli.js +358 -5
- package/packages/client/dist/commands/activate.js +394 -8
- package/packages/client/dist/commands/architecture-answers.js +274 -7
- package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
- package/packages/client/dist/commands/architecture-root-binding.js +51 -1
- package/packages/client/dist/commands/cache-status.js +112 -2
- package/packages/client/dist/commands/config.js +88 -1
- package/packages/client/dist/commands/doctor.js +635 -2
- package/packages/client/dist/commands/invoke.js +7200 -143
- package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
- package/packages/client/dist/commands/legacy-story-branch.js +96 -1
- package/packages/client/dist/commands/legacy-story-pr.js +276 -1
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
- package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
- package/packages/client/dist/commands/mutation-qa-git.js +41 -1
- package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
- package/packages/client/dist/commands/mutation-qa-run.js +219 -3
- package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
- package/packages/client/dist/commands/mutation-qa.js +220 -1
- package/packages/client/dist/commands/native-agent.js +136 -2
- package/packages/client/dist/commands/planning-diagnosis.js +43 -1
- package/packages/client/dist/commands/planning-generation.js +53 -1
- package/packages/client/dist/commands/planning-memory.js +40 -1
- package/packages/client/dist/commands/planning-research.js +42 -1
- package/packages/client/dist/commands/private-session.js +75 -1
- package/packages/client/dist/commands/property-qa.js +139 -1
- package/packages/client/dist/commands/qa-control.js +16 -1
- package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
- package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
- package/packages/client/dist/commands/qa-scan-capture.js +663 -5
- package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
- package/packages/client/dist/commands/qa-scan-review.js +826 -5
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
- package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
- package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
- package/packages/client/dist/commands/refactor-characterization.js +671 -21
- package/packages/client/dist/commands/refactor-commit.js +399 -13
- package/packages/client/dist/commands/refactor-control.js +142 -3
- package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
- package/packages/client/dist/commands/refactor-review.js +283 -5
- package/packages/client/dist/commands/refactor-root.js +588 -7
- package/packages/client/dist/commands/refresh-memory.js +156 -3
- package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
- package/packages/client/dist/commands/story-checkpoint.js +171 -1
- package/packages/client/dist/config/profile-directory.js +13 -1
- package/packages/client/dist/config/resolver-selection.js +278 -1
- package/packages/client/dist/config/secure-config.js +281 -12
- package/packages/client/dist/config.js +223 -2
- package/packages/client/dist/constants.js +25 -1
- package/packages/client/dist/context/context-collector.js +222 -2
- package/packages/client/dist/context/context-sanitizer.js +145 -1
- package/packages/client/dist/continuity/autonomous-governance.js +285 -1
- package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
- package/packages/client/dist/continuity/invoke-hooks.js +129 -1
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
- package/packages/client/dist/continuity/native-agent-store.js +69 -1
- package/packages/client/dist/continuity/native-agent-types.js +90 -1
- package/packages/client/dist/continuity/outbox.js +117 -1
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
- package/packages/client/dist/continuity/sqlite-store.d.ts +22 -1
- package/packages/client/dist/continuity/sqlite-store.js +2612 -81
- package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
- package/packages/client/dist/errors/error-messages.js +228 -2
- package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
- package/packages/client/dist/evidence/collector.js +347 -1
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +2 -0
- package/packages/client/dist/fs/atomic-state-replace.js +152 -1
- package/packages/client/dist/generated/command-registry.generated.js +4076 -1
- package/packages/client/dist/generated/public-projections.generated.js +149 -1
- package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
- package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
- package/packages/client/dist/git/epic-operational-state.d.ts +198 -0
- package/packages/client/dist/git/epic-operational-state.js +672 -0
- package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
- package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -1
- package/packages/client/dist/git/git-lifecycle-store.js +1981 -9
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
- package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
- package/packages/client/dist/git/legacy-story-pr.js +3538 -70
- package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
- package/packages/client/dist/i18n/first-run.js +60 -2
- package/packages/client/dist/index.js +47 -1
- package/packages/client/dist/invocation/invoke-input.js +24 -1
- package/packages/client/dist/license/index.js +5 -1
- package/packages/client/dist/license/license-client.js +304 -1
- package/packages/client/dist/machine/fingerprint.js +163 -2
- package/packages/client/dist/machine/index.js +5 -1
- package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
- package/packages/client/dist/memory/project-memory-writer.js +1007 -40
- package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
- package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +97 -0
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -0
- package/packages/client/dist/migrations/project-identity-capability.js +50 -1
- package/packages/client/dist/migrations/project-identity.js +493 -7
- package/packages/client/dist/migrations/state-json.d.ts +22 -0
- package/packages/client/dist/migrations/state-json.js +393 -4
- package/packages/client/dist/policy/architecture-policy.js +184 -2
- package/packages/client/dist/policy/index.js +7 -1
- package/packages/client/dist/policy/shared-policy-types.js +38 -0
- package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
- package/packages/client/dist/private-execution/clean-baseline.js +279 -2
- package/packages/client/dist/private-execution/codex-executor.js +574 -4
- package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
- package/packages/client/dist/private-execution/delivery.js +410 -13
- package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
- package/packages/client/dist/private-execution/implementation-validation.js +106 -2
- package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
- package/packages/client/dist/private-execution/isolated-session.js +725 -5
- package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
- package/packages/client/dist/private-execution/pact-test-source.js +258 -1
- package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
- package/packages/client/dist/private-execution/pact-write-set.js +172 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
- package/packages/client/dist/private-execution/private-report-store.js +42 -1
- package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
- package/packages/client/dist/private-execution/property-test-choices.js +147 -3
- package/packages/client/dist/private-execution/property-test-plan.js +271 -7
- package/packages/client/dist/private-execution/property-test-review.js +258 -4
- package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
- package/packages/client/dist/private-execution/property-test-source.js +139 -1
- package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
- package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
- package/packages/client/dist/private-execution/root-memory-request.js +29 -1
- package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
- package/packages/client/dist/private-execution/session-lease.js +63 -1
- package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
- package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
- package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
- package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
- package/packages/client/dist/private-execution/ux-write-set.js +191 -2
- package/packages/client/dist/registry/registry-reconciliation.js +234 -1
- package/packages/client/dist/resilience/circuit-breaker.js +170 -1
- package/packages/client/dist/resilience/degradation-manager.js +164 -1
- package/packages/client/dist/resilience/freshness-indicator.js +100 -1
- package/packages/client/dist/resilience/index.js +8 -1
- package/packages/client/dist/resilience/recovery-detector.js +74 -1
- package/packages/client/dist/resolvers/asset-resolver.js +13 -0
- package/packages/client/dist/resolvers/local-resolver.js +255 -8
- package/packages/client/dist/resolvers/remote-resolver.js +233 -1
- package/packages/client/dist/runner/binary.js +404 -1
- package/packages/client/dist/runner/cli.js +1571 -17
- package/packages/client/dist/runner/headless/adapters.js +49 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
- package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
- package/packages/client/dist/runner/headless/managed-profile.js +132 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
- package/packages/client/dist/runner/headless/resolver.js +231 -1
- package/packages/client/dist/runner/headless/run-yolo.js +885 -1
- package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
- package/packages/client/dist/runner/headless/types.js +574 -2
- package/packages/client/dist/runner/local-console.js +396 -13
- package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
- package/packages/client/dist/runner/project-identity.js +106 -1
- package/packages/client/dist/runner/scheduler.js +995 -7
- package/packages/client/dist/runner-cli.js +18 -2
- package/packages/client/dist/state/invocation-shape.js +13 -1
- package/packages/client/dist/state/project-state-snapshot.d.ts +8 -0
- package/packages/client/dist/state/project-state-snapshot.js +1731 -1
- package/packages/client/dist/state/state-json-repair.js +785 -3
- package/packages/client/dist/state/structural-dag-projection.js +118 -1
- package/packages/client/dist/telemetry/index.js +5 -1
- package/packages/client/dist/telemetry/offline-queue.js +131 -1
- package/packages/client/dist/tier/index.js +5 -1
- package/packages/client/dist/tier/tier-aware-client.js +405 -1
- package/packages/client/dist/types/index.js +38 -1
- package/packages/client/dist/version.js +27 -1
- package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
- package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
- package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
- package/packages/client/dist/yoloop/discovery-hook.js +300 -2
- package/packages/client/dist/yoloop/index.js +8 -1
- package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
- package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +65 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
- package/packages/client/dist/yoloop/target-normalization.js +180 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +8 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
- package/packages/shared/dist/yolo/spec-envelope.js +3 -6
- package/targets-stubs/antigravity/gemini.md +1 -1
- 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 +2 -2
- 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/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,13 +1,399 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
1
|
+
/** Root-owned, two-phase Git checkpoint for an accepted characterized refactor. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { mutationQaGit } from './mutation-qa-git.js';
|
|
6
|
+
import { privateRefactorDirectory, readPrivateRefactorAdmission, refactorSidecarDigest, verifyRootRefactor } from './refactor-root.js';
|
|
7
|
+
import { readRootRefactorSemanticReview } from './refactor-review.js';
|
|
8
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
9
|
+
const GIT_SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
|
|
10
|
+
function sha(value) {
|
|
11
|
+
return createHash('sha256').update(value).digest('hex');
|
|
12
|
+
}
|
|
13
|
+
function git(root, args) {
|
|
14
|
+
return mutationQaGit(root, args).toString('utf8').trim();
|
|
15
|
+
}
|
|
16
|
+
function names(root, args) {
|
|
17
|
+
return mutationQaGit(root, args).toString('utf8').split('\0').filter(Boolean);
|
|
18
|
+
}
|
|
19
|
+
function ordered(paths) {
|
|
20
|
+
return [...paths].sort((a, b) => Buffer.from(a).compare(Buffer.from(b)));
|
|
21
|
+
}
|
|
22
|
+
function exact(value, keys) {
|
|
23
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
24
|
+
&& Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
|
|
25
|
+
}
|
|
26
|
+
function physical(root, path) {
|
|
27
|
+
const target = join(root, path);
|
|
28
|
+
const stat = lstatSync(target);
|
|
29
|
+
if (!stat.isFile() || stat.isSymbolicLink() || realpathSync(target) !== target
|
|
30
|
+
|| stat.size < 1 || stat.size > 8 * 1024 * 1024) {
|
|
31
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
32
|
+
}
|
|
33
|
+
const bytes = readFileSync(target);
|
|
34
|
+
if (bytes.length !== stat.size)
|
|
35
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
36
|
+
return Object.freeze({ sha256: sha(bytes), mode: stat.mode & 0o777 });
|
|
37
|
+
}
|
|
38
|
+
function planPath(root, planSha256) {
|
|
39
|
+
if (!SHA256.test(planSha256))
|
|
40
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
41
|
+
return join(privateRefactorDirectory(root), `commit-plan-${planSha256}.json`);
|
|
42
|
+
}
|
|
43
|
+
function checkpointPath(root, planSha256) {
|
|
44
|
+
if (!SHA256.test(planSha256))
|
|
45
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
46
|
+
return join(privateRefactorDirectory(root), `commit-checkpoint-${planSha256}.json`);
|
|
47
|
+
}
|
|
48
|
+
function privateBytes(path, maximum) {
|
|
49
|
+
const stat = lstatSync(path);
|
|
50
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
51
|
+
|| (stat.mode & 0o077) !== 0 || stat.size < 100 || stat.size > maximum) {
|
|
52
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
53
|
+
}
|
|
54
|
+
const bytes = readFileSync(path);
|
|
55
|
+
if (bytes.length !== stat.size)
|
|
56
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
57
|
+
return bytes;
|
|
58
|
+
}
|
|
59
|
+
function persist(root, path, bytes) {
|
|
60
|
+
if (existsSync(path)) {
|
|
61
|
+
if (!privateBytes(path, 128 * 1024).equals(bytes)) {
|
|
62
|
+
throw new Error('refactor-root-commit-plan-conflict');
|
|
63
|
+
}
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const handle = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL
|
|
67
|
+
| (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
68
|
+
try {
|
|
69
|
+
writeFileSync(handle, bytes);
|
|
70
|
+
fsyncSync(handle);
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
closeSync(handle);
|
|
74
|
+
}
|
|
75
|
+
const directory = openSync(privateRefactorDirectory(root), constants.O_RDONLY
|
|
76
|
+
| (constants.O_DIRECTORY ?? 0));
|
|
77
|
+
try {
|
|
78
|
+
fsyncSync(directory);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
closeSync(directory);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function readPlan(root, planSha256) {
|
|
85
|
+
const raw = privateBytes(planPath(root, planSha256), 128 * 1024);
|
|
86
|
+
let parsed;
|
|
87
|
+
try {
|
|
88
|
+
parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
92
|
+
}
|
|
93
|
+
if (!exact(parsed, ['schemaVersion', 'kind', 'storyId', 'baseHead', 'branchRef',
|
|
94
|
+
'admissionSha256', 'baselineSha256', 'candidateSha256', 'reviewSha256',
|
|
95
|
+
'reviewRecordSha256', 'sidecarSha256', 'files', 'planSha256'])
|
|
96
|
+
|| parsed.schemaVersion !== 1 || parsed.kind !== 'private-root-refactor-commit-plan'
|
|
97
|
+
|| typeof parsed.storyId !== 'string' || !/^P[0-9]+(?:\.[0-9]+)+$/.test(parsed.storyId)
|
|
98
|
+
|| typeof parsed.baseHead !== 'string' || !GIT_SHA.test(parsed.baseHead)
|
|
99
|
+
|| typeof parsed.branchRef !== 'string'
|
|
100
|
+
|| ![`refs/heads/epic/${parsed.storyId.split('.')[0]}`,
|
|
101
|
+
`refs/heads/story/${parsed.storyId.split('.')[0]}/${parsed.storyId}`].includes(parsed.branchRef)
|
|
102
|
+
|| ![parsed.admissionSha256, parsed.baselineSha256, parsed.candidateSha256,
|
|
103
|
+
parsed.reviewSha256, parsed.reviewRecordSha256, parsed.sidecarSha256]
|
|
104
|
+
.every((value) => typeof value === 'string' && SHA256.test(value))
|
|
105
|
+
|| !Array.isArray(parsed.files) || parsed.files.length < 2 || parsed.files.length > 256
|
|
106
|
+
|| !parsed.files.every((file) => exact(file, ['path', 'sha256', 'mode'])
|
|
107
|
+
&& typeof file.path === 'string' && /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(file.path)
|
|
108
|
+
&& typeof file.sha256 === 'string' && SHA256.test(file.sha256)
|
|
109
|
+
&& Number.isSafeInteger(file.mode) && Number(file.mode) >= 0 && Number(file.mode) <= 0o777)
|
|
110
|
+
|| parsed.files.map((file) => file.path).join('\0')
|
|
111
|
+
!== ordered(parsed.files.map((file) => file.path)).join('\0')
|
|
112
|
+
|| new Set(parsed.files.map((file) => file.path)).size !== parsed.files.length
|
|
113
|
+
|| parsed.planSha256 !== planSha256) {
|
|
114
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
115
|
+
}
|
|
116
|
+
const { planSha256: _digest, ...body } = parsed;
|
|
117
|
+
if (sha(JSON.stringify(body)) !== planSha256
|
|
118
|
+
|| !raw.equals(Buffer.from(`${JSON.stringify(parsed)}\n`))) {
|
|
119
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
120
|
+
}
|
|
121
|
+
const admission = readPrivateRefactorAdmission(root, parsed.admissionSha256);
|
|
122
|
+
const admitted = new Set([...admission.files.map((file) => file.path),
|
|
123
|
+
...(admission.schemaVersion === 2 ? admission.newFiles.map((file) => file.path) : [])]);
|
|
124
|
+
if (admission.storyId !== parsed.storyId || admission.sourceHead !== parsed.baseHead
|
|
125
|
+
|| admission.sidecarSha256 !== parsed.sidecarSha256
|
|
126
|
+
|| parsed.files.some((file) => !admitted.has(file.path))) {
|
|
127
|
+
throw new Error('refactor-root-commit-plan-invalid');
|
|
128
|
+
}
|
|
129
|
+
return parsed;
|
|
130
|
+
}
|
|
131
|
+
function reviewRecordPath(root, plan) {
|
|
132
|
+
return join(privateRefactorDirectory(root), `review-${plan.admissionSha256}-${plan.candidateSha256}.json`);
|
|
133
|
+
}
|
|
134
|
+
function commitSubject(storyId) {
|
|
135
|
+
return `refactor(${storyId}): characterized change`;
|
|
136
|
+
}
|
|
137
|
+
function commitTrailer(planSha256) {
|
|
138
|
+
return `Neocortex-Refactor-Plan: ${planSha256}`;
|
|
139
|
+
}
|
|
140
|
+
function branch(root) {
|
|
141
|
+
return git(root, ['symbolic-ref', '-q', 'HEAD']);
|
|
142
|
+
}
|
|
143
|
+
function allowedDirty(root) {
|
|
144
|
+
return names(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
|
|
145
|
+
.every((entry) => entry.length >= 4 && entry[2] === ' ' && entry.slice(3).startsWith('.neocortex/'));
|
|
146
|
+
}
|
|
147
|
+
export function prepareRootRefactorCommit(projectRoot, admissionSha256, baselineSha256, authorizeRootPlan) {
|
|
148
|
+
if (!authorizeRootPlan)
|
|
149
|
+
throw new Error('refactor-root-commit-authorization-required');
|
|
150
|
+
try {
|
|
151
|
+
const root = resolve(projectRoot);
|
|
152
|
+
const accepted = readRootRefactorSemanticReview(root, admissionSha256, baselineSha256);
|
|
153
|
+
const admission = readPrivateRefactorAdmission(root, admissionSha256);
|
|
154
|
+
const containment = verifyRootRefactor(root, admissionSha256);
|
|
155
|
+
const branchRef = branch(root);
|
|
156
|
+
const epicId = admission.storyId.split('.')[0];
|
|
157
|
+
if (![`refs/heads/epic/${epicId}`,
|
|
158
|
+
`refs/heads/story/${epicId}/${admission.storyId}`].includes(branchRef)) {
|
|
159
|
+
throw new Error('refactor-root-commit-branch-invalid');
|
|
160
|
+
}
|
|
161
|
+
const tracked = names(root, ['diff', '--name-only', '-z', '--no-ext-diff', '--no-textconv']);
|
|
162
|
+
const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z']);
|
|
163
|
+
const paths = ordered([...tracked, ...untracked].filter((path) => !path.startsWith('.neocortex/')));
|
|
164
|
+
const admitted = new Set([...admission.files.map((file) => file.path),
|
|
165
|
+
...(admission.schemaVersion === 2 ? admission.newFiles.map((file) => file.path) : [])]);
|
|
166
|
+
if (paths.length !== containment.changedFileCount || paths.some((path) => !admitted.has(path))) {
|
|
167
|
+
throw new Error('refactor-root-commit-delta-invalid');
|
|
168
|
+
}
|
|
169
|
+
const files = paths.map((path) => Object.freeze({ path, ...physical(root, path) }));
|
|
170
|
+
const reviewRecordSha256 = sha(privateBytes(reviewRecordPath(root, {
|
|
171
|
+
admissionSha256, candidateSha256: accepted.candidateSha256,
|
|
172
|
+
}), 128 * 1024));
|
|
173
|
+
const body = { schemaVersion: 1, kind: 'private-root-refactor-commit-plan',
|
|
174
|
+
storyId: admission.storyId, baseHead: admission.sourceHead, branchRef,
|
|
175
|
+
admissionSha256, baselineSha256, candidateSha256: accepted.candidateSha256,
|
|
176
|
+
reviewSha256: accepted.reviewSha256, reviewRecordSha256,
|
|
177
|
+
sidecarSha256: admission.sidecarSha256, files };
|
|
178
|
+
const planSha256 = sha(JSON.stringify(body));
|
|
179
|
+
const record = { ...body, planSha256 };
|
|
180
|
+
if (git(root, ['rev-parse', '--verify', 'HEAD']) !== admission.sourceHead
|
|
181
|
+
|| refactorSidecarDigest(root) !== admission.sidecarSha256
|
|
182
|
+
|| files.some((file) => {
|
|
183
|
+
const current = physical(root, file.path);
|
|
184
|
+
return current.sha256 !== file.sha256 || current.mode !== file.mode;
|
|
185
|
+
})) {
|
|
186
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
187
|
+
}
|
|
188
|
+
persist(root, planPath(root, planSha256), Buffer.from(`${JSON.stringify(record)}\n`));
|
|
189
|
+
readPlan(root, planSha256);
|
|
190
|
+
return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-commit-plan',
|
|
191
|
+
storyId: admission.storyId, baseHead: admission.sourceHead, branchRef,
|
|
192
|
+
planSha256, fileCount: files.length, commitSubject: commitSubject(admission.storyId),
|
|
193
|
+
commitTrailer: commitTrailer(planSha256), gitCommitAuthorized: false,
|
|
194
|
+
checkpointAccepted: false, publicSafe: true });
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
|
|
198
|
+
throw error;
|
|
199
|
+
throw new Error('refactor-root-commit-unverified');
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export function verifyRootRefactorStaged(projectRoot, planSha256) {
|
|
203
|
+
try {
|
|
204
|
+
const root = resolve(projectRoot);
|
|
205
|
+
const plan = readPlan(root, planSha256);
|
|
206
|
+
if (branch(root) !== plan.branchRef || git(root, ['rev-parse', '--verify', 'HEAD']) !== plan.baseHead
|
|
207
|
+
|| refactorSidecarDigest(root) !== plan.sidecarSha256
|
|
208
|
+
|| sha(privateBytes(reviewRecordPath(root, plan), 128 * 1024)) !== plan.reviewRecordSha256) {
|
|
209
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
210
|
+
}
|
|
211
|
+
const staged = ordered(names(root, ['diff', '--cached', '--name-only', '-z', '--no-renames']));
|
|
212
|
+
const expected = plan.files.map((file) => file.path);
|
|
213
|
+
const unstaged = names(root, ['diff', '--name-only', '-z', '--no-renames'])
|
|
214
|
+
.filter((path) => !path.startsWith('.neocortex/'));
|
|
215
|
+
const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z'])
|
|
216
|
+
.filter((path) => !path.startsWith('.neocortex/'));
|
|
217
|
+
if (staged.join('\0') !== expected.join('\0') || unstaged.length || untracked.length) {
|
|
218
|
+
throw new Error('refactor-root-commit-staged-invalid');
|
|
219
|
+
}
|
|
220
|
+
for (const file of plan.files) {
|
|
221
|
+
const index = mutationQaGit(root, ['ls-files', '--stage', '-z', '--', file.path]).toString('utf8');
|
|
222
|
+
const match = index.match(/^(100644|100755) [a-f0-9]{40,64} 0\t([^\0]+)\0$/);
|
|
223
|
+
if (!match || match[2] !== file.path
|
|
224
|
+
|| match[1] !== ((file.mode & 0o111) ? '100755' : '100644')
|
|
225
|
+
|| sha(mutationQaGit(root, ['show', `:${file.path}`])) !== file.sha256
|
|
226
|
+
|| physical(root, file.path).sha256 !== file.sha256
|
|
227
|
+
|| physical(root, file.path).mode !== file.mode) {
|
|
228
|
+
throw new Error('refactor-root-commit-staged-invalid');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (branch(root) !== plan.branchRef || git(root, ['rev-parse', '--verify', 'HEAD']) !== plan.baseHead
|
|
232
|
+
|| refactorSidecarDigest(root) !== plan.sidecarSha256) {
|
|
233
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
234
|
+
}
|
|
235
|
+
return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-staged-verification',
|
|
236
|
+
planSha256, baseHead: plan.baseHead, fileCount: plan.files.length,
|
|
237
|
+
stagedWriteSetSha256: sha(JSON.stringify(plan.files)), gitCommitAuthorized: true,
|
|
238
|
+
checkpointAccepted: false, publicSafe: true });
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
|
|
242
|
+
throw error;
|
|
243
|
+
throw new Error('refactor-root-commit-unverified');
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function physicalCommit(root, plan) {
|
|
247
|
+
const head = git(root, ['rev-parse', '--verify', 'HEAD']);
|
|
248
|
+
const parents = git(root, ['show', '-s', '--format=%P', head]);
|
|
249
|
+
const object = mutationQaGit(root, ['cat-file', 'commit', head]);
|
|
250
|
+
const bodyOffset = object.indexOf(Buffer.from('\n\n'));
|
|
251
|
+
const message = bodyOffset < 0 ? Buffer.alloc(0) : object.subarray(bodyOffset + 2);
|
|
252
|
+
const expectedMessage = Buffer.from(`${commitSubject(plan.storyId)}\n\n${commitTrailer(plan.planSha256)}\n`);
|
|
253
|
+
if (!GIT_SHA.test(head) || parents !== plan.baseHead || !message.equals(expectedMessage)
|
|
254
|
+
|| branch(root) !== plan.branchRef || !allowedDirty(root)
|
|
255
|
+
|| refactorSidecarDigest(root) !== plan.sidecarSha256
|
|
256
|
+
|| sha(privateBytes(reviewRecordPath(root, plan), 128 * 1024)) !== plan.reviewRecordSha256) {
|
|
257
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
258
|
+
}
|
|
259
|
+
const changed = ordered(names(root, ['diff-tree', '--no-commit-id', '--name-only',
|
|
260
|
+
'--no-renames', '-r', '-z', head]));
|
|
261
|
+
if (changed.join('\0') !== plan.files.map((file) => file.path).join('\0')) {
|
|
262
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
263
|
+
}
|
|
264
|
+
for (const file of plan.files) {
|
|
265
|
+
const entry = mutationQaGit(root, ['ls-tree', '-z', head, '--', file.path]).toString('utf8');
|
|
266
|
+
const match = entry.match(/^(100644|100755) blob [a-f0-9]{40,64}\t([^\0]+)\0$/);
|
|
267
|
+
if (!match || match[2] !== file.path
|
|
268
|
+
|| match[1] !== ((file.mode & 0o111) ? '100755' : '100644')
|
|
269
|
+
|| sha(mutationQaGit(root, ['show', `${head}:${file.path}`])) !== file.sha256
|
|
270
|
+
|| physical(root, file.path).sha256 !== file.sha256
|
|
271
|
+
|| physical(root, file.path).mode !== file.mode) {
|
|
272
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (git(root, ['rev-parse', '--verify', 'HEAD']) !== head || branch(root) !== plan.branchRef) {
|
|
276
|
+
throw new Error('refactor-root-commit-physical-drift');
|
|
277
|
+
}
|
|
278
|
+
return head;
|
|
279
|
+
}
|
|
280
|
+
export function sealRootRefactorCommit(projectRoot, planSha256, authorizeRootSeal) {
|
|
281
|
+
if (!authorizeRootSeal)
|
|
282
|
+
throw new Error('refactor-root-commit-authorization-required');
|
|
283
|
+
try {
|
|
284
|
+
const root = resolve(projectRoot);
|
|
285
|
+
const plan = readPlan(root, planSha256);
|
|
286
|
+
const commitSha = physicalCommit(root, plan);
|
|
287
|
+
const receipt = Object.freeze({ schemaVersion: 1,
|
|
288
|
+
kind: 'root-refactor-commit-checkpoint', storyId: plan.storyId,
|
|
289
|
+
baseHead: plan.baseHead, commitSha, branchRef: plan.branchRef,
|
|
290
|
+
planSha256, candidateSha256: plan.candidateSha256, reviewSha256: plan.reviewSha256,
|
|
291
|
+
fileCount: plan.files.length, checkpointAccepted: true,
|
|
292
|
+
graphExecution: 'NOT_RUN', publicSafe: true });
|
|
293
|
+
persist(root, checkpointPath(root, planSha256), Buffer.from(`${JSON.stringify(receipt)}\n`));
|
|
294
|
+
if (!privateBytes(checkpointPath(root, planSha256), 8 * 1024)
|
|
295
|
+
.equals(Buffer.from(`${JSON.stringify(receipt)}\n`))) {
|
|
296
|
+
throw new Error('refactor-root-commit-checkpoint-invalid');
|
|
297
|
+
}
|
|
298
|
+
return receipt;
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
|
|
302
|
+
throw error;
|
|
303
|
+
throw new Error('refactor-root-commit-unverified');
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
export function readRootRefactorCommitCheckpoint(projectRoot, planSha256) {
|
|
307
|
+
try {
|
|
308
|
+
const root = resolve(projectRoot);
|
|
309
|
+
const plan = readPlan(root, planSha256);
|
|
310
|
+
const commitSha = physicalCommit(root, plan);
|
|
311
|
+
const bytes = privateBytes(checkpointPath(root, planSha256), 8 * 1024);
|
|
312
|
+
const receipt = JSON.parse(bytes.toString('utf8'));
|
|
313
|
+
if (!exact(receipt, ['schemaVersion', 'kind', 'storyId', 'baseHead', 'commitSha',
|
|
314
|
+
'branchRef', 'planSha256', 'candidateSha256', 'reviewSha256', 'fileCount',
|
|
315
|
+
'checkpointAccepted', 'graphExecution', 'publicSafe'])
|
|
316
|
+
|| receipt.schemaVersion !== 1 || receipt.kind !== 'root-refactor-commit-checkpoint'
|
|
317
|
+
|| receipt.commitSha !== commitSha || receipt.planSha256 !== planSha256
|
|
318
|
+
|| receipt.storyId !== plan.storyId || receipt.baseHead !== plan.baseHead
|
|
319
|
+
|| receipt.branchRef !== plan.branchRef || receipt.candidateSha256 !== plan.candidateSha256
|
|
320
|
+
|| receipt.reviewSha256 !== plan.reviewSha256 || receipt.fileCount !== plan.files.length
|
|
321
|
+
|| receipt.checkpointAccepted !== true || receipt.graphExecution !== 'NOT_RUN'
|
|
322
|
+
|| receipt.publicSafe !== true || !bytes.equals(Buffer.from(`${JSON.stringify(receipt)}\n`))) {
|
|
323
|
+
throw new Error('refactor-root-commit-checkpoint-invalid');
|
|
324
|
+
}
|
|
325
|
+
return receipt;
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
throw new Error('refactor-root-commit-checkpoint-invalid');
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
export function refactorCommitCliHandler(args) {
|
|
332
|
+
const action = args[0];
|
|
333
|
+
let projectRoot = '';
|
|
334
|
+
let admissionSha256 = '';
|
|
335
|
+
let baselineSha256 = '';
|
|
336
|
+
let planSha256 = '';
|
|
337
|
+
let authorizeRun = false;
|
|
338
|
+
let authorizePlan = false;
|
|
339
|
+
let authorizeSeal = false;
|
|
340
|
+
let format = 'plain';
|
|
341
|
+
const seen = new Set();
|
|
342
|
+
try {
|
|
343
|
+
if (!['commit-plan', 'commit-staged', 'commit-seal', 'commit-status'].includes(action ?? '')) {
|
|
344
|
+
throw new Error('refactor-root-commit-arguments-invalid');
|
|
345
|
+
}
|
|
346
|
+
for (let index = 1; index < args.length; index++) {
|
|
347
|
+
const token = args[index];
|
|
348
|
+
if (seen.has(token))
|
|
349
|
+
throw new Error('refactor-root-commit-arguments-invalid');
|
|
350
|
+
seen.add(token);
|
|
351
|
+
const next = () => {
|
|
352
|
+
const value = args[++index];
|
|
353
|
+
if (!value || value.startsWith('--'))
|
|
354
|
+
throw new Error('refactor-root-commit-arguments-invalid');
|
|
355
|
+
return value;
|
|
356
|
+
};
|
|
357
|
+
if (token === '--project-root')
|
|
358
|
+
projectRoot = next();
|
|
359
|
+
else if (token === '--admission-sha')
|
|
360
|
+
admissionSha256 = next();
|
|
361
|
+
else if (token === '--baseline-sha')
|
|
362
|
+
baselineSha256 = next();
|
|
363
|
+
else if (token === '--plan-sha')
|
|
364
|
+
planSha256 = next();
|
|
365
|
+
else if (token === '--authorize-run')
|
|
366
|
+
authorizeRun = true;
|
|
367
|
+
else if (token === '--authorize-root-commit-plan')
|
|
368
|
+
authorizePlan = true;
|
|
369
|
+
else if (token === '--authorize-root-seal')
|
|
370
|
+
authorizeSeal = true;
|
|
371
|
+
else if (token === '--format')
|
|
372
|
+
format = next();
|
|
373
|
+
else
|
|
374
|
+
throw new Error('refactor-root-commit-arguments-invalid');
|
|
375
|
+
}
|
|
376
|
+
if (!projectRoot || !['plain', 'json'].includes(format)
|
|
377
|
+
|| (action === 'commit-plan' && (!SHA256.test(admissionSha256)
|
|
378
|
+
|| !SHA256.test(baselineSha256) || planSha256 || !authorizeRun
|
|
379
|
+
|| !authorizePlan || authorizeSeal))
|
|
380
|
+
|| (action !== 'commit-plan' && (!SHA256.test(planSha256)
|
|
381
|
+
|| admissionSha256 || baselineSha256 || authorizeRun || authorizePlan
|
|
382
|
+
|| authorizeSeal !== (action === 'commit-seal')))) {
|
|
383
|
+
throw new Error('refactor-root-commit-arguments-invalid');
|
|
384
|
+
}
|
|
385
|
+
const result = action === 'commit-plan'
|
|
386
|
+
? prepareRootRefactorCommit(projectRoot, admissionSha256, baselineSha256, authorizePlan)
|
|
387
|
+
: action === 'commit-staged' ? verifyRootRefactorStaged(projectRoot, planSha256)
|
|
388
|
+
: action === 'commit-seal' ? sealRootRefactorCommit(projectRoot, planSha256, authorizeSeal)
|
|
389
|
+
: readRootRefactorCommitCheckpoint(projectRoot, planSha256);
|
|
390
|
+
process.stdout.write(`${JSON.stringify({ ok: true, result })}\n`);
|
|
391
|
+
return 0;
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
const reasonCode = error instanceof Error && /^refactor-root-[a-z-]+$/.test(error.message)
|
|
395
|
+
? error.message : 'refactor-root-commit-unverified';
|
|
396
|
+
process.stdout.write(`${JSON.stringify({ ok: false, reasonCode })}\n`);
|
|
397
|
+
return 1;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
@@ -1,3 +1,142 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/** Mechanical authenticated control transport; workflow decisions stay server-side. */
|
|
2
|
+
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { signNxInvokeRequest } from '../../../shared/dist/nx-invoke-signature.js';
|
|
5
|
+
import { COMMAND_REGISTRY_VERSION, COMMAND_REGISTRY_CHECKSUM } from '../generated/command-registry.generated.js';
|
|
6
|
+
import { CLIENT_VERSION } from '../version.js';
|
|
7
|
+
import { loadSecureConfig } from '../config/secure-config.js';
|
|
8
|
+
import { neocortexProfileDirectory } from '../config/profile-directory.js';
|
|
9
|
+
import { EncryptedCache } from '../cache/encrypted-cache.js';
|
|
10
|
+
import { LicenseClient } from '../license/license-client.js';
|
|
11
|
+
import { detectPlatform } from '../adapters/platform-detector.js';
|
|
12
|
+
const CONTROL_ERRORS = new Set([
|
|
13
|
+
'refactor-control-input-invalid', 'refactor-control-auth-required',
|
|
14
|
+
'refactor-control-tier-required', 'refactor-control-read-only',
|
|
15
|
+
'refactor-control-signature-required', 'refactor-control-client-unsupported',
|
|
16
|
+
'refactor-control-registry-mismatch', 'refactor-control-executor-unavailable',
|
|
17
|
+
]);
|
|
18
|
+
const CLIENT_CONTROL_ERRORS = new Set(['arguments-invalid', 'authorization-required', 'host-unsupported',
|
|
19
|
+
'project-unbound', 'auth-required', 'response-invalid', 'request-refused', 'outcome-unknown']
|
|
20
|
+
.map(code => `refactor-root-control-${code}`));
|
|
21
|
+
/** Enforce the byte budget while receiving; do not buffer an unbounded body. */
|
|
22
|
+
async function readControlResponse(response) {
|
|
23
|
+
const reader = response.body?.getReader();
|
|
24
|
+
if (!reader)
|
|
25
|
+
throw new Error('refactor-root-control-response-invalid');
|
|
26
|
+
let complete = false;
|
|
27
|
+
try {
|
|
28
|
+
const chunks = [];
|
|
29
|
+
let size = 0;
|
|
30
|
+
for (;;) {
|
|
31
|
+
const next = await reader.read();
|
|
32
|
+
if (next.done) {
|
|
33
|
+
complete = true;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
size += next.value.byteLength;
|
|
37
|
+
if (size > 16384)
|
|
38
|
+
throw new Error('refactor-root-control-response-invalid');
|
|
39
|
+
chunks.push(Buffer.from(next.value));
|
|
40
|
+
}
|
|
41
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new Error('refactor-root-control-response-invalid');
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
if (!complete)
|
|
48
|
+
await reader.cancel().catch(() => undefined);
|
|
49
|
+
reader.releaseLock();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export async function requestRootControl(family, input, fetchFn = fetch) {
|
|
53
|
+
if (family !== 'refactor' && family !== 'qa')
|
|
54
|
+
throw new Error('refactor-root-control-arguments-invalid');
|
|
55
|
+
const target = `/api/v1/invoke/${family}/control`;
|
|
56
|
+
const attempt = signNxInvokeRequest({ method: 'POST', target,
|
|
57
|
+
body: Buffer.from(JSON.stringify({ projectId: input.projectId, storyId: input.storyId,
|
|
58
|
+
platformTarget: input.platformTarget, registryVersion: COMMAND_REGISTRY_VERSION, registryChecksum: COMMAND_REGISTRY_CHECKSUM })),
|
|
59
|
+
bearerToken: input.token, clientVersion: CLIENT_VERSION });
|
|
60
|
+
const response = await fetchFn(`${input.serverUrl.replace(/\/+$/, '')}${target}`, {
|
|
61
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(200000),
|
|
62
|
+
headers: { ...attempt.headers, Authorization: `Bearer ${input.token}` }, body: attempt.body,
|
|
63
|
+
});
|
|
64
|
+
const value = await readControlResponse(response);
|
|
65
|
+
if (!response.ok)
|
|
66
|
+
throw new Error(typeof value?.error_code === 'string'
|
|
67
|
+
&& CONTROL_ERRORS.has(value.error_code.replace(/^qa-/, 'refactor-')) && value.error_code.startsWith(`${family}-`) ? value.error_code : 'refactor-root-control-request-refused');
|
|
68
|
+
const keys = ['schemaVersion', 'kind', 'status', 'completedStages', 'authority', 'qaAccepted', 'gitAuthority', 'billingAuthority', 'publicSafe'];
|
|
69
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
70
|
+
|| Object.keys(value).some(key => !keys.includes(key))
|
|
71
|
+
|| value.schemaVersion !== 1 || value.kind !== `root-${family}-control`
|
|
72
|
+
|| typeof value.status !== 'string' || !['advanced', 'waiting', 'blocked', 'candidate-ready', ...(family === 'qa' ? ['debt'] : [])].includes(value.status)
|
|
73
|
+
|| value.authority !== (family === 'qa' ? 'LOCAL_ROOT_QA_CANDIDATE_ONLY' : 'LOCAL_ROOT_CANDIDATE_ONLY') || value.qaAccepted !== false
|
|
74
|
+
|| value.gitAuthority !== 'NONE' || value.billingAuthority !== 'NONE' || value.publicSafe !== true
|
|
75
|
+
|| value.completedStages !== undefined && (typeof value.completedStages !== 'number' || !Number.isInteger(value.completedStages)
|
|
76
|
+
|| value.completedStages < 0 || value.completedStages > (family === 'qa' ? 3 : 7))) {
|
|
77
|
+
throw new Error('refactor-root-control-response-invalid');
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
export async function requestRefactorControl(input, fetchFn = fetch) {
|
|
82
|
+
return requestRootControl('refactor', input, fetchFn);
|
|
83
|
+
}
|
|
84
|
+
export async function refactorControlCliHandler(args, family = 'refactor') {
|
|
85
|
+
try {
|
|
86
|
+
let root = '';
|
|
87
|
+
let storyId = '';
|
|
88
|
+
let authorized = false;
|
|
89
|
+
let format = 'json';
|
|
90
|
+
const tokens = [...args];
|
|
91
|
+
if (tokens.shift() !== 'control')
|
|
92
|
+
throw new Error('refactor-root-control-arguments-invalid');
|
|
93
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
94
|
+
const token = tokens[i];
|
|
95
|
+
if (token === '--authorize-root-control')
|
|
96
|
+
authorized = true;
|
|
97
|
+
else if (token === '--project-root')
|
|
98
|
+
root = tokens[++i] ?? '';
|
|
99
|
+
else if (token === '--story')
|
|
100
|
+
storyId = tokens[++i] ?? '';
|
|
101
|
+
else if (token === '--format')
|
|
102
|
+
format = tokens[++i] ?? '';
|
|
103
|
+
else
|
|
104
|
+
throw new Error('refactor-root-control-arguments-invalid');
|
|
105
|
+
}
|
|
106
|
+
if (!authorized || !root || format !== 'json' || !/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/.test(storyId)) {
|
|
107
|
+
throw new Error('refactor-root-control-authorization-required');
|
|
108
|
+
}
|
|
109
|
+
const platformTarget = detectPlatform({ cwd: resolve(root), env: process.env }).targetId;
|
|
110
|
+
if (platformTarget !== 'codex')
|
|
111
|
+
throw new Error('refactor-root-control-host-unsupported');
|
|
112
|
+
const path = join(resolve(root), '.neocortex', 'state.json');
|
|
113
|
+
const stat = lstatSync(path);
|
|
114
|
+
if (!stat.isFile() || stat.isSymbolicLink() || realpathSync(path) !== path || stat.size > 16 * 1024 * 1024) {
|
|
115
|
+
throw new Error('refactor-root-control-project-unbound');
|
|
116
|
+
}
|
|
117
|
+
const projectId = JSON.parse(readFileSync(path, 'utf8')).config?.project_id;
|
|
118
|
+
if (typeof projectId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(projectId)) {
|
|
119
|
+
throw new Error('refactor-root-control-project-unbound');
|
|
120
|
+
}
|
|
121
|
+
const config = loadSecureConfig({ strictReadOnly: true });
|
|
122
|
+
if (!config?.licenseKey)
|
|
123
|
+
throw new Error('refactor-root-control-auth-required');
|
|
124
|
+
const serverUrl = process.env.NEOCORTEX_SERVER_URL ?? config.serverUrl;
|
|
125
|
+
if (!serverUrl)
|
|
126
|
+
throw new Error('refactor-root-control-auth-required');
|
|
127
|
+
const token = await new LicenseClient({ serverUrl, licenseKey: config.licenseKey,
|
|
128
|
+
cacheProvider: new EncryptedCache({ cacheDir: join(neocortexProfileDirectory(), 'cache'), passphrase: config.licenseKey }) }).getToken();
|
|
129
|
+
if (!token)
|
|
130
|
+
throw new Error('refactor-root-control-auth-required');
|
|
131
|
+
const result = await requestRootControl(family, { serverUrl, token, projectId, storyId, platformTarget });
|
|
132
|
+
process.stdout.write(`${JSON.stringify({ ok: true, control: result })}\n`);
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
const message = error instanceof Error ? error.message.replace(/^qa-/, 'refactor-') : '';
|
|
137
|
+
const reasonCode = CLIENT_CONTROL_ERRORS.has(message) || CONTROL_ERRORS.has(message)
|
|
138
|
+
? message : 'refactor-root-control-outcome-unknown';
|
|
139
|
+
process.stdout.write(`${JSON.stringify({ ok: false, reasonCode: family === 'qa' ? reasonCode.replace(/^refactor-/, 'qa-') : reasonCode })}\n`);
|
|
140
|
+
return 1;
|
|
141
|
+
}
|
|
142
|
+
}
|