@ornexus/neocortex 4.60.74 → 4.60.75

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.
Files changed (55) hide show
  1. package/dist/release-source.json +1 -1
  2. package/install.ps1 +1 -1
  3. package/install.sh +1 -1
  4. package/package.json +2 -2
  5. package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
  6. package/packages/client/dist/cache/encrypted-cache.js +1 -1
  7. package/packages/client/dist/commands/invoke.d.ts +38 -1
  8. package/packages/client/dist/commands/invoke.js +79 -79
  9. package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
  10. package/packages/client/dist/config/host-auth-broker.js +1 -0
  11. package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
  12. package/packages/client/dist/config/host-auth-reference.js +1 -0
  13. package/packages/client/dist/config/secure-config.js +1 -1
  14. package/packages/client/dist/continuity/native-agent-types.d.ts +11 -0
  15. package/packages/client/dist/continuity/native-agent-types.js +1 -1
  16. package/packages/client/dist/errors/error-messages.d.ts +3 -0
  17. package/packages/client/dist/errors/error-messages.js +2 -2
  18. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
  19. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  20. package/packages/client/dist/index.d.ts +2 -0
  21. package/packages/client/dist/index.js +1 -1
  22. package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
  23. package/packages/client/dist/license/host-auth-recovery.js +1 -0
  24. package/packages/client/dist/license/license-client.d.ts +10 -1
  25. package/packages/client/dist/license/license-client.js +1 -1
  26. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
  27. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
  28. package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
  29. package/packages/client/dist/runner/headless/background-root.js +1 -0
  30. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +9 -0
  31. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -2
  32. package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
  33. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
  34. package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
  35. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  36. package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
  37. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  38. package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
  39. package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
  40. package/packages/shared/dist/invocation/index.d.ts +7 -0
  41. package/packages/shared/dist/invocation/index.js +22 -0
  42. package/targets-stubs/antigravity/gemini.md +1 -1
  43. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  44. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  45. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  46. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  47. package/targets-stubs/claude-code/neocortex.md +2 -2
  48. package/targets-stubs/codex/AGENTS.md +24 -21
  49. package/targets-stubs/codex/README.md +6 -1
  50. package/targets-stubs/codex/neocortex.toml +7 -2
  51. package/targets-stubs/cursor/agent.md +2 -2
  52. package/targets-stubs/gemini-cli/agent.md +2 -2
  53. package/targets-stubs/opencode/neocortex-root.md +16 -1
  54. package/targets-stubs/opencode/neocortex.md +6 -0
  55. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -0,0 +1,158 @@
1
+ import { EncryptedCache } from '../cache/encrypted-cache.js';
2
+ export type AuthCauseV1 = 'valid' | 'near-expiry' | 'expired' | 'not-configured' | 'store-unavailable' | 'store-corrupt' | 'keychain-unavailable' | 'transport-error' | 'timeout' | 'rate-limited' | 'service-unavailable' | 'revoked' | 'scope-denied' | 'client-denied' | 'protocol-invalid' | 'persistence-failed' | 'rotation-uncertain' | 'capability-unavailable' | 'revision-conflict';
3
+ export type AuthRecoveryResultV1 = {
4
+ readonly status: 'authenticated';
5
+ readonly generation: number;
6
+ readonly accessCredential: string;
7
+ readonly expiresAt: string;
8
+ } | {
9
+ readonly status: 'refresh-required';
10
+ readonly cause: AuthCauseV1;
11
+ readonly action: 'prepare' | 'retry-later' | 'reactivate' | 'request-scope' | 'recover-explicitly' | 'stop';
12
+ } | {
13
+ readonly status: 'uncertain';
14
+ readonly cause: 'rotation-uncertain' | 'persistence-failed';
15
+ readonly recoveryId: string;
16
+ readonly action: 'reconcile' | 'recover-explicitly';
17
+ } | {
18
+ readonly status: 'not-configured';
19
+ readonly action: 'activate';
20
+ };
21
+ export type AuthRecoveryPhase = 'prepared' | 'request-started' | 'response-received' | 'generation-committed' | 'uncertain' | 'completed' | 'aborted-before-request';
22
+ export interface AuthRecoveryJournalV1 {
23
+ readonly recoveryId: string;
24
+ readonly operationId: string;
25
+ readonly idempotencyKey: string;
26
+ readonly requestDigest: string;
27
+ readonly owner: string;
28
+ readonly createdAt: string;
29
+ readonly expiresAt: string;
30
+ readonly attemptCount: 0 | 1;
31
+ readonly replayCount: 0 | 1;
32
+ readonly phase: AuthRecoveryPhase;
33
+ readonly responseDigest?: string;
34
+ }
35
+ export interface AuthGenerationDocumentV1 {
36
+ readonly schemaVersion: 'AuthGeneration/1.0';
37
+ readonly revision: number;
38
+ readonly identityHash: string;
39
+ readonly accepted: null | {
40
+ readonly generation: number;
41
+ readonly accessToken: string;
42
+ readonly accessExpiresAt: string;
43
+ readonly refreshToken: string | null;
44
+ readonly refreshExpiresAt: string | null;
45
+ readonly acceptedAt: string;
46
+ readonly responseDigest: string;
47
+ };
48
+ readonly activeRecovery: AuthRecoveryJournalV1 | null;
49
+ readonly receipts: readonly {
50
+ readonly recoveryId: string;
51
+ readonly operationId: string;
52
+ readonly outcome: string;
53
+ readonly completedAt: string;
54
+ }[];
55
+ }
56
+ export interface AuthGenerationStore {
57
+ read(identityHash: string): Promise<AuthGenerationDocumentV1 | null>;
58
+ compareAndSet(expectedRevision: number, document: AuthGenerationDocumentV1): Promise<void>;
59
+ }
60
+ /** Private generation adapter backed by EncryptedCache's mandatory CAS path. */
61
+ export declare class EncryptedAuthGenerationStore implements AuthGenerationStore {
62
+ private readonly cache;
63
+ constructor(cache: EncryptedCache);
64
+ private key;
65
+ read(identityHash: string): Promise<AuthGenerationDocumentV1 | null>;
66
+ compareAndSet(expectedRevision: number, document: AuthGenerationDocumentV1): Promise<void>;
67
+ }
68
+ export interface AuthRefreshSuccess {
69
+ readonly token: string;
70
+ readonly expiresAt: string;
71
+ readonly refreshToken?: string | null;
72
+ readonly refreshExpiresAt?: string | null;
73
+ }
74
+ export interface AuthRecoveryInput {
75
+ readonly identityHash: string;
76
+ readonly recoveryId: string;
77
+ readonly operationId: string;
78
+ readonly idempotencyKey: string;
79
+ readonly requestDigest: string;
80
+ readonly owner: string;
81
+ readonly leaseMs?: number;
82
+ readonly timeoutMs?: number;
83
+ readonly now?: () => number;
84
+ readonly refresh: (signal?: AbortSignal) => Promise<AuthRefreshSuccess>;
85
+ }
86
+ export declare function createAuthIdentityHash(parts: readonly string[]): string;
87
+ export declare function validateAuthGenerationDocument(value: unknown, expectedIdentityHash?: string): AuthGenerationDocumentV1;
88
+ export declare function recoverHostAuthentication(store: AuthGenerationStore, input: AuthRecoveryInput): Promise<AuthRecoveryResultV1>;
89
+ export type AuthBusinessReplayDecisionV1 = {
90
+ readonly kind: 'replay-once';
91
+ readonly recoveryId: string;
92
+ } | {
93
+ readonly kind: 'reconcile-receipt';
94
+ readonly operationId: string;
95
+ } | {
96
+ readonly kind: 'stop';
97
+ readonly reasonCode: string;
98
+ };
99
+ export declare function decideAuthBusinessReplay(input: {
100
+ readonly recoveryId: string;
101
+ readonly operationId: string;
102
+ readonly generationCommitted: boolean;
103
+ readonly identityMatches: boolean;
104
+ readonly requestMatches: boolean;
105
+ readonly replayCount: number;
106
+ readonly receipt: 'not-accepted' | 'accepted' | 'unknown';
107
+ readonly supportsIdempotency: boolean;
108
+ readonly rotationUncertain: boolean;
109
+ }): AuthBusinessReplayDecisionV1;
110
+ /**
111
+ * Reserves the single business replay by CAS before returning authorization.
112
+ * Consumers perform the business effect only after this function succeeds.
113
+ */
114
+ export declare function reserveAuthBusinessReplay(store: AuthGenerationStore, input: {
115
+ readonly identityHash: string;
116
+ readonly recoveryId: string;
117
+ readonly operationId: string;
118
+ readonly requestDigest: string;
119
+ readonly receipt: 'not-accepted' | 'accepted' | 'unknown';
120
+ readonly supportsIdempotency: boolean;
121
+ readonly rotationUncertain?: boolean;
122
+ }): Promise<AuthBusinessReplayDecisionV1>;
123
+ /** Records the compare-bound business outcome before a later recovery may replace the journal. */
124
+ export declare function completeAuthRecovery(store: AuthGenerationStore, input: {
125
+ readonly identityHash: string;
126
+ readonly recoveryId: string;
127
+ readonly operationId: string;
128
+ readonly outcome: string;
129
+ readonly completedAt?: string;
130
+ }): Promise<AuthGenerationDocumentV1>;
131
+ export type AuthCausalEvidenceV1 = {
132
+ readonly kind: 'token';
133
+ readonly credential: string;
134
+ readonly expiresAt: string;
135
+ readonly generation: number;
136
+ readonly now?: number;
137
+ } | {
138
+ readonly kind: 'configuration';
139
+ readonly configured: boolean;
140
+ } | {
141
+ readonly kind: 'store';
142
+ readonly cause: 'store-unavailable' | 'store-corrupt' | 'keychain-unavailable';
143
+ } | {
144
+ readonly kind: 'transport';
145
+ readonly timeout?: boolean;
146
+ readonly requestStarted?: boolean;
147
+ readonly recoveryId?: string;
148
+ } | {
149
+ readonly kind: 'http';
150
+ readonly status: number;
151
+ readonly errorCode?: string;
152
+ } | {
153
+ readonly kind: 'persistence';
154
+ readonly recoveryId: string;
155
+ };
156
+ /** Pure evidence-to-cause mapping. Generic HTTP status never proves revocation. */
157
+ export declare function classifyAuthCausalEvidence(evidence: AuthCausalEvidenceV1): AuthRecoveryResultV1;
158
+ export declare function newRecoveryId(): string;
@@ -0,0 +1 @@
1
+ import{createHash as v,randomUUID as D}from"node:crypto";class K{cache;constructor(t){this.cache=t}key(t){if(!u.test(t))throw new Error("auth-business-identity-mismatch");return`neocortex:auth-generation:v1:${t}`}async read(t){const r=await this.cache.getAuthoritative(this.key(t));if(r===null)return null;try{return d(JSON.parse(r),t)}catch(o){throw new Error("auth-generation-corrupt",{cause:o})}}async compareAndSet(t,r){d(r,r.identityHash);const o=this.key(r.identityHash),i=await this.cache.getAuthoritative(o);let s=0;if(i!==null)try{s=d(JSON.parse(i),r.identityHash).revision}catch(n){throw new Error("auth-generation-corrupt",{cause:n})}if(s!==t||r.revision!==t+1)throw new Error("auth-generation-revision-conflict");await this.cache.setAuthoritative(o,JSON.stringify(r),{expectedPlaintextSha256:i===null?null:v("sha256").update(i).digest("hex")})}}const u=/^[a-f0-9]{64}$/,p=/^[A-Za-z0-9._:-]{1,128}$/;function J(e){if(e.length!==5||e.some(t=>t.length===0||t.length>256||/[\r\n\0]/.test(t)))throw new Error("auth-business-identity-mismatch");return v("sha256").update("neocortex-auth-generation-v1\0").update(e.join("\0")).digest("hex")}function d(e,t){let r;try{r=JSON.stringify(e)}catch{throw new Error("auth-generation-corrupt")}if(!l(e)||typeof r!="string")throw new Error("auth-generation-corrupt");if(Buffer.byteLength(r,"utf8")>256*1024)throw new Error("auth-generation-capacity");const o=e;if(o.schemaVersion!=="AuthGeneration/1.0"||!Number.isSafeInteger(o.revision)||o.revision<0||!u.test(o.identityHash)||t&&o.identityHash!==t||!Array.isArray(o.receipts)||o.receipts.length>32)throw new Error("auth-generation-corrupt");if(!m(e,["schemaVersion","revision","identityHash","accepted","activeRecovery","receipts"]))throw new Error("auth-generation-corrupt");S(o.accepted),H(o.activeRecovery);for(const i of o.receipts)T(i);return o}function C(e){return{schemaVersion:"AuthGeneration/1.0",revision:0,identityHash:e,accepted:null,activeRecovery:null,receipts:[]}}async function h(e,t,r){const o=d({...t,...r,revision:t.revision+1},t.identityHash);return await e.compareAndSet(t.revision,o),o}async function U(e,t){if(!u.test(t.identityHash)||!u.test(t.requestDigest)||![t.recoveryId,t.operationId,t.idempotencyKey,t.owner].every(a=>p.test(a)))return{status:"refresh-required",cause:"protocol-invalid",action:"stop"};const r=t.now??Date.now,o=Math.min(Math.max(t.leaseMs??3e4,1),6e4),i=Math.min(Math.max(t.timeoutMs??3e4,1),3e4);let s;try{s=d(await e.read(t.identityHash)??C(t.identityHash),t.identityHash)}catch(a){return x(a)}const n=s.activeRecovery;if(n)if(n.recoveryId===t.recoveryId){if(!_(n,t))return{status:"refresh-required",cause:"protocol-invalid",action:"stop"};if((n.phase==="generation-committed"||n.phase==="completed")&&s.accepted)return A(s.accepted);if(n.attemptCount===1)return y(t.recoveryId,n.phase==="response-received"?"persistence-failed":"rotation-uncertain");if(Date.parse(n.expiresAt)>r()&&n.owner!==t.owner)return{status:"refresh-required",cause:"revision-conflict",action:"retry-later"}}else{if(n.attemptCount===1&&!["generation-committed","completed","aborted-before-request"].includes(n.phase))return y(n.recoveryId,n.phase==="response-received"?"persistence-failed":"rotation-uncertain");if(n.phase==="generation-committed")return{status:"refresh-required",cause:"revision-conflict",action:"retry-later"};if(n.attemptCount===0&&Date.parse(n.expiresAt)>r())return{status:"refresh-required",cause:"revision-conflict",action:"retry-later"}}const g={recoveryId:t.recoveryId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,requestDigest:t.requestDigest,owner:t.owner,createdAt:new Date(r()).toISOString(),expiresAt:new Date(r()+o).toISOString(),attemptCount:0,replayCount:0,phase:"prepared"};try{(!n||n.recoveryId!==t.recoveryId||n.owner!==t.owner||n.phase!=="prepared")&&(s=await h(e,s,{activeRecovery:g}));const a={...g,attemptCount:1,phase:"request-started"};s=await h(e,s,{activeRecovery:a});let c;try{c=await M(t.refresh,i)}catch{return await q(e,s,a),y(t.recoveryId,"rotation-uncertain")}if(!c.token||c.token.length>65536||!Number.isFinite(Date.parse(c.expiresAt)))return await q(e,s,a),y(t.recoveryId,"rotation-uncertain");const w=v("sha256").update(JSON.stringify(c)).digest("hex"),I={...a,phase:"response-received",responseDigest:w};s=await h(e,s,{activeRecovery:I});const k={generation:(s.accepted?.generation??0)+1,accessToken:c.token,accessExpiresAt:c.expiresAt,refreshToken:c.refreshToken??null,refreshExpiresAt:c.refreshExpiresAt??null,acceptedAt:new Date(r()).toISOString(),responseDigest:w},E={...I,phase:"generation-committed"},b=await h(e,s,{accepted:k,activeRecovery:E});return A(b.accepted)}catch(a){return s.activeRecovery?.attemptCount!==1?x(a):y(t.recoveryId,"persistence-failed")}}function R(e){return!e.identityMatches||!e.requestMatches?{kind:"stop",reasonCode:"auth-business-identity-mismatch"}:e.rotationUncertain||!e.generationCommitted?{kind:"stop",reasonCode:"auth-business-replay-unsafe"}:e.replayCount!==0?{kind:"stop",reasonCode:"auth-business-replay-exhausted"}:e.receipt==="accepted"?{kind:"reconcile-receipt",operationId:e.operationId}:e.receipt==="unknown"&&!e.supportsIdempotency?{kind:"reconcile-receipt",operationId:e.operationId}:{kind:"replay-once",recoveryId:e.recoveryId}}async function B(e,t){let r;try{r=d(await e.read(t.identityHash),t.identityHash)}catch{return{kind:"stop",reasonCode:"auth-business-replay-unsafe"}}const o=r.activeRecovery;if(!o||o.recoveryId!==t.recoveryId||o.operationId!==t.operationId)return{kind:"stop",reasonCode:"auth-business-identity-mismatch"};const i=R({recoveryId:t.recoveryId,operationId:t.operationId,generationCommitted:o.phase==="generation-committed"&&r.accepted!==null,identityMatches:r.identityHash===t.identityHash,requestMatches:o.requestDigest===t.requestDigest,replayCount:o.replayCount,receipt:t.receipt,supportsIdempotency:t.supportsIdempotency,rotationUncertain:t.rotationUncertain===!0||o.phase==="uncertain"});if(i.kind!=="replay-once")return i;try{return await h(e,r,{activeRecovery:{...o,replayCount:1}}),i}catch{return{kind:"stop",reasonCode:"auth-generation-revision-conflict"}}}async function G(e,t){if(!u.test(t.identityHash)||![t.recoveryId,t.operationId,t.outcome].every(n=>p.test(n)))throw new Error("auth-business-identity-mismatch");const r=d(await e.read(t.identityHash),t.identityHash),o=r.activeRecovery;if(!o||o.recoveryId!==t.recoveryId||o.operationId!==t.operationId)throw new Error("auth-business-identity-mismatch");const i=r.receipts.find(n=>n.recoveryId===t.recoveryId);if(i){if(i.operationId!==t.operationId||i.outcome!==t.outcome)throw new Error("auth-business-identity-mismatch");return r}if(o.phase!=="generation-committed"||r.accepted===null)throw new Error("auth-business-replay-unsafe");if(r.receipts.length>=32)throw new Error("auth-generation-capacity");const s=t.completedAt??new Date().toISOString();if(!f(s))throw new Error("auth-business-identity-mismatch");return h(e,r,{activeRecovery:{...o,phase:"completed"},receipts:[...r.receipts,{recoveryId:t.recoveryId,operationId:t.operationId,outcome:t.outcome,completedAt:s}]})}function F(e){switch(e.kind){case"token":{const t=e.now??Date.now(),r=Date.parse(e.expiresAt);return Number.isFinite(r)?r<=t?{status:"refresh-required",cause:"expired",action:"prepare"}:r-t<=3e5?{status:"refresh-required",cause:"near-expiry",action:"prepare"}:{status:"authenticated",generation:e.generation,accessCredential:e.credential,expiresAt:e.expiresAt}:{status:"refresh-required",cause:"protocol-invalid",action:"stop"}}case"configuration":return e.configured?{status:"refresh-required",cause:"store-unavailable",action:"stop"}:{status:"not-configured",action:"activate"};case"store":return{status:"refresh-required",cause:e.cause,action:e.cause==="store-unavailable"?"retry-later":"stop"};case"transport":return e.requestStarted?y(e.recoveryId??"unknown-recovery","rotation-uncertain"):{status:"refresh-required",cause:e.timeout?"timeout":"transport-error",action:"retry-later"};case"http":{const t=e.errorCode??"";return e.status===429?{status:"refresh-required",cause:"rate-limited",action:"retry-later"}:e.status>=500?{status:"refresh-required",cause:"service-unavailable",action:"retry-later"}:t==="invalid_grant"||t==="revoked"?{status:"refresh-required",cause:"revoked",action:"reactivate"}:t==="invalid_scope"||t==="scope_denied"?{status:"refresh-required",cause:"scope-denied",action:"request-scope"}:t==="client_denied"?{status:"refresh-required",cause:"client-denied",action:"stop"}:{status:"refresh-required",cause:"protocol-invalid",action:"stop"}}case"persistence":return y(e.recoveryId,"persistence-failed")}}function P(){return D()}function S(e){if(e!==null){if(!l(e)||!m(e,["generation","accessToken","accessExpiresAt","refreshToken","refreshExpiresAt","acceptedAt","responseDigest"]))throw new Error("auth-generation-corrupt");if(!Number.isSafeInteger(e.generation)||e.generation<1||typeof e.accessToken!="string"||e.accessToken.length===0||e.accessToken.length>65536||e.refreshToken!==null&&(typeof e.refreshToken!="string"||e.refreshToken.length>65536)||!f(e.accessExpiresAt)||!f(e.acceptedAt)||e.refreshExpiresAt!==null&&!f(e.refreshExpiresAt)||!u.test(e.responseDigest))throw new Error("auth-generation-corrupt")}}function H(e){if(e===null)return;if(!l(e)||!m(e,["recoveryId","operationId","idempotencyKey","requestDigest","owner","createdAt","expiresAt","attemptCount","replayCount","phase","responseDigest"],!0))throw new Error("auth-generation-corrupt");const t=["prepared","request-started","response-received","generation-committed","uncertain","completed","aborted-before-request"];if(![e.recoveryId,e.operationId,e.idempotencyKey,e.owner].every(r=>p.test(r))||!u.test(e.requestDigest)||!f(e.createdAt)||!f(e.expiresAt)||![0,1].includes(e.attemptCount)||![0,1].includes(e.replayCount)||!t.includes(e.phase)||e.responseDigest!==void 0&&!u.test(e.responseDigest))throw new Error("auth-generation-corrupt")}function T(e){if(!l(e)||!m(e,["recoveryId","operationId","outcome","completedAt"])||!p.test(e.recoveryId)||!p.test(e.operationId)||!p.test(e.outcome)||!f(e.completedAt))throw new Error("auth-generation-corrupt")}function _(e,t){return e.operationId===t.operationId&&e.idempotencyKey===t.idempotencyKey&&e.requestDigest===t.requestDigest}function A(e){return{status:"authenticated",generation:e.generation,accessCredential:e.accessToken,expiresAt:e.accessExpiresAt}}function y(e,t){return{status:"uncertain",cause:t,recoveryId:e,action:"recover-explicitly"}}function x(e){const t=e instanceof Error?e.message:"";return t==="auth-generation-revision-conflict"||t==="auth-recovery-backpressure"?{status:"refresh-required",cause:"revision-conflict",action:"retry-later"}:t==="auth-generation-corrupt"||t==="auth-generation-path-unsafe"?{status:"refresh-required",cause:"store-corrupt",action:"stop"}:{status:"refresh-required",cause:"store-unavailable",action:"retry-later"}}async function q(e,t,r){try{await h(e,t,{activeRecovery:{...r,phase:"uncertain"}})}catch{}}async function M(e,t){const r=new AbortController;let o;const i=new Promise((s,n)=>{o=setTimeout(()=>{r.abort(),n(new Error("auth-refresh-timeout"))},t),o.unref?.()});try{return await Promise.race([e(r.signal),i])}finally{o&&clearTimeout(o)}}function f(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function l(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function m(e,t,r=!1){const o=Object.keys(e).sort();return(r?t.slice(0,-1):t).every(s=>o.includes(s))&&o.every(s=>t.includes(s))}export{K as EncryptedAuthGenerationStore,F as classifyAuthCausalEvidence,G as completeAuthRecovery,J as createAuthIdentityHash,R as decideAuthBusinessReplay,P as newRecoveryId,U as recoverHostAuthentication,B as reserveAuthBusinessReplay,d as validateAuthGenerationDocument};
@@ -11,6 +11,7 @@
11
11
  * See the LICENSE file in the project root for full license text.
12
12
  */
13
13
  import type { CacheProvider } from '../types/index.js';
14
+ import type { AuthRecoveryResultV1 } from './host-auth-recovery.js';
14
15
  export interface LicenseClientOptions {
15
16
  readonly serverUrl: string;
16
17
  readonly licenseKey: string;
@@ -18,6 +19,8 @@ export interface LicenseClientOptions {
18
19
  readonly clientVersion?: string;
19
20
  /** Use only an already-valid cached JWT; never refresh or activate. */
20
21
  readonly strictReadOnly?: boolean;
22
+ /** Opt into P224 causal recovery. P224.04 owns enabling this in invoke wiring. */
23
+ readonly causalAuthRecovery?: boolean;
21
24
  }
22
25
  interface ActivationResult {
23
26
  readonly token: string;
@@ -42,8 +45,10 @@ export declare class LicenseClient {
42
45
  private readonly clientVersion;
43
46
  private readonly machineId;
44
47
  private readonly strictReadOnly;
48
+ private readonly causalAuthRecovery;
45
49
  private token;
46
50
  private refreshToken;
51
+ private lastRecoveryResult;
47
52
  constructor(options: LicenseClientOptions);
48
53
  /**
49
54
  * Get a valid JWT token. Checks memory, cache, refresh token, then activation.
@@ -60,6 +65,9 @@ export declare class LicenseClient {
60
65
  getToken(): Promise<string | null>;
61
66
  /** Read-only authentication classification. It never refreshes, activates, clears or writes cache state. */
62
67
  inspectToken(): Promise<LicenseTokenInspection>;
68
+ /** Last causal result, excluding raw server bodies and refresh credentials. */
69
+ getLastRecoveryResult(): AuthRecoveryResultV1 | null;
70
+ private refreshRequired;
63
71
  /**
64
72
  * Activate through the endpoint matching the configured credential type.
65
73
  * Stores token and refresh_token in memory and cache on success.
@@ -81,7 +89,8 @@ export declare class LicenseClient {
81
89
  /**
82
90
  * Force-refresh the token.
83
91
  * Used when tier_changed is detected or a 401 response indicates the token is expired.
84
- * Falls back to re-activation if refresh fails.
92
+ * Does not clear or re-activate on an ambiguous refresh failure. Recovery is
93
+ * governed by the causal result so transient or uncertain state is preserved.
85
94
  * NEVER throws - returns new token or null on failure.
86
95
  *
87
96
  * Story 18.8: Updated to prefer refresh over re-activate (preserves updated tier).
@@ -1 +1 @@
1
- import{decodeJwt as h}from"jose";import{NoOpCache as o}from"../types/index.js";import{getMachineFingerprint as l}from"../machine/fingerprint.js";import{CLIENT_VERSION as u}from"../version.js";const a="neocortex:jwt:token",s="neocortex:jwt:refresh_token",f=300,c=10080*60*1e3;class w{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;token=null;refreshToken=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new o,this.clientVersion=e.clientVersion??u,this.strictReadOnly=e.strictReadOnly??!1,this.machineId=l({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const t=await this.inspectToken();return t.status==="authenticated"?t.token:null}if(this.token){const t=this.checkTokenValidity(this.token);if(t==="valid")return this.token;if(t==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const t=this.checkTokenValidity(e);if(t==="valid")return e;if(t==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const t=await this.refresh();if(t?.token)return t.token}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const i=this.checkTokenValidity(e);return i==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:i==="needs-refresh"?"near-expiry":"expired"}}return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}async activate(){if(this.strictReadOnly)return null;try{const e=this.licenseKey.startsWith("nxk_"),i=e?"activate-key":"activate",t=e?{api_key:this.licenseKey}:{license_key:this.licenseKey},r=await fetch(`${this.serverUrl}/api/v1/license/${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,machine_id:this.machineId,client_version:this.clientVersion})});if(!r.ok)return null;const n=await r.json();return n.tier!==void 0&&n.tier!=="free"&&n.tier!=="pro"&&n.tier!=="enterprise"?null:(this.token=n.token,this.refreshToken=n.refresh_token??null,await this.cache.set(a,n.token,n.expires_in*1e3).catch(()=>{}),n.refresh_token&&await this.cache.set(s,n.refresh_token,c).catch(()=>{}),{token:n.token,expiresIn:n.expires_in,refreshToken:n.refresh_token,tier:n.tier})}catch{return null}}async refresh(e){if(this.strictReadOnly)return null;try{const i=this.refreshToken??await this.loadRefreshTokenFromCache();if(!i)return null;const t=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:i})});if(!t.ok)return this.refreshToken=null,await this.cache.set(s,"",1).catch(()=>{}),null;const r=await t.json();return this.token=r.token,this.refreshToken=r.refresh_token??null,await this.cache.set(a,r.token,r.expires_in*1e3).catch(()=>{}),r.refresh_token&&await this.cache.set(s,r.refresh_token,c).catch(()=>{}),{token:r.token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}catch{return null}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const i=h(e);if(!i.exp)return"expired";const t=Math.floor(Date.now()/1e3);return i.exp<=t?"expired":i.exp-t<=f?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(a)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(s);return e&&e.length>0?e:null}catch{return null}}}export{w as LicenseClient};
1
+ import{decodeJwt as h}from"jose";import{NoOpCache as o}from"../types/index.js";import{getMachineFingerprint as l}from"../machine/fingerprint.js";import{CLIENT_VERSION as u}from"../version.js";const s="neocortex:jwt:token",a="neocortex:jwt:refresh_token",f=300,c=10080*60*1e3;class v{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;causalAuthRecovery;token=null;refreshToken=null;lastRecoveryResult=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new o,this.clientVersion=e.clientVersion??u,this.strictReadOnly=e.strictReadOnly??!1,this.causalAuthRecovery=e.causalAuthRecovery??!1,this.machineId=l({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const t=await this.inspectToken();return t.status==="authenticated"?t.token:null}if(this.token){const t=this.checkTokenValidity(this.token);if(t==="valid")return this.token;if(t==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const t=this.checkTokenValidity(e);if(t==="valid")return e;if(t==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const t=await this.refresh();if(t?.token)return t.token;if(this.causalAuthRecovery)return null}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const n=this.checkTokenValidity(e);return n==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:n==="needs-refresh"?"near-expiry":"expired"}}return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}getLastRecoveryResult(){return this.lastRecoveryResult}refreshRequired(e,n){return this.lastRecoveryResult={status:"refresh-required",cause:e,action:n},null}async activate(){if(this.strictReadOnly)return null;try{const e=this.licenseKey.startsWith("nxk_"),n=e?"activate-key":"activate",t=e?{api_key:this.licenseKey}:{license_key:this.licenseKey},i=await fetch(`${this.serverUrl}/api/v1/license/${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,machine_id:this.machineId,client_version:this.clientVersion})});if(!i.ok)return null;const r=await i.json();return r.tier!==void 0&&r.tier!=="free"&&r.tier!=="pro"&&r.tier!=="enterprise"?null:(this.token=r.token,this.refreshToken=r.refresh_token??null,await this.cache.set(s,r.token,r.expires_in*1e3).catch(()=>{}),r.refresh_token&&await this.cache.set(a,r.refresh_token,c).catch(()=>{}),{token:r.token,expiresIn:r.expires_in,refreshToken:r.refresh_token,tier:r.tier})}catch{return null}}async refresh(e){if(this.strictReadOnly)return null;try{const n=this.refreshToken??await this.loadRefreshTokenFromCache();if(!n)return this.refreshRequired("not-configured","reactivate");const t=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n})});if(!t.ok){let r="";try{r=String((await t.json()).error??"")}catch{}return t.status===429?this.refreshRequired("rate-limited","retry-later"):t.status>=500?this.refreshRequired("service-unavailable","retry-later"):r==="invalid_grant"||r==="revoked"?this.refreshRequired("revoked","reactivate"):r==="invalid_scope"||r==="scope_denied"?this.refreshRequired("scope-denied","request-scope"):r==="client_denied"?this.refreshRequired("client-denied","stop"):this.refreshRequired("protocol-invalid","stop")}const i=await t.json();return this.token=i.token,this.refreshToken=i.refresh_token??null,await this.cache.set(s,i.token,i.expires_in*1e3).catch(()=>{}),i.refresh_token&&await this.cache.set(a,i.refresh_token,c).catch(()=>{}),this.lastRecoveryResult={status:"authenticated",generation:0,accessCredential:i.token,expiresAt:new Date(Date.now()+i.expires_in*1e3).toISOString()},{token:i.token,expiresIn:i.expires_in,refreshToken:i.refresh_token}}catch{return this.refreshRequired("transport-error","retry-later")}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:this.causalAuthRecovery?null:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const n=h(e);if(!n.exp)return"expired";const t=Math.floor(Date.now()/1e3);return n.exp<=t?"expired":n.exp-t<=f?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(s)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(a);return e&&e.length>0?e:null}catch{return null}}}export{v as LicenseClient};
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Contract-first admission for root-owned native background execution.
3
+ *
4
+ * This module deliberately does not spawn, persist tracked state, select graph
5
+ * work, or perform Git effects. It only converts an exact server-owned task
6
+ * directive into closed per-story entries for the host root.
7
+ */
8
+ import { type NativeBackgroundDispatchContractV1, type NativeDispatchBindingV1, type NativeHostAttestationV1 } from '../continuity/native-agent-types.js';
9
+ export declare const NATIVE_BACKGROUND_REASON_CODES: Readonly<{
10
+ readonly CONTRACT_INVALID: "directive-background-contract-invalid";
11
+ readonly BINDING_MISSING: "directive-background-binding-missing";
12
+ readonly WAVE_MISMATCH: "directive-background-wave-mismatch";
13
+ readonly GRAPH_STALE: "directive-background-graph-stale";
14
+ readonly CAPABILITY_UNVALIDATED: "native-background-capability-unvalidated";
15
+ readonly DEPTH_DENIED: "native-background-depth-denied";
16
+ readonly SETTLEMENT_INVALID: "native-background-settlement-invalid";
17
+ }>;
18
+ export type NativeBackgroundReasonCode = (typeof NATIVE_BACKGROUND_REASON_CODES)[keyof typeof NATIVE_BACKGROUND_REASON_CODES];
19
+ export interface NativeBackgroundTaskDirectiveV1 {
20
+ readonly kind: 'task';
21
+ readonly subagentType: 'neocortex';
22
+ readonly promptTemplate: string;
23
+ readonly storyIds: readonly string[];
24
+ readonly promptTemplates: readonly string[];
25
+ readonly dispatchBinding: NativeDispatchBindingV1;
26
+ readonly dispatchBindings: readonly NativeDispatchBindingV1[];
27
+ readonly backgroundDispatch: NativeBackgroundDispatchContractV1;
28
+ readonly rationale?: string;
29
+ }
30
+ export interface NativeBackgroundAdmissionInput {
31
+ readonly directive: unknown;
32
+ readonly supportsTaskDelegation: boolean;
33
+ readonly taskDelegationCapability: 'native_safe' | 'unsupported' | 'unvalidated' | 'disabled_by_override';
34
+ readonly hostAttestation: unknown;
35
+ readonly currentGraphRevision: string;
36
+ }
37
+ export interface AuthorizedNativeBackgroundEntryV1 {
38
+ readonly storyId: string;
39
+ readonly prompt: string;
40
+ readonly binding: NativeDispatchBindingV1;
41
+ }
42
+ export type EpicBackgroundDispatchDecisionV1 = Readonly<{
43
+ kind: 'launch';
44
+ entries: readonly AuthorizedNativeBackgroundEntryV1[];
45
+ hostAttestation: NativeHostAttestationV1;
46
+ }> | Readonly<{
47
+ kind: 'reconcile-existing';
48
+ dispatchKeys: readonly string[];
49
+ reasonCode: 'native-background-reconcile-existing';
50
+ }> | Readonly<{
51
+ kind: 'inline';
52
+ reasonCode: NativeBackgroundReasonCode;
53
+ }> | Readonly<{
54
+ kind: 'denied';
55
+ reasonCode: NativeBackgroundReasonCode;
56
+ }>;
57
+ /**
58
+ * Admit only the exact P224-CON-DISPATCH chain. Missing native authority is an
59
+ * explicit inline fallback; malformed or stale authority is denied.
60
+ */
61
+ export declare function planEpicBackgroundDispatch(input: NativeBackgroundAdmissionInput): EpicBackgroundDispatchDecisionV1;
@@ -0,0 +1 @@
1
+ import{isNativeBackgroundDispatchContractV1 as b,isNativeDispatchBindingV1 as h,isNativeHostAttestationV1 as I}from"../continuity/native-agent-types.js";const i=Object.freeze({CONTRACT_INVALID:"directive-background-contract-invalid",BINDING_MISSING:"directive-background-binding-missing",WAVE_MISMATCH:"directive-background-wave-mismatch",GRAPH_STALE:"directive-background-graph-stale",CAPABILITY_UNVALIDATED:"native-background-capability-unvalidated",DEPTH_DENIED:"native-background-depth-denied",SETTLEMENT_INVALID:"native-background-settlement-invalid"}),v=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/,f=/^\*yolo @docs\/stories\/([A-Za-z0-9._-]+)\.story\.md(?: branchless-preparation)?$/,y=/^(?:sha256:)?[a-f0-9]{64}$/i;function D(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function C(e,t){return e.schemaVersion===t.schemaVersion&&e.storyId===t.storyId&&e.graphRevision.toLowerCase()===t.graphRevision.toLowerCase()&&e.dispatchKey.toLowerCase()===t.dispatchKey.toLowerCase()&&e.requiredCapability===t.requiredCapability&&e.maxDepth===t.maxDepth&&e.publicSafe===t.publicSafe}function p(e){return e.toLowerCase().replace(/^sha256:/,"")}function T(e,t,n){return Object.freeze({storyId:e,prompt:t,binding:Object.freeze({...n})})}function _(e){if(!e.supportsTaskDelegation||e.taskDelegationCapability!=="native_safe"||!I(e.hostAttestation))return Object.freeze({kind:"inline",reasonCode:i.CAPABILITY_UNVALIDATED});if(!D(e.directive)||e.directive.kind!=="task"||e.directive.subagentType!=="neocortex"||!b(e.directive.backgroundDispatch))return Object.freeze({kind:"denied",reasonCode:i.CONTRACT_INVALID});if(!h(e.directive.dispatchBinding)||!Array.isArray(e.directive.dispatchBindings)||e.directive.dispatchBindings.length===0||!e.directive.dispatchBindings.every(h))return Object.freeze({kind:"denied",reasonCode:i.BINDING_MISSING});if(!y.test(e.currentGraphRevision))return Object.freeze({kind:"denied",reasonCode:i.GRAPH_STALE});const t=e.directive.storyIds,n=e.directive.promptTemplates,a=e.directive.dispatchBindings;if(!Array.isArray(t)||!Array.isArray(n)||t.length===0||t.length!==n.length||t.length!==a.length||new Set(t).size!==t.length||new Set(a.map(r=>r.dispatchKey)).size!==a.length||!C(e.directive.dispatchBinding,a[0]))return Object.freeze({kind:"denied",reasonCode:i.WAVE_MISMATCH});const g=p(e.currentGraphRevision),c=[];for(let r=0;r<t.length;r+=1){const s=t[r],d=n[r],o=a[r],A=typeof d=="string"?d.match(f):null;if(typeof s!="string"||!v.test(s)||!A||A[1]!==s||o.storyId!==s)return Object.freeze({kind:"denied",reasonCode:i.WAVE_MISMATCH});if(p(o.graphRevision)!==g)return Object.freeze({kind:"denied",reasonCode:i.GRAPH_STALE});if(o.maxDepth!==1||e.directive.backgroundDispatch.maxDepth!==1)return Object.freeze({kind:"denied",reasonCode:i.DEPTH_DENIED});c.push(T(s,d,o))}return Object.freeze({kind:"launch",entries:Object.freeze(c),hostAttestation:Object.freeze({...e.hostAttestation})})}export{i as NATIVE_BACKGROUND_REASON_CODES,_ as planEpicBackgroundDispatch};
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Root-owned execution of an already admitted native background frontier.
3
+ * Host-specific APIs are injected; raw handles never leave the launch/observe
4
+ * bridge and are absent from this module's public result.
5
+ */
6
+ import { type NativeAgentDispatchReceiptV1, type NativeHostAttestationV1 } from '../../continuity/native-agent-types.js';
7
+ import { type AuthorizedNativeBackgroundEntryV1 } from '../epic-background-dispatcher.js';
8
+ export declare const NATIVE_BACKGROUND_MAX_POLLS = 30;
9
+ export interface NativeBackgroundReservationV1 {
10
+ readonly action: 'spawn-once' | 'reconcile-existing';
11
+ readonly receipt: NativeAgentDispatchReceiptV1;
12
+ }
13
+ interface PrivateNativeHostLaunchV1 {
14
+ readonly rawHandle: string;
15
+ readonly rawParentHandle?: string | null;
16
+ }
17
+ export interface NativeBackgroundRootPorts {
18
+ /**
19
+ * Root-owned continuation/session/auth preflight. Implementations may use the
20
+ * supported P224.02/P224.03 interfaces, but must return only a public reason.
21
+ */
22
+ readonly preflight: (entries: readonly AuthorizedNativeBackgroundEntryV1[], hostAttestation: NativeHostAttestationV1) => Promise<Readonly<{
23
+ ok: true;
24
+ } | {
25
+ ok: false;
26
+ reasonCode: string;
27
+ }>>;
28
+ readonly reserve: (entry: AuthorizedNativeBackgroundEntryV1, hostAttestation: NativeHostAttestationV1) => Promise<NativeBackgroundReservationV1>;
29
+ readonly launch: (entry: AuthorizedNativeBackgroundEntryV1) => Promise<PrivateNativeHostLaunchV1>;
30
+ readonly recordSpawned: (entry: AuthorizedNativeBackgroundEntryV1, reservation: NativeBackgroundReservationV1, launch: PrivateNativeHostLaunchV1) => Promise<NativeAgentDispatchReceiptV1>;
31
+ readonly reconcileExisting: (entry: AuthorizedNativeBackgroundEntryV1, reservation: NativeBackgroundReservationV1) => Promise<NativeAgentDispatchReceiptV1>;
32
+ readonly awaitSettlement: (entry: AuthorizedNativeBackgroundEntryV1, receipt: NativeAgentDispatchReceiptV1, options: Readonly<{
33
+ maxPolls: 30;
34
+ signal?: AbortSignal;
35
+ }>) => Promise<NativeAgentDispatchReceiptV1>;
36
+ }
37
+ export interface NativeBackgroundRootResultV1 {
38
+ readonly kind: 'settled';
39
+ readonly settlement: NativeAgentDispatchReceiptV1;
40
+ readonly started: readonly NativeAgentDispatchReceiptV1[];
41
+ readonly publicSafe: true;
42
+ }
43
+ export declare class NativeBackgroundRootError extends Error {
44
+ readonly reasonCode: string;
45
+ constructor(reasonCode: string);
46
+ }
47
+ /**
48
+ * Reserve the whole frontier, launch only `spawn-once` entries, reconcile
49
+ * existing dispatches, then begin settlement. No settlement is awaited before
50
+ * every entry has produced a launch/reconciliation receipt.
51
+ */
52
+ export declare function runNativeBackgroundRoot(entries: readonly AuthorizedNativeBackgroundEntryV1[], hostAttestation: NativeHostAttestationV1, ports: NativeBackgroundRootPorts, options?: Readonly<{
53
+ signal?: AbortSignal;
54
+ }>): Promise<NativeBackgroundRootResultV1>;
55
+ export interface BoundedNativeBackgroundPollResultV1 {
56
+ readonly receipt: NativeAgentDispatchReceiptV1 | null;
57
+ readonly polls: number;
58
+ readonly exhausted: boolean;
59
+ }
60
+ /** Sequential by construction: at most one poll is in flight for one dispatch. */
61
+ export declare function boundedNativeBackgroundPoll(poll: (attempt: number) => Promise<NativeAgentDispatchReceiptV1 | null>, options?: Readonly<{
62
+ maxPolls?: number;
63
+ signal?: AbortSignal;
64
+ }>): Promise<BoundedNativeBackgroundPollResultV1>;
65
+ export {};
@@ -0,0 +1 @@
1
+ import{isNativeAgentDispatchReceiptV1 as m,NATIVE_AGENT_TERMINAL_STATES as g}from"../../continuity/native-agent-types.js";import{NATIVE_BACKGROUND_REASON_CODES as d}from"../epic-background-dispatcher.js";const w=30;class c extends Error{reasonCode;constructor(a){super(a),this.reasonCode=a,this.name="NativeBackgroundRootError"}}function u(e,a){if(!m(e)||e.storyId!==a.storyId||e.dispatchKey!==a.binding.dispatchKey||e.graphRevision.replace(/^sha256:/,"").toLowerCase()!==a.binding.graphRevision.replace(/^sha256:/,"").toLowerCase()||e.topology!=="native-agent")throw new c(d.SETTLEMENT_INVALID);return e}async function T(e,a,r,o={}){if(e.length===0)throw new c(d.WAVE_MISMATCH);const n=await r.preflight(e,a);if(!n.ok)throw new c(n.reasonCode);const i=await Promise.all(e.map(t=>r.reserve(t,a))),E=await Promise.all(e.map(async(t,l)=>{const s=i[l];if(u(s.receipt,t),s.action==="reconcile-existing")return u(await r.reconcileExisting(t,s),t);const h=await r.launch(t);return u(await r.recordSpawned(t,s,h),t)}));let f;try{f=await Promise.any(E.map((t,l)=>r.awaitSettlement(e[l],t,{maxPolls:w,...o.signal?{signal:o.signal}:{}}).then(s=>{const h=u(s,e[l]);if(!g.has(h.state))throw new c(d.SETTLEMENT_INVALID);return h})))}catch{throw new c(d.SETTLEMENT_INVALID)}return Object.freeze({kind:"settled",settlement:f,started:Object.freeze([...E]),publicSafe:!0})}async function A(e,a={}){const r=Math.max(1,Math.min(w,a.maxPolls??w));let o=null,n=0;for(let i=1;i<=r&&!a.signal?.aborted;i+=1)if(o=await e(i),n=i,o&&g.has(o.state))return Object.freeze({receipt:o,polls:n,exhausted:!1});return Object.freeze({receipt:o,polls:n,exhausted:n>=r})}export{w as NATIVE_BACKGROUND_MAX_POLLS,c as NativeBackgroundRootError,A as boundedNativeBackgroundPoll,T as runNativeBackgroundRoot};
@@ -3,6 +3,7 @@ import { type EpicTerminalReleaseAuthority, type P205TransientExecutionAuthority
3
3
  import { type EpicMergeCandidateQaAuthority } from './epic-merge-candidate-qa.js';
4
4
  import type { EpicMergeCandidateQaReceipt } from '../../../../shared/dist/yoloop/epic-terminal-git.js';
5
5
  import type { EpicPullRequestMergeGuardReceipt } from '../../../../shared/dist/yoloop/epic-terminal-git.js';
6
+ import { type ManagedEnvironmentCleanupAdapter, type ManagedEnvironmentCleanupReceiptV1, type ManagedEnvironmentCleanupRequestV1 } from './managed-environment-cleanup.js';
6
7
  export interface EpicTerminalGitSnapshot {
7
8
  readonly executionHeadSha: string;
8
9
  readonly originHeadSha: string;
@@ -15,6 +16,8 @@ export interface EpicTerminalGitSnapshot {
15
16
  readonly originBinding?: import('../../../../shared/dist/yoloop/epic-terminal-git.js').EpicOriginBindingEvidence | null;
16
17
  readonly nowIso?: string;
17
18
  readonly reconciliationCandidates: readonly GitReconciliationCandidate[];
19
+ /** Optional capability-bound resources. Absence means no environment effect is authorized. */
20
+ readonly managedEnvironmentCleanupRequests?: readonly ManagedEnvironmentCleanupRequestV1[];
18
21
  }
19
22
  export type EpicTerminalEffectResult<T extends object = object> = ({
20
23
  readonly ok: true;
@@ -25,6 +28,8 @@ export type EpicTerminalEffectResult<T extends object = object> = ({
25
28
  readonly externalPolicy: boolean;
26
29
  };
27
30
  export interface EpicTerminalGitAdapter {
31
+ /** Optional installed capability. Missing capability preserves managed resources as pending. */
32
+ readonly managedEnvironmentCleanup?: ManagedEnvironmentCleanupAdapter;
28
33
  /** Produce missing physical origin/aggregate-QA evidence before server projection. */
29
34
  prepareLifecycleEvidence?(input: {
30
35
  readonly epicId: string;
@@ -128,6 +133,8 @@ export interface EpicTerminalGitAdapter {
128
133
  readonly terminalReceipt: EpicTerminalGitReceipt;
129
134
  readonly reconciliationReceipts: readonly GitReconciliationReceipt[];
130
135
  readonly preservedDecisions: readonly GitReconciliationDecision[];
136
+ /** Kept separate from merge/Git reconciliation; production persistence requires an accepted store claim. */
137
+ readonly managedEnvironmentCleanupReceipts?: readonly ManagedEnvironmentCleanupReceiptV1[];
131
138
  }): Promise<EpicTerminalEffectResult>;
132
139
  }
133
140
  export interface EpicTerminalGitExecutionResult {
@@ -135,6 +142,8 @@ export interface EpicTerminalGitExecutionResult {
135
142
  readonly receipt: EpicTerminalGitReceipt;
136
143
  readonly reconciliationReceipts: readonly GitReconciliationReceipt[];
137
144
  readonly preservedDecisions: readonly GitReconciliationDecision[];
145
+ readonly managedEnvironmentCleanupReceipts: readonly ManagedEnvironmentCleanupReceiptV1[];
146
+ readonly managedEnvironmentCleanupPending: boolean;
138
147
  readonly reasonCodes: readonly string[];
139
148
  readonly publicSafe: true;
140
149
  }
@@ -1,2 +1,2 @@
1
- import{createHash as w}from"node:crypto";import{EPIC_TERMINAL_GIT_REASON_CODES as x,classifyGitReconciliationCandidate as N,validateEpicTerminalGitDirective as q}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{consumeEpicTerminalReleaseAuthority as P}from"../../git/git-lifecycle-store.js";import{verifiedEpicMergeCandidateReceipt as E}from"./epic-merge-candidate-qa.js";async function O(e,r,s){const c=await r.inspectReconciliation(e);if(!c.ok)return{ok:!1,reconciliationReceipts:[],preservedDecisions:[],reasonCodes:[c.reasonCode],publicSafe:!0};const o=await k({idempotencyKey:e.idempotencyKey,enabled:!0,dryRun:e.dryRun},c.candidates,r,s),l=await r.persistReconciliation({epicId:e.epicId,reconciliationReceipts:o.receipts,preservedDecisions:o.preserved}),u=C([...o.reasonCodes,...l.ok?[]:[l.reasonCode]]);return{ok:o.ok&&l.ok,reconciliationReceipts:o.receipts,preservedDecisions:o.preserved,reasonCodes:u,publicSafe:!0}}async function T(e,r,s,c){const o=s();if(!r.prepareLifecycleEvidence)return S(e,{ok:!1,reasonCode:"epic-aggregate-qa-producer-required",retryEligible:!1,externalPolicy:!1},o);const l=c?{ok:!0,originBindingCaptured:!1,aggregateQaRecorded:!0,terminalAuthority:c}:await r.prepareLifecycleEvidence({epicId:e.epicId,nowIso:o});if(!l.ok)return S(e,l,o);const u=l.terminalAuthority??l.p205Authority;if(!u)return S(e,{ok:!1,reasonCode:"epic-aggregate-qa-authority-required",retryEligible:!1,externalPolicy:!1},o);const p=await r.inspect(e);if(!p.ok)return S(e,p,o);const a=p.snapshot,h=q(e,{...a,nowIso:o});if(!h.ready)return y(!1,R(e,a,o,{strategy:e.strategy==="single_pr"?"single_pr":"direct",physicalStatus:"blocked_local_or_repo",retryEligible:h.reasonCodes.some(t=>t.endsWith("mismatch")||t.endsWith("active")),reasonCodes:h.reasonCodes}),[],[],h.reasonCodes);if(!a.aggregateQaReceipt||!P(u,{executionHeadSha:a.executionHeadSha,graphRevision:e.graphRevision,aggregateQaReceipt:a.aggregateQaReceipt,headReconciliationReceipt:a.headReconciliationReceipt}))return S(e,{ok:!1,reasonCode:"epic-aggregate-qa-authority-binding-mismatch",retryEligible:!1,externalPolicy:!1},o);if(h.reasonCodes.includes(x.ALREADY_COMPLETE)&&a.existingReceipt){const t=await r.verifyTerminalReceipt(e,a.existingReceipt,o);if(!t.ok)return y(!1,a.existingReceipt,[],[],[t.reasonCode]);const I=E(t.candidateAuthority,{mergeSha:a.existingReceipt.mergeSha,originHeadSha:a.existingReceipt.baseSha,executionHeadSha:a.existingReceipt.executionHeadSha,graphRevision:e.graphRevision});if(!I)return y(!1,a.existingReceipt,[],[],["epic-merge-candidate-authority-required"]);const B={...a.existingReceipt,candidateQa:I,...t.providerGuard?{providerGuard:t.providerGuard}:{}},f=await k({idempotencyKey:e.idempotencyKey,enabled:e.reconcile.enabled,dryRun:e.reconcile.dryRun},a.reconciliationCandidates,r,s),_=await r.persist({terminalReceipt:B,reconciliationReceipts:f.receipts,preservedDecisions:f.preserved}),A=C([...h.reasonCodes,...f.reasonCodes,..._.ok?[]:[_.reasonCode]]);return y(_.ok&&f.ok,B,f.receipts,f.preserved,A)}let i;const n=await r.prepareMergeObject({originBranch:e.originBranch,executionBranch:e.executionBranch,originHeadSha:a.originHeadSha,executionHeadSha:a.executionHeadSha,graphRevision:e.graphRevision,nowIso:o,message:[`merge(${e.epicId}): integrate ${e.executionBranch} into ${e.originBranch}`,"",`Neocortex-Epic: ${e.epicId}`,`Neocortex-Origin-Branch: ${e.originBranch}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Execution-Head: ${a.executionHeadSha}`,`Neocortex-Origin-Base: ${a.originHeadSha}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Aggregate-QA: ${e.localGates.aggregateQaReceipt.receiptRef}`,`Neocortex-Idempotency: ${e.idempotencyKey}`].join(`
2
- `)});if(!n.ok)return i=R(e,a,o,{strategy:"direct",physicalStatus:"blocked_local_or_repo",retryEligible:n.retryEligible,reasonCodes:[n.reasonCode]}),await r.persist({terminalReceipt:i,reconciliationReceipts:[],preservedDecisions:[]}),y(!1,i,[],[],i.reasonCodes);const g=E(n.candidateAuthority,{originHeadSha:a.originHeadSha,executionHeadSha:a.executionHeadSha,mergeSha:n.mergeSha,graphRevision:e.graphRevision});if(!g)return S(e,{ok:!1,reasonCode:"epic-merge-candidate-authority-required",retryEligible:!1,externalPolicy:!1},o);if(e.strategy!=="single_pr"){const t=await r.pushMergeObject({epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,executionHeadSha:a.executionHeadSha,expectedOriginSha:a.originHeadSha,mergeSha:n.mergeSha,graphRevision:e.graphRevision,candidateAuthority:n.candidateAuthority,storyCheckpointIds:e.storyCheckpointIds,aggregateQaReceipt:e.localGates.aggregateQaReceipt,nowIso:s()});t.ok?i=R(e,a,o,{strategy:"direct",mergeSha:n.mergeSha,pushedSha:t.pushedSha,candidateQa:g,physicalStatus:"pushed",retryEligible:!1,reasonCodes:[x.READY],completedAt:s()}):e.strategy==="direct_or_single_pr"&&t.externalPolicy?i=await H(e,a,r,o,s,g,n.candidateAuthority):i=R(e,a,o,{strategy:"direct",mergeSha:n.mergeSha,physicalStatus:t.externalPolicy?"denied_external_gate":"blocked_local_or_repo",retryEligible:t.retryEligible,reasonCodes:[t.reasonCode,...t.retryEligible?[x.RETRY_ELIGIBLE]:[]]})}else i=await H(e,a,r,o,s,g,n.candidateAuthority);const d=i.physicalStatus==="pushed"?await r.verifyTerminalReceipt(e,i,s()):null;if(d&&!d.ok){const t=R(e,a,o,{...i,physicalStatus:"blocked_local_or_repo",retryEligible:d.retryEligible,reasonCodes:[d.reasonCode]});return await r.persist({terminalReceipt:t,reconciliationReceipts:[],preservedDecisions:[]}),y(!1,t,[],[],t.reasonCodes)}if(d?.ok){const t=E(d.candidateAuthority,{mergeSha:i.mergeSha,originHeadSha:i.baseSha,executionHeadSha:i.executionHeadSha,graphRevision:e.graphRevision});if(!t)return y(!1,i,[],[],["epic-merge-candidate-authority-required"]);i={...i,candidateQa:t,...d.providerGuard?{providerGuard:d.providerGuard}:{}}}const m=i.physicalStatus==="pushed"?await k({idempotencyKey:e.idempotencyKey,enabled:e.reconcile.enabled,dryRun:e.reconcile.dryRun},a.reconciliationCandidates,r,s):{ok:!0,receipts:[],preserved:[],reasonCodes:[]},b=await r.persist({terminalReceipt:i,reconciliationReceipts:m.receipts,preservedDecisions:m.preserved}),G=C([...i.reasonCodes,...m.reasonCodes,...b.ok?[]:[b.reasonCode]]);return y(i.physicalStatus==="pushed"&&m.ok&&b.ok,i,m.receipts,m.preserved,G)}async function H(e,r,s,c,o,l,u){const p=await s.ensureSingleEpicPullRequest({epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,expectedStoryHeadSha:r.executionHeadSha,expectedPullRequestHeadSha:l.mergeSha,candidateQa:l,candidateAuthority:u,idempotencyKey:e.idempotencyKey,terminalBinding:{graphRevision:e.graphRevision,storyCheckpointIds:e.storyCheckpointIds,aggregateQaReceipt:e.localGates.aggregateQaReceipt,nowIso:o()}});if(!p.ok)return R(e,r,c,{strategy:"single_pr",physicalStatus:p.externalPolicy?"denied_external_gate":"blocked_local_or_repo",retryEligible:p.retryEligible,reasonCodes:[p.reasonCode]});const a=await s.mergeEpicPullRequest({epicId:e.epicId,prNumber:p.prNumber,originBranch:e.originBranch,executionBranch:e.executionBranch,expectedStoryHeadSha:r.executionHeadSha,expectedPullRequestHeadSha:l.mergeSha,expectedOriginHeadSha:r.originHeadSha,candidateQa:l,candidateAuthority:u,nowIso:o(),terminalBinding:{graphRevision:e.graphRevision,storyCheckpointIds:e.storyCheckpointIds,aggregateQaReceipt:e.localGates.aggregateQaReceipt}});return a.ok?R(e,r,c,{strategy:"single_pr",prNumber:p.prNumber,mergeSha:a.mergeSha,pushedSha:a.pushedSha,candidateQa:l,providerGuard:a.providerGuard,physicalStatus:"pushed",retryEligible:!1,reasonCodes:[x.READY],completedAt:o()}):R(e,r,c,{strategy:"single_pr",prNumber:p.prNumber,physicalStatus:a.externalPolicy?"denied_external_gate":"blocked_local_or_repo",retryEligible:a.retryEligible,reasonCodes:[a.reasonCode,...a.retryEligible?[x.RETRY_ELIGIBLE]:[]]})}async function k(e,r,s,c){if(!e.enabled)return{ok:!0,receipts:[],preserved:[],reasonCodes:[]};const o=[],l=[],u=[];let p=!0;const a=new Set,h={pull_request:0,local_branch:1,remote_branch:2};for(const i of[...r].sort((n,g)=>h[n.kind]-h[g.kind]||n.resourceId.localeCompare(g.resourceId))){const n=N(i);if(u.push(...n.reasonCodes),n.action==="preserve"){l.push(n);continue}if(i.kind!=="pull_request"&&a.has(i.branchName)){l.push({...n,action:"preserve",reasonCodes:["git-resource-related-pr-close-pending"]}),u.push("git-resource-related-pr-close-pending");continue}const g=`reconciliation:v2:${w("sha256").update([i.resourceId,n.action].join("\0")).digest("hex")}`,d=await s.applyReconciliation(i,n,e.dryRun);if(!d.ok){p=!1,i.kind==="pull_request"&&a.add(i.branchName),u.push(d.reasonCode),o.push({schemaVersion:1,resourceId:i.resourceId,action:n.action,outcome:"failed",idempotencyKey:g,reasonCodes:[d.reasonCode],recordedAt:c(),publicSafe:!0});continue}o.push({schemaVersion:1,resourceId:i.resourceId,action:n.action,outcome:d.outcome,idempotencyKey:g,reasonCodes:n.reasonCodes,recordedAt:c(),publicSafe:!0})}return{ok:p,receipts:o,preserved:l,reasonCodes:C(u)}}function R(e,r,s,c){return Object.freeze({schemaVersion:1,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,baseSha:r.originHeadSha,executionHeadSha:r.executionHeadSha,localGateReceiptRefs:e.localGates.receiptRefs,idempotencyKey:e.idempotencyKey,attemptStartedAt:s,publicSafe:!0,...c})}function S(e,r,s){const c="0".repeat(40),o={schemaVersion:1,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,baseSha:c,executionHeadSha:e.expectedExecutionHeadSha,strategy:e.strategy==="single_pr"?"single_pr":"direct",physicalStatus:r.externalPolicy?"denied_external_gate":"blocked_local_or_repo",localGateReceiptRefs:e.localGates.receiptRefs,idempotencyKey:e.idempotencyKey,attemptStartedAt:s,retryEligible:r.retryEligible,reasonCodes:[r.reasonCode],publicSafe:!0};return y(!1,o,[],[],o.reasonCodes)}function y(e,r,s,c,o){return{ok:e,receipt:r,reconciliationReceipts:s,preservedDecisions:c,reasonCodes:C(o),publicSafe:!0}}function C(e){return[...new Set(e)]}export{O as executeEpicGitReconciliation,T as executeEpicTerminalGit};
1
+ import{createHash as K}from"node:crypto";import{EPIC_TERMINAL_GIT_REASON_CODES as x,classifyGitReconciliationCandidate as D,validateEpicTerminalGitDirective as $}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{consumeEpicTerminalReleaseAuthority as Q}from"../../git/git-lifecycle-store.js";import{verifiedEpicMergeCandidateReceipt as I}from"./epic-merge-candidate-qa.js";import{executeManagedEnvironmentCleanup as A}from"./managed-environment-cleanup.js";async function Y(e,n,t){const p=await n.inspectReconciliation(e);if(!p.ok)return{ok:!1,reconciliationReceipts:[],preservedDecisions:[],reasonCodes:[p.reasonCode],publicSafe:!0};const r=await B({idempotencyKey:e.idempotencyKey,enabled:!0,dryRun:e.dryRun},p.candidates,n,t),c=await n.persistReconciliation({epicId:e.epicId,reconciliationReceipts:r.receipts,preservedDecisions:r.preserved}),u=C([...r.reasonCodes,...c.ok?[]:[c.reasonCode]]);return{ok:r.ok&&c.ok,reconciliationReceipts:r.receipts,preservedDecisions:r.preserved,reasonCodes:u,publicSafe:!0}}async function V(e,n,t,p){const r=t();if(!n.prepareLifecycleEvidence)return S(e,{ok:!1,reasonCode:"epic-aggregate-qa-producer-required",retryEligible:!1,externalPolicy:!1},r);const c=p?{ok:!0,originBindingCaptured:!1,aggregateQaRecorded:!0,terminalAuthority:p}:await n.prepareLifecycleEvidence({epicId:e.epicId,nowIso:r});if(!c.ok)return S(e,c,r);const u=c.terminalAuthority??c.p205Authority;if(!u)return S(e,{ok:!1,reasonCode:"epic-aggregate-qa-authority-required",retryEligible:!1,externalPolicy:!1},r);const l=await n.inspect(e);if(!l.ok)return S(e,l,r);const a=l.snapshot,h=$(e,{...a,nowIso:r});if(!h.ready)return y(!1,m(e,a,r,{strategy:e.strategy==="single_pr"?"single_pr":"direct",physicalStatus:"blocked_local_or_repo",retryEligible:h.reasonCodes.some(s=>s.endsWith("mismatch")||s.endsWith("active")),reasonCodes:h.reasonCodes}),[],[],h.reasonCodes);if(!a.aggregateQaReceipt||!Q(u,{executionHeadSha:a.executionHeadSha,graphRevision:e.graphRevision,aggregateQaReceipt:a.aggregateQaReceipt,headReconciliationReceipt:a.headReconciliationReceipt}))return S(e,{ok:!1,reasonCode:"epic-aggregate-qa-authority-binding-mismatch",retryEligible:!1,externalPolicy:!1},r);if(h.reasonCodes.includes(x.ALREADY_COMPLETE)&&a.existingReceipt){const s=await n.verifyTerminalReceipt(e,a.existingReceipt,r);if(!s.ok)return y(!1,a.existingReceipt,[],[],[s.reasonCode]);const H=I(s.candidateAuthority,{mergeSha:a.existingReceipt.mergeSha,originHeadSha:a.existingReceipt.baseSha,executionHeadSha:a.existingReceipt.executionHeadSha,graphRevision:e.graphRevision});if(!H)return y(!1,a.existingReceipt,[],[],["epic-merge-candidate-authority-required"]);const G={...a.existingReceipt,candidateQa:H,...s.providerGuard?{providerGuard:s.providerGuard}:{}},f=await B({idempotencyKey:e.idempotencyKey,enabled:e.reconcile.enabled,dryRun:e.reconcile.dryRun},a.reconciliationCandidates,n,t),E=await A(a.managedEnvironmentCleanupRequests??[],n.managedEnvironmentCleanup,t),k=await n.persist({terminalReceipt:G,reconciliationReceipts:f.receipts,preservedDecisions:f.preserved,managedEnvironmentCleanupReceipts:E.receipts}),P=C([...h.reasonCodes,...f.reasonCodes,...E.reasonCodes,...k.ok?[]:[k.reasonCode]]);return y(k.ok&&f.ok&&E.ok,G,f.receipts,f.preserved,P,E)}let o;const i=await n.prepareMergeObject({originBranch:e.originBranch,executionBranch:e.executionBranch,originHeadSha:a.originHeadSha,executionHeadSha:a.executionHeadSha,graphRevision:e.graphRevision,nowIso:r,message:[`merge(${e.epicId}): integrate ${e.executionBranch} into ${e.originBranch}`,"",`Neocortex-Epic: ${e.epicId}`,`Neocortex-Origin-Branch: ${e.originBranch}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Execution-Head: ${a.executionHeadSha}`,`Neocortex-Origin-Base: ${a.originHeadSha}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Aggregate-QA: ${e.localGates.aggregateQaReceipt.receiptRef}`,`Neocortex-Idempotency: ${e.idempotencyKey}`].join(`
2
+ `)});if(!i.ok)return o=m(e,a,r,{strategy:"direct",physicalStatus:"blocked_local_or_repo",retryEligible:i.retryEligible,reasonCodes:[i.reasonCode]}),await n.persist({terminalReceipt:o,reconciliationReceipts:[],preservedDecisions:[]}),y(!1,o,[],[],o.reasonCodes);const g=I(i.candidateAuthority,{originHeadSha:a.originHeadSha,executionHeadSha:a.executionHeadSha,mergeSha:i.mergeSha,graphRevision:e.graphRevision});if(!g)return S(e,{ok:!1,reasonCode:"epic-merge-candidate-authority-required",retryEligible:!1,externalPolicy:!1},r);if(e.strategy!=="single_pr"){const s=await n.pushMergeObject({epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,executionHeadSha:a.executionHeadSha,expectedOriginSha:a.originHeadSha,mergeSha:i.mergeSha,graphRevision:e.graphRevision,candidateAuthority:i.candidateAuthority,storyCheckpointIds:e.storyCheckpointIds,aggregateQaReceipt:e.localGates.aggregateQaReceipt,nowIso:t()});s.ok?o=m(e,a,r,{strategy:"direct",mergeSha:i.mergeSha,pushedSha:s.pushedSha,candidateQa:g,physicalStatus:"pushed",retryEligible:!1,reasonCodes:[x.READY],completedAt:t()}):e.strategy==="direct_or_single_pr"&&s.externalPolicy?o=await q(e,a,n,r,t,g,i.candidateAuthority):o=m(e,a,r,{strategy:"direct",mergeSha:i.mergeSha,physicalStatus:s.externalPolicy?"denied_external_gate":"blocked_local_or_repo",retryEligible:s.retryEligible,reasonCodes:[s.reasonCode,...s.retryEligible?[x.RETRY_ELIGIBLE]:[]]})}else o=await q(e,a,n,r,t,g,i.candidateAuthority);const d=o.physicalStatus==="pushed"?await n.verifyTerminalReceipt(e,o,t()):null;if(d&&!d.ok){const s=m(e,a,r,{...o,physicalStatus:"blocked_local_or_repo",retryEligible:d.retryEligible,reasonCodes:[d.reasonCode]});return await n.persist({terminalReceipt:s,reconciliationReceipts:[],preservedDecisions:[]}),y(!1,s,[],[],s.reasonCodes)}if(d?.ok){const s=I(d.candidateAuthority,{mergeSha:o.mergeSha,originHeadSha:o.baseSha,executionHeadSha:o.executionHeadSha,graphRevision:e.graphRevision});if(!s)return y(!1,o,[],[],["epic-merge-candidate-authority-required"]);o={...o,candidateQa:s,...d.providerGuard?{providerGuard:d.providerGuard}:{}}}const R=o.physicalStatus==="pushed"?await B({idempotencyKey:e.idempotencyKey,enabled:e.reconcile.enabled,dryRun:e.reconcile.dryRun},a.reconciliationCandidates,n,t):{ok:!0,receipts:[],preserved:[],reasonCodes:[]},b=o.physicalStatus==="pushed"?await A(a.managedEnvironmentCleanupRequests??[],n.managedEnvironmentCleanup,t):w(),_=await n.persist({terminalReceipt:o,reconciliationReceipts:R.receipts,preservedDecisions:R.preserved,managedEnvironmentCleanupReceipts:b.receipts}),N=C([...o.reasonCodes,...R.reasonCodes,...b.reasonCodes,..._.ok?[]:[_.reasonCode]]);return y(o.physicalStatus==="pushed"&&R.ok&&b.ok&&_.ok,o,R.receipts,R.preserved,N,b)}async function q(e,n,t,p,r,c,u){const l=await t.ensureSingleEpicPullRequest({epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,expectedStoryHeadSha:n.executionHeadSha,expectedPullRequestHeadSha:c.mergeSha,candidateQa:c,candidateAuthority:u,idempotencyKey:e.idempotencyKey,terminalBinding:{graphRevision:e.graphRevision,storyCheckpointIds:e.storyCheckpointIds,aggregateQaReceipt:e.localGates.aggregateQaReceipt,nowIso:r()}});if(!l.ok)return m(e,n,p,{strategy:"single_pr",physicalStatus:l.externalPolicy?"denied_external_gate":"blocked_local_or_repo",retryEligible:l.retryEligible,reasonCodes:[l.reasonCode]});const a=await t.mergeEpicPullRequest({epicId:e.epicId,prNumber:l.prNumber,originBranch:e.originBranch,executionBranch:e.executionBranch,expectedStoryHeadSha:n.executionHeadSha,expectedPullRequestHeadSha:c.mergeSha,expectedOriginHeadSha:n.originHeadSha,candidateQa:c,candidateAuthority:u,nowIso:r(),terminalBinding:{graphRevision:e.graphRevision,storyCheckpointIds:e.storyCheckpointIds,aggregateQaReceipt:e.localGates.aggregateQaReceipt}});return a.ok?m(e,n,p,{strategy:"single_pr",prNumber:l.prNumber,mergeSha:a.mergeSha,pushedSha:a.pushedSha,candidateQa:c,providerGuard:a.providerGuard,physicalStatus:"pushed",retryEligible:!1,reasonCodes:[x.READY],completedAt:r()}):m(e,n,p,{strategy:"single_pr",prNumber:l.prNumber,physicalStatus:a.externalPolicy?"denied_external_gate":"blocked_local_or_repo",retryEligible:a.retryEligible,reasonCodes:[a.reasonCode,...a.retryEligible?[x.RETRY_ELIGIBLE]:[]]})}async function B(e,n,t,p){if(!e.enabled)return{ok:!0,receipts:[],preserved:[],reasonCodes:[]};const r=[],c=[],u=[];let l=!0;const a=new Set,h={pull_request:0,local_branch:1,remote_branch:2};for(const o of[...n].sort((i,g)=>h[i.kind]-h[g.kind]||i.resourceId.localeCompare(g.resourceId))){const i=D(o);if(u.push(...i.reasonCodes),i.action==="preserve"){c.push(i);continue}if(o.kind!=="pull_request"&&a.has(o.branchName)){c.push({...i,action:"preserve",reasonCodes:["git-resource-related-pr-close-pending"]}),u.push("git-resource-related-pr-close-pending");continue}const g=`reconciliation:v2:${K("sha256").update([o.resourceId,i.action].join("\0")).digest("hex")}`,d=await t.applyReconciliation(o,i,e.dryRun);if(!d.ok){l=!1,o.kind==="pull_request"&&a.add(o.branchName),u.push(d.reasonCode),r.push({schemaVersion:1,resourceId:o.resourceId,action:i.action,outcome:"failed",idempotencyKey:g,reasonCodes:[d.reasonCode],recordedAt:p(),publicSafe:!0});continue}r.push({schemaVersion:1,resourceId:o.resourceId,action:i.action,outcome:d.outcome,idempotencyKey:g,reasonCodes:i.reasonCodes,recordedAt:p(),publicSafe:!0})}return{ok:l,receipts:r,preserved:c,reasonCodes:C(u)}}function m(e,n,t,p){return Object.freeze({schemaVersion:1,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,baseSha:n.originHeadSha,executionHeadSha:n.executionHeadSha,localGateReceiptRefs:e.localGates.receiptRefs,idempotencyKey:e.idempotencyKey,attemptStartedAt:t,publicSafe:!0,...p})}function S(e,n,t){const p="0".repeat(40),r={schemaVersion:1,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,baseSha:p,executionHeadSha:e.expectedExecutionHeadSha,strategy:e.strategy==="single_pr"?"single_pr":"direct",physicalStatus:n.externalPolicy?"denied_external_gate":"blocked_local_or_repo",localGateReceiptRefs:e.localGates.receiptRefs,idempotencyKey:e.idempotencyKey,attemptStartedAt:t,retryEligible:n.retryEligible,reasonCodes:[n.reasonCode],publicSafe:!0};return y(!1,r,[],[],r.reasonCodes)}function y(e,n,t,p,r,c=w()){return{ok:e,receipt:n,reconciliationReceipts:t,preservedDecisions:p,managedEnvironmentCleanupReceipts:c.receipts,managedEnvironmentCleanupPending:c.pending,reasonCodes:C(r),publicSafe:!0}}function w(){return{ok:!0,pending:!1,receipts:[],reasonCodes:[],publicSafe:!0}}function C(e){return[...new Set(e)]}export{Y as executeEpicGitReconciliation,V as executeEpicTerminalGit};
@@ -0,0 +1,95 @@
1
+ /**
2
+ * P224.05 -- fail-closed cleanup of explicitly managed temporary resources.
3
+ *
4
+ * This module owns policy and replay ordering only. Concrete host, process and
5
+ * interface effects stay behind an injected adapter. Production callers that
6
+ * do not have a supported adapter preserve resources as pending.
7
+ */
8
+ export type ManagedEnvironmentResourceKind = 'worktree' | 'process' | 'interface_entry';
9
+ export type ManagedEnvironmentEffect = 'remove_managed_worktree' | 'stop_owned_process' | 'remove_interface_entry';
10
+ export interface ManagedEnvironmentCleanupReceiptV1 {
11
+ readonly schemaVersion: 1;
12
+ readonly resourceId: string;
13
+ readonly effect: ManagedEnvironmentEffect;
14
+ readonly outcome: 'applied' | 'already_absent' | 'preserved' | 'failed';
15
+ readonly expectedOwnerDigest: string;
16
+ readonly expectedRevision: string;
17
+ readonly idempotencyKey: string;
18
+ readonly reasonCodes: readonly string[];
19
+ readonly checkedAt: string;
20
+ readonly recordedAt: string;
21
+ readonly publicSafe: true;
22
+ }
23
+ export interface ManagedEnvironmentCleanupRequestV1 {
24
+ readonly schemaVersion: 1;
25
+ readonly resourceId: string;
26
+ readonly epicId: string;
27
+ readonly expectedKind: ManagedEnvironmentResourceKind;
28
+ readonly expectedOwnerDigest: string;
29
+ readonly expectedRevision: string;
30
+ readonly effect: ManagedEnvironmentEffect;
31
+ readonly existingReceipt?: ManagedEnvironmentCleanupReceiptV1;
32
+ readonly publicSafe: true;
33
+ }
34
+ export interface ManagedEnvironmentSnapshotV1 {
35
+ readonly schemaVersion: 1;
36
+ readonly resourceId: string;
37
+ readonly epicId: string;
38
+ readonly ownerDigest: string;
39
+ readonly revision: string;
40
+ readonly kind: ManagedEnvironmentResourceKind;
41
+ readonly presence: 'present' | 'absent' | 'unknown';
42
+ readonly managed: boolean;
43
+ readonly active: boolean;
44
+ readonly clean: boolean | 'unknown';
45
+ readonly integrated: boolean;
46
+ readonly capability: 'supported' | 'unsupported';
47
+ readonly protected: boolean;
48
+ readonly primary: boolean;
49
+ readonly locked: boolean;
50
+ readonly submoduleActive: boolean;
51
+ readonly preservableIgnored: boolean;
52
+ readonly publicSafe: true;
53
+ }
54
+ export type ManagedEnvironmentEffectResult<T extends object> = ({
55
+ readonly ok: true;
56
+ } & T) | {
57
+ readonly ok: false;
58
+ readonly reasonCode: string;
59
+ };
60
+ export interface ManagedEnvironmentCleanupAdapter {
61
+ inspect(request: ManagedEnvironmentCleanupRequestV1): Promise<ManagedEnvironmentEffectResult<{
62
+ readonly snapshot: ManagedEnvironmentSnapshotV1;
63
+ }>>;
64
+ apply(input: {
65
+ readonly request: ManagedEnvironmentCleanupRequestV1;
66
+ readonly snapshot: ManagedEnvironmentSnapshotV1;
67
+ readonly effect: ManagedEnvironmentEffect;
68
+ readonly idempotencyKey: string;
69
+ }): Promise<ManagedEnvironmentEffectResult<{
70
+ readonly receipt: ManagedEnvironmentCleanupReceiptV1;
71
+ }>>;
72
+ reconcile(input: {
73
+ readonly request: ManagedEnvironmentCleanupRequestV1;
74
+ readonly receipt: ManagedEnvironmentCleanupReceiptV1;
75
+ }): Promise<ManagedEnvironmentEffectResult<{
76
+ readonly receipt: ManagedEnvironmentCleanupReceiptV1;
77
+ }>>;
78
+ }
79
+ export interface ManagedEnvironmentCleanupResult {
80
+ readonly ok: boolean;
81
+ readonly pending: boolean;
82
+ readonly receipts: readonly ManagedEnvironmentCleanupReceiptV1[];
83
+ readonly reasonCodes: readonly string[];
84
+ readonly publicSafe: true;
85
+ }
86
+ interface Classification {
87
+ readonly action: 'apply' | 'already_absent' | 'preserve';
88
+ readonly pending: boolean;
89
+ readonly reasonCodes: readonly string[];
90
+ }
91
+ /** Reconcile durable evidence before any new effect, then apply at most once. */
92
+ export declare function executeManagedEnvironmentCleanup(requests: readonly ManagedEnvironmentCleanupRequestV1[], adapter: ManagedEnvironmentCleanupAdapter | undefined, now: () => string): Promise<ManagedEnvironmentCleanupResult>;
93
+ export declare function classifyManagedEnvironmentSnapshot(request: ManagedEnvironmentCleanupRequestV1, snapshot: ManagedEnvironmentSnapshotV1): Classification;
94
+ export declare function managedEnvironmentCleanupIdempotencyKey(request: Pick<ManagedEnvironmentCleanupRequestV1, 'resourceId' | 'effect' | 'expectedOwnerDigest' | 'expectedRevision'>): string;
95
+ export {};
@@ -0,0 +1 @@
1
+ import{createHash as E}from"node:crypto";const D={remove_managed_worktree:"worktree",stop_owned_process:"process",remove_interface_entry:"interface_entry"};async function M(e,n,c){const t=[],a=[],h=new Set;let d=!1,s=!1;for(const r of e){const R=`${r.resourceId}\0${r.effect}`;if(h.has(R)){const i=m(r,I(r),"managed-environment-request-duplicate",c());t.push(i),a.push(...i.reasonCodes),d=!0,s=!0;continue}h.add(R);const w=$(r);if(w){const i=m(r,I(r),w,c());t.push(i),a.push(w),d=!0,s=!0;continue}const u=I(r);if(!n){const i=x(r,u,"preserved",["managed-environment-capability-unsupported"],c());t.push(i),a.push(...i.reasonCodes),d=!0;continue}if(r.existingReceipt){if(!k(r.existingReceipt,r)||r.existingReceipt.idempotencyKey!==u){const b=m(r,u,"managed-environment-receipt-binding-mismatch",c());t.push(b),a.push(...b.reasonCodes),d=!0,s=!0;continue}const i=await n.reconcile({request:r,receipt:r.existingReceipt});if(!i.ok||!k(i.receipt,r)||i.receipt.idempotencyKey!==u){const b=i.ok?"managed-environment-receipt-binding-mismatch":i.reasonCode,A=m(r,u,b,c());t.push(A),a.push(b),d=!0,s=!0;continue}const f=K(i.receipt);if(f.failed||!f.pending){t.push(i.receipt),a.push(...i.receipt.reasonCodes),d||=f.pending,s||=f.failed;continue}}const y=await n.inspect(r);if(!y.ok){const i=m(r,u,y.reasonCode,c());t.push(i),a.push(y.reasonCode),d=!0,s=!0;continue}const l=V(r,y.snapshot);if(a.push(...l.reasonCodes),l.action==="preserve"){t.push(x(r,u,"preserved",l.reasonCodes,c())),d||=l.pending;continue}if(l.action==="already_absent"){t.push(x(r,u,"already_absent",l.reasonCodes,c()));continue}const g=await n.apply({request:r,snapshot:y.snapshot,effect:r.effect,idempotencyKey:u});if(!g.ok||!k(g.receipt,r)||g.receipt.idempotencyKey!==u){const i=g.ok?"managed-environment-receipt-binding-mismatch":g.reasonCode,f=m(r,u,i,c());t.push(f),a.push(i),d=!0,s=!0;continue}const p=await n.reconcile({request:r,receipt:g.receipt});if(!p.ok||!k(p.receipt,r)||p.receipt.idempotencyKey!==u){const i=p.ok?"managed-environment-receipt-binding-mismatch":p.reasonCode,f=m(r,u,i,c());t.push(f),a.push(i),d=!0,s=!0;continue}t.push(p.receipt),a.push(...p.receipt.reasonCodes);const _=K(p.receipt);d||=_.pending,s||=_.failed}return{ok:!s&&!d,pending:d,receipts:t,reasonCodes:S(a),publicSafe:!0}}function V(e,n){return N(n)?n.resourceId!==e.resourceId||n.epicId!==e.epicId?o(!1,"managed-environment-identity-mismatch"):n.kind!==e.expectedKind||D[e.effect]!==n.kind?o(!1,"managed-environment-kind-mismatch"):n.managed?n.ownerDigest!==e.expectedOwnerDigest?o(!1,"managed-environment-owner-replaced"):n.revision!==e.expectedRevision?o(!1,"managed-environment-revision-stale"):n.presence==="absent"?{action:"already_absent",pending:!1,reasonCodes:["managed-environment-already-absent"]}:n.presence!=="present"?o(!0,"managed-environment-presence-unknown"):n.capability!=="supported"?o(!0,"managed-environment-capability-unsupported"):n.primary?o(!0,"managed-environment-primary-preserved"):n.protected?o(!0,"managed-environment-protected"):n.active?o(!0,"managed-environment-active"):n.locked?o(!0,"managed-environment-locked"):n.submoduleActive?o(!0,"managed-environment-submodule-active"):n.clean==="unknown"?o(!0,"managed-environment-cleanliness-unknown"):n.clean?n.preservableIgnored?o(!0,"managed-environment-preservable-ignored"):n.integrated?{action:"apply",pending:!1,reasonCodes:[]}:o(!0,"managed-environment-integration-unproven"):o(!0,"managed-environment-dirty"):o(!1,"managed-environment-ownership-unproven"):o(!0,"managed-environment-snapshot-invalid")}function I(e){return`environment-cleanup:v1:${E("sha256").update([e.resourceId,e.effect,e.expectedOwnerDigest,e.expectedRevision].join("\0")).digest("hex")}`}function $(e){return e.schemaVersion!==1||e.publicSafe!==!0||!v(e.resourceId)||!v(e.epicId)||!C(e.expectedOwnerDigest)||!C(e.expectedRevision)||D[e.effect]!==e.expectedKind?"managed-environment-request-invalid":null}function N(e){return e.schemaVersion===1&&e.publicSafe===!0&&v(e.resourceId)&&v(e.epicId)&&C(e.ownerDigest)&&C(e.revision)&&["worktree","process","interface_entry"].includes(e.kind)&&["present","absent","unknown"].includes(e.presence)&&["supported","unsupported"].includes(e.capability)&&(typeof e.clean=="boolean"||e.clean==="unknown")&&[e.managed,e.active,e.integrated,e.protected,e.primary,e.locked,e.submoduleActive,e.preservableIgnored].every(n=>typeof n=="boolean")}function k(e,n){return e.schemaVersion===1&&e.publicSafe===!0&&e.resourceId===n.resourceId&&e.effect===n.effect&&e.expectedOwnerDigest===n.expectedOwnerDigest&&e.expectedRevision===n.expectedRevision&&["applied","already_absent","preserved","failed"].includes(e.outcome)&&v(e.idempotencyKey)&&e.reasonCodes.length<=128&&e.reasonCodes.every(v)&&O(e.checkedAt)&&O(e.recordedAt)}function K(e){return e.outcome==="failed"?{pending:!0,failed:!0}:e.outcome!=="preserved"?{pending:!1,failed:!1}:{pending:!e.reasonCodes.every(c=>["managed-environment-ownership-unproven","managed-environment-owner-replaced","managed-environment-revision-stale","managed-environment-kind-mismatch","managed-environment-identity-mismatch"].includes(c)),failed:!1}}function o(e,n){return{action:"preserve",pending:e,reasonCodes:[n]}}function x(e,n,c,t,a){return{schemaVersion:1,resourceId:e.resourceId,effect:e.effect,outcome:c,expectedOwnerDigest:e.expectedOwnerDigest,expectedRevision:e.expectedRevision,idempotencyKey:n,reasonCodes:S(t),checkedAt:a,recordedAt:a,publicSafe:!0}}function m(e,n,c,t){return x(e,n,"failed",[c],t)}function v(e){return typeof e=="string"&&e.length>0&&e.length<=240&&/^[A-Za-z0-9._:/@#-]+$/.test(e)}function C(e){return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)}function O(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function S(e){return[...new Set(e)]}export{V as classifyManagedEnvironmentSnapshot,M as executeManagedEnvironmentCleanup,I as managedEnvironmentCleanupIdempotencyKey};