@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 +1,172 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* P222.26: derive a closed, local Pact artifact set from the exact OpenAPI input.
|
|
3
|
+
* Paths remain private client state; only hashes and bounded counts may become
|
|
4
|
+
* public binding evidence. This does not grant a child or package.json writes.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
import { parseDocument } from 'yaml';
|
|
10
|
+
const SPEC_PATH = 'docs/api/openapi.yaml';
|
|
11
|
+
const MAX_SPEC_BYTES = 5 * 1024 * 1024;
|
|
12
|
+
const MAX_ENDPOINTS = 256;
|
|
13
|
+
const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']);
|
|
14
|
+
function plainRecord(value) {
|
|
15
|
+
return !!value && typeof value === 'object' && !Array.isArray(value)
|
|
16
|
+
&& Object.getPrototypeOf(value) === Object.prototype;
|
|
17
|
+
}
|
|
18
|
+
function regularPath(root, relative) {
|
|
19
|
+
let current = root;
|
|
20
|
+
for (const part of relative.split('/')) {
|
|
21
|
+
current = join(current, part);
|
|
22
|
+
let entry;
|
|
23
|
+
try {
|
|
24
|
+
entry = lstatSync(current);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === 'ENOENT')
|
|
28
|
+
return false;
|
|
29
|
+
throw new Error('pact-write-set-path-unsafe');
|
|
30
|
+
}
|
|
31
|
+
if (entry.isSymbolicLink() || (current === join(root, relative)
|
|
32
|
+
? !entry.isFile() : !entry.isDirectory())) {
|
|
33
|
+
throw new Error('pact-write-set-path-unsafe');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
function slug(endpointPath, method) {
|
|
39
|
+
const cleaned = endpointPath.replace(/^\//, '').replace(/[{}]/g, '')
|
|
40
|
+
.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase();
|
|
41
|
+
return `${method.toLowerCase()}-${cleaned || 'root'}`;
|
|
42
|
+
}
|
|
43
|
+
/** No filesystem mutation and no protected content returned. */
|
|
44
|
+
export function derivePactWriteSet(projectRoot, generateProvider) {
|
|
45
|
+
if (typeof generateProvider !== 'boolean')
|
|
46
|
+
throw new Error('pact-write-set-options-invalid');
|
|
47
|
+
const root = resolve(projectRoot);
|
|
48
|
+
try {
|
|
49
|
+
if (realpathSync(root) !== root || !lstatSync(root).isDirectory()) {
|
|
50
|
+
throw new Error('pact-write-set-path-unsafe');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error('pact-write-set-path-unsafe');
|
|
55
|
+
}
|
|
56
|
+
if (!regularPath(root, SPEC_PATH))
|
|
57
|
+
return { outcome: 'skipped', reasonCode: 'PACT_SKIPPED_NO_OPENAPI' };
|
|
58
|
+
const entry = lstatSync(join(root, SPEC_PATH));
|
|
59
|
+
if (entry.size < 1 || entry.size > MAX_SPEC_BYTES)
|
|
60
|
+
throw new Error('pact-write-set-spec-size-invalid');
|
|
61
|
+
const bytes = readFileSync(join(root, SPEC_PATH));
|
|
62
|
+
const specSha256 = createHash('sha256').update(bytes).digest('hex');
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
const source = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
66
|
+
const document = parseDocument(source, { strict: true, stringKeys: true,
|
|
67
|
+
uniqueKeys: true, schema: 'core', customTags: [] });
|
|
68
|
+
if (document.errors.length > 0 || document.warnings.length > 0) {
|
|
69
|
+
return { outcome: 'skipped', reasonCode: 'PACT_SKIPPED_INVALID_YAML' };
|
|
70
|
+
}
|
|
71
|
+
parsed = document.toJS({ maxAliasCount: 0 });
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return { outcome: 'skipped', reasonCode: 'PACT_SKIPPED_INVALID_YAML' };
|
|
75
|
+
}
|
|
76
|
+
if (!plainRecord(parsed) || parsed.openapi !== '3.1.0') {
|
|
77
|
+
return { outcome: 'skipped', reasonCode: 'PACT_SKIPPED_UNSUPPORTED_VERSION' };
|
|
78
|
+
}
|
|
79
|
+
if (!plainRecord(parsed.paths) || Object.keys(parsed.paths).length === 0) {
|
|
80
|
+
return { outcome: 'skipped', reasonCode: 'PACT_SKIPPED_EMPTY_PATHS' };
|
|
81
|
+
}
|
|
82
|
+
const files = new Set();
|
|
83
|
+
const interactions = [];
|
|
84
|
+
let endpointCount = 0;
|
|
85
|
+
for (const [endpointPath, operations] of Object.entries(parsed.paths)) {
|
|
86
|
+
if (!endpointPath.startsWith('/') || endpointPath.length > 180
|
|
87
|
+
|| /[\u0000-\u001f\u007f?#]/.test(endpointPath) || !plainRecord(operations)
|
|
88
|
+
|| endpointPath.split('/').some((segment) => (segment.includes('{') || segment.includes('}'))
|
|
89
|
+
&& !/^[^{}]*\{[^{}]+\}[^{}]*$/.test(segment))) {
|
|
90
|
+
throw new Error('pact-write-set-spec-shape-invalid');
|
|
91
|
+
}
|
|
92
|
+
for (const [method, operation] of Object.entries(operations)) {
|
|
93
|
+
const normalizedMethod = method.toLowerCase();
|
|
94
|
+
if (!METHODS.has(normalizedMethod))
|
|
95
|
+
continue;
|
|
96
|
+
if (!plainRecord(operation))
|
|
97
|
+
throw new Error('pact-write-set-spec-shape-invalid');
|
|
98
|
+
// The first-generation test transport uses fetch, which cannot send
|
|
99
|
+
// TRACE or request bodies on GET/HEAD. Refuse before a private lease is
|
|
100
|
+
// issued instead of admitting an artifact the generator cannot execute.
|
|
101
|
+
if (normalizedMethod === 'trace'
|
|
102
|
+
|| (normalizedMethod === 'get' || normalizedMethod === 'head')
|
|
103
|
+
&& operation.requestBody !== undefined) {
|
|
104
|
+
throw new Error('pact-write-set-method-unsupported');
|
|
105
|
+
}
|
|
106
|
+
// Keep lease preflight aligned with the first-generation generator.
|
|
107
|
+
// An unsupported media type, absent response status or missing schema
|
|
108
|
+
// must refuse before a private agent receives the protected step.
|
|
109
|
+
if (operation.requestBody !== undefined) {
|
|
110
|
+
const body = operation.requestBody;
|
|
111
|
+
const content = plainRecord(body) ? body.content : undefined;
|
|
112
|
+
const json = plainRecord(content) ? content['application/json'] : undefined;
|
|
113
|
+
if (!plainRecord(json) || !plainRecord(json.schema)) {
|
|
114
|
+
throw new Error('pact-write-set-operation-unsupported');
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const responses = operation.responses;
|
|
118
|
+
const status = plainRecord(responses)
|
|
119
|
+
? ['200', '201', ...Object.keys(responses)
|
|
120
|
+
.filter((key) => /^[1-5][0-9]{2}$/.test(key)).sort()]
|
|
121
|
+
.find((key) => plainRecord(responses[key])) : undefined;
|
|
122
|
+
if (!status)
|
|
123
|
+
throw new Error('pact-write-set-operation-unsupported');
|
|
124
|
+
const response = responses[status];
|
|
125
|
+
if ((status === '204' || normalizedMethod === 'head') && plainRecord(response)
|
|
126
|
+
&& (response.schema !== undefined
|
|
127
|
+
|| plainRecord(response.content) && Object.keys(response.content).length > 0)) {
|
|
128
|
+
throw new Error('pact-write-set-operation-unsupported');
|
|
129
|
+
}
|
|
130
|
+
if (status !== '204' && normalizedMethod !== 'head' && plainRecord(response)) {
|
|
131
|
+
const content = response.content;
|
|
132
|
+
if (content !== undefined) {
|
|
133
|
+
if (!plainRecord(content))
|
|
134
|
+
throw new Error('pact-write-set-operation-unsupported');
|
|
135
|
+
if (Object.keys(content).length > 0) {
|
|
136
|
+
const json = content['application/json'];
|
|
137
|
+
if (!plainRecord(json) || !plainRecord(json.schema)) {
|
|
138
|
+
throw new Error('pact-write-set-operation-unsupported');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (response.schema !== undefined && !plainRecord(response.schema)) {
|
|
143
|
+
throw new Error('pact-write-set-operation-unsupported');
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
endpointCount += 1;
|
|
147
|
+
if (endpointCount > MAX_ENDPOINTS)
|
|
148
|
+
throw new Error('pact-write-set-endpoint-limit');
|
|
149
|
+
const candidate = `tests/pact/consumer/${slug(endpointPath, method)}.test.ts`;
|
|
150
|
+
if (candidate.length > 240 || files.has(candidate)) {
|
|
151
|
+
throw new Error('pact-write-set-path-collision');
|
|
152
|
+
}
|
|
153
|
+
files.add(candidate);
|
|
154
|
+
interactions.push(Object.freeze({ filePath: candidate,
|
|
155
|
+
method: normalizedMethod.toUpperCase(), endpointPath }));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (endpointCount === 0)
|
|
159
|
+
return { outcome: 'skipped', reasonCode: 'PACT_SKIPPED_EMPTY_PATHS' };
|
|
160
|
+
const providerPath = generateProvider ? 'tests/pact/provider/verify.test.ts' : undefined;
|
|
161
|
+
if (providerPath)
|
|
162
|
+
files.add(providerPath);
|
|
163
|
+
const paths = Object.freeze([...files].sort());
|
|
164
|
+
interactions.sort((left, right) => left.filePath < right.filePath ? -1
|
|
165
|
+
: left.filePath > right.filePath ? 1 : 0);
|
|
166
|
+
return { outcome: 'ready', writeSet: Object.freeze({
|
|
167
|
+
schemaVersion: 1, specSha256,
|
|
168
|
+
pathsSha256: createHash('sha256').update(JSON.stringify(paths)).digest('hex'),
|
|
169
|
+
endpointCount, paths, interactions: Object.freeze(interactions),
|
|
170
|
+
...(providerPath ? { providerPath } : {}),
|
|
171
|
+
}) };
|
|
172
|
+
}
|
|
@@ -1,5 +1,406 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
6
|
+
import { canonicalPlanningIntake, createPlanningReceiptV1, planningIntakeRevision, projectDiagnosedEpicState } from '../../../shared/dist/planning/diagnosis-state.js';
|
|
7
|
+
const HEX = /^[a-f0-9]{64}$/;
|
|
8
|
+
const EPIC = /^P[1-9][0-9]{0,11}$/;
|
|
9
|
+
const CLAIM = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
10
|
+
const ARTIFACT_NAMES = ['idea', 'diagnosis', 'enrichment', 'index'];
|
|
11
|
+
// Full hashes of server-owned step identifiers; do not publish their plaintext.
|
|
12
|
+
const DIAGNOSIS_STEP_DIGEST = 'acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c';
|
|
13
|
+
const ENRICHMENT_STEP_DIGEST = '81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369';
|
|
14
|
+
function record(value) {
|
|
15
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
function digest(value) {
|
|
18
|
+
return createHash('sha256').update(value).digest('hex');
|
|
19
|
+
}
|
|
20
|
+
function git(root, args) {
|
|
21
|
+
return execFileSync('git', [...args], { cwd: root, encoding: 'utf8',
|
|
22
|
+
stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 65_536 }).trim();
|
|
23
|
+
}
|
|
24
|
+
function regularBytes(root, path, maxBytes) {
|
|
25
|
+
const full = join(root, path);
|
|
26
|
+
const entry = lstatSync(full);
|
|
27
|
+
if (!entry.isFile() || entry.isSymbolicLink() || entry.size < 1 || entry.size > maxBytes) {
|
|
28
|
+
throw new Error('planning-diagnosis-physical-artifact-invalid');
|
|
29
|
+
}
|
|
30
|
+
return readFileSync(full);
|
|
31
|
+
}
|
|
32
|
+
function stepMatches(value, expectedDigest) {
|
|
33
|
+
return typeof value === 'string' && value.length <= 128 && digest(value) === expectedDigest;
|
|
34
|
+
}
|
|
35
|
+
function documentMatches(content, epicId, stepDigest) {
|
|
36
|
+
const header = /^---\n([\s\S]{1,8192}?)\n---\n/.exec(content.replace(/\r\n/g, '\n'))?.[1];
|
|
37
|
+
if (!header)
|
|
38
|
+
return false;
|
|
39
|
+
const lines = header.split('\n');
|
|
40
|
+
const scalar = (key) => {
|
|
41
|
+
const found = lines.filter((line) => line.startsWith(`${key}:`));
|
|
42
|
+
return found.length === 1
|
|
43
|
+
? found[0].slice(key.length + 1).trim().replace(/^(?:"(.*)"|'(.*)')$/, '$1$2')
|
|
44
|
+
: undefined;
|
|
45
|
+
};
|
|
46
|
+
return scalar('epic_id') === epicId && scalar('status') === 'completed'
|
|
47
|
+
&& stepMatches(scalar('step'), stepDigest);
|
|
48
|
+
}
|
|
49
|
+
/** Read only an owner-private pending claim file; absence is an explicit snapshot. */
|
|
50
|
+
export function planningPendingSidecarDigest(root) {
|
|
51
|
+
const path = join(root, '.neocortex/pending-epic-claims.json');
|
|
52
|
+
let entry;
|
|
53
|
+
try {
|
|
54
|
+
entry = lstatSync(path);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (error.code === 'ENOENT')
|
|
58
|
+
return undefined;
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
const directory = lstatSync(join(root, '.neocortex'));
|
|
62
|
+
if (!directory.isDirectory() || directory.isSymbolicLink()
|
|
63
|
+
|| directory.uid !== process.getuid?.() || (directory.mode & 0o022) !== 0
|
|
64
|
+
|| !entry.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.()
|
|
65
|
+
|| (entry.mode & 0o077) !== 0 || entry.size < 1 || entry.size > 128 * 1024) {
|
|
66
|
+
throw new Error('planning-pending-sidecar-invalid');
|
|
67
|
+
}
|
|
68
|
+
const bytes = readFileSync(path);
|
|
69
|
+
if (bytes.length !== entry.size)
|
|
70
|
+
throw new Error('planning-pending-sidecar-invalid');
|
|
71
|
+
return digest(bytes);
|
|
72
|
+
}
|
|
73
|
+
export function planningPhysicalPatchDigest(root, paths, ownTemporaryPath, allowPendingSidecar = true) {
|
|
74
|
+
const allowed = new Set(Object.values(paths));
|
|
75
|
+
const ownPaths = new Set(['.neocortex/state.json.planning.lock',
|
|
76
|
+
...(ownTemporaryPath ? [ownTemporaryPath] : [])]);
|
|
77
|
+
const status = execFileSync('git', ['status', '--porcelain=v1', '-z', '--untracked-files=all'], {
|
|
78
|
+
cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 128 * 1024,
|
|
79
|
+
}).toString('utf8').split('\0').filter(Boolean);
|
|
80
|
+
const untracked = [];
|
|
81
|
+
const seen = new Set();
|
|
82
|
+
for (const entry of status) {
|
|
83
|
+
const code = entry.slice(0, 2);
|
|
84
|
+
const path = entry.slice(3);
|
|
85
|
+
if (ownPaths.has(path) && code === '??')
|
|
86
|
+
continue;
|
|
87
|
+
if (entry[2] !== ' ' || !allowed.has(path)
|
|
88
|
+
&& (!allowPendingSidecar || path !== '.neocortex/pending-epic-claims.json')
|
|
89
|
+
|| path === '.neocortex/pending-epic-claims.json' && code !== '??'
|
|
90
|
+
|| path !== '.neocortex/pending-epic-claims.json' && code !== '??' && code !== ' M'
|
|
91
|
+
|| seen.has(path))
|
|
92
|
+
throw new Error('planning-diagnosis-write-scope-conflict');
|
|
93
|
+
seen.add(path);
|
|
94
|
+
if (code === '??' && allowed.has(path))
|
|
95
|
+
untracked.push(path);
|
|
96
|
+
}
|
|
97
|
+
if ([...allowed].some((path) => !seen.has(path))) {
|
|
98
|
+
throw new Error('planning-diagnosis-write-scope-conflict');
|
|
99
|
+
}
|
|
100
|
+
const tracked = execFileSync('git', ['diff', '--binary', '--no-ext-diff', '--no-textconv', 'HEAD', '--'], {
|
|
101
|
+
cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 2 * 1024 * 1024,
|
|
102
|
+
});
|
|
103
|
+
const patches = [tracked];
|
|
104
|
+
for (const path of untracked.sort()) {
|
|
105
|
+
const result = spawnSync('git', ['diff', '--no-index', '--binary', '--no-ext-diff', '--', '/dev/null', path], {
|
|
106
|
+
cwd: root, encoding: 'buffer', maxBuffer: 2 * 1024 * 1024,
|
|
107
|
+
});
|
|
108
|
+
if (result.status !== 1 || !Buffer.isBuffer(result.stdout)) {
|
|
109
|
+
throw new Error('planning-diagnosis-patch-invalid');
|
|
110
|
+
}
|
|
111
|
+
patches.push(result.stdout);
|
|
112
|
+
}
|
|
113
|
+
return digest(Buffer.concat(patches.map((patch) => Buffer.concat([patch, Buffer.from('\n')]))));
|
|
114
|
+
}
|
|
115
|
+
function validateReview(value) {
|
|
116
|
+
if (!record(value) || Object.keys(value).sort().join('|') !== [
|
|
117
|
+
'schemaVersion', 'verdict', 'claimId', 'epicId', 'logicalFingerprint', 'sourceHead',
|
|
118
|
+
'sourceBranch', 'sourceStateSha256', 'admission', 'artifactDigests',
|
|
119
|
+
'qaEvidenceId', 'intake', 'artifactSummary',
|
|
120
|
+
].sort().join('|') || value.schemaVersion !== 'PlanningDiagnosisRootReview/1'
|
|
121
|
+
|| value.verdict !== 'accepted' || typeof value.claimId !== 'string' || !CLAIM.test(value.claimId)
|
|
122
|
+
|| typeof value.epicId !== 'string' || !EPIC.test(value.epicId)
|
|
123
|
+
|| typeof value.logicalFingerprint !== 'string' || !HEX.test(value.logicalFingerprint)
|
|
124
|
+
|| typeof value.sourceHead !== 'string' || !/^[a-f0-9]{40}$/.test(value.sourceHead)
|
|
125
|
+
|| typeof value.sourceBranch !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,127}$/.test(value.sourceBranch)
|
|
126
|
+
|| typeof value.sourceStateSha256 !== 'string' || !HEX.test(value.sourceStateSha256)
|
|
127
|
+
|| !record(value.admission) || value.admission.schemaVersion !== 1
|
|
128
|
+
|| value.admission.outcome !== 'admitted-unverified'
|
|
129
|
+
|| value.admission.baseSha !== value.sourceHead
|
|
130
|
+
|| value.admission.executionBranch !== value.sourceBranch
|
|
131
|
+
|| typeof value.admission.patchSha256 !== 'string' || !HEX.test(value.admission.patchSha256)
|
|
132
|
+
|| typeof value.qaEvidenceId !== 'string' || !/^qa-[a-z0-9-]{8,80}$/.test(value.qaEvidenceId)
|
|
133
|
+
|| !record(value.artifactDigests)
|
|
134
|
+
|| Object.keys(value.artifactDigests).sort().join('|') !== [...ARTIFACT_NAMES].sort().join('|')
|
|
135
|
+
|| ARTIFACT_NAMES.some((name) => typeof value.artifactDigests[name] !== 'string'
|
|
136
|
+
|| !HEX.test(value.artifactDigests[name]))) {
|
|
137
|
+
throw new Error('planning-diagnosis-review-invalid');
|
|
138
|
+
}
|
|
139
|
+
canonicalPlanningIntake(value.intake);
|
|
140
|
+
createPlanningReceiptV1({ kind: 'diagnosis', epicId: value.epicId,
|
|
141
|
+
intakeRevision: planningIntakeRevision(value.intake),
|
|
142
|
+
artifactSummary: value.artifactSummary, accepted: true });
|
|
143
|
+
}
|
|
144
|
+
function physicalEvidence(root, review, checkPatch, ownTemporaryPath) {
|
|
145
|
+
if (git(root, ['rev-parse', 'HEAD']) !== review.sourceHead
|
|
146
|
+
|| git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== review.sourceBranch) {
|
|
147
|
+
throw new Error('planning-diagnosis-head-conflict');
|
|
148
|
+
}
|
|
149
|
+
const stateDir = lstatSync(join(root, '.neocortex'));
|
|
150
|
+
const sidecarEntry = lstatSync(join(root, '.neocortex/pending-epic-claims.json'));
|
|
151
|
+
if (!stateDir.isDirectory() || stateDir.isSymbolicLink()
|
|
152
|
+
|| (stateDir.mode & 0o022) !== 0
|
|
153
|
+
|| !sidecarEntry.isFile() || sidecarEntry.isSymbolicLink()
|
|
154
|
+
|| sidecarEntry.uid !== process.getuid?.() || (sidecarEntry.mode & 0o077) !== 0) {
|
|
155
|
+
throw new Error('planning-diagnosis-claim-boundary-invalid');
|
|
156
|
+
}
|
|
157
|
+
const sidecar = JSON.parse(regularBytes(root, '.neocortex/pending-epic-claims.json', 128 * 1024).toString('utf8'));
|
|
158
|
+
const operation = record(sidecar) && record(sidecar.operations)
|
|
159
|
+
? sidecar.operations[review.logicalFingerprint] : undefined;
|
|
160
|
+
if (!record(operation) || operation.claimId !== review.claimId || operation.epicId !== review.epicId) {
|
|
161
|
+
throw new Error('planning-diagnosis-claim-conflict');
|
|
162
|
+
}
|
|
163
|
+
const prefix = `.neocortex/planning/epic-${review.epicId}`;
|
|
164
|
+
const paths = { idea: `${prefix}/idea.json`, diagnosis: `${prefix}/diagnosis.md`,
|
|
165
|
+
enrichment: `${prefix}/enriched-prompt.md`, index: '.neocortex/planning/planning.json' };
|
|
166
|
+
if (!Array.isArray(review.admission.changedPaths)
|
|
167
|
+
|| [...review.admission.changedPaths].sort().join('|') !== Object.values(paths).sort().join('|')
|
|
168
|
+
|| checkPatch && planningPhysicalPatchDigest(root, paths, ownTemporaryPath) !== review.admission.patchSha256) {
|
|
169
|
+
throw new Error('planning-diagnosis-admission-patch-conflict');
|
|
170
|
+
}
|
|
171
|
+
const artifacts = { idea: regularBytes(root, paths.idea, 32 * 1024),
|
|
172
|
+
diagnosis: regularBytes(root, paths.diagnosis, 256 * 1024),
|
|
173
|
+
enrichment: regularBytes(root, paths.enrichment, 256 * 1024),
|
|
174
|
+
index: regularBytes(root, paths.index, 128 * 1024) };
|
|
175
|
+
for (const name of ARTIFACT_NAMES) {
|
|
176
|
+
if (digest(artifacts[name]) !== review.artifactDigests[name]) {
|
|
177
|
+
throw new Error('planning-diagnosis-artifact-conflict');
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const idea = JSON.parse(artifacts.idea.toString('utf8'));
|
|
181
|
+
const index = JSON.parse(artifacts.index.toString('utf8'));
|
|
182
|
+
const intake = canonicalPlanningIntake(review.intake);
|
|
183
|
+
const indexEpic = record(index) && record(index.epics)
|
|
184
|
+
? index.epics[review.epicId] : undefined;
|
|
185
|
+
const indexOutputs = record(indexEpic) ? indexEpic.output_files : undefined;
|
|
186
|
+
if (!record(idea) || idea.epic_id !== review.epicId || idea.status !== 'diagnosed'
|
|
187
|
+
|| idea.raw_input !== intake.rawIntent || !record(indexEpic)
|
|
188
|
+
|| indexEpic.id !== review.epicId || indexEpic.idea !== intake.rawIntent
|
|
189
|
+
|| indexEpic.status !== 'diagnosed'
|
|
190
|
+
|| !documentMatches(artifacts.diagnosis.toString('utf8'), review.epicId, DIAGNOSIS_STEP_DIGEST)
|
|
191
|
+
|| !documentMatches(artifacts.enrichment.toString('utf8'), review.epicId, ENRICHMENT_STEP_DIGEST)
|
|
192
|
+
|| !Array.isArray(indexEpic.steps_completed) || indexEpic.steps_completed.length !== 1
|
|
193
|
+
|| !stepMatches(indexEpic.steps_completed[0], DIAGNOSIS_STEP_DIGEST)
|
|
194
|
+
|| !record(indexOutputs) || !isDeepStrictEqual(indexOutputs, { diagnosis: paths.diagnosis })
|
|
195
|
+
|| typeof indexEpic.created_at !== 'string' || !Number.isFinite(Date.parse(indexEpic.created_at))
|
|
196
|
+
|| indexEpic.completed_at !== null) {
|
|
197
|
+
throw new Error('planning-diagnosis-artifact-identity-conflict');
|
|
198
|
+
}
|
|
199
|
+
if (typeof intake.goal !== 'string' || !intake.goal.trim()
|
|
200
|
+
|| typeof intake.desiredOutcome !== 'string' || !intake.desiredOutcome.trim()
|
|
201
|
+
|| !Array.isArray(intake.users) || intake.users.length === 0
|
|
202
|
+
|| !Array.isArray(intake.surfaces) || intake.surfaces.length === 0) {
|
|
203
|
+
throw new Error('planning-diagnosis-critical-intake-missing');
|
|
204
|
+
}
|
|
205
|
+
const intakeRevision = planningIntakeRevision(intake);
|
|
206
|
+
const receipt = createPlanningReceiptV1({ kind: 'diagnosis', epicId: review.epicId,
|
|
207
|
+
intakeRevision, artifactSummary: review.artifactSummary, accepted: true });
|
|
208
|
+
const checkpoint = { schemaVersion: 1, epicId: review.epicId, intake, intakeRevision,
|
|
209
|
+
diagnosisReceipt: receipt };
|
|
210
|
+
return { checkpoint, receiptId: receipt.receiptId };
|
|
211
|
+
}
|
|
212
|
+
function physicalCheckpoint(root, review, ownTemporaryPath) {
|
|
213
|
+
const evidence = physicalEvidence(root, review, true, ownTemporaryPath);
|
|
214
|
+
const stateRaw = regularBytes(root, '.neocortex/state.json', 8 * 1024 * 1024);
|
|
215
|
+
if (digest(stateRaw) !== review.sourceStateSha256) {
|
|
216
|
+
throw new Error('planning-diagnosis-state-conflict');
|
|
217
|
+
}
|
|
218
|
+
const state = JSON.parse(stateRaw.toString('utf8'));
|
|
219
|
+
if (!record(state) || record(state.scope) && state.scope.kind === 'projected') {
|
|
220
|
+
throw new Error('planning-diagnosis-state-invalid');
|
|
221
|
+
}
|
|
222
|
+
projectDiagnosedEpicState(state, { claimId: review.claimId, epicId: review.epicId,
|
|
223
|
+
checkpoint: evidence.checkpoint });
|
|
224
|
+
return { stateRaw, state, ...evidence };
|
|
225
|
+
}
|
|
226
|
+
function physicalAcceptance(review, diagnosisReceiptId) {
|
|
227
|
+
const fields = {
|
|
228
|
+
schemaVersion: 'PlanningDiagnosisPhysicalAcceptance/1',
|
|
229
|
+
claimId: review.claimId, epicId: review.epicId,
|
|
230
|
+
diagnosisReceiptId, qaEvidenceId: review.qaEvidenceId,
|
|
231
|
+
sourceHead: review.sourceHead, sourceStateSha256: review.sourceStateSha256,
|
|
232
|
+
admissionPatchSha256: review.admission.patchSha256,
|
|
233
|
+
artifactDigests: review.artifactDigests,
|
|
234
|
+
};
|
|
235
|
+
return { ...fields, receiptId: digest(JSON.stringify(fields)), publicSafe: true };
|
|
236
|
+
}
|
|
237
|
+
/** P02 may consume only a physically sealed P01 for the same durable claim. */
|
|
238
|
+
export function acceptedPlanningDiagnosisPredecessor(stateInput, claimId, epicId, allowResearched = false) {
|
|
239
|
+
const state = record(stateInput) ? stateInput : undefined;
|
|
240
|
+
const epics = state && record(state.epics) ? state.epics : undefined;
|
|
241
|
+
const epic = epics?.[epicId];
|
|
242
|
+
if (!record(epic) || epic.id !== epicId || epic.source !== 'create-epic'
|
|
243
|
+
|| epic.status !== 'diagnosed' && !(allowResearched && epic.status === 'researched')
|
|
244
|
+
|| !record(epic.createEpicPlanningClaim)
|
|
245
|
+
|| epic.createEpicPlanningClaim.claimId !== claimId
|
|
246
|
+
|| epic.createEpicPlanningClaim.epicId !== epicId
|
|
247
|
+
|| !record(epic.createEpicPlanning) || !record(epic.createEpicPlanningPhysical)) {
|
|
248
|
+
throw new Error('planning-research-predecessor-invalid');
|
|
249
|
+
}
|
|
250
|
+
const checkpoint = epic.createEpicPlanning;
|
|
251
|
+
const physical = epic.createEpicPlanningPhysical;
|
|
252
|
+
const artifactDigests = record(physical.artifactDigests) ? physical.artifactDigests : undefined;
|
|
253
|
+
const intake = canonicalPlanningIntake(checkpoint.intake);
|
|
254
|
+
const revision = planningIntakeRevision(intake);
|
|
255
|
+
const ledger = state && record(state.epic_id_ledger) ? state.epic_id_ledger : undefined;
|
|
256
|
+
const receipt = record(checkpoint.diagnosisReceipt) ? checkpoint.diagnosisReceipt : undefined;
|
|
257
|
+
if (checkpoint.schemaVersion !== 1 || checkpoint.epicId !== epicId
|
|
258
|
+
|| checkpoint.intakeRevision !== revision
|
|
259
|
+
|| !allowResearched && checkpoint.researchReceipt !== undefined
|
|
260
|
+
|| typeof intake.goal !== 'string' || !intake.goal.trim()
|
|
261
|
+
|| typeof intake.desiredOutcome !== 'string' || !intake.desiredOutcome.trim()
|
|
262
|
+
|| typeof intake.rawIntent !== 'string' || !intake.rawIntent.trim()
|
|
263
|
+
|| !Array.isArray(intake.users) || intake.users.length === 0
|
|
264
|
+
|| !Array.isArray(intake.surfaces) || intake.surfaces.length === 0
|
|
265
|
+
|| !Array.isArray(ledger?.reserved_ids) || !ledger.reserved_ids.includes(epicId)
|
|
266
|
+
|| !receipt || receipt.kind !== 'diagnosis' || receipt.epicId !== epicId
|
|
267
|
+
|| receipt.intakeRevision !== revision || receipt.accepted !== true
|
|
268
|
+
|| typeof receipt.artifactSummary !== 'string'
|
|
269
|
+
|| !isDeepStrictEqual(receipt, createPlanningReceiptV1({ kind: 'diagnosis', epicId,
|
|
270
|
+
intakeRevision: revision, artifactSummary: receipt.artifactSummary, accepted: true }))
|
|
271
|
+
|| physical.schemaVersion !== 'PlanningDiagnosisPhysicalAcceptance/1'
|
|
272
|
+
|| physical.claimId !== claimId || physical.epicId !== epicId
|
|
273
|
+
|| physical.diagnosisReceiptId !== receipt.receiptId
|
|
274
|
+
|| typeof physical.qaEvidenceId !== 'string'
|
|
275
|
+
|| !/^qa-[a-z0-9-]{8,80}$/.test(physical.qaEvidenceId)
|
|
276
|
+
|| typeof physical.sourceHead !== 'string' || !/^[a-f0-9]{40}$/.test(physical.sourceHead)
|
|
277
|
+
|| typeof physical.sourceStateSha256 !== 'string' || !HEX.test(physical.sourceStateSha256)
|
|
278
|
+
|| typeof physical.admissionPatchSha256 !== 'string' || !HEX.test(physical.admissionPatchSha256)
|
|
279
|
+
|| !artifactDigests
|
|
280
|
+
|| Object.keys(artifactDigests).sort().join('|') !== [...ARTIFACT_NAMES].sort().join('|')
|
|
281
|
+
|| ARTIFACT_NAMES.some((name) => typeof artifactDigests[name] !== 'string'
|
|
282
|
+
|| !HEX.test(artifactDigests[name]))) {
|
|
283
|
+
throw new Error('planning-research-predecessor-invalid');
|
|
284
|
+
}
|
|
285
|
+
const fields = { schemaVersion: physical.schemaVersion, claimId, epicId,
|
|
286
|
+
diagnosisReceiptId: receipt.receiptId, qaEvidenceId: physical.qaEvidenceId,
|
|
287
|
+
sourceHead: physical.sourceHead, sourceStateSha256: physical.sourceStateSha256,
|
|
288
|
+
admissionPatchSha256: physical.admissionPatchSha256,
|
|
289
|
+
artifactDigests };
|
|
290
|
+
if (!isDeepStrictEqual(physical, { ...fields, receiptId: digest(JSON.stringify(fields)), publicSafe: true })) {
|
|
291
|
+
throw new Error('planning-research-predecessor-invalid');
|
|
292
|
+
}
|
|
293
|
+
return { intakeRevision: revision, diagnosisReceiptId: receipt.receiptId,
|
|
294
|
+
rawIntent: intake.rawIntent };
|
|
295
|
+
}
|
|
296
|
+
function acceptedReplay(root, review) {
|
|
297
|
+
const evidence = physicalEvidence(root, review, false);
|
|
298
|
+
const state = JSON.parse(regularBytes(root, '.neocortex/state.json', 8 * 1024 * 1024).toString('utf8'));
|
|
299
|
+
const epics = record(state) && record(state.epics) ? state.epics : undefined;
|
|
300
|
+
const epic = epics?.[review.epicId];
|
|
301
|
+
const ledger = record(state) && record(state.epic_id_ledger) ? state.epic_id_ledger : undefined;
|
|
302
|
+
if (!record(epic) || !record(epic.createEpicPlanning)
|
|
303
|
+
|| !record(epic.createEpicPlanningClaim)
|
|
304
|
+
|| epic.createEpicPlanningClaim.claimId !== review.claimId
|
|
305
|
+
|| epic.createEpicPlanningClaim.epicId !== review.epicId
|
|
306
|
+
|| epic.createEpicPlanning.epicId !== review.epicId
|
|
307
|
+
|| epic.createEpicPlanning.intakeRevision !== evidence.checkpoint.intakeRevision
|
|
308
|
+
|| !isDeepStrictEqual(epic.createEpicPlanning.intake, evidence.checkpoint.intake)
|
|
309
|
+
|| !isDeepStrictEqual(epic.createEpicPlanning.diagnosisReceipt, evidence.checkpoint.diagnosisReceipt)
|
|
310
|
+
|| !isDeepStrictEqual(epic.createEpicPlanningPhysical, physicalAcceptance(review, evidence.receiptId))
|
|
311
|
+
|| !Array.isArray(ledger?.reserved_ids) || !ledger.reserved_ids.includes(review.epicId)) {
|
|
312
|
+
throw new Error('planning-diagnosis-replay-conflict');
|
|
313
|
+
}
|
|
314
|
+
return evidence.receiptId;
|
|
315
|
+
}
|
|
316
|
+
/** Root-only state transition after a separately accepted review of the exact admitted patch. */
|
|
317
|
+
export function sealPlanningDiagnosis(projectRoot, reviewInput) {
|
|
318
|
+
validateReview(reviewInput);
|
|
319
|
+
const review = reviewInput;
|
|
320
|
+
const root = resolve(projectRoot);
|
|
321
|
+
if (realpathSync(root) !== root || git(root, ['rev-parse', '--show-toplevel']) !== root) {
|
|
322
|
+
throw new Error('planning-diagnosis-root-invalid');
|
|
323
|
+
}
|
|
324
|
+
const stateDir = join(root, '.neocortex');
|
|
325
|
+
const lockPath = join(stateDir, 'state.json.planning.lock');
|
|
326
|
+
const lock = openSync(lockPath, 'wx', 0o600);
|
|
327
|
+
let temporaryPath;
|
|
328
|
+
try {
|
|
329
|
+
const currentRaw = regularBytes(root, '.neocortex/state.json', 8 * 1024 * 1024);
|
|
330
|
+
if (digest(currentRaw) !== review.sourceStateSha256) {
|
|
331
|
+
const diagnosisReceiptId = acceptedReplay(root, review);
|
|
332
|
+
return { epicId: review.epicId, diagnosisReceiptId, qaEvidenceId: review.qaEvidenceId };
|
|
333
|
+
}
|
|
334
|
+
const before = physicalCheckpoint(root, review);
|
|
335
|
+
const projected = projectDiagnosedEpicState(before.state, {
|
|
336
|
+
claimId: review.claimId, epicId: review.epicId, checkpoint: before.checkpoint,
|
|
337
|
+
});
|
|
338
|
+
if (projected === before.state)
|
|
339
|
+
throw new Error('planning-diagnosis-already-sealed');
|
|
340
|
+
const acceptance = physicalAcceptance(review, before.receiptId);
|
|
341
|
+
const projectedEpics = projected.epics;
|
|
342
|
+
const next = { ...projected, epics: { ...projectedEpics,
|
|
343
|
+
[review.epicId]: { ...projectedEpics[review.epicId], createEpicPlanningPhysical: acceptance },
|
|
344
|
+
} };
|
|
345
|
+
const commonRaw = git(root, ['rev-parse', '--git-common-dir']);
|
|
346
|
+
const commonDir = isAbsolute(commonRaw) ? resolve(commonRaw) : resolve(root, commonRaw);
|
|
347
|
+
if (realpathSync(commonDir) !== commonDir || lstatSync(commonDir).isSymbolicLink()) {
|
|
348
|
+
throw new Error('planning-diagnosis-backup-dir-invalid');
|
|
349
|
+
}
|
|
350
|
+
const backupDir = join(commonDir, 'neocortex-planning');
|
|
351
|
+
mkdirSync(backupDir, { recursive: true, mode: 0o700 });
|
|
352
|
+
const backupEntry = lstatSync(backupDir);
|
|
353
|
+
if (!backupEntry.isDirectory() || backupEntry.isSymbolicLink()
|
|
354
|
+
|| backupEntry.uid !== process.getuid?.() || (backupEntry.mode & 0o077) !== 0) {
|
|
355
|
+
throw new Error('planning-diagnosis-backup-dir-invalid');
|
|
356
|
+
}
|
|
357
|
+
const suffix = randomUUID();
|
|
358
|
+
const backup = openSync(join(backupDir, `state-backup-${suffix}.json`), 'wx', 0o600);
|
|
359
|
+
try {
|
|
360
|
+
writeFileSync(backup, before.stateRaw);
|
|
361
|
+
fsyncSync(backup);
|
|
362
|
+
}
|
|
363
|
+
finally {
|
|
364
|
+
closeSync(backup);
|
|
365
|
+
}
|
|
366
|
+
const backupDirectory = openSync(backupDir, 'r');
|
|
367
|
+
try {
|
|
368
|
+
fsyncSync(backupDirectory);
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
closeSync(backupDirectory);
|
|
372
|
+
}
|
|
373
|
+
temporaryPath = join(stateDir, `state.json.planning-tmp-${suffix}`);
|
|
374
|
+
const temporary = openSync(temporaryPath, 'wx', 0o600);
|
|
375
|
+
try {
|
|
376
|
+
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`);
|
|
377
|
+
fsyncSync(temporary);
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
closeSync(temporary);
|
|
381
|
+
}
|
|
382
|
+
if (!physicalCheckpoint(root, review, `.neocortex/state.json.planning-tmp-${suffix}`).stateRaw.equals(before.stateRaw)) {
|
|
383
|
+
throw new Error('planning-diagnosis-state-conflict');
|
|
384
|
+
}
|
|
385
|
+
renameSync(temporaryPath, join(stateDir, 'state.json'));
|
|
386
|
+
temporaryPath = undefined;
|
|
387
|
+
const stateDirectory = openSync(stateDir, 'r');
|
|
388
|
+
try {
|
|
389
|
+
fsyncSync(stateDirectory);
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
closeSync(stateDirectory);
|
|
393
|
+
}
|
|
394
|
+
return { epicId: review.epicId, diagnosisReceiptId: before.receiptId,
|
|
395
|
+
qaEvidenceId: review.qaEvidenceId };
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
if (temporaryPath)
|
|
399
|
+
try {
|
|
400
|
+
unlinkSync(temporaryPath);
|
|
401
|
+
}
|
|
402
|
+
catch { /* preserve primary failure */ }
|
|
403
|
+
closeSync(lock);
|
|
404
|
+
unlinkSync(lockPath);
|
|
405
|
+
}
|
|
406
|
+
}
|