@ornexus/neocortex 4.60.73 → 4.60.74
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 +1216 -1210
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +1 -108
- package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
- package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
- package/packages/client/dist/adapters/codex-adapter.js +2 -80
- package/packages/client/dist/adapters/cursor-adapter.js +4 -115
- package/packages/client/dist/adapters/gemini-adapter.js +2 -71
- package/packages/client/dist/adapters/grok-adapter.js +2 -42
- package/packages/client/dist/adapters/index.js +1 -22
- package/packages/client/dist/adapters/platform-detector.js +1 -212
- package/packages/client/dist/adapters/target-adapter.js +0 -12
- package/packages/client/dist/adapters/vscode-adapter.js +2 -72
- package/packages/client/dist/agent/refresh-stubs.js +2 -417
- package/packages/client/dist/agent/update-agent-yaml.js +1 -102
- package/packages/client/dist/agent/update-description.js +1 -251
- package/packages/client/dist/cache/crypto-utils.js +1 -78
- package/packages/client/dist/cache/encrypted-cache.js +1 -108
- package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
- package/packages/client/dist/cache/index.js +1 -13
- package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
- package/packages/client/dist/checkpoint/index.js +1 -11
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
- package/packages/client/dist/cli.js +5 -358
- package/packages/client/dist/commands/activate.js +8 -394
- package/packages/client/dist/commands/architecture-answers.js +7 -274
- package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
- package/packages/client/dist/commands/architecture-root-binding.js +1 -51
- package/packages/client/dist/commands/cache-status.js +2 -112
- package/packages/client/dist/commands/config.js +1 -88
- package/packages/client/dist/commands/doctor.js +2 -635
- package/packages/client/dist/commands/invoke.js +143 -7200
- package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
- package/packages/client/dist/commands/legacy-story-branch.js +1 -96
- package/packages/client/dist/commands/legacy-story-pr.js +1 -276
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
- package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
- package/packages/client/dist/commands/mutation-qa-git.js +1 -41
- package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
- package/packages/client/dist/commands/mutation-qa-run.js +3 -219
- package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
- package/packages/client/dist/commands/mutation-qa.js +1 -220
- package/packages/client/dist/commands/native-agent.js +2 -136
- package/packages/client/dist/commands/planning-diagnosis.js +1 -43
- package/packages/client/dist/commands/planning-generation.js +1 -53
- package/packages/client/dist/commands/planning-memory.js +1 -40
- package/packages/client/dist/commands/planning-research.js +1 -42
- package/packages/client/dist/commands/private-session.js +1 -75
- package/packages/client/dist/commands/property-qa.js +1 -139
- package/packages/client/dist/commands/qa-control.js +1 -16
- package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
- package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
- package/packages/client/dist/commands/qa-scan-capture.js +5 -663
- package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
- package/packages/client/dist/commands/qa-scan-review.js +5 -826
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
- package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
- package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
- package/packages/client/dist/commands/refactor-characterization.js +21 -671
- package/packages/client/dist/commands/refactor-commit.js +13 -399
- package/packages/client/dist/commands/refactor-control.js +3 -142
- package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
- package/packages/client/dist/commands/refactor-review.js +5 -283
- package/packages/client/dist/commands/refactor-root.js +7 -588
- package/packages/client/dist/commands/refresh-memory.js +3 -156
- package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
- package/packages/client/dist/commands/story-checkpoint.js +1 -171
- package/packages/client/dist/config/profile-directory.js +1 -13
- package/packages/client/dist/config/resolver-selection.js +1 -278
- package/packages/client/dist/config/secure-config.js +12 -281
- package/packages/client/dist/config.js +2 -223
- package/packages/client/dist/constants.js +1 -25
- package/packages/client/dist/context/context-collector.js +2 -222
- package/packages/client/dist/context/context-sanitizer.js +1 -145
- package/packages/client/dist/continuity/autonomous-governance.js +1 -285
- package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
- package/packages/client/dist/continuity/invoke-hooks.js +1 -129
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
- package/packages/client/dist/continuity/native-agent-store.js +1 -69
- package/packages/client/dist/continuity/native-agent-types.js +1 -90
- package/packages/client/dist/continuity/outbox.js +1 -117
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
- package/packages/client/dist/continuity/sqlite-store.js +81 -2612
- package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
- package/packages/client/dist/errors/error-messages.js +2 -228
- package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
- package/packages/client/dist/evidence/collector.js +1 -347
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +0 -2
- package/packages/client/dist/fs/atomic-state-replace.js +1 -152
- package/packages/client/dist/generated/command-registry.generated.js +1 -4076
- package/packages/client/dist/generated/public-projections.generated.js +1 -149
- package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
- package/packages/client/dist/git/epic-operational-state.js +2 -672
- package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
- package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
- package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
- package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
- package/packages/client/dist/git/legacy-story-pr.js +70 -3538
- package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
- package/packages/client/dist/i18n/first-run.js +2 -60
- package/packages/client/dist/index.js +1 -47
- package/packages/client/dist/invocation/invoke-input.js +1 -24
- package/packages/client/dist/license/index.js +1 -5
- package/packages/client/dist/license/license-client.js +1 -304
- package/packages/client/dist/machine/fingerprint.js +2 -163
- package/packages/client/dist/machine/index.js +1 -5
- package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
- package/packages/client/dist/memory/project-memory-writer.js +40 -1007
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
- package/packages/client/dist/migrations/project-identity-capability.js +1 -50
- package/packages/client/dist/migrations/project-identity.js +7 -493
- package/packages/client/dist/migrations/state-json.js +4 -393
- package/packages/client/dist/policy/architecture-policy.js +2 -184
- package/packages/client/dist/policy/index.js +1 -7
- package/packages/client/dist/policy/shared-policy-types.js +0 -38
- package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
- package/packages/client/dist/private-execution/clean-baseline.js +2 -279
- package/packages/client/dist/private-execution/codex-executor.js +4 -574
- package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
- package/packages/client/dist/private-execution/delivery.js +13 -410
- package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
- package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
- package/packages/client/dist/private-execution/implementation-validation.js +2 -106
- package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
- package/packages/client/dist/private-execution/isolated-session.js +5 -725
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
- package/packages/client/dist/private-execution/pact-test-source.js +1 -258
- package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
- package/packages/client/dist/private-execution/pact-write-set.js +1 -172
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
- package/packages/client/dist/private-execution/private-report-store.js +1 -42
- package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
- package/packages/client/dist/private-execution/property-test-choices.js +3 -147
- package/packages/client/dist/private-execution/property-test-plan.js +7 -271
- package/packages/client/dist/private-execution/property-test-review.js +4 -258
- package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
- package/packages/client/dist/private-execution/property-test-source.js +1 -139
- package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
- package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
- package/packages/client/dist/private-execution/root-memory-request.js +1 -29
- package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
- package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
- package/packages/client/dist/private-execution/session-lease.js +1 -63
- package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
- package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
- package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
- package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
- package/packages/client/dist/private-execution/ux-write-set.js +2 -191
- package/packages/client/dist/registry/registry-reconciliation.js +1 -234
- package/packages/client/dist/resilience/circuit-breaker.js +1 -170
- package/packages/client/dist/resilience/degradation-manager.js +1 -164
- package/packages/client/dist/resilience/freshness-indicator.js +1 -100
- package/packages/client/dist/resilience/index.js +1 -8
- package/packages/client/dist/resilience/recovery-detector.js +1 -74
- package/packages/client/dist/resolvers/asset-resolver.js +0 -13
- package/packages/client/dist/resolvers/local-resolver.js +8 -255
- package/packages/client/dist/resolvers/remote-resolver.js +1 -233
- package/packages/client/dist/runner/binary.js +1 -404
- package/packages/client/dist/runner/cli.js +17 -1571
- package/packages/client/dist/runner/headless/adapters.js +1 -49
- package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
- package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
- package/packages/client/dist/runner/headless/managed-profile.js +1 -132
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
- package/packages/client/dist/runner/headless/resolver.js +1 -231
- package/packages/client/dist/runner/headless/run-yolo.js +1 -885
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
- package/packages/client/dist/runner/headless/types.js +2 -574
- package/packages/client/dist/runner/local-console.js +13 -396
- package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
- package/packages/client/dist/runner/project-identity.js +1 -106
- package/packages/client/dist/runner/scheduler.js +7 -995
- package/packages/client/dist/runner-cli.js +2 -18
- package/packages/client/dist/state/invocation-shape.js +1 -13
- package/packages/client/dist/state/project-state-snapshot.js +1 -1731
- package/packages/client/dist/state/state-json-repair.js +3 -785
- package/packages/client/dist/state/structural-dag-projection.js +1 -118
- package/packages/client/dist/telemetry/index.js +1 -5
- package/packages/client/dist/telemetry/offline-queue.js +1 -131
- package/packages/client/dist/tier/index.js +1 -5
- package/packages/client/dist/tier/tier-aware-client.js +1 -405
- package/packages/client/dist/types/index.js +1 -38
- package/packages/client/dist/version.js +1 -27
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
- package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
- package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
- package/packages/client/dist/yoloop/discovery-hook.js +2 -300
- package/packages/client/dist/yoloop/index.js +1 -8
- package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
- package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
- package/packages/client/dist/yoloop/target-normalization.js +1 -180
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
- package/packages/shared/dist/yolo/change-evidence.js +1 -1
- package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
- 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,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
|
+
import{createHash as g}from"node:crypto";import{lstatSync as C,readFileSync as D,realpathSync as I}from"node:fs";import{join as _,resolve as k}from"node:path";import{parseDocument as N}from"yaml";const j="docs/api/openapi.yaml",z=5*1024*1024,K=256,L=new Set(["get","post","put","patch","delete","head","options","trace"]);function e(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.getPrototypeOf(r)===Object.prototype}function M(r,c){let t=r;for(const w of c.split("/")){t=_(t,w);let a;try{a=C(t)}catch(O){if(O.code==="ENOENT")return!1;throw new Error("pact-write-set-path-unsafe")}if(a.isSymbolicLink()||(t===_(r,c)?!a.isFile():!a.isDirectory()))throw new Error("pact-write-set-path-unsafe")}return!0}function $(r,c){const t=r.replace(/^\//,"").replace(/[{}]/g,"").replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase();return`${c.toLowerCase()}-${t||"root"}`}function v(r,c){if(typeof c!="boolean")throw new Error("pact-write-set-options-invalid");const t=k(r);try{if(I(t)!==t||!C(t).isDirectory())throw new Error("pact-write-set-path-unsafe")}catch{throw new Error("pact-write-set-path-unsafe")}if(!M(t,j))return{outcome:"skipped",reasonCode:"PACT_SKIPPED_NO_OPENAPI"};const w=C(_(t,j));if(w.size<1||w.size>z)throw new Error("pact-write-set-spec-size-invalid");const a=D(_(t,j)),O=g("sha256").update(a).digest("hex");let d;try{const o=new TextDecoder("utf-8",{fatal:!0}).decode(a),s=N(o,{strict:!0,stringKeys:!0,uniqueKeys:!0,schema:"core",customTags:[]});if(s.errors.length>0||s.warnings.length>0)return{outcome:"skipped",reasonCode:"PACT_SKIPPED_INVALID_YAML"};d=s.toJS({maxAliasCount:0})}catch{return{outcome:"skipped",reasonCode:"PACT_SKIPPED_INVALID_YAML"}}if(!e(d)||d.openapi!=="3.1.0")return{outcome:"skipped",reasonCode:"PACT_SKIPPED_UNSUPPORTED_VERSION"};if(!e(d.paths)||Object.keys(d.paths).length===0)return{outcome:"skipped",reasonCode:"PACT_SKIPPED_EMPTY_PATHS"};const l=new Set,A=[];let P=0;for(const[o,s]of Object.entries(d.paths)){if(!o.startsWith("/")||o.length>180||/[\u0000-\u001f\u007f?#]/.test(o)||!e(s)||o.split("/").some(u=>(u.includes("{")||u.includes("}"))&&!/^[^{}]*\{[^{}]+\}[^{}]*$/.test(u)))throw new Error("pact-write-set-spec-shape-invalid");for(const[u,f]of Object.entries(s)){const p=u.toLowerCase();if(!L.has(p))continue;if(!e(f))throw new Error("pact-write-set-spec-shape-invalid");if(p==="trace"||(p==="get"||p==="head")&&f.requestBody!==void 0)throw new Error("pact-write-set-method-unsupported");if(f.requestBody!==void 0){const n=f.requestBody,h=e(n)?n.content:void 0,b=e(h)?h["application/json"]:void 0;if(!e(b)||!e(b.schema))throw new Error("pact-write-set-operation-unsupported")}const m=f.responses,y=e(m)?["200","201",...Object.keys(m).filter(n=>/^[1-5][0-9]{2}$/.test(n)).sort()].find(n=>e(m[n])):void 0;if(!y)throw new Error("pact-write-set-operation-unsupported");const i=m[y];if((y==="204"||p==="head")&&e(i)&&(i.schema!==void 0||e(i.content)&&Object.keys(i.content).length>0))throw new Error("pact-write-set-operation-unsupported");if(y!=="204"&&p!=="head"&&e(i)){const n=i.content;if(n!==void 0){if(!e(n))throw new Error("pact-write-set-operation-unsupported");if(Object.keys(n).length>0){const h=n["application/json"];if(!e(h)||!e(h.schema))throw new Error("pact-write-set-operation-unsupported")}}if(i.schema!==void 0&&!e(i.schema))throw new Error("pact-write-set-operation-unsupported")}if(P+=1,P>K)throw new Error("pact-write-set-endpoint-limit");const S=`tests/pact/consumer/${$(o,u)}.test.ts`;if(S.length>240||l.has(S))throw new Error("pact-write-set-path-collision");l.add(S),A.push(Object.freeze({filePath:S,method:p.toUpperCase(),endpointPath:o}))}}if(P===0)return{outcome:"skipped",reasonCode:"PACT_SKIPPED_EMPTY_PATHS"};const E=c?"tests/pact/provider/verify.test.ts":void 0;E&&l.add(E);const T=Object.freeze([...l].sort());return A.sort((o,s)=>o.filePath<s.filePath?-1:o.filePath>s.filePath?1:0),{outcome:"ready",writeSet:Object.freeze({schemaVersion:1,specSha256:O,pathsSha256:g("sha256").update(JSON.stringify(T)).digest("hex"),endpointCount:P,paths:T,interactions:Object.freeze(A),...E?{providerPath:E}:{}})}}export{v as derivePactWriteSet};
|
|
@@ -1,406 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
}
|
|
1
|
+
import{execFileSync as q,spawnSync as Y}from"node:child_process";import{createHash as v,randomUUID as ii}from"node:crypto";import{closeSync as D,fsyncSync as _,lstatSync as w,mkdirSync as ni,openSync as j,readFileSync as V,realpathSync as J,renameSync as ei,unlinkSync as L,writeFileSync as T}from"node:fs";import{isAbsolute as ti,join as m,resolve as B}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{canonicalPlanningIntake as H,createPlanningReceiptV1 as N,planningIntakeRevision as F,projectDiagnosedEpicState as M}from"../../../shared/dist/planning/diagnosis-state.js";const x=/^[a-f0-9]{64}$/,si=/^P[1-9][0-9]{0,11}$/,ci=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,A=["idea","diagnosis","enrichment","index"],G="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",ai="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369";function o(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function S(i){return v("sha256").update(i).digest("hex")}function O(i,n){return q("git",[...n],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:65536}).trim()}function I(i,n,e){const t=m(i,n),c=w(t);if(!c.isFile()||c.isSymbolicLink()||c.size<1||c.size>e)throw new Error("planning-diagnosis-physical-artifact-invalid");return V(t)}function U(i,n){return typeof i=="string"&&i.length<=128&&S(i)===n}function Z(i,n,e){const t=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(i.replace(/\r\n/g,`
|
|
2
|
+
`))?.[1];if(!t)return!1;const c=t.split(`
|
|
3
|
+
`),a=d=>{const g=c.filter(r=>r.startsWith(`${d}:`));return g.length===1?g[0].slice(d.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return a("epic_id")===n&&a("status")==="completed"&&U(a("step"),e)}function mi(i){const n=m(i,".neocortex/pending-epic-claims.json");let e;try{e=w(n)}catch(a){if(a.code==="ENOENT")return;throw a}const t=w(m(i,".neocortex"));if(!t.isDirectory()||t.isSymbolicLink()||t.uid!==process.getuid?.()||(t.mode&18)!==0||!e.isFile()||e.isSymbolicLink()||e.uid!==process.getuid?.()||(e.mode&63)!==0||e.size<1||e.size>128*1024)throw new Error("planning-pending-sidecar-invalid");const c=V(n);if(c.length!==e.size)throw new Error("planning-pending-sidecar-invalid");return S(c)}function ri(i,n,e,t=!0){const c=new Set(Object.values(n)),a=new Set([".neocortex/state.json.planning.lock",...e?[e]:[]]),d=q("git",["status","--porcelain=v1","-z","--untracked-files=all"],{cwd:i,stdio:["ignore","pipe","ignore"],maxBuffer:128*1024}).toString("utf8").split("\0").filter(Boolean),g=[],r=new Set;for(const l of d){const h=l.slice(0,2),s=l.slice(3);if(!(a.has(s)&&h==="??")){if(l[2]!==" "||!c.has(s)&&(!t||s!==".neocortex/pending-epic-claims.json")||s===".neocortex/pending-epic-claims.json"&&h!=="??"||s!==".neocortex/pending-epic-claims.json"&&h!=="??"&&h!==" M"||r.has(s))throw new Error("planning-diagnosis-write-scope-conflict");r.add(s),h==="??"&&c.has(s)&&g.push(s)}}if([...c].some(l=>!r.has(l)))throw new Error("planning-diagnosis-write-scope-conflict");const p=[q("git",["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"],{cwd:i,stdio:["ignore","pipe","ignore"],maxBuffer:2*1024*1024})];for(const l of g.sort()){const h=Y("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",l],{cwd:i,encoding:"buffer",maxBuffer:2097152});if(h.status!==1||!Buffer.isBuffer(h.stdout))throw new Error("planning-diagnosis-patch-invalid");p.push(h.stdout)}return S(Buffer.concat(p.map(l=>Buffer.concat([l,Buffer.from(`
|
|
4
|
+
`)]))))}function oi(i){if(!o(i)||Object.keys(i).sort().join("|")!==["schemaVersion","verdict","claimId","epicId","logicalFingerprint","sourceHead","sourceBranch","sourceStateSha256","admission","artifactDigests","qaEvidenceId","intake","artifactSummary"].sort().join("|")||i.schemaVersion!=="PlanningDiagnosisRootReview/1"||i.verdict!=="accepted"||typeof i.claimId!="string"||!ci.test(i.claimId)||typeof i.epicId!="string"||!si.test(i.epicId)||typeof i.logicalFingerprint!="string"||!x.test(i.logicalFingerprint)||typeof i.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(i.sourceHead)||typeof i.sourceBranch!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,127}$/.test(i.sourceBranch)||typeof i.sourceStateSha256!="string"||!x.test(i.sourceStateSha256)||!o(i.admission)||i.admission.schemaVersion!==1||i.admission.outcome!=="admitted-unverified"||i.admission.baseSha!==i.sourceHead||i.admission.executionBranch!==i.sourceBranch||typeof i.admission.patchSha256!="string"||!x.test(i.admission.patchSha256)||typeof i.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(i.qaEvidenceId)||!o(i.artifactDigests)||Object.keys(i.artifactDigests).sort().join("|")!==[...A].sort().join("|")||A.some(n=>typeof i.artifactDigests[n]!="string"||!x.test(i.artifactDigests[n])))throw new Error("planning-diagnosis-review-invalid");H(i.intake),N({kind:"diagnosis",epicId:i.epicId,intakeRevision:F(i.intake),artifactSummary:i.artifactSummary,accepted:!0})}function W(i,n,e,t){if(O(i,["rev-parse","HEAD"])!==n.sourceHead||O(i,["symbolic-ref","--quiet","--short","HEAD"])!==n.sourceBranch)throw new Error("planning-diagnosis-head-conflict");const c=w(m(i,".neocortex")),a=w(m(i,".neocortex/pending-epic-claims.json"));if(!c.isDirectory()||c.isSymbolicLink()||(c.mode&18)!==0||!a.isFile()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&63)!==0)throw new Error("planning-diagnosis-claim-boundary-invalid");const d=JSON.parse(I(i,".neocortex/pending-epic-claims.json",128*1024).toString("utf8")),g=o(d)&&o(d.operations)?d.operations[n.logicalFingerprint]:void 0;if(!o(g)||g.claimId!==n.claimId||g.epicId!==n.epicId)throw new Error("planning-diagnosis-claim-conflict");const r=`.neocortex/planning/epic-${n.epicId}`,f={idea:`${r}/idea.json`,diagnosis:`${r}/diagnosis.md`,enrichment:`${r}/enriched-prompt.md`,index:".neocortex/planning/planning.json"};if(!Array.isArray(n.admission.changedPaths)||[...n.admission.changedPaths].sort().join("|")!==Object.values(f).sort().join("|")||e&&ri(i,f,t)!==n.admission.patchSha256)throw new Error("planning-diagnosis-admission-patch-conflict");const p={idea:I(i,f.idea,32*1024),diagnosis:I(i,f.diagnosis,256*1024),enrichment:I(i,f.enrichment,256*1024),index:I(i,f.index,128*1024)};for(const P of A)if(S(p[P])!==n.artifactDigests[P])throw new Error("planning-diagnosis-artifact-conflict");const l=JSON.parse(p.idea.toString("utf8")),h=JSON.parse(p.index.toString("utf8")),s=H(n.intake),u=o(h)&&o(h.epics)?h.epics[n.epicId]:void 0,y=o(u)?u.output_files:void 0;if(!o(l)||l.epic_id!==n.epicId||l.status!=="diagnosed"||l.raw_input!==s.rawIntent||!o(u)||u.id!==n.epicId||u.idea!==s.rawIntent||u.status!=="diagnosed"||!Z(p.diagnosis.toString("utf8"),n.epicId,G)||!Z(p.enrichment.toString("utf8"),n.epicId,ai)||!Array.isArray(u.steps_completed)||u.steps_completed.length!==1||!U(u.steps_completed[0],G)||!o(y)||!b(y,{diagnosis:f.diagnosis})||typeof u.created_at!="string"||!Number.isFinite(Date.parse(u.created_at))||u.completed_at!==null)throw new Error("planning-diagnosis-artifact-identity-conflict");if(typeof s.goal!="string"||!s.goal.trim()||typeof s.desiredOutcome!="string"||!s.desiredOutcome.trim()||!Array.isArray(s.users)||s.users.length===0||!Array.isArray(s.surfaces)||s.surfaces.length===0)throw new Error("planning-diagnosis-critical-intake-missing");const E=F(s),k=N({kind:"diagnosis",epicId:n.epicId,intakeRevision:E,artifactSummary:n.artifactSummary,accepted:!0});return{checkpoint:{schemaVersion:1,epicId:n.epicId,intake:s,intakeRevision:E,diagnosisReceipt:k},receiptId:k.receiptId}}function X(i,n,e){const t=W(i,n,!0,e),c=I(i,".neocortex/state.json",8*1024*1024);if(S(c)!==n.sourceStateSha256)throw new Error("planning-diagnosis-state-conflict");const a=JSON.parse(c.toString("utf8"));if(!o(a)||o(a.scope)&&a.scope.kind==="projected")throw new Error("planning-diagnosis-state-invalid");return M(a,{claimId:n.claimId,epicId:n.epicId,checkpoint:t.checkpoint}),{stateRaw:c,state:a,...t}}function K(i,n){const e={schemaVersion:"PlanningDiagnosisPhysicalAcceptance/1",claimId:i.claimId,epicId:i.epicId,diagnosisReceiptId:n,qaEvidenceId:i.qaEvidenceId,sourceHead:i.sourceHead,sourceStateSha256:i.sourceStateSha256,admissionPatchSha256:i.admission.patchSha256,artifactDigests:i.artifactDigests};return{...e,receiptId:S(JSON.stringify(e)),publicSafe:!0}}function yi(i,n,e,t=!1){const c=o(i)?i:void 0,d=(c&&o(c.epics)?c.epics:void 0)?.[e];if(!o(d)||d.id!==e||d.source!=="create-epic"||d.status!=="diagnosed"&&!(t&&d.status==="researched")||!o(d.createEpicPlanningClaim)||d.createEpicPlanningClaim.claimId!==n||d.createEpicPlanningClaim.epicId!==e||!o(d.createEpicPlanning)||!o(d.createEpicPlanningPhysical))throw new Error("planning-research-predecessor-invalid");const g=d.createEpicPlanning,r=d.createEpicPlanningPhysical,f=o(r.artifactDigests)?r.artifactDigests:void 0,p=H(g.intake),l=F(p),h=c&&o(c.epic_id_ledger)?c.epic_id_ledger:void 0,s=o(g.diagnosisReceipt)?g.diagnosisReceipt:void 0;if(g.schemaVersion!==1||g.epicId!==e||g.intakeRevision!==l||!t&&g.researchReceipt!==void 0||typeof p.goal!="string"||!p.goal.trim()||typeof p.desiredOutcome!="string"||!p.desiredOutcome.trim()||typeof p.rawIntent!="string"||!p.rawIntent.trim()||!Array.isArray(p.users)||p.users.length===0||!Array.isArray(p.surfaces)||p.surfaces.length===0||!Array.isArray(h?.reserved_ids)||!h.reserved_ids.includes(e)||!s||s.kind!=="diagnosis"||s.epicId!==e||s.intakeRevision!==l||s.accepted!==!0||typeof s.artifactSummary!="string"||!b(s,N({kind:"diagnosis",epicId:e,intakeRevision:l,artifactSummary:s.artifactSummary,accepted:!0}))||r.schemaVersion!=="PlanningDiagnosisPhysicalAcceptance/1"||r.claimId!==n||r.epicId!==e||r.diagnosisReceiptId!==s.receiptId||typeof r.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(r.qaEvidenceId)||typeof r.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(r.sourceHead)||typeof r.sourceStateSha256!="string"||!x.test(r.sourceStateSha256)||typeof r.admissionPatchSha256!="string"||!x.test(r.admissionPatchSha256)||!f||Object.keys(f).sort().join("|")!==[...A].sort().join("|")||A.some(y=>typeof f[y]!="string"||!x.test(f[y])))throw new Error("planning-research-predecessor-invalid");const u={schemaVersion:r.schemaVersion,claimId:n,epicId:e,diagnosisReceiptId:s.receiptId,qaEvidenceId:r.qaEvidenceId,sourceHead:r.sourceHead,sourceStateSha256:r.sourceStateSha256,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:f};if(!b(r,{...u,receiptId:S(JSON.stringify(u)),publicSafe:!0}))throw new Error("planning-research-predecessor-invalid");return{intakeRevision:l,diagnosisReceiptId:s.receiptId,rawIntent:p.rawIntent}}function di(i,n){const e=W(i,n,!1),t=JSON.parse(I(i,".neocortex/state.json",8*1024*1024).toString("utf8")),a=(o(t)&&o(t.epics)?t.epics:void 0)?.[n.epicId],d=o(t)&&o(t.epic_id_ledger)?t.epic_id_ledger:void 0;if(!o(a)||!o(a.createEpicPlanning)||!o(a.createEpicPlanningClaim)||a.createEpicPlanningClaim.claimId!==n.claimId||a.createEpicPlanningClaim.epicId!==n.epicId||a.createEpicPlanning.epicId!==n.epicId||a.createEpicPlanning.intakeRevision!==e.checkpoint.intakeRevision||!b(a.createEpicPlanning.intake,e.checkpoint.intake)||!b(a.createEpicPlanning.diagnosisReceipt,e.checkpoint.diagnosisReceipt)||!b(a.createEpicPlanningPhysical,K(n,e.receiptId))||!Array.isArray(d?.reserved_ids)||!d.reserved_ids.includes(n.epicId))throw new Error("planning-diagnosis-replay-conflict");return e.receiptId}function Si(i,n){oi(n);const e=n,t=B(i);if(J(t)!==t||O(t,["rev-parse","--show-toplevel"])!==t)throw new Error("planning-diagnosis-root-invalid");const c=m(t,".neocortex"),a=m(c,"state.json.planning.lock"),d=j(a,"wx",384);let g;try{const r=I(t,".neocortex/state.json",8388608);if(S(r)!==e.sourceStateSha256){const Q=di(t,e);return{epicId:e.epicId,diagnosisReceiptId:Q,qaEvidenceId:e.qaEvidenceId}}const f=X(t,e),p=M(f.state,{claimId:e.claimId,epicId:e.epicId,checkpoint:f.checkpoint});if(p===f.state)throw new Error("planning-diagnosis-already-sealed");const l=K(e,f.receiptId),h=p.epics,s={...p,epics:{...h,[e.epicId]:{...h[e.epicId],createEpicPlanningPhysical:l}}},u=O(t,["rev-parse","--git-common-dir"]),y=ti(u)?B(u):B(t,u);if(J(y)!==y||w(y).isSymbolicLink())throw new Error("planning-diagnosis-backup-dir-invalid");const E=m(y,"neocortex-planning");ni(E,{recursive:!0,mode:448});const k=w(E);if(!k.isDirectory()||k.isSymbolicLink()||k.uid!==process.getuid?.()||(k.mode&63)!==0)throw new Error("planning-diagnosis-backup-dir-invalid");const R=ii(),P=j(m(E,`state-backup-${R}.json`),"wx",384);try{T(P,f.stateRaw),_(P)}finally{D(P)}const C=j(E,"r");try{_(C)}finally{D(C)}g=m(c,`state.json.planning-tmp-${R}`);const $=j(g,"wx",384);try{T($,`${JSON.stringify(s,null,2)}
|
|
5
|
+
`),_($)}finally{D($)}if(!X(t,e,`.neocortex/state.json.planning-tmp-${R}`).stateRaw.equals(f.stateRaw))throw new Error("planning-diagnosis-state-conflict");ei(g,m(c,"state.json")),g=void 0;const z=j(c,"r");try{_(z)}finally{D(z)}return{epicId:e.epicId,diagnosisReceiptId:f.receiptId,qaEvidenceId:e.qaEvidenceId}}finally{if(g)try{L(g)}catch{}D(d),L(a)}}export{yi as acceptedPlanningDiagnosisPredecessor,mi as planningPendingSidecarDigest,ri as planningPhysicalPatchDigest,Si as sealPlanningDiagnosis};
|