@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,7 +1,274 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
/**
|
|
2
|
+
* P222.26: root-owned, local-only collection of the five Pact decisions.
|
|
3
|
+
* The answers never enter invoke args, tracked state, public metadata or logs.
|
|
4
|
+
* Saving this record does not authorize a private architecture child.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
9
|
+
import { closeSync, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
10
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
11
|
+
const MAX_INPUT_BYTES = 4096;
|
|
12
|
+
const PACT_QUESTION_IDS = Object.freeze([
|
|
13
|
+
'PACT-Q1-CONSUMER', 'PACT-Q2-PROVIDER', 'PACT-Q3-BROKER',
|
|
14
|
+
'PACT-Q4-MATCHERS', 'PACT-Q5-VERIFY',
|
|
15
|
+
]);
|
|
16
|
+
const STAGE_CHAIN = Object.freeze([
|
|
17
|
+
'arch-prd', 'arch-architecture', 'arch-fitness-functions', 'arch-api-contracts',
|
|
18
|
+
]);
|
|
19
|
+
function object(value) {
|
|
20
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
}
|
|
22
|
+
function exactKeys(value, keys) {
|
|
23
|
+
return Object.keys(value).length === keys.length
|
|
24
|
+
&& keys.every((key) => Object.hasOwn(value, key));
|
|
25
|
+
}
|
|
26
|
+
function safeName(value) {
|
|
27
|
+
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(value);
|
|
28
|
+
}
|
|
29
|
+
function safeBrokerUrl(value) {
|
|
30
|
+
if (value === null)
|
|
31
|
+
return true;
|
|
32
|
+
if (typeof value !== 'string' || value.length > 512
|
|
33
|
+
|| !value.startsWith('https://') || /[\s\\]/.test(value))
|
|
34
|
+
return false;
|
|
35
|
+
try {
|
|
36
|
+
const url = new URL(value);
|
|
37
|
+
return url.protocol === 'https:' && !!url.hostname && !url.username && !url.password
|
|
38
|
+
&& !url.search && !url.hash;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function parseAnswers(value) {
|
|
45
|
+
if (!object(value) || !exactKeys(value, [
|
|
46
|
+
'consumer', 'provider', 'brokerUrl', 'matchersAggressive', 'generateProvider',
|
|
47
|
+
]) || !safeName(value.consumer) || !safeName(value.provider)
|
|
48
|
+
|| !safeBrokerUrl(value.brokerUrl)
|
|
49
|
+
|| typeof value.matchersAggressive !== 'boolean'
|
|
50
|
+
|| typeof value.generateProvider !== 'boolean') {
|
|
51
|
+
throw new Error('architecture-answers-invalid');
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
consumer: value.consumer, provider: value.provider, brokerUrl: value.brokerUrl,
|
|
55
|
+
matchersAggressive: value.matchersAggressive, generateProvider: value.generateProvider,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function checkedPrivateDirectory(projectRoot, create) {
|
|
59
|
+
const root = resolve(projectRoot);
|
|
60
|
+
const top = execFileSync('git', ['rev-parse', '--show-toplevel'], {
|
|
61
|
+
cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
62
|
+
}).trim();
|
|
63
|
+
if (realpathSync(root) !== root || resolve(top) !== root) {
|
|
64
|
+
throw new Error('architecture-answers-private-store-invalid');
|
|
65
|
+
}
|
|
66
|
+
const commonRaw = execFileSync('git', ['rev-parse', '--git-common-dir'], {
|
|
67
|
+
cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
68
|
+
}).trim();
|
|
69
|
+
const commonDir = isAbsolute(commonRaw) ? resolve(commonRaw) : resolve(root, commonRaw);
|
|
70
|
+
if (realpathSync(commonDir) !== commonDir || lstatSync(commonDir).isSymbolicLink()) {
|
|
71
|
+
throw new Error('architecture-answers-private-store-invalid');
|
|
72
|
+
}
|
|
73
|
+
const directory = join(commonDir, 'neocortex-architecture');
|
|
74
|
+
if (!existsSync(directory) && !create)
|
|
75
|
+
return undefined;
|
|
76
|
+
if (create)
|
|
77
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
78
|
+
const entry = lstatSync(directory);
|
|
79
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()
|
|
80
|
+
|| entry.uid !== process.getuid?.() || (entry.mode & 0o077) !== 0) {
|
|
81
|
+
throw new Error('architecture-answers-private-store-invalid');
|
|
82
|
+
}
|
|
83
|
+
return directory;
|
|
84
|
+
}
|
|
85
|
+
function answerContext(projectRoot, allowDelegated) {
|
|
86
|
+
const statePath = join(projectRoot, '.neocortex', 'state.json');
|
|
87
|
+
const stateEntry = lstatSync(statePath);
|
|
88
|
+
if (!stateEntry.isFile() || stateEntry.isSymbolicLink()) {
|
|
89
|
+
throw new Error('architecture-answers-state-invalid');
|
|
90
|
+
}
|
|
91
|
+
const rawState = readFileSync(statePath, 'utf8');
|
|
92
|
+
const state = JSON.parse(rawState);
|
|
93
|
+
const archPlan = object(state) && object(state.archPlan) ? state.archPlan : undefined;
|
|
94
|
+
const checkpoint = archPlan && object(archPlan.execution) ? archPlan.execution : undefined;
|
|
95
|
+
const rows = checkpoint?.acceptedStages;
|
|
96
|
+
if (!checkpoint || checkpoint.schemaVersion !== 1 || checkpoint.owner !== 'root'
|
|
97
|
+
|| checkpoint.evidencePolicy !== 'v2-required'
|
|
98
|
+
|| checkpoint.currentStageCommand !== 'generate-pacts'
|
|
99
|
+
|| !(checkpoint.continuationState === 'ask-user'
|
|
100
|
+
&& JSON.stringify(checkpoint.questionIds) === JSON.stringify(PACT_QUESTION_IDS)
|
|
101
|
+
|| allowDelegated && checkpoint.continuationState === 'delegate'
|
|
102
|
+
&& JSON.stringify(checkpoint.questionIds) === '[]')
|
|
103
|
+
|| typeof checkpoint.targetEpicId !== 'string'
|
|
104
|
+
|| !/^P[1-9][0-9]{0,11}$/.test(checkpoint.targetEpicId)
|
|
105
|
+
|| !object(state) || !object(state.epics) || !Object.hasOwn(state.epics, checkpoint.targetEpicId)
|
|
106
|
+
|| typeof checkpoint.graphRevision !== 'string'
|
|
107
|
+
|| !/^[a-f0-9]{64}$/.test(checkpoint.graphRevision)
|
|
108
|
+
|| !Array.isArray(rows) || rows.length !== STAGE_CHAIN.length
|
|
109
|
+
|| !rows.every((row, index) => object(row) && row.stageCommand === STAGE_CHAIN[index]
|
|
110
|
+
&& row.targetEpicId === checkpoint.targetEpicId
|
|
111
|
+
&& object(row.completionEvidence) && object(row.validationEvidence))) {
|
|
112
|
+
throw new Error('architecture-answers-checkpoint-invalid');
|
|
113
|
+
}
|
|
114
|
+
const delegatedReceipt = checkpoint.continuationState === 'delegate'
|
|
115
|
+
? checkpoint.pactAnswerReceipt : undefined;
|
|
116
|
+
if (checkpoint.continuationState === 'delegate'
|
|
117
|
+
&& (!object(delegatedReceipt) || !exactKeys(delegatedReceipt, [
|
|
118
|
+
'schemaVersion', 'targetEpicId', 'graphRevision', 'stateSha256',
|
|
119
|
+
'answersSha256', 'questionIds', 'publicSafe',
|
|
120
|
+
]) || delegatedReceipt.schemaVersion !== 'PactAnswerReceipt/1'
|
|
121
|
+
|| delegatedReceipt.targetEpicId !== checkpoint.targetEpicId
|
|
122
|
+
|| delegatedReceipt.graphRevision !== checkpoint.graphRevision
|
|
123
|
+
|| typeof delegatedReceipt.stateSha256 !== 'string'
|
|
124
|
+
|| !/^[a-f0-9]{64}$/.test(delegatedReceipt.stateSha256)
|
|
125
|
+
|| typeof delegatedReceipt.answersSha256 !== 'string'
|
|
126
|
+
|| !/^[a-f0-9]{64}$/.test(delegatedReceipt.answersSha256)
|
|
127
|
+
|| JSON.stringify(delegatedReceipt.questionIds) !== JSON.stringify(PACT_QUESTION_IDS)
|
|
128
|
+
|| delegatedReceipt.publicSafe !== true)) {
|
|
129
|
+
throw new Error('architecture-answers-checkpoint-invalid');
|
|
130
|
+
}
|
|
131
|
+
return { targetEpicId: checkpoint.targetEpicId, graphRevision: checkpoint.graphRevision,
|
|
132
|
+
stateSha256: checkpoint.continuationState === 'ask-user'
|
|
133
|
+
? createHash('sha256').update(rawState).digest('hex')
|
|
134
|
+
: delegatedReceipt.stateSha256,
|
|
135
|
+
...(delegatedReceipt ? { delegatedReceipt: delegatedReceipt } : {}) };
|
|
136
|
+
}
|
|
137
|
+
function receiptFor(record) {
|
|
138
|
+
return {
|
|
139
|
+
schemaVersion: 'PactAnswerReceipt/1', targetEpicId: record.targetEpicId,
|
|
140
|
+
graphRevision: record.graphRevision, stateSha256: record.stateSha256,
|
|
141
|
+
answersSha256: record.checksumSha256,
|
|
142
|
+
questionIds: PACT_QUESTION_IDS, publicSafe: true,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function checkedRecord(context, answers, nonce) {
|
|
146
|
+
const payload = { schemaVersion: nonce ? 'PactLocalAnswers/2' : 'PactLocalAnswers/1',
|
|
147
|
+
...context, ...(nonce ? { nonce } : {}), answers };
|
|
148
|
+
return { ...payload,
|
|
149
|
+
checksumSha256: createHash('sha256').update(`${JSON.stringify(payload)}\n`).digest('hex') };
|
|
150
|
+
}
|
|
151
|
+
/** Store explicit answers without mutating the tracked architecture checkpoint. */
|
|
152
|
+
export function savePactAnswers(projectRoot, value) {
|
|
153
|
+
const answers = parseAnswers(value);
|
|
154
|
+
const context = answerContext(projectRoot, false);
|
|
155
|
+
const existing = loadPrivatePactRecord(projectRoot);
|
|
156
|
+
if (existing) {
|
|
157
|
+
if (!isDeepStrictEqual(existing.answers, answers))
|
|
158
|
+
throw new Error('architecture-answers-conflict');
|
|
159
|
+
return receiptFor(existing);
|
|
160
|
+
}
|
|
161
|
+
const record = checkedRecord(context, answers, randomBytes(32).toString('hex'));
|
|
162
|
+
const canonical = `${JSON.stringify(record)}\n`;
|
|
163
|
+
const directory = checkedPrivateDirectory(projectRoot, true);
|
|
164
|
+
const target = join(directory, `pact-answers-${record.targetEpicId}-${record.graphRevision}.json`);
|
|
165
|
+
if (existsSync(target))
|
|
166
|
+
throw new Error('architecture-answers-conflict');
|
|
167
|
+
const temporary = join(directory, `pact-answers-tmp-${randomUUID()}.json`);
|
|
168
|
+
let linked = false;
|
|
169
|
+
const file = openSync(temporary, 'wx', 0o600);
|
|
170
|
+
try {
|
|
171
|
+
writeFileSync(file, canonical);
|
|
172
|
+
fsyncSync(file);
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
closeSync(file);
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
linkSync(temporary, target);
|
|
179
|
+
linked = true;
|
|
180
|
+
const handle = openSync(directory, 'r');
|
|
181
|
+
try {
|
|
182
|
+
fsyncSync(handle);
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
closeSync(handle);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
unlinkSync(temporary);
|
|
190
|
+
if (!linked && existsSync(target))
|
|
191
|
+
throw new Error('architecture-answers-conflict');
|
|
192
|
+
}
|
|
193
|
+
return receiptFor(record);
|
|
194
|
+
}
|
|
195
|
+
function loadPrivatePactRecord(projectRoot, requireDelegated = false) {
|
|
196
|
+
const context = answerContext(projectRoot, true);
|
|
197
|
+
if (requireDelegated && !context.delegatedReceipt) {
|
|
198
|
+
throw new Error('architecture-answers-checkpoint-invalid');
|
|
199
|
+
}
|
|
200
|
+
const directory = checkedPrivateDirectory(projectRoot, false);
|
|
201
|
+
if (!directory)
|
|
202
|
+
return undefined;
|
|
203
|
+
const target = join(directory, `pact-answers-${context.targetEpicId}-${context.graphRevision}.json`);
|
|
204
|
+
if (!existsSync(target))
|
|
205
|
+
return undefined;
|
|
206
|
+
const entry = lstatSync(target);
|
|
207
|
+
if (!entry.isFile() || entry.isSymbolicLink() || entry.size > 8192
|
|
208
|
+
|| entry.uid !== process.getuid?.() || (entry.mode & 0o077) !== 0) {
|
|
209
|
+
throw new Error('architecture-answers-conflict');
|
|
210
|
+
}
|
|
211
|
+
const raw = readFileSync(target, 'utf8');
|
|
212
|
+
const parsed = JSON.parse(raw);
|
|
213
|
+
if (!object(parsed) || !(parsed.schemaVersion === 'PactLocalAnswers/1' && exactKeys(parsed, [
|
|
214
|
+
'schemaVersion', 'targetEpicId', 'graphRevision', 'stateSha256', 'answers', 'checksumSha256',
|
|
215
|
+
]) || parsed.schemaVersion === 'PactLocalAnswers/2' && exactKeys(parsed, [
|
|
216
|
+
'schemaVersion', 'targetEpicId', 'graphRevision', 'stateSha256', 'nonce', 'answers', 'checksumSha256',
|
|
217
|
+
]) && typeof parsed.nonce === 'string' && /^[a-f0-9]{64}$/.test(parsed.nonce))
|
|
218
|
+
|| parsed.targetEpicId !== context.targetEpicId
|
|
219
|
+
|| parsed.graphRevision !== context.graphRevision
|
|
220
|
+
|| parsed.stateSha256 !== context.stateSha256) {
|
|
221
|
+
throw new Error('architecture-answers-conflict');
|
|
222
|
+
}
|
|
223
|
+
const record = checkedRecord({ targetEpicId: context.targetEpicId,
|
|
224
|
+
graphRevision: context.graphRevision, stateSha256: context.stateSha256 }, parseAnswers(parsed.answers), parsed.schemaVersion === 'PactLocalAnswers/2' ? parsed.nonce : undefined);
|
|
225
|
+
const canonical = `${JSON.stringify(record)}\n`;
|
|
226
|
+
if (raw !== canonical || context.delegatedReceipt
|
|
227
|
+
&& JSON.stringify(receiptFor(record)) !== JSON.stringify(context.delegatedReceipt)) {
|
|
228
|
+
throw new Error('architecture-answers-conflict');
|
|
229
|
+
}
|
|
230
|
+
return record;
|
|
231
|
+
}
|
|
232
|
+
/** Revalidate the private record against the exact current root checkpoint. Never print answers. */
|
|
233
|
+
export function loadPactAnswerReceipt(projectRoot) {
|
|
234
|
+
const record = loadPrivatePactRecord(projectRoot);
|
|
235
|
+
return record ? receiptFor(record) : undefined;
|
|
236
|
+
}
|
|
237
|
+
/** Internal private handoff only. Callers must never log or return `answers`. */
|
|
238
|
+
export function loadPactPrivateAnswers(projectRoot) {
|
|
239
|
+
const record = loadPrivatePactRecord(projectRoot, true);
|
|
240
|
+
return record ? { receipt: receiptFor(record), answers: record.answers } : undefined;
|
|
241
|
+
}
|
|
242
|
+
async function readBoundedStdin() {
|
|
243
|
+
const chunks = [];
|
|
244
|
+
let total = 0;
|
|
245
|
+
for await (const chunk of process.stdin) {
|
|
246
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
247
|
+
total += bytes.length;
|
|
248
|
+
if (total > MAX_INPUT_BYTES)
|
|
249
|
+
throw new Error('architecture-answers-input-too-large');
|
|
250
|
+
chunks.push(bytes);
|
|
251
|
+
}
|
|
252
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
253
|
+
}
|
|
254
|
+
export async function architectureAnswersCliHandler(args) {
|
|
255
|
+
if ((args[0] !== 'save' && args[0] !== 'status')
|
|
256
|
+
|| (args.length > 1 && (args.length !== 3 || args[1] !== '--project-root' || !args[2]))) {
|
|
257
|
+
process.stdout.write('{"ok":false,"reasonCode":"architecture-answers-usage-invalid","publicSafe":true}\n');
|
|
258
|
+
return 1;
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
const root = args[2] ?? process.cwd();
|
|
262
|
+
const receipt = args[0] === 'save'
|
|
263
|
+
? savePactAnswers(root, await readBoundedStdin()) : loadPactAnswerReceipt(root);
|
|
264
|
+
process.stdout.write(`${JSON.stringify({ ok: true, ...receipt,
|
|
265
|
+
...(receipt ? {} : { recorded: false, publicSafe: true }) })}\n`);
|
|
266
|
+
return 0;
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
const code = error instanceof Error && /^architecture-answers-[a-z-]+$/.test(error.message)
|
|
270
|
+
? error.message : 'architecture-answers-failed';
|
|
271
|
+
process.stdout.write(`${JSON.stringify({ ok: false, reasonCode: code, publicSafe: true })}\n`);
|
|
272
|
+
return 1;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
@@ -1,4 +1,253 @@
|
|
|
1
|
-
import{architectureMemoryPredecessorCount
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { architectureMemoryPredecessorCount } from './architecture-non-ui-continuation.js';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
6
|
+
import { listProjectMemoryTargets } from '../memory/shared-project-memory-types.js';
|
|
7
|
+
import { parseRefreshMemoryArgs, verifyProjectMemoryTargets } from './refresh-memory.js';
|
|
8
|
+
export function acceptedArchitectureTerminalMemoryReceipt(value, execution) {
|
|
9
|
+
if (!isRecord(value) || !isRecord(execution)
|
|
10
|
+
|| Object.keys(value).sort().join(',') !== [
|
|
11
|
+
'schemaVersion', 'targetEpicId', 'graphRevision', 'sourceHead', 'canonicalSha256',
|
|
12
|
+
'projectionSha256', 'fileCount', 'completionReceiptId', 'validationReceiptId',
|
|
13
|
+
'receiptId', 'status', 'evidenceIds', 'publicSafe',
|
|
14
|
+
].sort().join(',')
|
|
15
|
+
|| value.schemaVersion !== 'ArchitectureTerminalMemoryReceipt/1'
|
|
16
|
+
|| value.targetEpicId !== execution.targetEpicId
|
|
17
|
+
|| value.graphRevision !== execution.graphRevision
|
|
18
|
+
|| value.completionReceiptId !== execution.completionEvidence?.receiptId
|
|
19
|
+
|| value.validationReceiptId !== execution.validationEvidence?.receiptId
|
|
20
|
+
|| typeof value.sourceHead !== 'string' || !/^[a-f0-9]{40}$/.test(value.sourceHead)
|
|
21
|
+
|| ![value.graphRevision, value.canonicalSha256, value.projectionSha256,
|
|
22
|
+
value.completionReceiptId, value.validationReceiptId, value.receiptId]
|
|
23
|
+
.every((field) => typeof field === 'string' && /^[a-f0-9]{64}$/.test(field))
|
|
24
|
+
|| !Number.isInteger(value.fileCount) || value.fileCount < 1
|
|
25
|
+
|| value.fileCount > 64 || value.status !== 'passed'
|
|
26
|
+
|| value.publicSafe !== true || !Array.isArray(value.evidenceIds)
|
|
27
|
+
|| value.evidenceIds.length !== 1)
|
|
28
|
+
return false;
|
|
29
|
+
const fields = {
|
|
30
|
+
schemaVersion: value.schemaVersion, targetEpicId: value.targetEpicId,
|
|
31
|
+
graphRevision: value.graphRevision, sourceHead: value.sourceHead,
|
|
32
|
+
canonicalSha256: value.canonicalSha256, projectionSha256: value.projectionSha256,
|
|
33
|
+
fileCount: value.fileCount, completionReceiptId: value.completionReceiptId,
|
|
34
|
+
validationReceiptId: value.validationReceiptId,
|
|
35
|
+
};
|
|
36
|
+
const receiptId = hash(JSON.stringify(fields));
|
|
37
|
+
return value.receiptId === receiptId
|
|
38
|
+
&& value.evidenceIds[0] === `memory-physical-${receiptId.slice(0, 24)}`;
|
|
39
|
+
}
|
|
40
|
+
function isRecord(value) {
|
|
41
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
42
|
+
}
|
|
43
|
+
function hash(value) {
|
|
44
|
+
return createHash('sha256').update(value).digest('hex');
|
|
45
|
+
}
|
|
46
|
+
/** A root-only physical seal; child output and a copied JSON assertion are insufficient. */
|
|
47
|
+
export function deriveArchitectureTerminalMemoryReceipt(projectRoot, execution) {
|
|
48
|
+
if (!isRecord(execution) || execution.owner !== 'root'
|
|
49
|
+
|| execution.currentStageCommand !== 'update-memory'
|
|
50
|
+
|| execution.continuationState !== 'delegate'
|
|
51
|
+
|| execution.childStatus !== 'succeeded'
|
|
52
|
+
|| execution.evidencePolicy !== 'v2-required'
|
|
53
|
+
|| typeof execution.targetEpicId !== 'string'
|
|
54
|
+
|| !/^P[1-9][0-9]{0,11}$/.test(execution.targetEpicId)
|
|
55
|
+
|| typeof execution.graphRevision !== 'string'
|
|
56
|
+
|| !/^[a-f0-9]{64}$/.test(execution.graphRevision)
|
|
57
|
+
|| !Array.isArray(execution.acceptedStages) || execution.acceptedStages.length !== architectureMemoryPredecessorCount(execution)
|
|
58
|
+
|| !isRecord(execution.reviewDecision) || execution.reviewDecision.decision !== 'approved'
|
|
59
|
+
|| !isRecord(execution.completionEvidence) || execution.completionEvidence.status !== 'succeeded'
|
|
60
|
+
|| execution.completionEvidence.stageCommand !== 'update-memory'
|
|
61
|
+
|| !isRecord(execution.validationEvidence) || execution.validationEvidence.status !== 'passed'
|
|
62
|
+
|| execution.validationEvidence.stageCommand !== 'update-memory'
|
|
63
|
+
|| typeof execution.completionEvidence.receiptId !== 'string'
|
|
64
|
+
|| !/^[a-f0-9]{64}$/.test(execution.completionEvidence.receiptId)
|
|
65
|
+
|| typeof execution.validationEvidence.receiptId !== 'string'
|
|
66
|
+
|| !/^[a-f0-9]{64}$/.test(execution.validationEvidence.receiptId)) {
|
|
67
|
+
throw new Error('architecture-terminal-memory-evidence-incomplete');
|
|
68
|
+
}
|
|
69
|
+
const verification = verifyProjectMemoryTargets(parseRefreshMemoryArgs([
|
|
70
|
+
'--verify', '--project-root', projectRoot,
|
|
71
|
+
]));
|
|
72
|
+
const head = execFileSync('git', ['rev-parse', 'HEAD'], {
|
|
73
|
+
cwd: projectRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
74
|
+
}).trim();
|
|
75
|
+
if (!/^[a-f0-9]{40}$/.test(head))
|
|
76
|
+
throw new Error('architecture-terminal-memory-head-invalid');
|
|
77
|
+
const canonical = readFileSync(join(projectRoot, 'NEOCORTEX.md'));
|
|
78
|
+
const committedCanonical = execFileSync('git', ['show', 'HEAD:NEOCORTEX.md'], {
|
|
79
|
+
cwd: projectRoot, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 65_536,
|
|
80
|
+
});
|
|
81
|
+
if (!canonical.equals(committedCanonical) || hash(canonical) !== verification.canonicalSha256) {
|
|
82
|
+
throw new Error('architecture-terminal-memory-uncommitted');
|
|
83
|
+
}
|
|
84
|
+
const projectPaths = [...new Set(['NEOCORTEX.md', ...listProjectMemoryTargets().flatMap((target) => [
|
|
85
|
+
target.primaryFile, ...target.secondaryFiles.filter((file) => file.scope === 'project').map((file) => file.path),
|
|
86
|
+
])])];
|
|
87
|
+
const changedTracked = execFileSync('git', ['diff', '--name-only', 'HEAD', '--', ...projectPaths], {
|
|
88
|
+
cwd: projectRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
89
|
+
}).trim();
|
|
90
|
+
if (changedTracked)
|
|
91
|
+
throw new Error('architecture-terminal-memory-uncommitted');
|
|
92
|
+
// Persisting the accepted public checkpoint advances HEAD after the memory
|
|
93
|
+
// commit. Keep its immutable seal only across independently inspected,
|
|
94
|
+
// single-parent state-only commits, including every intermediate commit.
|
|
95
|
+
let sourceHead = head;
|
|
96
|
+
if (execution.terminalMemoryCheckpoint !== undefined) {
|
|
97
|
+
if (!acceptedArchitectureTerminalMemoryReceipt(execution.terminalMemoryCheckpoint, execution)) {
|
|
98
|
+
throw new Error('architecture-terminal-memory-checkpoint-invalid');
|
|
99
|
+
}
|
|
100
|
+
sourceHead = execution.terminalMemoryCheckpoint.sourceHead;
|
|
101
|
+
const git = (args) => execFileSync('git', args, {
|
|
102
|
+
cwd: projectRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 1024 * 1024,
|
|
103
|
+
}).trim();
|
|
104
|
+
try {
|
|
105
|
+
git(['merge-base', '--is-ancestor', sourceHead, head]);
|
|
106
|
+
const commits = git(['rev-list', '--max-count=257', '--reverse', '--parents', `${sourceHead}..${head}`])
|
|
107
|
+
.split('\n').filter(Boolean);
|
|
108
|
+
if (commits.length > 256)
|
|
109
|
+
throw new Error('checkpoint-range-too-large');
|
|
110
|
+
for (const row of commits) {
|
|
111
|
+
const ids = row.split(' ');
|
|
112
|
+
if (ids.length !== 2)
|
|
113
|
+
throw new Error('checkpoint-merge-unverified');
|
|
114
|
+
const paths = git(['diff-tree', '--no-commit-id', '--name-only', '-r', ids[0]]).split('\n').filter(Boolean);
|
|
115
|
+
if (paths.length !== 1 || paths[0] !== '.neocortex/state.json')
|
|
116
|
+
throw new Error('checkpoint-range-not-state-only');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
throw new Error('architecture-terminal-memory-checkpoint-range-invalid');
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const fields = {
|
|
124
|
+
schemaVersion: 'ArchitectureTerminalMemoryReceipt/1',
|
|
125
|
+
targetEpicId: execution.targetEpicId,
|
|
126
|
+
graphRevision: execution.graphRevision,
|
|
127
|
+
sourceHead,
|
|
128
|
+
canonicalSha256: verification.canonicalSha256,
|
|
129
|
+
projectionSha256: verification.projectionSha256,
|
|
130
|
+
fileCount: verification.fileCount,
|
|
131
|
+
completionReceiptId: execution.completionEvidence.receiptId,
|
|
132
|
+
validationReceiptId: execution.validationEvidence.receiptId,
|
|
133
|
+
};
|
|
134
|
+
const receiptId = hash(JSON.stringify(fields));
|
|
135
|
+
return {
|
|
136
|
+
...fields, receiptId, status: 'passed',
|
|
137
|
+
evidenceIds: [`memory-physical-${receiptId.slice(0, 24)}`],
|
|
138
|
+
publicSafe: true,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** Root-only CAS: seal a committed, verified memory projection into local state. */
|
|
142
|
+
export function sealArchitectureTerminalMemory(projectRoot) {
|
|
143
|
+
const root = resolve(projectRoot);
|
|
144
|
+
const top = execFileSync('git', ['rev-parse', '--show-toplevel'], {
|
|
145
|
+
cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
146
|
+
}).trim();
|
|
147
|
+
if (realpathSync(root) !== root || resolve(top) !== root) {
|
|
148
|
+
throw new Error('architecture-terminal-memory-project-root-invalid');
|
|
149
|
+
}
|
|
150
|
+
const stateDir = join(root, '.neocortex');
|
|
151
|
+
const statePath = join(stateDir, 'state.json');
|
|
152
|
+
const lockPath = join(stateDir, 'state.json.architecture.lock');
|
|
153
|
+
const lock = openSync(lockPath, 'wx', 0o600);
|
|
154
|
+
let temporaryPath;
|
|
155
|
+
try {
|
|
156
|
+
const entry = lstatSync(statePath);
|
|
157
|
+
if (!entry.isFile() || entry.isSymbolicLink()) {
|
|
158
|
+
throw new Error('architecture-terminal-memory-state-invalid');
|
|
159
|
+
}
|
|
160
|
+
const raw = readFileSync(statePath, 'utf8');
|
|
161
|
+
const state = JSON.parse(raw);
|
|
162
|
+
if (!isRecord(state) || !isRecord(state.archPlan) || !isRecord(state.archPlan.execution)
|
|
163
|
+
|| !isRecord(state.epics) || state.scope && isRecord(state.scope) && state.scope.kind === 'projected'
|
|
164
|
+
|| !Object.hasOwn(state.epics, String(state.archPlan.execution.targetEpicId))
|
|
165
|
+
|| state.archPlan.execution.terminalMemoryCheckpoint !== undefined) {
|
|
166
|
+
throw new Error('architecture-terminal-memory-state-invalid');
|
|
167
|
+
}
|
|
168
|
+
const receipt = deriveArchitectureTerminalMemoryReceipt(root, state.archPlan.execution);
|
|
169
|
+
const commonRaw = execFileSync('git', ['rev-parse', '--git-common-dir'], {
|
|
170
|
+
cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
171
|
+
}).trim();
|
|
172
|
+
const commonDir = isAbsolute(commonRaw) ? resolve(commonRaw) : resolve(root, commonRaw);
|
|
173
|
+
if (realpathSync(commonDir) !== commonDir || lstatSync(commonDir).isSymbolicLink()) {
|
|
174
|
+
throw new Error('architecture-terminal-memory-backup-dir-invalid');
|
|
175
|
+
}
|
|
176
|
+
const backupDir = join(commonDir, 'neocortex-architecture');
|
|
177
|
+
mkdirSync(backupDir, { recursive: true, mode: 0o700 });
|
|
178
|
+
const backupEntry = lstatSync(backupDir);
|
|
179
|
+
if (!backupEntry.isDirectory() || backupEntry.isSymbolicLink()
|
|
180
|
+
|| backupEntry.uid !== process.getuid?.() || (backupEntry.mode & 0o077) !== 0) {
|
|
181
|
+
throw new Error('architecture-terminal-memory-backup-dir-invalid');
|
|
182
|
+
}
|
|
183
|
+
if (readFileSync(statePath, 'utf8') !== raw)
|
|
184
|
+
throw new Error('architecture-terminal-memory-state-conflict');
|
|
185
|
+
const suffix = randomUUID();
|
|
186
|
+
const backupPath = join(backupDir, `state-backup-${suffix}.json`);
|
|
187
|
+
const backup = openSync(backupPath, 'wx', 0o600);
|
|
188
|
+
try {
|
|
189
|
+
writeFileSync(backup, raw);
|
|
190
|
+
fsyncSync(backup);
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
closeSync(backup);
|
|
194
|
+
}
|
|
195
|
+
const backupDirectory = openSync(backupDir, 'r');
|
|
196
|
+
try {
|
|
197
|
+
fsyncSync(backupDirectory);
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
closeSync(backupDirectory);
|
|
201
|
+
}
|
|
202
|
+
const next = { ...state, archPlan: { ...state.archPlan,
|
|
203
|
+
execution: { ...state.archPlan.execution, terminalMemoryCheckpoint: receipt } } };
|
|
204
|
+
temporaryPath = join(stateDir, `state.json.architecture-tmp-${suffix}`);
|
|
205
|
+
const temporary = openSync(temporaryPath, 'wx', 0o600);
|
|
206
|
+
try {
|
|
207
|
+
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`);
|
|
208
|
+
fsyncSync(temporary);
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
closeSync(temporary);
|
|
212
|
+
}
|
|
213
|
+
if (readFileSync(statePath, 'utf8') !== raw)
|
|
214
|
+
throw new Error('architecture-terminal-memory-state-conflict');
|
|
215
|
+
if (deriveArchitectureTerminalMemoryReceipt(root, state.archPlan.execution).receiptId !== receipt.receiptId) {
|
|
216
|
+
throw new Error('architecture-terminal-memory-physical-conflict');
|
|
217
|
+
}
|
|
218
|
+
renameSync(temporaryPath, statePath);
|
|
219
|
+
temporaryPath = undefined;
|
|
220
|
+
const directory = openSync(stateDir, 'r');
|
|
221
|
+
try {
|
|
222
|
+
fsyncSync(directory);
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
closeSync(directory);
|
|
226
|
+
}
|
|
227
|
+
return receipt;
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
if (temporaryPath)
|
|
231
|
+
try {
|
|
232
|
+
unlinkSync(temporaryPath);
|
|
233
|
+
}
|
|
234
|
+
catch { /* preserve primary failure */ }
|
|
235
|
+
closeSync(lock);
|
|
236
|
+
unlinkSync(lockPath);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
export async function architectureMemoryTerminalCliHandler(args) {
|
|
240
|
+
try {
|
|
241
|
+
if (args[0] !== 'seal' || args.length !== 1 && args.length !== 3
|
|
242
|
+
|| args.length === 3 && args[1] !== '--project-root') {
|
|
243
|
+
throw new Error('usage: architecture-memory seal [--project-root <path>]');
|
|
244
|
+
}
|
|
245
|
+
const receipt = sealArchitectureTerminalMemory(args.length === 3 ? args[2] : process.cwd());
|
|
246
|
+
console.log(`Architecture memory sealed: receipt=${receipt.receiptId} head=${receipt.sourceHead} files=${receipt.fileCount}`);
|
|
247
|
+
return 0;
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
251
|
+
return 1;
|
|
252
|
+
}
|
|
253
|
+
}
|