@ornexus/neocortex 4.60.72 → 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 +24 -24
- 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,12 +1,669 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Epic P101.07 -- invoke.ts hooks for yoloop state persistence.
|
|
3
|
+
*
|
|
4
|
+
* Two hooks:
|
|
5
|
+
* - `readYoloopForRequest(args, projectRoot)` — pre-request; returns
|
|
6
|
+
* `YoloopPersistedState | undefined` to embed in stateSnapshot.yoloop.
|
|
7
|
+
* Returns undefined (no-op) for non-yoloop invocations to avoid I/O.
|
|
8
|
+
* - `persistYoloopFromResponse(metadata, projectRoot)` — post-response;
|
|
9
|
+
* if the server returned `yoloopStateUpdate`, apply operations locally.
|
|
10
|
+
* Authoritative rollover/successor-transition failures are returned to the invoke boundary;
|
|
11
|
+
* auxiliary legacy updates retain bounded fail-soft compatibility.
|
|
12
|
+
*
|
|
13
|
+
* Trigger detection is regex-based over the first token of `args`, aligned
|
|
14
|
+
* with the P96.01 TRIGGER_ALIASES set for yoloop. Cheap enough to run on
|
|
15
|
+
* every invoke.
|
|
16
|
+
*/
|
|
17
|
+
import { statSync } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { YoloopClientStateStore } from './yoloop-client-state-store.js';
|
|
20
|
+
import { isYoloopInvocation } from './target-normalization.js';
|
|
21
|
+
import { applyStateMigration, StateMigrationApplyError } from '../migrations/state-json.js';
|
|
22
|
+
/**
|
|
23
|
+
* Detect whether an args string is a yoloop invocation (including aliases).
|
|
24
|
+
* Matches: `*yoloop`, `yoloop`, `*auto-yolo`, `*epic-runner`, `*story-runner`,
|
|
25
|
+
* `*loop-yolo`, `*auto-epic` (case-insensitive, with optional leading whitespace
|
|
26
|
+
* and optional `*` prefix).
|
|
27
|
+
*/
|
|
28
|
+
export function isYoloopTrigger(args) {
|
|
29
|
+
return isYoloopInvocation(args);
|
|
30
|
+
}
|
|
31
|
+
export const YOLOOP_PERSISTENCE_REASON_CODES = Object.freeze({
|
|
32
|
+
stateReadFailed: 'YOLOOP_STATE_READ_FAILED',
|
|
33
|
+
authoritativeWritebackFailed: 'YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED',
|
|
34
|
+
auxiliaryWritebackFailed: 'YOLOOP_AUXILIARY_WRITEBACK_FAILED',
|
|
35
|
+
});
|
|
36
|
+
export class YoloopStateReadError extends Error {
|
|
37
|
+
reasonCode;
|
|
38
|
+
constructor(reasonCode) {
|
|
39
|
+
super(reasonCode);
|
|
40
|
+
this.reasonCode = reasonCode;
|
|
41
|
+
this.name = 'YoloopStateReadError';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function publicPersistenceReason(error, fallback) {
|
|
45
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
46
|
+
return message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0] ?? fallback;
|
|
47
|
+
}
|
|
48
|
+
const RECOVERABLE_AUTHORITATIVE_WRITE_CODES = new Set([
|
|
49
|
+
'YOLOOP_RUN_REVISION_CONFLICT',
|
|
50
|
+
'YOLOOP_RUN_SNAPSHOT_CONFLICT',
|
|
51
|
+
'YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT',
|
|
52
|
+
'EAGAIN',
|
|
53
|
+
'EBUSY',
|
|
54
|
+
'EMFILE',
|
|
55
|
+
'ENFILE',
|
|
56
|
+
]);
|
|
57
|
+
function shouldRetryAuthoritativeWrite(error) {
|
|
58
|
+
const reason = publicPersistenceReason(error, '');
|
|
59
|
+
if (RECOVERABLE_AUTHORITATIVE_WRITE_CODES.has(reason))
|
|
60
|
+
return true;
|
|
61
|
+
const code = error?.code;
|
|
62
|
+
return typeof code === 'string' && RECOVERABLE_AUTHORITATIVE_WRITE_CODES.has(code);
|
|
63
|
+
}
|
|
64
|
+
// =====================================================================
|
|
65
|
+
// P121.05 -- Zero-config *yoloop auto-resolve
|
|
66
|
+
// =====================================================================
|
|
67
|
+
/**
|
|
68
|
+
* P121.05: Yoloop trigger regex (mirror of `isYoloopTrigger` predicate, but
|
|
69
|
+
* exposes capture group + match index for token-aware rewrites).
|
|
70
|
+
*/
|
|
71
|
+
const YOLOOP_TRIGGER_TOKEN_RE = /^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;
|
|
72
|
+
/**
|
|
73
|
+
* P121.05 -- Zero-config `*yoloop`. When the user types `*yoloop` (or any
|
|
74
|
+
* alias) with no args, auto-resolve to `<projectRoot>/docs/epics/` if that
|
|
75
|
+
* directory exists.
|
|
76
|
+
*
|
|
77
|
+
* Behavior:
|
|
78
|
+
* - Yoloop trigger detection: same regex as P101.07 / P120.04.
|
|
79
|
+
* - Args-empty detection: trigger token + optional whitespace; remainder
|
|
80
|
+
* `=== ''` after `.trim()`.
|
|
81
|
+
* - Directory existence: synchronous `fs.statSync(...).isDirectory()`,
|
|
82
|
+
* wrapped in try/catch.
|
|
83
|
+
* - Rewrite: appends ` @docs/epics/` to the matched trigger token,
|
|
84
|
+
* preserving the original token (canonical or alias) and any leading
|
|
85
|
+
* `*` prefix.
|
|
86
|
+
* - Fail-soft: any error -> `ctx.logger.warn` + return unchanged args.
|
|
87
|
+
*
|
|
88
|
+
* Mutates `ctx.args` in place when auto-resolve fires. Caller (invoke.ts)
|
|
89
|
+
* propagates the new value via the InvokeOptions immutable update pattern.
|
|
90
|
+
*
|
|
91
|
+
* AC1, AC2, AC3, AC4, AC5, AC6, AC7, AC8, AC13.
|
|
92
|
+
*/
|
|
93
|
+
export function maybeAutoResolveYoloopArgs(ctx) {
|
|
94
|
+
// Defensive: defensive types -- unexpected non-strings get a no-op.
|
|
95
|
+
if (typeof ctx.args !== 'string' || ctx.args.length === 0) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// 1. Match yoloop trigger token (with optional `*` prefix).
|
|
99
|
+
const match = ctx.args.match(YOLOOP_TRIGGER_TOKEN_RE);
|
|
100
|
+
if (!match) {
|
|
101
|
+
// Not a yoloop trigger -> nothing to do.
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
// 2. Strip the matched trigger from `args` and check the remainder.
|
|
105
|
+
// `match[0]` is the matched substring including any leading whitespace
|
|
106
|
+
// and the optional `*` prefix and the trigger token. Anything after
|
|
107
|
+
// the trigger token (and any trailing whitespace) is the explicit args.
|
|
108
|
+
const matchedToken = match[0]; // e.g., "*yoloop" or " yoloop"
|
|
109
|
+
const remainder = ctx.args.slice(matchedToken.length).trim();
|
|
110
|
+
if (remainder !== '') {
|
|
111
|
+
// Explicit args present -> never rewrite (AC6, backward compat).
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
// 3. Check whether `<projectRoot>/docs/epics/` exists and is a directory.
|
|
115
|
+
// Wrapped in try/catch so any fs error (permission denied, ENOENT,
|
|
116
|
+
// unexpected errors from `node:fs`) is swallowed -> args unchanged.
|
|
117
|
+
let isDir = false;
|
|
118
|
+
try {
|
|
119
|
+
const target = join(ctx.projectRoot, 'docs', 'epics');
|
|
120
|
+
const stat = statSync(target);
|
|
121
|
+
isDir = stat.isDirectory();
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
// Fail-soft: log warn + bail. Args remain unchanged. Server emits the
|
|
125
|
+
// existing `INVALID_YOLOOP_TARGET` error if/when the request reaches it.
|
|
126
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
127
|
+
ctx.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${msg}. Proceeding with raw args.`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (!isDir) {
|
|
131
|
+
// Directory does not exist (or `docs/epics` is a file) -> args unchanged.
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// 4. Rewrite: preserve the matched trigger token and append ` @docs/epics/`.
|
|
135
|
+
// Canonical examples:
|
|
136
|
+
// `*yoloop` -> `*yoloop @docs/epics/`
|
|
137
|
+
// `*auto-yolo` -> `*auto-yolo @docs/epics/`
|
|
138
|
+
// ` yoloop ` -> ` yoloop @docs/epics/`
|
|
139
|
+
ctx.args = `${matchedToken} @docs/epics/`;
|
|
140
|
+
// 5. Surface the auto-resolution at info level so operators see the
|
|
141
|
+
// transformation in stderr without being noisy on every invoke.
|
|
142
|
+
ctx.logger?.info?.(`[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/`);
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Pre-request hook: read client-side yoloop state for the given project.
|
|
146
|
+
* Returns undefined for non-yoloop invocations (no I/O). A yoloop read or
|
|
147
|
+
* recovery failure is authoritative and fails closed so the server can never
|
|
148
|
+
* reinterpret corrupt/unavailable persisted state as a fresh session.
|
|
149
|
+
*/
|
|
150
|
+
export async function readYoloopForRequest(args, projectRoot, nowIso) {
|
|
151
|
+
if (!isYoloopTrigger(args))
|
|
152
|
+
return undefined;
|
|
153
|
+
try {
|
|
154
|
+
const store = new YoloopClientStateStore(projectRoot);
|
|
155
|
+
return await store.readAll(nowIso);
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
const reasonCode = publicPersistenceReason(err, YOLOOP_PERSISTENCE_REASON_CODES.stateReadFailed);
|
|
159
|
+
process.stderr.write(`[yoloop] ${reasonCode}. Local yoloop authority was not read; no request was sent.\n`);
|
|
160
|
+
throw new YoloopStateReadError(reasonCode);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Post-response hook: apply server-provided operations to local state.
|
|
165
|
+
* Safe to call for any response — no-op if no yoloopStateUpdate present.
|
|
166
|
+
* A `rollover_session` or `commit_successor_transition` update is
|
|
167
|
+
* authoritative: failure is returned to the caller so instructions cannot be
|
|
168
|
+
* released before durable state exists.
|
|
169
|
+
* Non-rollover legacy operations retain fail-soft compatibility.
|
|
170
|
+
*/
|
|
171
|
+
export async function persistYoloopFromResponse(metadata, projectRoot, nowIso) {
|
|
172
|
+
if (!metadata)
|
|
173
|
+
return { ok: true, authoritative: false, reasonCodes: [] };
|
|
174
|
+
const update = metadata.yoloopStateUpdate;
|
|
175
|
+
if (!update || !Array.isArray(update.operations) || update.operations.length === 0) {
|
|
176
|
+
return { ok: true, authoritative: false, reasonCodes: [] };
|
|
177
|
+
}
|
|
178
|
+
const authoritative = update.operations.some((operation) => operation.type === 'rollover_session'
|
|
179
|
+
|| operation.type === 'commit_successor_transition');
|
|
180
|
+
let lastError;
|
|
181
|
+
const attempts = authoritative ? 3 : 1;
|
|
182
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
183
|
+
try {
|
|
184
|
+
const store = new YoloopClientStateStore(projectRoot);
|
|
185
|
+
await store.applyUpdate(update, nowIso);
|
|
186
|
+
return { ok: true, authoritative, reasonCodes: [] };
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
lastError = error;
|
|
190
|
+
if (!authoritative || attempt + 1 >= attempts || !shouldRetryAuthoritativeWrite(error))
|
|
191
|
+
break;
|
|
192
|
+
// A fresh store rereads and recovers any prepared manifest. These
|
|
193
|
+
// bounded internal attempts do not create a new server run, dispatch,
|
|
194
|
+
// entitlement charge, strike or cooldown.
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
{
|
|
198
|
+
const err = lastError;
|
|
199
|
+
const reasonCode = publicPersistenceReason(err, authoritative
|
|
200
|
+
? YOLOOP_PERSISTENCE_REASON_CODES.authoritativeWritebackFailed
|
|
201
|
+
: YOLOOP_PERSISTENCE_REASON_CODES.auxiliaryWritebackFailed);
|
|
202
|
+
if (authoritative) {
|
|
203
|
+
process.stderr.write(`[yoloop] ${reasonCode}. Authoritative yoloop transition was not persisted; no continuation instructions were released.\n`);
|
|
204
|
+
return { ok: false, authoritative: true, reasonCodes: [reasonCode] };
|
|
205
|
+
}
|
|
206
|
+
process.stderr.write(`[yoloop] ${reasonCode}. Auxiliary state update was not persisted; retry the same command.\n`);
|
|
207
|
+
return { ok: true, authoritative: false, reasonCodes: [reasonCode] };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function isPlainRecord(value) {
|
|
211
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
212
|
+
}
|
|
213
|
+
function boundedPublicStrings(value, max) {
|
|
214
|
+
return Array.isArray(value)
|
|
215
|
+
&& value.length <= max
|
|
216
|
+
&& value.every((entry) => typeof entry === 'string' && entry.length > 0 && entry.length <= 160 && /^[A-Za-z0-9_.:+-]+$/.test(entry));
|
|
217
|
+
}
|
|
218
|
+
function projectedOrPartialState(value) {
|
|
219
|
+
if (!isPlainRecord(value.scope))
|
|
220
|
+
return false;
|
|
221
|
+
return value.scope.kind === 'projected'
|
|
222
|
+
|| (typeof value.scope.omittedStoryCount === 'number' && value.scope.omittedStoryCount > 0)
|
|
223
|
+
|| (typeof value.scope.omittedEpicCount === 'number' && value.scope.omittedEpicCount > 0);
|
|
224
|
+
}
|
|
225
|
+
function stripRequestOnlyStateFields(value) {
|
|
226
|
+
const canonical = { ...value };
|
|
227
|
+
delete canonical.scope;
|
|
228
|
+
delete canonical.stateSummary;
|
|
229
|
+
delete canonical.graphRetrieval;
|
|
230
|
+
delete canonical.runnerBootstrap;
|
|
231
|
+
delete canonical.projectEvidence;
|
|
232
|
+
delete canonical.continuity;
|
|
233
|
+
delete canonical.implementCheckpoint;
|
|
234
|
+
return canonical;
|
|
235
|
+
}
|
|
236
|
+
function doneLikeStatus(value) {
|
|
237
|
+
return typeof value === 'string' && ['done', 'completed', 'merged'].includes(value.trim().toLowerCase());
|
|
238
|
+
}
|
|
239
|
+
function safeInlineYoloBranch(value) {
|
|
240
|
+
return /^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(value)
|
|
241
|
+
&& !value.includes('..')
|
|
242
|
+
&& !value.includes('//')
|
|
243
|
+
&& !value.includes('@{')
|
|
244
|
+
&& !value.endsWith('/')
|
|
245
|
+
&& !value.endsWith('.')
|
|
246
|
+
&& !value.endsWith('.lock');
|
|
247
|
+
}
|
|
248
|
+
async function persistInlineYoloMaterialization(metadata, projectRoot) {
|
|
249
|
+
const syntheticStory = metadata.syntheticStory;
|
|
250
|
+
if (!isPlainRecord(syntheticStory)) {
|
|
251
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-mutation-missing' };
|
|
252
|
+
}
|
|
253
|
+
const schemaVersion = syntheticStory.schemaVersion;
|
|
254
|
+
const epicId = syntheticStory.epicId;
|
|
255
|
+
const storyId = syntheticStory.storyId;
|
|
256
|
+
const storyPath = syntheticStory.storyPath;
|
|
257
|
+
const deterministicKey = syntheticStory.deterministicKey;
|
|
258
|
+
const storyContent = syntheticStory.storyContent;
|
|
259
|
+
const storyContentSha256 = syntheticStory.storyContentSha256;
|
|
260
|
+
const lifecycle = syntheticStory.lifecycle;
|
|
261
|
+
if (schemaVersion !== 2
|
|
262
|
+
|| typeof epicId !== 'string' || !/^P9\d{18}$/.test(epicId)
|
|
263
|
+
|| typeof storyId !== 'string' || storyId !== `${epicId}.01.000001`
|
|
264
|
+
|| typeof storyPath !== 'string' || storyPath !== `docs/stories/${storyId}.story.md`
|
|
265
|
+
|| typeof deterministicKey !== 'string' || !/^[a-f0-9]{16}$/.test(deterministicKey)
|
|
266
|
+
|| typeof storyContentSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(storyContentSha256)
|
|
267
|
+
|| typeof storyContent !== 'string' || storyContent.length === 0 || storyContent.length > 131_072
|
|
268
|
+
|| !isPlainRecord(lifecycle)
|
|
269
|
+
|| lifecycle.branchMode !== 'epic'
|
|
270
|
+
|| lifecycle.executionBranch !== `epic/${epicId}`
|
|
271
|
+
|| typeof lifecycle.originBranch !== 'string'
|
|
272
|
+
|| !safeInlineYoloBranch(lifecycle.originBranch)
|
|
273
|
+
|| typeof lifecycle.graphRevision !== 'string' || !/^[a-f0-9]{64}$/.test(lifecycle.graphRevision)
|
|
274
|
+
|| lifecycle.isolatedSyntheticEpic !== true
|
|
275
|
+
|| syntheticStory.publicSafe !== true || syntheticStory.sanitized !== true) {
|
|
276
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-mutation-invalid' };
|
|
277
|
+
}
|
|
278
|
+
const fs = await import('node:fs/promises');
|
|
279
|
+
const path = await import('node:path');
|
|
280
|
+
const crypto = await import('node:crypto');
|
|
281
|
+
if (crypto.createHash('sha256').update(storyContent).digest('hex') !== storyContentSha256) {
|
|
282
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-content-integrity-invalid' };
|
|
283
|
+
}
|
|
284
|
+
const stateDir = path.join(projectRoot, '.neocortex');
|
|
285
|
+
const statePath = path.join(stateDir, 'state.json');
|
|
286
|
+
const absoluteStoryPath = path.join(projectRoot, ...storyPath.split('/'));
|
|
287
|
+
let rawState;
|
|
288
|
+
try {
|
|
289
|
+
rawState = await fs.readFile(statePath, 'utf8');
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-missing' };
|
|
293
|
+
}
|
|
294
|
+
const sourceStateSha256 = crypto.createHash('sha256').update(rawState).digest('hex');
|
|
295
|
+
let parsedState;
|
|
296
|
+
try {
|
|
297
|
+
parsedState = JSON.parse(rawState);
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-corrupt' };
|
|
301
|
+
}
|
|
302
|
+
if (!isPlainRecord(parsedState) || !isPlainRecord(parsedState.stories) || !isPlainRecord(parsedState.epics)
|
|
303
|
+
|| projectedOrPartialState(parsedState)) {
|
|
304
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-not-full' };
|
|
305
|
+
}
|
|
306
|
+
if (!isPlainRecord(parsedState.config) || parsedState.config.default_branch !== lifecycle.originBranch) {
|
|
307
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-origin-branch-conflict' };
|
|
308
|
+
}
|
|
309
|
+
const previousStory = parsedState.stories[storyId];
|
|
310
|
+
if (previousStory !== undefined && (!isPlainRecord(previousStory)
|
|
311
|
+
|| previousStory.epic_id !== epicId
|
|
312
|
+
|| previousStory.story_file !== storyPath
|
|
313
|
+
|| !isPlainRecord(previousStory.inlineYolo)
|
|
314
|
+
|| previousStory.inlineYolo.deterministicKey !== deterministicKey)) {
|
|
315
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-conflict' };
|
|
316
|
+
}
|
|
317
|
+
const previousEpic = parsedState.epics[epicId];
|
|
318
|
+
if (previousEpic !== undefined && (!isPlainRecord(previousEpic)
|
|
319
|
+
|| previousEpic.id !== epicId
|
|
320
|
+
|| previousEpic.source !== 'inline-yolo-materialization'
|
|
321
|
+
|| previousEpic.branch_mode !== 'epic'
|
|
322
|
+
|| previousEpic.execution_branch !== lifecycle.executionBranch
|
|
323
|
+
|| previousEpic.origin_branch !== lifecycle.originBranch
|
|
324
|
+
|| previousEpic.graph_revision !== lifecycle.graphRevision
|
|
325
|
+
|| !isPlainRecord(previousEpic.inlineYoloLifecycle)
|
|
326
|
+
|| previousEpic.inlineYoloLifecycle.deterministicKey !== deterministicKey
|
|
327
|
+
|| previousEpic.inlineYoloLifecycle.isolatedSyntheticEpic !== true
|
|
328
|
+
|| !Array.isArray(previousEpic.stories))) {
|
|
329
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-epic-conflict' };
|
|
330
|
+
}
|
|
331
|
+
const epic = isPlainRecord(previousEpic) ? previousEpic : {};
|
|
332
|
+
const previousStoryIds = Array.isArray(epic.stories) ? epic.stories : [];
|
|
333
|
+
if (previousStoryIds.some((entry) => typeof entry !== 'string') || new Set(previousStoryIds).size !== previousStoryIds.length) {
|
|
334
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-epic-story-list-invalid' };
|
|
335
|
+
}
|
|
336
|
+
for (const existingId of previousStoryIds) {
|
|
337
|
+
const existingStory = parsedState.stories[existingId];
|
|
338
|
+
if (!isPlainRecord(existingStory) || existingStory.id !== existingId || existingStory.epic_id !== epicId) {
|
|
339
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-epic-ownership-conflict' };
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
try {
|
|
343
|
+
const existingContent = await fs.readFile(absoluteStoryPath, 'utf8');
|
|
344
|
+
const materializationIdentityPreserved = existingContent.includes(`id: ${storyId}`)
|
|
345
|
+
&& existingContent.includes(`synthetic_key: ${deterministicKey}`);
|
|
346
|
+
if (existingContent !== storyContent && !materializationIdentityPreserved) {
|
|
347
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-file-conflict' };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
if (error.code !== 'ENOENT') {
|
|
352
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-story-file-unreadable' };
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const storyIds = previousStoryIds.includes(storyId)
|
|
356
|
+
? [...previousStoryIds]
|
|
357
|
+
: [...previousStoryIds, storyId];
|
|
358
|
+
const stories = {
|
|
359
|
+
...parsedState.stories,
|
|
360
|
+
[storyId]: {
|
|
361
|
+
...(isPlainRecord(previousStory) ? previousStory : {}),
|
|
362
|
+
id: storyId,
|
|
363
|
+
epic_id: epicId,
|
|
364
|
+
title: 'Synthetic inline USER STORY for yolo',
|
|
365
|
+
status: isPlainRecord(previousStory) && typeof previousStory.status === 'string' ? previousStory.status : 'backlog',
|
|
366
|
+
steps_completed: isPlainRecord(previousStory) && Array.isArray(previousStory.steps_completed) ? previousStory.steps_completed : [],
|
|
367
|
+
last_step: isPlainRecord(previousStory) ? previousStory.last_step ?? null : null,
|
|
368
|
+
branch_name: isPlainRecord(previousStory) ? previousStory.branch_name ?? null : null,
|
|
369
|
+
story_file: storyPath,
|
|
370
|
+
source: 'inline-yolo-materialization',
|
|
371
|
+
inlineYolo: {
|
|
372
|
+
...(isPlainRecord(previousStory) && isPlainRecord(previousStory.inlineYolo) ? previousStory.inlineYolo : {}),
|
|
373
|
+
schemaVersion: 2,
|
|
374
|
+
deterministicKey,
|
|
375
|
+
publicSafe: true,
|
|
376
|
+
sanitized: true,
|
|
377
|
+
materializedBeforeExecution: true,
|
|
378
|
+
ephemeralExecutionForbidden: true,
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
const completedStories = storyIds.filter((id) => isPlainRecord(stories[id]) && doneLikeStatus(stories[id].status)).length;
|
|
383
|
+
const previousInlineYolo = isPlainRecord(parsedState.inlineYolo) ? parsedState.inlineYolo : {};
|
|
384
|
+
const previousMaterializations = isPlainRecord(previousInlineYolo.materializations)
|
|
385
|
+
? previousInlineYolo.materializations : {};
|
|
386
|
+
const nextState = stripRequestOnlyStateFields({
|
|
387
|
+
...parsedState,
|
|
388
|
+
stories,
|
|
389
|
+
epics: {
|
|
390
|
+
...parsedState.epics,
|
|
391
|
+
[epicId]: {
|
|
392
|
+
...epic,
|
|
393
|
+
id: epicId,
|
|
394
|
+
title: typeof epic.title === 'string' ? epic.title : 'Isolated synthetic inline yolo lifecycle',
|
|
395
|
+
status: completedStories === storyIds.length && storyIds.length > 0 ? 'done' : 'in-progress',
|
|
396
|
+
source: 'inline-yolo-materialization',
|
|
397
|
+
branch_mode: 'epic',
|
|
398
|
+
execution_branch: lifecycle.executionBranch,
|
|
399
|
+
origin_branch: lifecycle.originBranch,
|
|
400
|
+
graph_revision: lifecycle.graphRevision,
|
|
401
|
+
stories: storyIds,
|
|
402
|
+
total_stories: storyIds.length,
|
|
403
|
+
completed_stories: completedStories,
|
|
404
|
+
...(completedStories === storyIds.length && storyIds.length > 0 ? {} : { completed_at: null }),
|
|
405
|
+
inlineYoloLifecycle: {
|
|
406
|
+
schemaVersion: 2,
|
|
407
|
+
deterministicKey,
|
|
408
|
+
isolatedSyntheticEpic: true,
|
|
409
|
+
},
|
|
410
|
+
},
|
|
411
|
+
},
|
|
412
|
+
inlineYolo: {
|
|
413
|
+
...previousInlineYolo,
|
|
414
|
+
schemaVersion: 2,
|
|
415
|
+
materializations: {
|
|
416
|
+
...previousMaterializations,
|
|
417
|
+
[storyId]: {
|
|
418
|
+
schemaVersion: 2,
|
|
419
|
+
epicId,
|
|
420
|
+
storyId,
|
|
421
|
+
storyPath,
|
|
422
|
+
deterministicKey,
|
|
423
|
+
storyContentSha256,
|
|
424
|
+
sourceStateSha256,
|
|
425
|
+
lifecycle,
|
|
426
|
+
publicSafe: true,
|
|
427
|
+
sanitized: true,
|
|
428
|
+
materializedBeforeExecution: true,
|
|
429
|
+
ephemeralExecutionForbidden: true,
|
|
430
|
+
pipelineTrigger: `*yolo @${storyPath}`,
|
|
431
|
+
reasonCodes: Array.isArray(syntheticStory.reasonCodes) ? syntheticStory.reasonCodes : [],
|
|
432
|
+
},
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
last_updated: new Date().toISOString(),
|
|
436
|
+
});
|
|
437
|
+
const suffix = `${Date.now()}-${crypto.randomBytes(6).toString('hex')}`;
|
|
438
|
+
const stateTmpPath = path.join(stateDir, `state.json.tmp.${suffix}`);
|
|
439
|
+
const storyTmpPath = `${absoluteStoryPath}.tmp.${suffix}`;
|
|
440
|
+
const backupPath = path.join(stateDir, `state.json.backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
441
|
+
const lockPath = path.join(stateDir, 'state.json.inline-yolo.lock');
|
|
442
|
+
let storyCreated = false;
|
|
443
|
+
let lockHandle;
|
|
444
|
+
const syncDirectory = async (directory) => {
|
|
445
|
+
let handle;
|
|
446
|
+
try {
|
|
447
|
+
handle = await fs.open(directory, 'r');
|
|
448
|
+
await handle.sync();
|
|
449
|
+
}
|
|
450
|
+
catch (error) {
|
|
451
|
+
const code = error.code;
|
|
452
|
+
if (!['EINVAL', 'ENOTSUP', 'EPERM', 'EISDIR'].includes(code ?? ''))
|
|
453
|
+
throw error;
|
|
454
|
+
}
|
|
455
|
+
finally {
|
|
456
|
+
await handle?.close().catch(() => undefined);
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
const durableExclusiveWrite = async (temporaryPath, content) => {
|
|
460
|
+
const handle = await fs.open(temporaryPath, 'wx', 0o600);
|
|
461
|
+
try {
|
|
462
|
+
await handle.writeFile(content, 'utf8');
|
|
463
|
+
await handle.sync();
|
|
464
|
+
}
|
|
465
|
+
finally {
|
|
466
|
+
await handle.close();
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
try {
|
|
470
|
+
await fs.mkdir(stateDir, { recursive: true });
|
|
471
|
+
await fs.mkdir(path.dirname(absoluteStoryPath), { recursive: true });
|
|
472
|
+
try {
|
|
473
|
+
lockHandle = await fs.open(lockPath, 'wx', 0o600);
|
|
474
|
+
await lockHandle.writeFile(`${process.pid}\n${sourceStateSha256}\n`, 'utf8');
|
|
475
|
+
await lockHandle.sync();
|
|
476
|
+
}
|
|
477
|
+
catch (error) {
|
|
478
|
+
if (error.code === 'EEXIST') {
|
|
479
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-writeback-locked' };
|
|
480
|
+
}
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
// Compare-and-swap under the cooperative lock. A stale response may never
|
|
484
|
+
// replace state that changed after it was read and validated above.
|
|
485
|
+
const currentRawState = await fs.readFile(statePath, 'utf8');
|
|
486
|
+
const currentStateSha256 = crypto.createHash('sha256').update(currentRawState).digest('hex');
|
|
487
|
+
if (currentStateSha256 !== sourceStateSha256) {
|
|
488
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-state-cas-conflict' };
|
|
489
|
+
}
|
|
490
|
+
try {
|
|
491
|
+
await fs.access(absoluteStoryPath);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
await durableExclusiveWrite(storyTmpPath, storyContent);
|
|
495
|
+
await fs.rename(storyTmpPath, absoluteStoryPath);
|
|
496
|
+
await syncDirectory(path.dirname(absoluteStoryPath));
|
|
497
|
+
storyCreated = true;
|
|
498
|
+
}
|
|
499
|
+
await fs.copyFile(statePath, backupPath);
|
|
500
|
+
const backupHandle = await fs.open(backupPath, 'r');
|
|
501
|
+
try {
|
|
502
|
+
await backupHandle.sync();
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
await backupHandle.close();
|
|
506
|
+
}
|
|
507
|
+
await durableExclusiveWrite(stateTmpPath, JSON.stringify(nextState, null, 2));
|
|
508
|
+
await fs.rename(stateTmpPath, statePath);
|
|
509
|
+
await syncDirectory(stateDir);
|
|
510
|
+
process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${storyId}; backup=${path.basename(backupPath)}.\n`);
|
|
511
|
+
return { applied: true, blocking: false, reasonCode: 'inline-yolo-materialized' };
|
|
512
|
+
}
|
|
513
|
+
catch (error) {
|
|
514
|
+
await Promise.allSettled([fs.unlink(stateTmpPath), fs.unlink(storyTmpPath)]);
|
|
515
|
+
if (storyCreated) {
|
|
516
|
+
const currentStory = await fs.readFile(absoluteStoryPath, 'utf8').catch(() => undefined);
|
|
517
|
+
if (currentStory === storyContent)
|
|
518
|
+
await fs.unlink(absoluteStoryPath).catch(() => undefined);
|
|
519
|
+
}
|
|
520
|
+
const message = error.message ?? String(error);
|
|
521
|
+
process.stderr.write(`[Neocortex] inline yolo materialization failed: ${message}.\n`);
|
|
522
|
+
return { applied: false, blocking: true, reasonCode: 'inline-yolo-persistence-failed' };
|
|
523
|
+
}
|
|
524
|
+
finally {
|
|
525
|
+
await lockHandle?.close().catch(() => undefined);
|
|
526
|
+
if (lockHandle)
|
|
527
|
+
await fs.unlink(lockPath).catch(() => undefined);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
export async function persistMigratedStateFromResponse(metadata, projectRoot) {
|
|
531
|
+
if (!metadata || metadata.stateMutated !== true) {
|
|
532
|
+
return { applied: false, blocking: false, reasonCode: 'state-writeback-not-requested' };
|
|
533
|
+
}
|
|
534
|
+
if (metadata.stateMutationStrategy === 'merge-inline-yolo-v2'
|
|
535
|
+
|| metadata.stateMutationReason === 'inline-yolo-materialized-synthetic-story') {
|
|
536
|
+
return persistInlineYoloMaterialization(metadata, projectRoot);
|
|
537
|
+
}
|
|
538
|
+
if (metadata.stateMutationStrategy === 'state-migration-v1' || metadata.stateMigrationPlan !== undefined) {
|
|
539
|
+
const rawPlan = metadata.stateMigrationPlan;
|
|
540
|
+
const directiveKeys = new Set([
|
|
541
|
+
'schemaVersion', 'operationId', 'sourceSchemaVersion', 'targetSchemaVersion',
|
|
542
|
+
'sourceCanonicalHash', 'targetCanonicalHash', 'steps', 'migratedEpicIds',
|
|
543
|
+
'migratedStoryIds', 'preservedUnknownFieldCount', 'reasonCodes', 'sourceByteDigest',
|
|
544
|
+
]);
|
|
545
|
+
if (!isPlainRecord(rawPlan)
|
|
546
|
+
|| Object.keys(rawPlan).some((key) => !directiveKeys.has(key))
|
|
547
|
+
|| rawPlan.schemaVersion !== 'StateMigrationPlan/1.0'
|
|
548
|
+
|| typeof rawPlan.operationId !== 'string' || !/^smig_[a-f0-9]{32}$/.test(rawPlan.operationId)
|
|
549
|
+
|| typeof rawPlan.sourceCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(rawPlan.sourceCanonicalHash)
|
|
550
|
+
|| typeof rawPlan.targetCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(rawPlan.targetCanonicalHash)
|
|
551
|
+
|| typeof rawPlan.sourceByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(rawPlan.sourceByteDigest)
|
|
552
|
+
|| ![0, 1, 'absent'].includes(rawPlan.sourceSchemaVersion)
|
|
553
|
+
|| rawPlan.targetSchemaVersion !== 1
|
|
554
|
+
|| !Array.isArray(rawPlan.steps) || rawPlan.steps.length > 8192
|
|
555
|
+
|| rawPlan.steps.some((step) => !isPlainRecord(step)
|
|
556
|
+
|| Object.keys(step).some((key) => !['kind', 'source', 'target'].includes(key))
|
|
557
|
+
|| !['initialize-collection', 'merge-epic', 'merge-story', 'preserve-legacy', 'remove-legacy', 'set-schema-version'].includes(String(step.kind))
|
|
558
|
+
|| typeof step.target !== 'string' || step.target.length > 512 || !/^[A-Za-z0-9_.:[\]-]+$/.test(step.target)
|
|
559
|
+
|| (step.source !== undefined && (typeof step.source !== 'string' || step.source.length > 512 || !/^[A-Za-z0-9_.:[\]-]+$/.test(step.source))))
|
|
560
|
+
|| !boundedPublicStrings(rawPlan.migratedEpicIds, 4096)
|
|
561
|
+
|| !boundedPublicStrings(rawPlan.migratedStoryIds, 4096)
|
|
562
|
+
|| !boundedPublicStrings(rawPlan.reasonCodes, 32)
|
|
563
|
+
|| !Number.isSafeInteger(rawPlan.preservedUnknownFieldCount) || rawPlan.preservedUnknownFieldCount < 0) {
|
|
564
|
+
return { applied: false, blocking: true, reasonCode: 'state-migration-plan-missing-or-invalid' };
|
|
565
|
+
}
|
|
566
|
+
try {
|
|
567
|
+
const migrationReceipt = applyStateMigration(projectRoot, rawPlan);
|
|
568
|
+
const backupPath = `.neocortex/state.json.migration-backup-${migrationReceipt.operationId}`;
|
|
569
|
+
process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${migrationReceipt.outcome}; operation=${migrationReceipt.operationId}; backup=${migrationReceipt.backupHash ? backupPath : 'none'}.\n`);
|
|
570
|
+
return {
|
|
571
|
+
applied: migrationReceipt.outcome === 'applied',
|
|
572
|
+
blocking: false,
|
|
573
|
+
reasonCode: migrationReceipt.outcome === 'applied' ? 'state-migration-applied' : 'state-migration-replay-verified',
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
catch (error) {
|
|
577
|
+
const reasonCode = error instanceof StateMigrationApplyError ? error.reasonCode : 'state-migration-apply-failed';
|
|
578
|
+
process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${reasonCode}.\n`);
|
|
579
|
+
return { applied: false, blocking: true, reasonCode };
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
const migratedState = metadata.migratedState;
|
|
583
|
+
if (!migratedState || typeof migratedState !== 'object' || Array.isArray(migratedState)) {
|
|
584
|
+
return { applied: false, blocking: true, reasonCode: 'state-writeback-payload-missing' };
|
|
585
|
+
}
|
|
586
|
+
if (projectedOrPartialState(migratedState)) {
|
|
587
|
+
process.stderr.write('[Neocortex] Refused projected/partial state replacement; canonical state was not modified.\n');
|
|
588
|
+
return { applied: false, blocking: true, reasonCode: 'state-writeback-partial-rejected' };
|
|
589
|
+
}
|
|
590
|
+
process.stderr.write('[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.\n');
|
|
591
|
+
return { applied: false, blocking: true, reasonCode: 'state-migration-plan-missing-or-invalid' };
|
|
592
|
+
}
|
|
593
|
+
// =====================================================================
|
|
594
|
+
// P120.04 -- Discovery hook integration
|
|
595
|
+
// =====================================================================
|
|
596
|
+
/**
|
|
597
|
+
* P120.04: lazy-loaded discovery hook wrapper.
|
|
598
|
+
*
|
|
599
|
+
* Short-circuits BEFORE the dynamic import when `featureFlag` is off, so
|
|
600
|
+
* clients with `YOLOOP_AUTO_DISCOVERY` unset (default) never load the
|
|
601
|
+
* discovery-hook module. ESM tree-shakers can prune the entire module +
|
|
602
|
+
* its `shared-discover-epics.ts` mirror in production builds.
|
|
603
|
+
*
|
|
604
|
+
* Defensive try/catch around the dynamic import handles the
|
|
605
|
+
* (vanishingly unlikely) case where the hook module is missing or the
|
|
606
|
+
* dynamic import itself throws -- never blocks the invoke flow.
|
|
607
|
+
*
|
|
608
|
+
* Caller (invoke.ts) is expected to ALSO wrap this in a try/catch as
|
|
609
|
+
* belt-and-suspenders.
|
|
610
|
+
*/
|
|
611
|
+
export async function maybeRunDiscoveryHook(ctx) {
|
|
612
|
+
// Flag-off short-circuit -- preserves tree-shaking + zero overhead.
|
|
613
|
+
if (!ctx.featureFlag) {
|
|
614
|
+
return {
|
|
615
|
+
applied: false,
|
|
616
|
+
added: Object.freeze([]),
|
|
617
|
+
skipped: Object.freeze([]),
|
|
618
|
+
storiesAdded: 0,
|
|
619
|
+
reason: 'flag off',
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
try {
|
|
623
|
+
const mod = await import('./discovery-hook.js');
|
|
624
|
+
return await mod.runDiscoveryHook(ctx);
|
|
625
|
+
}
|
|
626
|
+
catch (err) {
|
|
627
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
628
|
+
ctx.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${msg}. Proceeding without enrichment.`);
|
|
629
|
+
return {
|
|
630
|
+
applied: false,
|
|
631
|
+
added: Object.freeze([]),
|
|
632
|
+
skipped: Object.freeze([]),
|
|
633
|
+
storiesAdded: 0,
|
|
634
|
+
reason: `lazy load error: ${msg}`,
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// =====================================================================
|
|
639
|
+
// P158.06 -- Pre-command graph retrieval hook integration
|
|
640
|
+
// =====================================================================
|
|
641
|
+
/**
|
|
642
|
+
* P158.06 / P198.02: lazy-loaded graph retrieval wrapper.
|
|
643
|
+
*
|
|
644
|
+
* Short-circuits before dynamic import when the feature flag is off. When on,
|
|
645
|
+
* command eligibility, profiles and budgets are resolved by the public command
|
|
646
|
+
* context policy shadow. Runtime errors are public-warning/fail-soft and never
|
|
647
|
+
* block invoke.
|
|
648
|
+
*/
|
|
649
|
+
export async function maybeRunGraphRetrievalHook(ctx) {
|
|
650
|
+
if (!ctx.featureFlag) {
|
|
651
|
+
return {
|
|
652
|
+
applied: false,
|
|
653
|
+
reason: 'flag_off',
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
const mod = await import('../graph-retrieval/pre-command-hook.js');
|
|
658
|
+
return await mod.runGraphRetrievalHook(ctx);
|
|
659
|
+
}
|
|
660
|
+
catch (err) {
|
|
661
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
662
|
+
ctx.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${msg}. Proceeding without enrichment.`);
|
|
663
|
+
return {
|
|
664
|
+
applied: false,
|
|
665
|
+
reason: 'hook_error',
|
|
666
|
+
warning: msg,
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
}
|