@ornexus/neocortex 4.66.9 → 4.66.11
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 +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/invoke.d.ts +4 -1
- package/packages/client/dist/commands/invoke.js +81 -78
- package/packages/client/dist/errors/error-messages.js +2 -2
- package/packages/client/dist/errors/transport-failure.d.ts +5 -0
- package/packages/client/dist/errors/transport-failure.js +1 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/git/epic-state-recovery.d.ts +6 -0
- package/packages/client/dist/git/epic-state-recovery.js +2 -0
- package/packages/client/dist/git/published-story-reconciliation.d.ts +15 -0
- package/packages/client/dist/git/published-story-reconciliation.js +4 -2
- package/packages/client/dist/license/license-client.js +1 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.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-sentinel.md +1 -1
- 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 +12 -7
- package/targets-stubs/codex/neocortex-sentinel.toml +5 -0
- package/targets-stubs/codex/neocortex.toml +5 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const r="support@neocortex.sh",c={AUTH_REFRESH_REQUIRED:{en:{summary:"Authentication requires a causal check.",whatHappened:"Credentials are configured, but the reason a valid token is unavailable was not classified. The current login and credential store were preserved.",whatToDo:"Run the local read-only authentication doctor, then follow its cause-specific action. Do not re-activate unless revocation is confirmed.",command:"neocortex-client auth-doctor --format plain"},"pt-BR":{summary:"A autentica\xE7\xE3o exige uma verifica\xE7\xE3o causal.",whatHappened:"As credenciais est\xE3o configuradas, mas a causa da indisponibilidade de um token v\xE1lido n\xE3o foi classificada. O login atual e o store de credenciais foram preservados.",whatToDo:"Execute o diagn\xF3stico local somente leitura e siga a a\xE7\xE3o espec\xEDfica da causa. N\xE3o reative sem revoga\xE7\xE3o confirmada.",command:"neocortex-client auth-doctor --format plain"}},AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${r} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${r}.`}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function n(a=process.env){return(a.LC_ALL??a.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function u(a,o=n()){const e=c[a];return e?e[o]??e.en??null:null}function p(a,o=n()){const e=o==="pt-BR",t={"near-expiry":{en:"Prepare authentication outside strict read-only mode, then retry once.",pt:"Prepare a autentica\xE7\xE3o fora do modo estritamente somente leitura e tente uma vez."},expired:{en:"Prepare authentication outside strict read-only mode.",pt:"Prepare a autentica\xE7\xE3o fora do modo estritamente somente leitura."},"store-unavailable":{en:"Restore access to the local credential store; do not delete it.",pt:"Restaure o acesso ao store local; n\xE3o o apague."},"store-corrupt":{en:"Stop and recover the credential store explicitly; do not overwrite it.",pt:"Pare e recupere o store de credenciais explicitamente; n\xE3o o sobrescreva."},"keychain-unavailable":{en:"Unlock or restore the system keychain, then retry.",pt:"Desbloqueie ou restaure o keychain do sistema e tente novamente."},"transport-error":{en:"Check connectivity and retry later; the current login was preserved.",pt:"Verifique a conex\xE3o e tente depois; o login atual foi preservado."},timeout:{en:"Stop the current recovery and retry only after its outcome is known.",pt:"Pare a recupera\xE7\xE3o atual e tente novamente somente ap\xF3s conhecer o resultado."},"rate-limited":{en:"Wait for the retry window while preserving the current login.",pt:"Aguarde a janela de nova tentativa preservando o login atual."},"service-unavailable":{en:"Retry later; do not clear local authentication.",pt:"Tente novamente depois; n\xE3o limpe a autentica\xE7\xE3o local."},revoked:{en:"Re-activate with an authorized license credential.",pt:"Reative com uma credencial de licen\xE7a autorizada.",command:e?"neocortex activate SUA-LICENSE-KEY":"neocortex activate YOUR-LICENSE-KEY"},"scope-denied":{en:"Request the required scope; do not elevate it locally.",pt:"Solicite o escopo necess\xE1rio; n\xE3o o eleve localmente."},"client-denied":{en:"Stop and restore the authorized client policy.",pt:"Pare e restaure a pol\xEDtica de cliente autorizada."},"protocol-invalid":{en:"Stop and inspect the supported authentication contract.",pt:"Pare e inspecione o contrato de autentica\xE7\xE3o suportado."},"persistence-failed":{en:"Recover explicitly; do not repeat refresh or restore an older credential.",pt:"Recupere explicitamente; n\xE3o repita o refresh nem restaure uma credencial anterior."},"rotation-uncertain":{en:"Stop and recover explicitly; do not repeat refresh.",pt:"Pare e fa\xE7a recupera\xE7\xE3o expl\xEDcita; n\xE3o repita o refresh."},"capability-unavailable":{en:"Use a supported host capability; do not export credentials.",pt:"Use uma capability de host suportada; n\xE3o exporte credenciais."},"revision-conflict":{en:"Wait for the current owner and re-read the accepted generation.",pt:"Aguarde o owner atual e releia a gera\xE7\xE3o aceita."}}[a];return{summary:e?"A autentica\xE7\xE3o requer uma a\xE7\xE3o causal.":"Authentication requires a causal action.",whatHappened:e?`A causa confirmada \xE9 ${a}; nenhum segredo ou corpo bruto foi exibido.`:`The confirmed cause is ${a}; no secret or raw response body was exposed.`,whatToDo:e?t.pt:t.en,...t.command?{command:t.command}:{}}}function l(a,o=n()){const e=[];e.push(""),e.push(`[Neocortex] ${a.summary}`),e.push("");const i=o==="pt-BR"?"O que aconteceu":"What happened",t=o==="pt-BR"?"O que fazer":"What to do",s=o==="pt-BR"?`Precisa de ajuda? ${r}`:`Need help? ${r}`;return e.push(`${i}: ${a.whatHappened}`),e.push(`${t}: ${a.whatToDo}`),a.command&&(e.push(""),e.push(` ${a.command}`)),a.url&&(e.push(""),e.push(` ${a.url}`)),e.push(""),e.push(s),e.push(""),e.join(`
|
|
2
|
-
`)}function d(
|
|
1
|
+
const r="support@neocortex.sh",c={AUTH_REFRESH_REQUIRED:{en:{summary:"Authentication requires a causal check.",whatHappened:"Credentials are configured, but the reason a valid token is unavailable was not classified. The current login and credential store were preserved.",whatToDo:"Run the local read-only authentication doctor, then follow its cause-specific action. Do not re-activate unless revocation is confirmed.",command:"neocortex-client auth-doctor --format plain"},"pt-BR":{summary:"A autentica\xE7\xE3o exige uma verifica\xE7\xE3o causal.",whatHappened:"As credenciais est\xE3o configuradas, mas a causa da indisponibilidade de um token v\xE1lido n\xE3o foi classificada. O login atual e o store de credenciais foram preservados.",whatToDo:"Execute o diagn\xF3stico local somente leitura e siga a a\xE7\xE3o espec\xEDfica da causa. N\xE3o reative sem revoga\xE7\xE3o confirmada.",command:"neocortex-client auth-doctor --format plain"}},AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${r} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${r}.`}},NETWORK_ERROR:{en:{summary:"Connection to Neocortex failed.",whatHappened:"The client could not complete the HTTPS exchange. The credential store was preserved.",whatToDo:"Run the online doctor in the same terminal or editor session to check access to the API.",command:"neocortex-client doctor --json"},"pt-BR":{summary:"Falha na conex\xE3o com o Neocortex.",whatHappened:"O cliente n\xE3o conseguiu concluir a comunica\xE7\xE3o HTTPS. As credenciais locais foram preservadas.",whatToDo:"Execute o doctor no mesmo terminal ou editor para verificar o acesso \xE0 API.",command:"neocortex-client doctor --json"}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function n(o=process.env){return(o.LC_ALL??o.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function u(o,a=n()){const e=c[o];return e?e[a]??e.en??null:null}function p(o,a=n()){const e=a==="pt-BR",t={"near-expiry":{en:"Prepare authentication outside strict read-only mode, then retry once.",pt:"Prepare a autentica\xE7\xE3o fora do modo estritamente somente leitura e tente uma vez."},expired:{en:"Prepare authentication outside strict read-only mode.",pt:"Prepare a autentica\xE7\xE3o fora do modo estritamente somente leitura."},"store-unavailable":{en:"Restore access to the local credential store; do not delete it.",pt:"Restaure o acesso ao store local; n\xE3o o apague."},"store-corrupt":{en:"Stop and recover the credential store explicitly; do not overwrite it.",pt:"Pare e recupere o store de credenciais explicitamente; n\xE3o o sobrescreva."},"keychain-unavailable":{en:"Unlock or restore the system keychain, then retry.",pt:"Desbloqueie ou restaure o keychain do sistema e tente novamente."},"transport-error":{en:"Check connectivity and retry later; the current login was preserved.",pt:"Verifique a conex\xE3o e tente depois; o login atual foi preservado."},timeout:{en:"Stop the current recovery and retry only after its outcome is known.",pt:"Pare a recupera\xE7\xE3o atual e tente novamente somente ap\xF3s conhecer o resultado."},"rate-limited":{en:"Wait for the retry window while preserving the current login.",pt:"Aguarde a janela de nova tentativa preservando o login atual."},"service-unavailable":{en:"Retry later; do not clear local authentication.",pt:"Tente novamente depois; n\xE3o limpe a autentica\xE7\xE3o local."},revoked:{en:"Re-activate with an authorized license credential.",pt:"Reative com uma credencial de licen\xE7a autorizada.",command:e?"neocortex activate SUA-LICENSE-KEY":"neocortex activate YOUR-LICENSE-KEY"},"scope-denied":{en:"Request the required scope; do not elevate it locally.",pt:"Solicite o escopo necess\xE1rio; n\xE3o o eleve localmente."},"client-denied":{en:"Stop and restore the authorized client policy.",pt:"Pare e restaure a pol\xEDtica de cliente autorizada."},"protocol-invalid":{en:"Stop and inspect the supported authentication contract.",pt:"Pare e inspecione o contrato de autentica\xE7\xE3o suportado."},"persistence-failed":{en:"Recover explicitly; do not repeat refresh or restore an older credential.",pt:"Recupere explicitamente; n\xE3o repita o refresh nem restaure uma credencial anterior."},"rotation-uncertain":{en:"Stop and recover explicitly; do not repeat refresh.",pt:"Pare e fa\xE7a recupera\xE7\xE3o expl\xEDcita; n\xE3o repita o refresh."},"capability-unavailable":{en:"Use a supported host capability; do not export credentials.",pt:"Use uma capability de host suportada; n\xE3o exporte credenciais."},"revision-conflict":{en:"Wait for the current owner and re-read the accepted generation.",pt:"Aguarde o owner atual e releia a gera\xE7\xE3o aceita."}}[o];return{summary:e?"A autentica\xE7\xE3o requer uma a\xE7\xE3o causal.":"Authentication requires a causal action.",whatHappened:e?`A causa confirmada \xE9 ${o}; nenhum segredo ou corpo bruto foi exibido.`:`The confirmed cause is ${o}; no secret or raw response body was exposed.`,whatToDo:e?t.pt:t.en,...t.command?{command:t.command}:{}}}function l(o,a=n()){const e=[];e.push(""),e.push(`[Neocortex] ${o.summary}`),e.push("");const i=a==="pt-BR"?"O que aconteceu":"What happened",t=a==="pt-BR"?"O que fazer":"What to do",s=a==="pt-BR"?`Precisa de ajuda? ${r}`:`Need help? ${r}`;return e.push(`${i}: ${o.whatHappened}`),e.push(`${t}: ${o.whatToDo}`),o.command&&(e.push(""),e.push(` ${o.command}`)),o.url&&(e.push(""),e.push(` ${o.url}`)),e.push(""),e.push(s),e.push(""),e.join(`
|
|
2
|
+
`)}function d(o){if(!o||typeof o!="object")return null;const a=o;return typeof a.code=="string"&&(a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"||a.code==="ETIMEDOUT"||a.code==="ECONNRESET")||typeof a.message=="string"&&(/connect/i.test(a.message)&&/refus/i.test(a.message)||/fetch failed/i.test(a.message))?"ECONNREFUSED":null}export{n as detectErrorLocale,l as formatHumanizedError,p as humanizeAuthRefreshRequired,u as humanizeError,d as inferErrorCodeFromException};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type TransportFailureCause = 'dns-resolution' | 'tls-verification' | 'connection-unavailable' | 'transport-error' | 'timeout';
|
|
2
|
+
/** Classify only known runtime error codes. Messages and addresses stay local. */
|
|
3
|
+
export declare function classifyTransportFailure(error: unknown, timedOut: boolean): TransportFailureCause;
|
|
4
|
+
/** These codes occur during DNS or connection setup, before HTTP can dispatch. */
|
|
5
|
+
export declare function mayRetryBeforeDispatch(error: unknown): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function N(_){return _ instanceof Error?_.cause instanceof Error?_.cause:_:{}}function n(_,T){const{code:E,name:r}=N(_);return T||r==="TimeoutError"||E==="UND_ERR_CONNECT_TIMEOUT"||E==="UND_ERR_HEADERS_TIMEOUT"||E==="UND_ERR_BODY_TIMEOUT"||E==="ETIMEDOUT"?"timeout":E==="ENOTFOUND"||E==="EAI_AGAIN"?"dns-resolution":E==="CERT_HAS_EXPIRED"||E==="CERT_NOT_YET_VALID"||E==="ERR_TLS_CERT_ALTNAME_INVALID"||E==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||E==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||E==="DEPTH_ZERO_SELF_SIGNED_CERT"||E==="SELF_SIGNED_CERT_IN_CHAIN"?"tls-verification":E==="ECONNREFUSED"||E==="ENETUNREACH"||E==="EHOSTUNREACH"||E==="ECONNRESET"?"connection-unavailable":"transport-error"}function t(_){const{code:T}=N(_);return T==="EAI_AGAIN"||T==="ECONNREFUSED"||T==="ENETUNREACH"||T==="EHOSTUNREACH"||T==="UND_ERR_CONNECT_TIMEOUT"}export{n as classifyTransportFailure,t as mayRetryBeforeDispatch};
|
|
@@ -259,7 +259,7 @@ export declare function persistDirectYoloWaveStoryCheckpoint(input: {
|
|
|
259
259
|
/** P230.05 (REQ-04): the graph revision this commit was verified against before any effect. */
|
|
260
260
|
readonly expectedGraphRevision?: string;
|
|
261
261
|
}): Promise<DirectYoloCheckpointResult<StoryCommitCheckpoint>>;
|
|
262
|
-
declare function resolveLogicalAuthority(projectRootInput: string, storyId: string): Promise<{
|
|
262
|
+
declare function resolveLogicalAuthority(projectRootInput: string, storyId: string, loadRootMemoryEffect?: boolean): Promise<{
|
|
263
263
|
projectRoot: string;
|
|
264
264
|
storyId: string;
|
|
265
265
|
story: Record<string, unknown>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile as St}from"node:child_process";import{createHash as It,randomBytes as Ee,timingSafeEqual as xt}from"node:crypto";import{existsSync as fe}from"node:fs";import{readFile as M,realpath as je}from"node:fs/promises";import{join as U,resolve as $}from"node:path";import{promisify as bt}from"node:util";import{readRootMemoryEffectForCheckpoint as kt}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as Dt,verifyRootMemoryPhysicalWriteSet as Ae}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as Et,resolveEpicStoryIds as jt}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as _e,storyWriteSetCovers as et,validateStoryWriteScope as At}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as K,applyGitLifecycleRuntimeOverlay as Be,computeImmutableStoryQaEvidenceDigest as _t,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as ue,computeP205StoryQaEvidenceDigest as Bt,computeLegacyDirectYoloRecoveryReceiptRef as Ct,ensureRuntimeEpic as P,ensureRuntimeStory as Ce,ensureGitLifecyclePrivateChildDirectory as He,executeP205TransientAuthorities as Ht,executeP205TransientAuthority as Ot,isP226GateReasonCode as Oe,projectP205TransientExecutionEvidence as tt,publicStoryReviewArtifactFromBytes as $t,publicStoryReviewArtifactFromGit as pe,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Lt,mutateGitLifecycleRuntime as L,P205_COMPLETE_COMMAND as rt,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as $e,STORY_WRITE_SET_MAX_ENTRIES as ot,storyWriteSetExtensionPaths as Nt,assertGitLifecyclePrivateFile as Z,releaseGitLifecyclePhysicalIntegrationLock as V,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as qt,verifyGitLifecyclePhysicalIntegrationLock as le,verifyAcceptedGitLifecycleStoryCheckpoint as Le}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Ne,anchoredRemoveFile as it}from"./secure-filesystem-boundary.js";import{GOVERNANCE_CHECKPOINT_TRAILER_KEYS as nt,GOVERNANCE_DIGEST_TRAILER as at,GOVERNANCE_REASON_CODES as he,captureStoryGovernanceSync as Pt,detectGovernanceModeSync as Tt,governanceReceiptRefs as zt,isGovernanceRepositoryPath as Gt,readGovernanceStateSourceSync as Wt,storyReviewGovernancePath as Mt,verifyStoryGovernanceBinding as Kt}from"./governance-runtime-store.js";import{parseNeocortexTrailers as ct,trailerReasonKey as ye,trailerValue as ie}from"./neocortex-trailers.js";import{StoryWorktreeManager as Vt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ft,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as st,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as T}from"./git-lifecycle-step-ids.js";const ne=bt(St),ae=3600*1e3;async function qr(e){let t,o=!1;try{const r=await me(e.projectRoot,e.storyId);if(await Pe(r.projectRoot)){if(e.expiredSetupRecovery)return a("direct-yolo-expired-setup-recovery-invalid");const S=await dt(r);return{ok:!0,value:ft(r,S,!1)}}const i=N(e.nowIso),n=Date.parse(i),f=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),p=await O(r.projectRoot,{required:!0}),s=g(p.epics[r.epicId]),d=g(s?.branch_lease),u=e.expiredSetupRecovery;if(u&&!pr(u,p.revision,d,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const w=d&&Number.isFinite(Date.parse(String(d.expiresAt)))&&Date.parse(String(d.expiresAt))>n;if(w&&d?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let h=Y(s?.origin_binding,r.executionBranch,r.originBranch),y;if(f===r.executionBranch){if(!h){if(s?.origin_binding!==void 0&&s?.origin_binding!==null||w)return a("direct-yolo-origin-binding-invalid");const S=await gr(r,c,i);if(!S.ok)return S;h=S.value.binding,y={originRef:S.value.originRef,originHeadSha:S.value.binding.originHeadSha}}}else{if(f!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(h&&h.originHeadSha!==c){if(!u||!await C(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,c]))return a("direct-yolo-origin-binding-conflict");const m=`refs/heads/${r.executionBranch}`;if(!await C(r.projectRoot,["show-ref","--verify","--quiet",m]))return a("direct-yolo-execution-branch-missing");const j=await l(r.projectRoot,["rev-parse",m]);if(!await C(r.projectRoot,["merge-base","--is-ancestor",j,c]))return a("direct-yolo-execution-branch-diverged")}if(h??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await se(r.projectRoot)).some(m=>m.branch===r.executionBranch&&$(m.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const b=await G(r.projectRoot),A=`refs/heads/${r.executionBranch}`;if(await C(r.projectRoot,["show-ref","--verify","--quiet",A])){const m=await l(r.projectRoot,["rev-parse",A]);if(m!==c){if(!await C(r.projectRoot,["merge-base","--is-ancestor",m,c]))return a("direct-yolo-execution-branch-diverged");u||await l(r.projectRoot,["update-ref",A,c,m])}u?t={checkoutBefore:b,executionRef:A,executionBranch:r.executionBranch,executionHead:m,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(u)return a("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await G(r.projectRoot)!==b)return a("direct-yolo-checkout-payload-raced")}const R=t?.originHead??await l(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return a("direct-yolo-current-branch-mismatch");if(w&&d?.ownerStoryId===e.storyId)return d.setupHeadSha!==R?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:De(r,h,String(d.expiresAt),!0)};const _=i,v=new Date(n+3600*1e3).toISOString(),D=`setup-${Ee(32).toString("hex")}`,x=u?p:await O(r.projectRoot,{required:!0});return await L(r.projectRoot,S=>{const b=P(S,r.epicId),A=g(b.branch_lease);if(u&&JSON.stringify(A)!==JSON.stringify(u.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(A&&Date.parse(String(A.expiresAt))>n&&A.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const m=Y(b.origin_binding,r.executionBranch,r.originBranch);if(b.origin_binding&&!m)throw new Error("direct-yolo-origin-binding-conflict");if(m&&JSON.stringify(m)!==JSON.stringify(h))throw new Error("direct-yolo-origin-binding-conflict");b.branch_mode="epic",b.execution_branch=r.executionBranch,b.origin_branch=r.originBranch,b.graph_revision=r.graphRevision,b.origin_binding=h,b.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:_,expiresAt:v,setupHeadSha:R}},{expectedRevision:u?.expectedRuntimeRevision??x.revision,preCommit:async()=>{if(t){if((await se(r.projectRoot)).some(b=>b.branch===r.executionBranch&&$(b.path)!==r.projectRoot)||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await G(r.projectRoot)!==t.checkoutBefore||!await C(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await l(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await l(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await l(r.projectRoot,["switch",r.executionBranch]),await G(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==R)throw new Error("direct-yolo-setup-physical-state-raced");if(y&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${y.originRef}^{commit}`]).catch(()=>"")!==y.originHeadSha||await Ze(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,R])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:De(r,h,v,!1)}}catch(r){return o&&t&&await lr($(e.projectRoot),t).catch(()=>{}),a(W(r,"direct-yolo-setup-failed"))}}async function Pr(e){let t;try{const o=await me(e.projectRoot,e.storyId);if(await Pe(o.projectRoot))return await Jt(o,N(e.nowIso));const r=await F(e.projectRoot,e.storyId),i=N(e.nowIso),n=U(r.projectRoot,".neocortex/state.json"),f=await M(n,"utf8"),c=await G(r.projectRoot),p=await l(r.projectRoot,["rev-parse","HEAD"]),s=`refs/heads/${r.executionBranch}`,d=await O(r.projectRoot,{required:!0}),u=g(d.epics[r.epicId]),w=Y(u?.origin_binding,r.executionBranch,r.originBranch),h=g(u?.branch_lease);if(!w)return a("direct-yolo-origin-binding-invalid");if(!h||!Ve(h,e.storyId,i)||h?.sessionId!==h?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const y=await K(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(h.sessionId),idempotencyKey:String(h.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!y.ok)return a(y.reasonCode);if(t=y,p!==h.setupHeadSha||!await C(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,p])||await l(r.projectRoot,["rev-parse",s])!==p)return a("direct-yolo-setup-head-mismatch");if((await se(r.projectRoot)).some(b=>b.branch===r.executionBranch&&$(b.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const _=g(JSON.parse(f)),v=g(g(_?.stories)?.[e.storyId]),D=g(d.stories[e.storyId]);if(!v||!["backlog","ready_to_start"].includes(String(v.status))||v.steps_completed!==void 0&&(!Array.isArray(v.steps_completed)||v.steps_completed.length>0)||v.branch_name||v.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const x=D?.status==="branch-ready"&&D.last_step===T&&Array.isArray(D.steps_completed)&&D.steps_completed.length===1&&D.steps_completed[0]===T&&ee(D).sort().join(",")==="last_step,status,steps_completed";if(D&&ee(D).length>0&&!x)return a("direct-yolo-setup-story-progress-conflict");const S=async()=>{if(Date.parse(String(h.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await le(t.path,t.owner)||await M(n,"utf8")!==f||await G(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==p||!await C(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,p])||await l(r.projectRoot,["rev-parse",s])!==p)throw new Error("direct-yolo-setup-physical-state-raced")};return x?await S():await L(r.projectRoot,b=>{const A=g(b.epics[r.epicId]),m=Ce(b,e.storyId);if(JSON.stringify(A?.branch_lease)!==JSON.stringify(h)||JSON.stringify(A?.origin_binding)!==JSON.stringify(w)||A?.graph_revision!==r.graphRevision||ee(m).length>0)throw new Error("direct-yolo-setup-runtime-raced");m.status="branch-ready",m.last_step=T,m.steps_completed=[T]},{expectedRevision:d.revision,preCommit:S}),{ok:!0,value:Object.freeze({...De(r,w,String(h.expiresAt),x),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:p})}}catch(o){return a(W(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await V(t.path,t.owner).catch(()=>{})}}async function Tr(e){try{const t=await F(e.projectRoot,e.storyId),o=z(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),r=X(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!r.ok)return a(r.reasonCode);t.rootMemoryEffect&&Ae(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await l(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet});const i=t.governanceMode==="runtime-store"?ze(t):void 0;if((i?i.review:pe(t.projectRoot,e.storyId,":"))?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(z(await H(t.projectRoot,["diff","--name-only","-z"])).some(k=>o.includes(k)))return a("direct-yolo-user-overlap");const c=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return a("direct-yolo-staged-diff-empty");const p=B(c),s=B([...t.authorizedWriteSet].sort().join("\0")),d=N(e.nowIso),u=await O(t.projectRoot,{required:!0});let w=g(u.epics[t.epicId]?.branch_lease),h;if(!Ve(w,e.storyId,d)){const I=w!==void 0&&Date.parse(String(w.expiresAt))>Date.parse(d)?void 0:await ht(t.projectRoot,u,t.epicId,e.storyId,d);if(!I||!await C(t.projectRoot,["merge-base","--is-ancestor",I.setupHeadSha,"HEAD"]))return a("direct-yolo-setup-handoff-owner-invalid");h=I,w={schemaVersion:1,ownerStoryId:e.storyId,sessionId:I.sessionId,idempotencyKey:I.idempotencyKey,acquiredAt:d,expiresAt:new Date(Math.min(Date.parse(I.expiresAt),Date.parse(d)+tr)).toISOString(),setupHeadSha:I.setupHeadSha}}const y=String(w.sessionId),R=String(w.expiresAt),_=new Date(Math.min(Date.parse(R),Date.parse(d)+300*1e3)).toISOString(),v=await Q(t.projectRoot,e.storyId),D=v?.state==="issued"&&v.fromSessionId===y&&v.bundleDigest===p&&v.claimRevision===s&&Date.parse(v.expiresAt)>Date.parse(d),x=D?v.expiresAt:_,S=D?v.token:Ee(32).toString("base64url"),b=B(S),A=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:y,tokenDigest:b,bundleDigest:p,claimRevision:s,expiresAt:x}),m=B(JSON.stringify(A)),j=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:x,persistent:!1,createdAt:d});if(!j.ok)return a(j.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ye(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:y,token:S,tokenDigest:b,bundleDigest:p,claimRevision:s,grantDigest:m,expiresAt:x}),await L(t.projectRoot,k=>{const I=P(k,t.epicId);if(h){const q=g(I.branch_lease);if(q&&Date.parse(String(q.expiresAt))>Date.parse(d))throw new Error("direct-yolo-setup-handoff-owner-raced");I.branch_lease={...w}}const E=g(I.branch_lease);if(!Ve(E,e.storyId,d)||E?.sessionId!==y||E.idempotencyKey!==y)throw new Error("direct-yolo-setup-handoff-owner-raced");E.handoffGrant=A},{expectedRevision:u.revision,preCommit:async()=>{if(!await le(j.path,j.owner))throw new Error("direct-yolo-integration-lock-raced");const k=await Q(t.projectRoot,e.storyId);if(!k||k.state!=="issued"||k.grantDigest!==m||k.tokenDigest!==b)throw new Error("direct-yolo-setup-handoff-token-raced");if(h&&(await lt(t.projectRoot,e.storyId))?.sessionId!==h.sessionId)throw new Error("direct-yolo-setup-handoff-owner-raced")}}),h&&await or(t.projectRoot,e.storyId)}finally{await V(j.path,j.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:y,bundleDigest:p,claimRevision:s,grantDigest:m,expiresAt:x,reused:D,publicSafe:!0,...i?{governance:i.receipt}:{}})}}catch(t){return a(t instanceof Error&&(/^direct-yolo-/.test(t.message)||Rt.has(t.message))?t.message:"direct-yolo-setup-handoff-failed")}}async function zr(e){try{const t=await F(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=z(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),i=X(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&Ae(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=t.governanceMode==="runtime-store"?ze(t):void 0,f=n?n.review:pe(t.projectRoot,e.storyId,":");if(f?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(z(await H(t.projectRoot,["diff","--name-only","-z"])).some(k=>r.includes(k)))return a("direct-yolo-user-overlap");const p=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!p)return a("direct-yolo-staged-diff-empty");const s=B(p),d=B([...t.authorizedWriteSet].sort().join("\0")),u=await ut(t.projectRoot,e.storyId),w=u.state==="valid"&&u.plan.epicId===t.epicId&&u.plan.executionBranch===t.executionBranch&&u.plan.preparedBase===o&&u.plan.bundleDigest===s&&u.plan.claimRevision===d?u.plan:void 0,h=w?.graphRevision??t.graphRevision,y=Me({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,graphRevision:h,claimRevision:d}),R=N(e.nowIso),_={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:h,preparedBase:o,bundleDigest:s,claimRevision:d,idempotencyKey:y,issuedAt:w?.issuedAt??R};let v=e.setupLeaseHandoff??await ir(t.projectRoot,e.storyId,s,d,R);const D=await O(t.projectRoot,{required:!0}),x=g(D.epics[t.epicId]?.branch_lease),S=x?.ownerStoryId===e.storyId&&x.sessionId===y&&x.idempotencyKey===y&&typeof x.expiresAt=="string"&&Date.parse(x.expiresAt)>Date.parse(R)?x:void 0;if(S&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const b=g(S?.handoffConsumption);if(b){const k=await Q(t.projectRoot,e.storyId);if(!k||!["consuming","consumed"].includes(k.state)||k.fromSessionId!==b.fromSessionId||k.tokenDigest!==b.tokenDigest||k.bundleDigest!==s||k.claimRevision!==d||b.bundleDigest!==s||b.claimRevision!==d||k.consumedBySessionId!==y||b.consumedBySessionId!==y)return a("direct-yolo-setup-handoff-consume-invalid");if(k.state==="consuming"){if(!k.token||B(k.token)!==k.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");v={sessionId:k.fromSessionId,token:k.token}}}const A=S?String(S.expiresAt):new Date(Date.parse(R)+ae).toISOString(),m=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:A,persistent:!0,createdAt:S&&typeof S.acquiredAt=="string"?S.acquiredAt:R});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{v&&e.setupLeaseHandoff===void 0&&(await nr(t.projectRoot,e.storyId,v.sessionId,v.token,y,R),await e.setupHandoffFault?.("after-consuming-persisted")),await L(t.projectRoot,k=>{const I=P(k,t.epicId),E=g(I.branch_lease),q=E&&Date.parse(String(E.expiresAt))>Date.parse(R),oe=E?.ownerStoryId===e.storyId&&E.sessionId===y&&E.idempotencyKey===y,de=E?.ownerStoryId===e.storyId&&E.sessionId===E.idempotencyKey&&typeof E.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(E.idempotencyKey),J=q&&de&&cr({current:E,handoff:v,storyId:e.storyId,bundleDigest:s,claimRevision:d,nowIso:R});if(v&&q&&!oe&&!J)throw new Error("direct-yolo-setup-handoff-invalid");if(q&&!oe&&!J)throw new Error("direct-yolo-writer-active");const Qe=J?g(E?.handoffGrant):void 0,Xe=Qe?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(E?.sessionId),tokenDigest:String(Qe.tokenDigest),bundleDigest:s,claimRevision:d,consumedBySessionId:y,consumedAt:R}:void 0;I.branch_mode="epic",I.execution_branch=t.executionBranch,I.origin_branch=t.originBranch,I.graph_revision=t.graphRevision,I.branch_lease=q&&oe?E:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:y,idempotencyKey:y,acquiredAt:R,expiresAt:A,...Xe?{handoffConsumption:Xe}:{}}},{expectedRevision:D.revision,preCommit:async()=>{if(!await le(m.path,m.owner))throw new Error("direct-yolo-integration-lock-raced");await Xt(t.projectRoot,_)}})}catch(k){throw await V(m.path,m.owner).catch(()=>{}),k}v&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await ar(t.projectRoot,t.epicId,e.storyId,v.sessionId,v.token,s,d,y,R));const j=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${s}`,`Neocortex-Review-Artifact-Digest: ${f.digest}`,`Neocortex-Graph-Revision: ${h}`,`Neocortex-Claim-Revision: ${d}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Dt(t.rootMemoryEffect)}`]:[],...n?[`${at}: ${n.receipt.governanceDigest}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,reviewArtifactDigest:f.digest,graphRevision:h,claimRevision:d,idempotencyKey:y,changedPaths:Object.freeze(r),trailers:j,...n?{governance:n.receipt}:{}})}}catch(t){return a(W(t,"direct-yolo-begin-failed"))}}async function Gr(e){let t,o,r;try{const i=await F(e.projectRoot,e.storyId);t=i;const n=e.preFastForwardAuthorizedWriteSet;if(n!==void 0&&!qe(n))return a("direct-yolo-write-set-invalid");const f=n??i.authorizedWriteSet,c=await l(i.projectRoot,["rev-parse","HEAD"]);let p=await O(i.projectRoot,{required:!0});const s=g(p.stories[e.storyId]?.checkpoint);if(s){const j=typeof s.headSha=="string"?s.headSha:"",k=typeof s.graphRevision=="string"?s.graphRevision:"",I=/^[a-f0-9]{40,64}$/.test(j)?z(await H(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",j])):[],E=X(I,f,e.storyId,i.rootMemoryEffect,i.governanceMode);if(!(/^[a-f0-9]{40,64}$/.test(j)&&await C(i.projectRoot,["merge-base","--is-ancestor",j,c]))||!/^[a-f0-9]{64}$/.test(k)||!E.ok)return a("direct-yolo-replay-invalid");const oe=await Ie(e,i.projectRoot,c,k);if(!await Le(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,oe.transientAuthority,f))return a("direct-yolo-replay-invalid");if(!await xe(i.projectRoot,i.executionBranch,c,I))return a("direct-yolo-replay-head-raced");if(e.push&&!await We(i.projectRoot,e.remote??"origin",i.executionBranch,j))return a("direct-yolo-remote-head-mismatch");const de=Array.isArray(s.receiptRefs)?s.receiptRefs.find(J=>typeof J=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(J)):void 0;return de&&typeof s.idempotencyKey=="string"&&await qt(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:de.slice(20)}),await ce(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const d=c,u=await ge(i,e.storyId,d,n?{claimWriteSet:n}:{});if(!u.ok)return a(u.reasonCode);const{baseSha:w,changedPaths:h,bundleDigest:y,graphRevision:R,claimRevision:_,idempotencyKey:v,governance:D}=u.value,x=g(p.epics[i.epicId]?.branch_lease),S=N(e.nowIso),b=x?.ownerStoryId===e.storyId&&x.idempotencyKey===v&&x.sessionId===v&&Date.parse(String(x.expiresAt))>Date.now()?x:void 0;if(x&&Date.parse(String(x.expiresAt))>Date.now()&&!b)return a("direct-yolo-writer-active");const A=b??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:v,idempotencyKey:v,acquiredAt:S,expiresAt:new Date(Date.parse(S)+ae).toISOString()},m=await K(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:v,idempotencyKey:v,expiresAt:String(A.expiresAt),persistent:!0,createdAt:String(A.acquiredAt)});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,b||(p=(await L(i.projectRoot,k=>{const I=P(k,i.epicId),E=g(I.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(S))throw new Error("direct-yolo-writer-active");if(I.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");I.branch_lease=A},{expectedRevision:p.revision})).document),o=A;{const j=await Ie(e,i.projectRoot,d,R);if(!await xe(i.projectRoot,i.executionBranch,d,h))return a("direct-yolo-head-raced");if(e.push){const E=re(e.remote??"origin");if(await l(i.projectRoot,["push",E,i.executionBranch]),!await Je(i.projectRoot,E,i.executionBranch,d))return a("direct-yolo-remote-head-mismatch")}const k=await we({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:w,headSha:d,bundleDigest:y,graphRevision:R,claimRevision:_,idempotencyKey:v,qaExecution:j,physicalLockOwnerDigest:ue(m.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect,...D?{governance:D}:{}});return await e.beforeCheckpointPersist?.(),await ve({projectRoot:i.projectRoot,checkpoint:k,remote:e.push?e.remote??"origin":void 0,expectedRevision:p.revision,expectedLease:A,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:R,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:j.transientAuthority,authorizedWriteSet:f})?(await ce(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:k}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(W(i,"direct-yolo-finalize-failed"))}finally{r&&await V(r.path,r.owner).catch(()=>{}),t&&o?await Se(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await dr(t,e.storyId).catch(()=>{})}}function qe(e){return Array.isArray(e)&&e.length>0&&e.length<=ot&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}async function Wr(e,t,o,r={}){try{return/^[a-f0-9]{40,64}$/.test(o)?await ge(e,t,o,{claimWriteSet:e.authorizedWriteSet,...r.expectedGraphRevision!==void 0?{expectedGraphRevision:r.expectedGraphRevision}:{}}):a("direct-yolo-recovery-commit-invalid")}catch(i){return a(W(i,"direct-yolo-commit-verification-failed"))}}async function ge(e,t,o,r={}){if(r.claimWriteSet!==void 0&&!qe(r.claimWriteSet))return a("direct-yolo-write-set-invalid");if(r.expectedGraphRevision!==void 0&&!/^[a-f0-9]{64}$/.test(r.expectedGraphRevision))return a("direct-yolo-graph-revision-invalid");const i=r.claimWriteSet??e.authorizedWriteSet,n=await l(e.projectRoot,["rev-parse",`${o}^`]),f=await H(e.projectRoot,["show","--no-patch","--format=%B",o]),c=z(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),p=X(c,i,t,e.rootMemoryEffect,e.governanceMode);if(!p.ok)return a(p.reasonCode);e.rootMemoryEffect&&Ae(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:n,headRef:o,childPaths:i});const s=B([...i].sort().join("\0")),d=await ut(e.projectRoot,t);if(d.state==="invalid")return a("direct-yolo-commit-plan-invalid");const u=d.state==="valid"?d.plan:void 0;if(u&&(u.epicId!==e.epicId||u.executionBranch!==e.executionBranch))return a("direct-yolo-commit-plan-invalid");if(u&&u.claimRevision!==s)return a("direct-yolo-commit-plan-claim-changed");if(u&&u.preparedBase!==n)return a("direct-yolo-commit-plan-base-mismatch");const w=ct(f,nt);if(!w.ok)return a(`direct-yolo-trailer-duplicate:${w.key}`);const h=w.values;if(r.expectedGraphRevision!==void 0&&u&&u.graphRevision!==r.expectedGraphRevision)return a(`direct-yolo-trailer-mismatch:${ye("Neocortex-Graph-Revision")}`);const y=r.expectedGraphRevision??u?.graphRevision??e.graphRevision,R=s,_=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",n],["Neocortex-Bundle-Digest",u?.bundleDigest??""],["Neocortex-Graph-Revision",y],["Neocortex-Claim-Revision",R]];for(const[j,k]of _){const I=ie(h,j);if(I===void 0)return a(`direct-yolo-trailer-missing:${ye(j)}`);if(j==="Neocortex-Bundle-Digest"&&!u){if(!/^[a-f0-9]{64}$/.test(I))return a(`direct-yolo-trailer-mismatch:${ye(j)}`);continue}if(I!==k)return a(`direct-yolo-trailer-mismatch:${ye(j)}`)}const v=ie(h,"Neocortex-Bundle-Digest"),D=ie(h,at);if(e.governanceMode!=="runtime-store"&&D!==void 0)return a(he.MISMATCH);const x=e.governanceMode==="runtime-store"?Ge({projectRoot:e.projectRoot,epicId:e.epicId,storyId:t},D):void 0,S=x?x.review:pe(e.projectRoot,t,o);if(S?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const b=ie(h,"Neocortex-Review-Artifact-Digest");if(b!==void 0&&b!==S.digest)return a("direct-yolo-review-artifact-digest-mismatch");const A=B(await H(e.projectRoot,["diff","--binary","--full-index",`${n}..${o}`]));if(v!==A)return a("direct-yolo-bundle-digest-mismatch");const m=Me({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:n,bundleDigest:v,graphRevision:y,claimRevision:R});return u&&u.idempotencyKey!==m?a("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:n,changedPaths:c,bundleDigest:v,graphRevision:y,claimRevision:R,idempotencyKey:m,...x?{governance:x.receipt}:{}}}}async function Mr(e){try{const t=await F(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return a("direct-yolo-recovery-commit-invalid");const o=await l(t.projectRoot,["rev-parse",e.commitSha]);if(Lt[e.storyId]!==o)return await Yt(e,t,o);if(await l(t.projectRoot,["rev-parse","HEAD"])!==o)return a("direct-yolo-recovery-head-mismatch");await l(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await l(t.projectRoot,["rev-parse",`${o}^`]),i=await H(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=z(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!X(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const c=B(i),p=B([...n].sort().join("\0")),s=B(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),d=N(e.nowIso),u=new Date(Date.parse(d)+ae).toISOString(),w=await O(t.projectRoot,{required:!0}),h=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:s,idempotencyKey:s,expiresAt:u,persistent:!0,createdAt:d});if(!h.ok)return a(h.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const y={schemaVersion:1,ownerStoryId:e.storyId,sessionId:s,idempotencyKey:s,acquiredAt:d,expiresAt:u};let R=!1;try{const _=await L(t.projectRoot,A=>{const m=P(A,t.epicId),j=g(m.branch_lease);if(j&&Date.parse(String(j.expiresAt))>Date.parse(d)&&!Re(j,y))throw new Error("direct-yolo-recovery-writer-active");if(m.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");m.branch_mode="epic",m.execution_branch=t.executionBranch,m.origin_branch=t.originBranch,m.branch_lease=y},{expectedRevision:w.revision});R=!0;const v=await Ie(e,t.projectRoot,o,t.graphRevision);if(!await xe(t.projectRoot,t.executionBranch,o,n))return a("direct-yolo-recovery-head-raced");if(e.push){const A=re(e.remote??"origin"),m=(await l(t.projectRoot,["ls-remote","--heads",A,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!m||!await C(t.projectRoot,["merge-base","--is-ancestor",o,m]))return a("direct-yolo-recovery-remote-proof-missing")}const D=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:p,idempotencyKey:s,qaExecution:v,physicalLockOwnerDigest:ue(h.owner),nowIso:d,legacyReceiptRef:void 0}),x=await Ct(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!x)return a("direct-yolo-recovery-evidence-invalid");const S=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,x])});return await ve({projectRoot:t.projectRoot,checkpoint:S,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:_.document.revision,expectedLease:y,expectedGraphRevision:t.graphRevision,physicalLockPath:h.path,physicalLockOwner:h.owner,transientAuthority:v.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:S}:a("direct-yolo-recovery-persist-failed")}finally{await V(h.path,h.owner).catch(()=>{}),R&&await Se(t.projectRoot,t.epicId,y).catch(()=>{})}}catch(t){return a(W(t,"direct-yolo-recovery-failed"))}}async function Yt(e,t,o){const r=await H(t.projectRoot,["show","--no-patch","--format=%B",o]),i=ct(r,nt);if(!i.ok||ie(i.values,"Neocortex-Story")!==e.storyId)return a("direct-yolo-recovery-not-allowlisted");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o||!await C(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]))return a("direct-yolo-recovery-head-mismatch");const n=await ge(t,e.storyId,o);if(!n.ok)return a(n.reasonCode);const{baseSha:f,changedPaths:c,bundleDigest:p,graphRevision:s,claimRevision:d,idempotencyKey:u,governance:w}=n.value,h=re(e.remote??"origin");let y=!1;try{y=await We(t.projectRoot,h,t.executionBranch,o)}catch{y=!1}if(!y)return a("direct-yolo-recovery-remote-proof-missing");const R=N(e.nowIso),_=new Date(Date.parse(R)+ae).toISOString(),v=await O(t.projectRoot,{required:!0});if(g(v.stories[e.storyId]?.checkpoint))return a("direct-yolo-checkpoint-conflict");const D=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:_,persistent:!0,createdAt:R});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const x={schemaVersion:1,ownerStoryId:e.storyId,sessionId:u,idempotencyKey:u,acquiredAt:R,expiresAt:_};let S=!1;try{const b=await L(t.projectRoot,k=>{const I=P(k,t.epicId),E=g(I.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(R)&&!Re(E,x))throw new Error("direct-yolo-recovery-writer-active");if(I.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");I.branch_mode="epic",I.execution_branch=t.executionBranch,I.origin_branch=t.originBranch,I.branch_lease=x},{expectedRevision:v.revision});S=!0;const A=await Ie(e,t.projectRoot,o,s);if(!await xe(t.projectRoot,t.executionBranch,o,c))return a("direct-yolo-recovery-head-raced");const m=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:f,headSha:o,bundleDigest:p,graphRevision:s,claimRevision:d,idempotencyKey:u,qaExecution:A,physicalLockOwnerDigest:ue(D.owner),nowIso:R,legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,...w?{governance:w}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:m,remote:h,remotePolicy:"ancestor-recovery",expectedRevision:b.document.revision,expectedLease:x,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:s,physicalLockPath:D.path,physicalLockOwner:D.owner,transientAuthority:A.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:m}):a("direct-yolo-recovery-persist-failed")}finally{await V(D.path,D.owner).catch(()=>{}),S&&await Se(t.projectRoot,t.epicId,x).catch(()=>{})}}async function Pe(e){const t=await je(await l(e,["rev-parse","--absolute-git-dir"])),o=await je(await l(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function dt(e){const t=await O(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(u=>u.storyId===e.storyId&&u.epicId===e.epicId&&u.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await je(await l(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const f=await new Vt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!f.ok||f.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=Y(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const p=r.syncedSha??r.baseSha,s=await l(e.projectRoot,["rev-parse","HEAD"]),d=`refs/heads/${e.executionBranch}`;if(s!==p||!await C(e.projectRoot,["merge-base","--is-ancestor",p,d])||!await C(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,p]))throw new Error("direct-yolo-worktree-base-divergent");if(f.value.clean!==!0||(await H(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-worktree-dirty");return{leaseId:r.leaseId,temporaryBranch:r.temporaryBranch,authorizedBase:p,headSha:s,expiresAt:r.expiresAt,binding:c}}function ft(e,t,o){return Object.freeze({...De(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Jt(e,t){const o=await dt(e),r=Te(e.projectRoot),i=g(JSON.parse(r)),n=g(g(i?.stories)?.[e.storyId]),f=await O(e.projectRoot,{required:!0}),c=g(f.stories[e.storyId]);if(!n||!["backlog","ready_to_start"].includes(String(n.status))||n.steps_completed!==void 0&&(!Array.isArray(n.steps_completed)||n.steps_completed.length>0)||n.branch_name||n.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const p=c?.status==="branch-ready"&&c.last_step===T&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===T&&ee(c).sort().join(",")==="last_step,status,steps_completed";if(c&&ee(c).length>0&&!p)return a("direct-yolo-setup-story-progress-conflict");p||await L(e.projectRoot,u=>{const w=Ce(u,e.storyId);if(ee(w).length>0)throw new Error("direct-yolo-setup-runtime-raced");w.status="branch-ready",w.last_step=T,w.steps_completed=[T]},{expectedRevision:f.revision,preCommit:async()=>{if(Te(e.projectRoot)!==r||await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.temporaryBranch||await l(e.projectRoot,["rev-parse","HEAD"])!==o.headSha||(await H(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}});const s=await O(e.projectRoot,{required:!0}),d=await ht(e.projectRoot,s,e.epicId,e.storyId,t);if(d?.leaseId!==o.leaseId||d.setupHeadSha!==o.headSha){const u=`setup-${Ee(32).toString("hex")}`;await rr(e.projectRoot,{schemaVersion:1,kind:pt,epicId:e.epicId,ownerStoryId:e.storyId,sessionId:u,idempotencyKey:u,leaseId:o.leaseId,acquiredAt:t,expiresAt:o.expiresAt,setupHeadSha:o.headSha})}return{ok:!0,value:Object.freeze({...ft(e,o,p),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:o.headSha})}}async function Kr(e,t){const o=await F(e,t),r=await O(o.projectRoot,{required:!0}),i=Y(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Vr(e,t,o,r,i="tracked"){return X(e,t,o,r,i)}function Fr(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Yr=ae,Ut="p205-wave:";function Jr(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=B(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function Zt(e){return`${Ut}${e.waveHeadSha}:${e.waveDigest}`}async function Ur(e){let t;try{t=await Ht(e.projectRoot,{headSha:e.headSha,graphRevisions:e.graphRevisions,...e.nowIso!==void 0?{nowIso:e.nowIso}:{}})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:Oe(r)?r:"p205-complete-gate-failed"}}try{await e.qaRunner?.({projectRoot:e.projectRoot,storyId:e.storyId,headSha:e.headSha})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:Oe(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Zr(e,t,o,r){const i=re(t);return await l(e,["push",i,o]),Je(e,i,o,r)}async function Qr(e){try{const t=await F(e.projectRoot,e.storyId);if(e.authorizedWriteSet!==void 0&&!qe(e.authorizedWriteSet))return a("direct-yolo-write-set-invalid");const o=e.authorizedWriteSet??t.authorizedWriteSet,r=e.coverage.waveHeadSha,i=e.coverage.waveStoryIds.indexOf(e.storyId);if(i<0||e.coverage.waveCommitShas[i]!==e.headSha)return a("direct-yolo-wave-coverage-invalid");if(await l(t.projectRoot,["rev-parse","HEAD"])!==r||await l(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==r||!await C(t.projectRoot,["merge-base","--is-ancestor",e.headSha,r]))return a("direct-yolo-wave-head-raced");const n=await O(t.projectRoot,{required:!0}),f=g(n.stories[e.storyId]?.checkpoint);if(f){if(f.headSha!==e.headSha)return a("direct-yolo-checkpoint-conflict");const x=e.authorities.get(String(f.graphRevision));return await Le(t.projectRoot,f,e.storyId,t.epicId,t.executionBranch,x??null,o)?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:f}):a("direct-yolo-replay-invalid")}const c=await ge(t,e.storyId,e.headSha,{...e.authorizedWriteSet!==void 0?{claimWriteSet:e.authorizedWriteSet}:{},...e.expectedGraphRevision!==void 0?{expectedGraphRevision:e.expectedGraphRevision}:{}});if(!c.ok)return a(c.reasonCode);const{baseSha:p,bundleDigest:s,graphRevision:d,claimRevision:u,idempotencyKey:w,governance:h}=c.value,y=i===0?void 0:e.coverage.waveCommitShas[i-1];if(y!==void 0&&p!==y)return a("direct-yolo-wave-chain-invalid");const R=e.authorities.get(d),_=tt(R);if(!R||!_||_.executionHeadSha!==r||_.graphRevision!==d)return a("direct-yolo-wave-qa-unbound");const v=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:p,headSha:e.headSha,bundleDigest:s,graphRevision:d,claimRevision:u,idempotencyKey:w,qaExecution:{contract:"P205-CI-02",command:rt,manifestDigest:_.manifestDigest,gateIds:_.gateIds,resultDigest:_.resultDigest,transientAuthority:R},physicalLockOwnerDigest:ue(e.physicalLock.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Zt(e.coverage)],...h?{governance:h}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:v,remote:e.remote,expectedRevision:n.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:d,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:R,authorizedWriteSet:o,expectedHeadSha:r,keepLease:!0})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:v}):a("direct-yolo-checkpoint-persist-failed")}catch(t){return a(W(t,"direct-yolo-wave-persist-failed"))}}async function me(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=$(e),r=g(JSON.parse(Te(o))),i=await O(o,{required:!0}),n=Be(r,i),f=Tt({projectRoot:o,storyId:t});if(!f.ok)throw new Error(f.reasonCode);const c=f.mode,p=g(n.stories),s=g(n.epics),d=g(p?.[t]),u=String(d?.epic_id??t.split(".")[0]),w=g(s?.[u]),h=String(w?.execution_branch??""),y=String(w?.origin_branch??""),R=String(w?.graph_revision??""),_=Array.isArray(d?.files_to_modify)?d.files_to_modify:[],v=Nt(d).filter(ur),D=[..._,...v],x=D.length>0?_e(t,D):void 0,S=x?.ok?x.scopes:[];if(!d)throw new Error("direct-yolo-story-state-missing");if(v.length>0&&S.length>ot)throw new Error("direct-yolo-write-set-too-large");if(w?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!te(h)||!await C(o,["check-ref-format","--branch",h]))throw new Error("direct-yolo-execution-branch-invalid");if(!te(y)||!await C(o,["check-ref-format","--branch",y]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(R))throw new Error("direct-yolo-graph-revision-invalid");const b=await kt({projectRoot:o,storyId:t,graphRevision:R,executionBranch:h,childPaths:S});return{projectRoot:o,storyId:t,story:d,epicId:u,executionBranch:h,originBranch:y,graphRevision:R,authorizedWriteSet:S,rootMemoryEffect:b,governanceMode:c}}async function Xr(e){try{const t=await me(e.projectRoot,e.storyId);return t.governanceMode!=="runtime-store"?a("governance-capture-not-applicable"):await Pe(t.projectRoot)?a("governance-capture-root-required"):{ok:!0,value:ze(t).receipt}}catch(t){return a(W(t,"governance-capture-failed"))}}function Te(e){const t=Wt(e);if(!t.ok)throw new Error(t.reasonCode);if(!t.value)throw new Error("direct-yolo-story-state-missing");return t.value.toString("utf8")}function ze(e){const t=Pt(e);if(!t.ok)throw new Error(t.reasonCode);return Ge(e,t.value.governanceDigest)}function Ge(e,t){const o=Kt({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Mt(e.storyId));if(!r)throw new Error(he.MISMATCH);return{receipt:o.value.receipt,review:$t(e.storyId,r)}}async function F(e,t){const o=await me(e,t);if(await l(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function we(e){const t=e.nowIso,o=await H(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=z(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=_t({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Bt({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),f=`story-qa:${n}`,c=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:f}),p=e.governance?Ge(e,e.governance.governanceDigest).review:pe(e.projectRoot,e.storyId,e.headSha);if(p?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const s=B(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,f,B(o),[...r].sort().join(","),p.digest].join("\0")),d=`story-review:${s}`,u=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:s,reviewArtifactDigest:p.digest,qaReceiptRef:f,verdict:"approved",reviewedAt:t,receiptRef:d}),w=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,f,d,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[],...e.governance?zt(e.governance):[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(w),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:u,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function ve(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await L(t,n=>{const f=P(n,o.epicId);if(e.expectedLease){const d=g(f.branch_lease);if(!Re(d,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(d?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(f.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const c=Ce(n,o.storyId),p=g(c.checkpoint);if(p&&p.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=st;const s=Array.isArray(c.steps_completed)?c.steps_completed.filter(d=>typeof d=="string"):[];c.steps_completed=[...new Set([...s,Ft,st])],e.keepLease||(f.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await l(t,["rev-parse","HEAD"])!==n||await l(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await C(t,["merge-base","--is-ancestor",o.headSha,n]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await Le(t,o,o.storyId,o.epicId,o.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await le(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await We(t,r,o.branch,o.headSha):await Je(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function We(e,t,o,r){const i=re(t),n=(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await C(e,["merge-base","--is-ancestor",r,n]))}function Me(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Qt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Ke(e,t){const o=await $e(e),r=await He(o,"commit-plans"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:U(r,i)}}async function Xt(e,t){const o=await Ke(e,t.storyId);await Ne(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`),await
|
|
3
|
-
`),await
|
|
4
|
-
`),await Z(o.path,o.parent)}async function Q(e,t){try{const o=await yt(e,t);await Z(o.path,o.parent);const r=JSON.parse(await M(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function ir(e,t,o,r,i){const n=await Q(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||B(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function nr(e,t,o,r,i,n){const f=await Q(e,t);if(!f||f.state==="consumed"||f.fromSessionId!==o||f.token!==r||f.tokenDigest!==B(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(f.state==="consuming"){if(f.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await Ye(e,{...f,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function ar(e,t,o,r,i,n,f,c,p){const s=await Q(e,o);if(s?.state==="consumed"&&s.fromSessionId===r&&s.consumedBySessionId===c)return;const d=await O(e,{required:!0}),u=g(d.epics[t]?.branch_lease),w=g(u?.handoffConsumption);if(!s||s.state!=="consuming"||s.fromSessionId!==r||s.token!==i||s.tokenDigest!==B(i)||s.bundleDigest!==n||s.claimRevision!==f||s.consumedBySessionId!==c||u?.ownerStoryId!==o||u.sessionId!==c||w?.kind!=="direct-yolo-setup-handoff-consumption"||w.state!=="consumed"||w.fromSessionId!==r||w.tokenDigest!==s.tokenDigest||w.bundleDigest!==n||w.claimRevision!==f||w.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ye(e,{schemaVersion:1,kind:s.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:s.tokenDigest,bundleDigest:s.bundleDigest,claimRevision:s.claimRevision,grantDigest:s.grantDigest,expiresAt:s.expiresAt,consumedBySessionId:c,consumedAt:p})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function cr(e){const t=g(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?B(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&sr(t.tokenDigest,r))}function sr(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&xt(o,r)}function Re(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Se(e,t,o){await L(e,r=>{const i=P(r,t),n=g(i.branch_lease);Re(n,o)&&(i.branch_lease=null)})}async function dr(e,t){const o=await O(e.projectRoot,{required:!0}),r=g(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!be(r.sessionId)||!be(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await K(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(r.sessionId),idempotencyKey:String(r.idempotencyKey),createdAt:String(r.acquiredAt),expiresAt:String(r.expiresAt),persistent:!0});if(!i.ok)return;await V(i.path,i.owner)&&await Se(e.projectRoot,e.epicId,r)}async function Ie(e,t,o,r){const i=await Ot(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=tt(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:rt,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function xe(e,t,o,r){return await l(e,["rev-parse","HEAD"])!==o||await l(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await C(e,["diff","--cached","--quiet"])?!1:C(e,["diff","--quiet","HEAD","--",...r])}async function Je(e,t,o,r){const i=re(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function X(e,t,o,r,i="tracked"){if(e.length===0||e.some(c=>!Ue(c)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};if(i==="runtime-store")return fr(e,t,o,r);const n=t.length>0?_e(o,t):void 0;return n?.ok?[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`].every(c=>e.includes(c))?r&&(r.storyId!==o||r.childClaimRevision!==B([...n.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(c=>!et(n.scopes,c)&&!r?.files.some(p=>p.path===c))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}}function fr(e,t,o,r){if(e.some(Gt))return{ok:!1,reasonCode:he.WRITE_SET_FORBIDDEN};const i=t.length>0?_e(o,t):void 0;if(!i?.ok)return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const n=`docs/stories/${o}.story.md`;return!e.includes(n)||!e.some(f=>f!==n)?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==B([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(f=>!et(i.scopes,f)&&!r?.files.some(c=>c.path===f))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function ee(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function ur(e){return typeof e!="string"||e.length>512||!Ue(e)||!At(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Ue(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function be(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function te(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function re(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function B(e){return It("sha256").update(e).digest("hex")}function z(e){return e.split("\0").filter(Boolean)}function N(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function pr(e,t,o,r,i){const n=g(e.expectedLease),f=n?.sessionId,c=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof f=="string"&&/^setup-[a-f0-9]{64}$/.test(f)&&n.idempotencyKey===f&&Number.isFinite(c)&&c<=i}async function lr(e,t){let o=await l(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await l(e,["rev-parse","HEAD"])!==t.originHead||await G(e)!==t.checkoutBefore)return;await l(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await l(e,["rev-parse","HEAD"])!==t.originHead||await G(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await C(e,["show-ref","--verify","--quiet",t.executionRef]))return;await l(e,["rev-parse",t.executionRef])===t.originHead&&await l(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const hr=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],yr=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function Y(e,t,o){const r=g(e);if(!r||r.originBranch!==o||r.executionBranch!==t||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt)))return;const i=Object.keys(r).sort().join("\0");if(r.schemaVersion===1)return r.capturedFromCurrentCheckout!==!0||i!==hr.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==yr.join("\0")?void 0:r}async function gr(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await C(e.projectRoot,["show-ref","--verify","--quiet",r]))return a("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await l(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return a("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await se(e.projectRoot)).some(p=>p.branch===e.executionBranch&&$(p.path)!==e.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const f=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",f]).catch(()=>"")!==t)return a("direct-yolo-setup-physical-state-raced");const c=await Ze(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?a("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?a("direct-yolo-origin-ancestry-unverifiable"):{ok:!0,value:{originRef:r,binding:{schemaVersion:2,originBranch:e.originBranch,originHeadSha:i,executionBranch:e.executionBranch,capturedFrom:"branch-ref",capturedAt:o}}}}const gt=3e4,mr=3,wr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class ke extends Error{}function vr(e,t=gt){return{timeout:t,killSignal:"SIGKILL",env:{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_HTTP_LOW_SPEED_LIMIT:"1000",GIT_HTTP_LOW_SPEED_TIME:"30",...e.GIT_SSH_COMMAND?{}:{GIT_SSH_COMMAND:wr}}}}async function Rr(e){if(!te(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ne("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:$(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...vr(process.env,e.fetchTimeoutMs??gt)}),{ok:!0}}catch(t){const o=String(t.stderr??"");return{ok:!1,reasonCode:/non-fast-forward|\[rejected\]/.test(o)?"origin-binding-start-fetch-non-fast-forward":"origin-binding-start-fetch-unavailable"}}}const Sr=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function eo(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=$(e),i=g(JSON.parse(await M(U(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await O(r),f=Be(i,n),c=g(g(f.epics)?.[t]);if(!c)return o;const p=wt(f,t,c),s=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,d=await mt(r,c,i),u=g(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:p,terminal:Sr.has(String(c.status??"").toLowerCase()),bound:!!Y(u,s,d),executionBranch:s,originBranch:d})}catch{return o}}async function mt(e,t,o){if(typeof t.origin_branch=="string"&&t.origin_branch.length>0)return t.origin_branch;const r=g(o.config)?.default_branch;if(r!=null&&String(r).length>0)return String(r);const i=await l(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]).catch(()=>"");if(i.startsWith("origin/")&&i.length>7)return i.slice(7);const n=[];for(const f of["main","master"])await C(e,["rev-parse","--verify","--quiet",`refs/heads/${f}^{commit}`])&&await C(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${f}^{commit}`])&&n.push(f);return n.length===1?n[0]:""}function wt(e,t,o){if(o.branch_mode==="epic")return"recorded-epic";if(o.branch_mode!==void 0&&o.branch_mode!==null)return"not-epic";const r=g(e.stories)??{},n=jt(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const p=g(r[c]);return p?[{...p,id:c}]:[]}),f=Et({...o,id:t},n);return f.mode==="epic"&&(f.source==="new-epic-default"||f.source==="epic-boundary")?"resolved-epic":"not-epic"}function vt(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function to(e){const t=N(e.nowIso),o=Date.parse(t),r=(c,p={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...p,outcome:"refused",reasonCode:c,executionRefCreated:!1,capturedAt:t});if(!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(e.epicId))return r("origin-binding-start-target-ambiguous");const i=$(e.projectRoot);let n=e.originFetch,f="origin-binding-start-raced";for(let c=0;c<mr;c+=1){let p,s={};try{const d=g(JSON.parse(await M(U(i,".neocortex/state.json"),"utf8")));if(!d)return r("origin-binding-start-state-invalid");const u=await O(i),w=Be(d,u),h=g(g(w.epics)?.[e.epicId]);if(!h)return r("origin-binding-start-target-ambiguous");if(wt(w,e.epicId,h)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const y=typeof h.execution_branch=="string"&&h.execution_branch.length>0?h.execution_branch:`epic/${e.epicId}`,R=await mt(i,h,d);if(s={executionBranch:y,originBranch:R},!te(y)||!te(R)||y===R||!await C(i,["check-ref-format","--branch",y])||!await C(i,["check-ref-format","--branch",R]))return r("origin-binding-start-branch-invalid",s);const _=g(u.epics[e.epicId]),v=_?.origin_binding??h.origin_binding;if(v!=null){const I=Y(v,y,R);return I?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:I.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",s)}if(vt(g(_?.branch_lease??h.branch_lease),o))return r("origin-binding-start-lease-inconsistent",s);if(n??=await Rr({projectRoot:i,originBranch:R,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,s);const D=`refs/remotes/origin/${R}`,x=`refs/heads/${R}`,S=await l(i,["rev-parse","--verify","--quiet",`${x}^{commit}`]).catch(()=>""),b=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(S)||S!==b)return r("origin-binding-start-origin-stale",s);if((await se(i)).some(I=>I.branch===y&&$(I.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",s);const m=`refs/heads/${y}`,j=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(j){const I=await Ze(i,["merge-base","--is-ancestor",S,j]);if(I===1)return r("direct-yolo-origin-not-ancestor",s);if(I!==0)return r("direct-yolo-origin-ancestry-unverifiable",s)}const k={schemaVersion:2,originBranch:R,originHeadSha:S,executionBranch:y,capturedFrom:"branch-ref",capturedAt:t};return await L(i,I=>{const E=P(I,e.epicId);if(E.origin_binding!==void 0&&E.origin_binding!==null)throw new ke("origin-binding-start-raced");if(vt(g(E.branch_lease),o))throw new ke("origin-binding-start-lease-inconsistent");E.origin_binding=k},{expectedRevision:u.revision,preCommit:async()=>{const I=await l(i,["rev-parse","--verify","--quiet",`${x}^{commit}`]).catch(()=>""),E=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>""),q=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(I!==S||E!==S||q!==j)throw new ke("origin-binding-start-raced");j||(await l(i,["update-ref",m,S,""]),p={ref:m,sha:S})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:S,outcome:"captured",executionRefCreated:p!==void 0,capturedAt:t})}catch(d){if(p&&await l(i,["update-ref","-d",p.ref,p.sha]).catch(()=>{}),d instanceof Error&&d.message==="git-lifecycle-runtime-revision-conflict"){f="origin-binding-start-raced";continue}return d instanceof ke?r(d.message,s):r("origin-binding-start-failed",s)}}return r(f)}function De(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function G(e){const t=z(await H(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Ue(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await l(e,["hash-object","--no-filters","--",r])}`}));return B([await H(e,["diff","--cached","--binary","--full-index"]),await H(e,["diff","--binary","--full-index"]),await H(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function ro(e){const t=$(e),o=await l(t,["rev-parse","HEAD"]),r=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await G(t);if(await l(t,["rev-parse","HEAD"])!==o||await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function se(e){const t=[];let o;for(const r of(await H(e,["worktree","list","--porcelain","-z"])).split("\0"))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}const Rt=new Set(Object.values(he));function W(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&Oe(e.message)||e instanceof Error&&Rt.has(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function a(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function Ze(e,t){try{return await ne("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function l(e,t){return String((await ne("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function H(e,t){return String((await ne("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function C(e,t){try{return await ne("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Yr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Ut as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,gt as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,Pr as acceptDirectYoloSetupCheckpoint,zr as beginDirectYoloStoryCommit,ro as captureDirectYoloCheckoutEvidence,Xr as captureDirectYoloStoryGovernance,to as captureEpicOriginBindingAtYoloopStart,Fr as directYoloCommitIdempotencyKey,Jr as directYoloWaveQaCoverage,Zt as directYoloWaveReceiptRef,Rr as fetchOriginForYoloopStart,Gr as finalizeDirectYoloStoryCheckpoint,ur as isDirectYoloWriteSetExtensionScope,Tr as issueDirectYoloSetupLeaseHandoff,Qr as persistDirectYoloWaveStoryCheckpoint,qr as prepareDirectYoloSetup,Zr as pushDirectYoloWaveHead,eo as readYoloopStartEpic,Mr as recoverLegacyDirectYoloStoryCheckpoint,Kr as resolveDirectYoloIntegrationAuthority,Ur as runDirectYoloWaveP205,Vr as validateDirectYoloWriteSet,Wr as verifyDirectYoloIntegrationCommit,vr as yoloopStartGitNetworkExecOptions};
|
|
1
|
+
import{execFile as xt}from"node:child_process";import{createHash as bt,randomBytes as Ee,timingSafeEqual as kt}from"node:crypto";import{existsSync as ue}from"node:fs";import{readFile as V,realpath as je}from"node:fs/promises";import{join as X,resolve as N}from"node:path";import{promisify as Dt}from"node:util";import{rootProjectMemoryPaths as Et}from"../private-execution/shared-root-memory-types.js";import{readRootMemoryEffectForCheckpoint as Ae}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as ot,verifyRootMemoryPhysicalWriteSet as _e}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as jt,resolveEpicStoryIds as At}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as Be,storyWriteSetCovers as Ce,validateStoryWriteScope as _t}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as He,computeImmutableStoryQaEvidenceDigest as Bt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as pe,computeP205StoryQaEvidenceDigest as Ct,computeLegacyDirectYoloRecoveryReceiptRef as Ht,ensureRuntimeEpic as z,ensureRuntimeStory as Oe,ensureGitLifecyclePrivateChildDirectory as $e,executeP205TransientAuthorities as Ot,executeP205TransientAuthority as $t,isP226GateReasonCode as Le,projectP205TransientExecutionEvidence as it,publicStoryReviewArtifactFromBytes as Lt,publicStoryReviewArtifactFromGit as le,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Nt,mutateGitLifecycleRuntime as P,P205_COMPLETE_COMMAND as nt,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as Ne,STORY_WRITE_SET_MAX_ENTRIES as at,storyWriteSetExtensionPaths as Pt,assertGitLifecyclePrivateFile as ee,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as qt,verifyGitLifecyclePhysicalIntegrationLock as he,verifyAcceptedGitLifecycleStoryCheckpoint as Pe}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as qe,anchoredRemoveFile as ct}from"./secure-filesystem-boundary.js";import{GOVERNANCE_CHECKPOINT_TRAILER_KEYS as st,GOVERNANCE_DIGEST_TRAILER as dt,GOVERNANCE_REASON_CODES as ye,captureStoryGovernanceSync as Tt,detectGovernanceModeSync as zt,governanceReceiptRefs as Gt,isGovernanceRepositoryPath as Wt,readGovernanceStateSourceSync as Mt,storyReviewGovernancePath as Kt,verifyStoryGovernanceBinding as Vt}from"./governance-runtime-store.js";import{parseNeocortexTrailers as ft,trailerReasonKey as ae,trailerValue as J}from"./neocortex-trailers.js";import{StoryWorktreeManager as Ft}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Yt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ut,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as G}from"./git-lifecycle-step-ids.js";const ce=Dt(xt),se=3600*1e3;async function Tr(e){let t,o=!1;try{const r=await me(e.projectRoot,e.storyId);if(await ze(r.projectRoot)){if(e.expiredSetupRecovery)return a("direct-yolo-expired-setup-recovery-invalid");const S=await pt(r);return{ok:!0,value:lt(r,S,!1)}}const i=q(e.nowIso),n=Date.parse(i),d=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),u=await O(r.projectRoot,{required:!0}),s=g(u.epics[r.epicId]),f=g(s?.branch_lease),p=e.expiredSetupRecovery;if(p&&!lr(p,u.revision,f,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const v=f&&Number.isFinite(Date.parse(String(f.expiresAt)))&&Date.parse(String(f.expiresAt))>n;if(v&&f?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let y=Z(s?.origin_binding,r.executionBranch,r.originBranch),h;if(d===r.executionBranch){if(!y){if(s?.origin_binding!==void 0&&s?.origin_binding!==null||v)return a("direct-yolo-origin-binding-invalid");const S=await mr(r,c,i);if(!S.ok)return S;y=S.value.binding,h={originRef:S.value.originRef,originHeadSha:S.value.binding.originHeadSha}}}else{if(d!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(y&&y.originHeadSha!==c){if(!p||!await C(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,c]))return a("direct-yolo-origin-binding-conflict");const m=`refs/heads/${r.executionBranch}`;if(!await C(r.projectRoot,["show-ref","--verify","--quiet",m]))return a("direct-yolo-execution-branch-missing");const D=await l(r.projectRoot,["rev-parse",m]);if(!await C(r.projectRoot,["merge-base","--is-ancestor",D,c]))return a("direct-yolo-execution-branch-diverged")}if(y??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await fe(r.projectRoot)).some(m=>m.branch===r.executionBranch&&N(m.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const R=await W(r.projectRoot),j=`refs/heads/${r.executionBranch}`;if(await C(r.projectRoot,["show-ref","--verify","--quiet",j])){const m=await l(r.projectRoot,["rev-parse",j]);if(m!==c){if(!await C(r.projectRoot,["merge-base","--is-ancestor",m,c]))return a("direct-yolo-execution-branch-diverged");p||await l(r.projectRoot,["update-ref",j,c,m])}p?t={checkoutBefore:R,executionRef:j,executionBranch:r.executionBranch,executionHead:m,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(p)return a("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await W(r.projectRoot)!==R)return a("direct-yolo-checkout-payload-raced")}const I=t?.originHead??await l(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return a("direct-yolo-current-branch-mismatch");if(v&&f?.ownerStoryId===e.storyId)return f.setupHeadSha!==I?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:De(r,y,String(f.expiresAt),!0)};const _=i,w=new Date(n+3600*1e3).toISOString(),E=`setup-${Ee(32).toString("hex")}`,k=p?u:await O(r.projectRoot,{required:!0});return await P(r.projectRoot,S=>{const R=z(S,r.epicId),j=g(R.branch_lease);if(p&&JSON.stringify(j)!==JSON.stringify(p.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(j&&Date.parse(String(j.expiresAt))>n&&j.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const m=Z(R.origin_binding,r.executionBranch,r.originBranch);if(R.origin_binding&&!m)throw new Error("direct-yolo-origin-binding-conflict");if(m&&JSON.stringify(m)!==JSON.stringify(y))throw new Error("direct-yolo-origin-binding-conflict");R.branch_mode="epic",R.execution_branch=r.executionBranch,R.origin_branch=r.originBranch,R.graph_revision=r.graphRevision,R.origin_binding=y,R.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:E,idempotencyKey:E,acquiredAt:_,expiresAt:w,setupHeadSha:I}},{expectedRevision:p?.expectedRuntimeRevision??k.revision,preCommit:async()=>{if(t){if((await fe(r.projectRoot)).some(R=>R.branch===r.executionBranch&&N(R.path)!==r.projectRoot)||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await W(r.projectRoot)!==t.checkoutBefore||!await C(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await l(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await l(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await l(r.projectRoot,["switch",r.executionBranch]),await W(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==I)throw new Error("direct-yolo-setup-physical-state-raced");if(h&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${h.originRef}^{commit}`]).catch(()=>"")!==h.originHeadSha||await et(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,I])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:De(r,y,w,!1)}}catch(r){return o&&t&&await hr(N(e.projectRoot),t).catch(()=>{}),a(K(r,"direct-yolo-setup-failed"))}}async function zr(e){let t;try{const o=await me(e.projectRoot,e.storyId);if(await ze(o.projectRoot))return await Ut(o,q(e.nowIso));const r=await U(e.projectRoot,e.storyId),i=q(e.nowIso),n=X(r.projectRoot,".neocortex/state.json"),d=await V(n,"utf8"),c=await W(r.projectRoot),u=await l(r.projectRoot,["rev-parse","HEAD"]),s=`refs/heads/${r.executionBranch}`,f=await O(r.projectRoot,{required:!0}),p=g(f.epics[r.epicId]),v=Z(p?.origin_binding,r.executionBranch,r.originBranch),y=g(p?.branch_lease);if(!v)return a("direct-yolo-origin-binding-invalid");if(!y||!Je(y,e.storyId,i)||y?.sessionId!==y?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const h=await F(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(y.sessionId),idempotencyKey:String(y.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!h.ok)return a(h.reasonCode);if(t=h,u!==y.setupHeadSha||!await C(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,u])||await l(r.projectRoot,["rev-parse",s])!==u)return a("direct-yolo-setup-head-mismatch");if((await fe(r.projectRoot)).some(R=>R.branch===r.executionBranch&&N(R.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const _=g(JSON.parse(d)),w=g(g(_?.stories)?.[e.storyId]),E=g(f.stories[e.storyId]);if(!w||!["backlog","ready_to_start"].includes(String(w.status))||w.steps_completed!==void 0&&(!Array.isArray(w.steps_completed)||w.steps_completed.length>0)||w.branch_name||w.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const k=E?.status==="branch-ready"&&E.last_step===G&&Array.isArray(E.steps_completed)&&E.steps_completed.length===1&&E.steps_completed[0]===G&&oe(E).sort().join(",")==="last_step,status,steps_completed";if(E&&oe(E).length>0&&!k)return a("direct-yolo-setup-story-progress-conflict");const S=async()=>{if(Date.parse(String(y.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await he(t.path,t.owner)||await V(n,"utf8")!==d||await W(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==u||!await C(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,u])||await l(r.projectRoot,["rev-parse",s])!==u)throw new Error("direct-yolo-setup-physical-state-raced")};return k?await S():await P(r.projectRoot,R=>{const j=g(R.epics[r.epicId]),m=Oe(R,e.storyId);if(JSON.stringify(j?.branch_lease)!==JSON.stringify(y)||JSON.stringify(j?.origin_binding)!==JSON.stringify(v)||j?.graph_revision!==r.graphRevision||oe(m).length>0)throw new Error("direct-yolo-setup-runtime-raced");m.status="branch-ready",m.last_step=G,m.steps_completed=[G]},{expectedRevision:f.revision,preCommit:S}),{ok:!0,value:Object.freeze({...De(r,v,String(y.expiresAt),k),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:u})}}catch(o){return a(K(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await Y(t.path,t.owner).catch(()=>{})}}async function Gr(e){try{const t=await U(e.projectRoot,e.storyId),o=T(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),r=re(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!r.ok)return a(r.reasonCode);t.rootMemoryEffect&&_e(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await l(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet});const i=t.governanceMode==="runtime-store"?We(t):void 0;if((i?i.review:le(t.projectRoot,e.storyId,":"))?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(T(await H(t.projectRoot,["diff","--name-only","-z"])).some(b=>o.includes(b)))return a("direct-yolo-user-overlap");const c=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return a("direct-yolo-staged-diff-empty");const u=B(c),s=B([...t.authorizedWriteSet].sort().join("\0")),f=q(e.nowIso),p=await O(t.projectRoot,{required:!0});let v=g(p.epics[t.epicId]?.branch_lease),y;if(!Je(v,e.storyId,f)){const x=v!==void 0&&Date.parse(String(v.expiresAt))>Date.parse(f)?void 0:await gt(t.projectRoot,p,t.epicId,e.storyId,f);if(!x||!await C(t.projectRoot,["merge-base","--is-ancestor",x.setupHeadSha,"HEAD"]))return a("direct-yolo-setup-handoff-owner-invalid");y=x,v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:x.sessionId,idempotencyKey:x.idempotencyKey,acquiredAt:f,expiresAt:new Date(Math.min(Date.parse(x.expiresAt),Date.parse(f)+rr)).toISOString(),setupHeadSha:x.setupHeadSha}}const h=String(v.sessionId),I=String(v.expiresAt),_=new Date(Math.min(Date.parse(I),Date.parse(f)+300*1e3)).toISOString(),w=await te(t.projectRoot,e.storyId),E=w?.state==="issued"&&w.fromSessionId===h&&w.bundleDigest===u&&w.claimRevision===s&&Date.parse(w.expiresAt)>Date.parse(f),k=E?w.expiresAt:_,S=E?w.token:Ee(32).toString("base64url"),R=B(S),j=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:h,tokenDigest:R,bundleDigest:u,claimRevision:s,expiresAt:k}),m=B(JSON.stringify(j)),D=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:k,persistent:!1,createdAt:f});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ze(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:h,token:S,tokenDigest:R,bundleDigest:u,claimRevision:s,grantDigest:m,expiresAt:k}),await P(t.projectRoot,b=>{const x=z(b,t.epicId);if(y){const $=g(x.branch_lease);if($&&Date.parse(String($.expiresAt))>Date.parse(f))throw new Error("direct-yolo-setup-handoff-owner-raced");x.branch_lease={...v}}const A=g(x.branch_lease);if(!Je(A,e.storyId,f)||A?.sessionId!==h||A.idempotencyKey!==h)throw new Error("direct-yolo-setup-handoff-owner-raced");A.handoffGrant=j},{expectedRevision:p.revision,preCommit:async()=>{if(!await he(D.path,D.owner))throw new Error("direct-yolo-integration-lock-raced");const b=await te(t.projectRoot,e.storyId);if(!b||b.state!=="issued"||b.grantDigest!==m||b.tokenDigest!==R)throw new Error("direct-yolo-setup-handoff-token-raced");if(y&&(await yt(t.projectRoot,e.storyId))?.sessionId!==y.sessionId)throw new Error("direct-yolo-setup-handoff-owner-raced")}}),y&&await ir(t.projectRoot,e.storyId)}finally{await Y(D.path,D.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:h,bundleDigest:u,claimRevision:s,grantDigest:m,expiresAt:k,reused:E,publicSafe:!0,...i?{governance:i.receipt}:{}})}}catch(t){return a(t instanceof Error&&(/^direct-yolo-/.test(t.message)||It.has(t.message))?t.message:"direct-yolo-setup-handoff-failed")}}async function Wr(e){try{const t=await U(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=T(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),i=re(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&_e(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=t.governanceMode==="runtime-store"?We(t):void 0,d=n?n.review:le(t.projectRoot,e.storyId,":");if(d?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(T(await H(t.projectRoot,["diff","--name-only","-z"])).some(b=>r.includes(b)))return a("direct-yolo-user-overlap");const u=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!u)return a("direct-yolo-staged-diff-empty");const s=B(u),f=B([...t.authorizedWriteSet].sort().join("\0")),p=await Ye(t.projectRoot,e.storyId),v=p.state==="valid"&&p.plan.epicId===t.epicId&&p.plan.executionBranch===t.executionBranch&&p.plan.preparedBase===o&&p.plan.bundleDigest===s&&p.plan.claimRevision===f?p.plan:void 0,y=v?.graphRevision??t.graphRevision,h=Ve({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,graphRevision:y,claimRevision:f}),I=q(e.nowIso),_={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:y,preparedBase:o,bundleDigest:s,claimRevision:f,idempotencyKey:h,issuedAt:v?.issuedAt??I};let w=e.setupLeaseHandoff??await nr(t.projectRoot,e.storyId,s,f,I);const E=await O(t.projectRoot,{required:!0}),k=g(E.epics[t.epicId]?.branch_lease),S=k?.ownerStoryId===e.storyId&&k.sessionId===h&&k.idempotencyKey===h&&typeof k.expiresAt=="string"&&Date.parse(k.expiresAt)>Date.parse(I)?k:void 0;if(S&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const R=g(S?.handoffConsumption);if(R){const b=await te(t.projectRoot,e.storyId);if(!b||!["consuming","consumed"].includes(b.state)||b.fromSessionId!==R.fromSessionId||b.tokenDigest!==R.tokenDigest||b.bundleDigest!==s||b.claimRevision!==f||R.bundleDigest!==s||R.claimRevision!==f||b.consumedBySessionId!==h||R.consumedBySessionId!==h)return a("direct-yolo-setup-handoff-consume-invalid");if(b.state==="consuming"){if(!b.token||B(b.token)!==b.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");w={sessionId:b.fromSessionId,token:b.token}}}const j=S?String(S.expiresAt):new Date(Date.parse(I)+se).toISOString(),m=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:j,persistent:!0,createdAt:S&&typeof S.acquiredAt=="string"?S.acquiredAt:I});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{w&&e.setupLeaseHandoff===void 0&&(await ar(t.projectRoot,e.storyId,w.sessionId,w.token,h,I),await e.setupHandoffFault?.("after-consuming-persisted")),await P(t.projectRoot,b=>{const x=z(b,t.epicId),A=g(x.branch_lease),$=A&&Date.parse(String(A.expiresAt))>Date.parse(I),L=A?.ownerStoryId===e.storyId&&A.sessionId===h&&A.idempotencyKey===h,M=A?.ownerStoryId===e.storyId&&A.sessionId===A.idempotencyKey&&typeof A.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(A.idempotencyKey),Q=$&&M&&sr({current:A,handoff:w,storyId:e.storyId,bundleDigest:s,claimRevision:f,nowIso:I});if(w&&$&&!L&&!Q)throw new Error("direct-yolo-setup-handoff-invalid");if($&&!L&&!Q)throw new Error("direct-yolo-writer-active");const tt=Q?g(A?.handoffGrant):void 0,rt=tt?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(A?.sessionId),tokenDigest:String(tt.tokenDigest),bundleDigest:s,claimRevision:f,consumedBySessionId:h,consumedAt:I}:void 0;x.branch_mode="epic",x.execution_branch=t.executionBranch,x.origin_branch=t.originBranch,x.graph_revision=t.graphRevision,x.branch_lease=$&&L?A:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:I,expiresAt:j,...rt?{handoffConsumption:rt}:{}}},{expectedRevision:E.revision,preCommit:async()=>{if(!await he(m.path,m.owner))throw new Error("direct-yolo-integration-lock-raced");await er(t.projectRoot,_)}})}catch(b){throw await Y(m.path,m.owner).catch(()=>{}),b}w&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await cr(t.projectRoot,t.epicId,e.storyId,w.sessionId,w.token,s,f,h,I));const D=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${s}`,`Neocortex-Review-Artifact-Digest: ${d.digest}`,`Neocortex-Graph-Revision: ${y}`,`Neocortex-Claim-Revision: ${f}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${ot(t.rootMemoryEffect)}`]:[],...n?[`${dt}: ${n.receipt.governanceDigest}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,reviewArtifactDigest:d.digest,graphRevision:y,claimRevision:f,idempotencyKey:h,changedPaths:Object.freeze(r),trailers:D,...n?{governance:n.receipt}:{}})}}catch(t){return a(K(t,"direct-yolo-begin-failed"))}}async function Mr(e){let t,o,r;try{const i=await U(e.projectRoot,e.storyId);t=i;const n=e.preFastForwardAuthorizedWriteSet;if(n!==void 0&&!Te(n))return a("direct-yolo-write-set-invalid");const d=n??i.authorizedWriteSet,c=await l(i.projectRoot,["rev-parse","HEAD"]);let u=await O(i.projectRoot,{required:!0});const s=g(u.stories[e.storyId]?.checkpoint);if(s){const D=typeof s.headSha=="string"?s.headSha:"",b=typeof s.graphRevision=="string"?s.graphRevision:"",x=/^[a-f0-9]{40,64}$/.test(D)?T(await H(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",D])):[],A=re(x,d,e.storyId,i.rootMemoryEffect,i.governanceMode);if(!(/^[a-f0-9]{40,64}$/.test(D)&&await C(i.projectRoot,["merge-base","--is-ancestor",D,c]))||!/^[a-f0-9]{64}$/.test(b)||!A.ok)return a("direct-yolo-replay-invalid");const L=await Ie(e,i.projectRoot,c,b);if(!await Pe(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,L.transientAuthority,d))return a("direct-yolo-replay-invalid");if(!await xe(i.projectRoot,i.executionBranch,c,x))return a("direct-yolo-replay-head-raced");if(e.push&&!await Ke(i.projectRoot,e.remote??"origin",i.executionBranch,D))return a("direct-yolo-remote-head-mismatch");const M=Array.isArray(s.receiptRefs)?s.receiptRefs.find(Q=>typeof Q=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(Q)):void 0;return M&&typeof s.idempotencyKey=="string"&&await qt(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:M.slice(20)}),await de(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const f=c,p=await ge(i,e.storyId,f,n?{claimWriteSet:n}:{});if(!p.ok)return a(p.reasonCode);const{baseSha:v,changedPaths:y,bundleDigest:h,graphRevision:I,claimRevision:_,idempotencyKey:w,governance:E}=p.value,k=g(u.epics[i.epicId]?.branch_lease),S=q(e.nowIso),R=k?.ownerStoryId===e.storyId&&k.idempotencyKey===w&&k.sessionId===w&&Date.parse(String(k.expiresAt))>Date.now()?k:void 0;if(k&&Date.parse(String(k.expiresAt))>Date.now()&&!R)return a("direct-yolo-writer-active");const j=R??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:w,idempotencyKey:w,acquiredAt:S,expiresAt:new Date(Date.parse(S)+se).toISOString()},m=await F(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,R||(u=(await P(i.projectRoot,b=>{const x=z(b,i.epicId),A=g(x.branch_lease);if(A&&Date.parse(String(A.expiresAt))>Date.parse(S))throw new Error("direct-yolo-writer-active");if(x.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");x.branch_lease=j},{expectedRevision:u.revision})).document),o=j;{const D=await Ie(e,i.projectRoot,f,I);if(!await xe(i.projectRoot,i.executionBranch,f,y))return a("direct-yolo-head-raced");if(e.push){const A=ne(e.remote??"origin");if(await l(i.projectRoot,["push",A,i.executionBranch]),!await Qe(i.projectRoot,A,i.executionBranch,f))return a("direct-yolo-remote-head-mismatch")}const b=await we({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:v,headSha:f,bundleDigest:h,graphRevision:I,claimRevision:_,idempotencyKey:w,qaExecution:D,physicalLockOwnerDigest:pe(m.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect,...E?{governance:E}:{}});return await e.beforeCheckpointPersist?.(),await ve({projectRoot:i.projectRoot,checkpoint:b,remote:e.push?e.remote??"origin":void 0,expectedRevision:u.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:I,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:D.transientAuthority,authorizedWriteSet:d})?(await de(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:b}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(K(i,"direct-yolo-finalize-failed"))}finally{r&&await Y(r.path,r.owner).catch(()=>{}),t&&o?await Se(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await fr(t,e.storyId).catch(()=>{})}}function Te(e){return Array.isArray(e)&&e.length>0&&e.length<=at&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}async function Kr(e,t,o,r={}){try{return/^[a-f0-9]{40,64}$/.test(o)?await ge(e,t,o,{claimWriteSet:e.authorizedWriteSet,...r.expectedGraphRevision!==void 0?{expectedGraphRevision:r.expectedGraphRevision}:{}}):a("direct-yolo-recovery-commit-invalid")}catch(i){return a(K(i,"direct-yolo-commit-verification-failed"))}}async function ge(e,t,o,r={}){if(r.claimWriteSet!==void 0&&!Te(r.claimWriteSet))return a("direct-yolo-write-set-invalid");if(r.expectedGraphRevision!==void 0&&!/^[a-f0-9]{64}$/.test(r.expectedGraphRevision))return a("direct-yolo-graph-revision-invalid");const i=r.claimWriteSet??e.authorizedWriteSet,n=await l(e.projectRoot,["rev-parse",`${o}^`]),d=await H(e.projectRoot,["show","--no-patch","--format=%B",o]),c=T(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),u=re(c,i,t,e.rootMemoryEffect,e.governanceMode);if(!u.ok)return a(u.reasonCode);e.rootMemoryEffect&&_e(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:n,headRef:o,childPaths:i});const s=B([...i].sort().join("\0")),f=await Ye(e.projectRoot,t);if(f.state==="invalid")return a("direct-yolo-commit-plan-invalid");const p=f.state==="valid"?f.plan:void 0;if(p&&(p.epicId!==e.epicId||p.executionBranch!==e.executionBranch))return a("direct-yolo-commit-plan-invalid");if(p&&p.claimRevision!==s)return a("direct-yolo-commit-plan-claim-changed");if(p&&p.preparedBase!==n)return a("direct-yolo-commit-plan-base-mismatch");const v=ft(d,st);if(!v.ok)return a(`direct-yolo-trailer-duplicate:${v.key}`);const y=v.values;if(r.expectedGraphRevision!==void 0&&p&&p.graphRevision!==r.expectedGraphRevision)return a(`direct-yolo-trailer-mismatch:${ae("Neocortex-Graph-Revision")}`);const h=r.expectedGraphRevision??p?.graphRevision??e.graphRevision,I=s,_=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",n],["Neocortex-Bundle-Digest",p?.bundleDigest??""],["Neocortex-Graph-Revision",h],["Neocortex-Claim-Revision",I]];for(const[D,b]of _){const x=J(y,D);if(x===void 0)return a(`direct-yolo-trailer-missing:${ae(D)}`);if(D==="Neocortex-Bundle-Digest"&&!p){if(!/^[a-f0-9]{64}$/.test(x))return a(`direct-yolo-trailer-mismatch:${ae(D)}`);continue}if(x!==b)return a(`direct-yolo-trailer-mismatch:${ae(D)}`)}const w=J(y,"Neocortex-Bundle-Digest"),E=J(y,dt);if(e.governanceMode!=="runtime-store"&&E!==void 0)return a(ye.MISMATCH);const k=e.governanceMode==="runtime-store"?Me({projectRoot:e.projectRoot,epicId:e.epicId,storyId:t},E):void 0,S=k?k.review:le(e.projectRoot,t,o);if(S?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const R=J(y,"Neocortex-Review-Artifact-Digest");if(R!==void 0&&R!==S.digest)return a("direct-yolo-review-artifact-digest-mismatch");const j=B(await H(e.projectRoot,["diff","--binary","--full-index",`${n}..${o}`]));if(w!==j)return a("direct-yolo-bundle-digest-mismatch");const m=Ve({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:n,bundleDigest:w,graphRevision:h,claimRevision:I});return p&&p.idempotencyKey!==m?a("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:n,changedPaths:c,bundleDigest:w,graphRevision:h,claimRevision:I,idempotencyKey:m,...k?{governance:k.receipt}:{}}}}async function Vr(e){try{const t=await U(e.projectRoot,e.storyId,!1);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return a("direct-yolo-recovery-commit-invalid");const o=await l(t.projectRoot,["rev-parse",e.commitSha]);if(Nt[e.storyId]!==o)return await Jt(e,t,o);if(await Ae({...t,childPaths:t.authorizedWriteSet}),await l(t.projectRoot,["rev-parse","HEAD"])!==o)return a("direct-yolo-recovery-head-mismatch");await l(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await l(t.projectRoot,["rev-parse",`${o}^`]),i=await H(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=T(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!re(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const c=B(i),u=B([...n].sort().join("\0")),s=B(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),f=q(e.nowIso),p=new Date(Date.parse(f)+se).toISOString(),v=await O(t.projectRoot,{required:!0}),y=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:s,idempotencyKey:s,expiresAt:p,persistent:!0,createdAt:f});if(!y.ok)return a(y.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const h={schemaVersion:1,ownerStoryId:e.storyId,sessionId:s,idempotencyKey:s,acquiredAt:f,expiresAt:p};let I=!1;try{const _=await P(t.projectRoot,j=>{const m=z(j,t.epicId),D=g(m.branch_lease);if(D&&Date.parse(String(D.expiresAt))>Date.parse(f)&&!Re(D,h))throw new Error("direct-yolo-recovery-writer-active");if(m.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");m.branch_mode="epic",m.execution_branch=t.executionBranch,m.origin_branch=t.originBranch,m.branch_lease=h},{expectedRevision:v.revision});I=!0;const w=await Ie(e,t.projectRoot,o,t.graphRevision);if(!await xe(t.projectRoot,t.executionBranch,o,n))return a("direct-yolo-recovery-head-raced");if(e.push){const j=ne(e.remote??"origin"),m=(await l(t.projectRoot,["ls-remote","--heads",j,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!m||!await C(t.projectRoot,["merge-base","--is-ancestor",o,m]))return a("direct-yolo-recovery-remote-proof-missing")}const E=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:u,idempotencyKey:s,qaExecution:w,physicalLockOwnerDigest:pe(y.owner),nowIso:f,legacyReceiptRef:void 0}),k=await Ht(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!k)return a("direct-yolo-recovery-evidence-invalid");const S=Object.freeze({...E,receiptRefs:Object.freeze([...E.receiptRefs,k])});return await ve({projectRoot:t.projectRoot,checkpoint:S,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:_.document.revision,expectedLease:h,expectedGraphRevision:t.graphRevision,physicalLockPath:y.path,physicalLockOwner:y.owner,transientAuthority:w.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:S}:a("direct-yolo-recovery-persist-failed")}finally{await Y(y.path,y.owner).catch(()=>{}),I&&await Se(t.projectRoot,t.epicId,h).catch(()=>{})}}catch(t){return a(K(t,"direct-yolo-recovery-failed"))}}async function Jt(e,t,o){const r=await H(t.projectRoot,["show","--no-patch","--format=%B",o]),i=ft(r,st);if(!i.ok||J(i.values,"Neocortex-Story")!==e.storyId)return a("direct-yolo-recovery-not-allowlisted");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o||!await C(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]))return a("direct-yolo-recovery-head-mismatch");const n=J(i.values,"Neocortex-Root-Memory-Effect");let d=t.graphRevision;if(n!==void 0){if(!/^[a-f0-9]{64}$/.test(n))return a("direct-yolo-recovery-root-governance-unverified");const D=await Ye(t.projectRoot,e.storyId);if(D.state==="invalid")return a("direct-yolo-commit-plan-invalid");if(D.state==="valid"&&(d=D.plan.graphRevision),J(i.values,"Neocortex-Graph-Revision")!==d)return a(`direct-yolo-trailer-mismatch:${ae("Neocortex-Graph-Revision")}`)}let c;try{c=await Ae({...t,graphRevision:d,childPaths:t.authorizedWriteSet})}catch{return a("direct-yolo-recovery-root-governance-unverified")}if((c?ot(c):void 0)!==n)return a("direct-yolo-recovery-root-governance-unverified");const u=await ge({...t,rootMemoryEffect:c},e.storyId,o);if(!u.ok){if(u.reasonCode==="direct-yolo-write-set-unauthorized"){const D=T(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","--no-renames","-r","-z",o])),b=new Set([...Et(),`docs/epics/epic-${t.epicId}.md`]);if(D.some(x=>b.has(x)&&!Ce(t.authorizedWriteSet,x)&&!c?.files.some(A=>A.path===x)))return a("direct-yolo-recovery-root-governance-unverified")}return a(u.reasonCode)}const{baseSha:s,changedPaths:f,bundleDigest:p,graphRevision:v,claimRevision:y,idempotencyKey:h,governance:I}=u.value,_=ne(e.remote??"origin");let w=!1;try{w=await Ke(t.projectRoot,_,t.executionBranch,o)}catch{w=!1}if(!w)return a("direct-yolo-recovery-remote-proof-missing");const E=q(e.nowIso),k=new Date(Date.parse(E)+se).toISOString(),S=await O(t.projectRoot,{required:!0});if(g(S.stories[e.storyId]?.checkpoint))return a("direct-yolo-checkpoint-conflict");const R=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:k,persistent:!0,createdAt:E});if(!R.ok)return a(R.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const j={schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:E,expiresAt:k};let m=!1;try{const D=await P(t.projectRoot,$=>{const L=z($,t.epicId),M=g(L.branch_lease);if(M&&Date.parse(String(M.expiresAt))>Date.parse(E)&&!Re(M,j))throw new Error("direct-yolo-recovery-writer-active");if(L.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");L.branch_mode="epic",L.execution_branch=t.executionBranch,L.origin_branch=t.originBranch,L.branch_lease=j},{expectedRevision:S.revision});m=!0;const b=await Ie(e,t.projectRoot,o,v);if(!await xe(t.projectRoot,t.executionBranch,o,f))return a("direct-yolo-recovery-head-raced");const x=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:s,headSha:o,bundleDigest:p,graphRevision:v,claimRevision:y,idempotencyKey:h,qaExecution:b,physicalLockOwnerDigest:pe(R.owner),nowIso:E,legacyReceiptRef:void 0,rootMemoryEffect:c,...I?{governance:I}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:x,remote:_,remotePolicy:"ancestor-recovery",expectedRevision:D.document.revision,expectedLease:j,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:v,physicalLockPath:R.path,physicalLockOwner:R.owner,transientAuthority:b.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?(await de(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:x}):a("direct-yolo-recovery-persist-failed")}finally{await Y(R.path,R.owner).catch(()=>{}),m&&await Se(t.projectRoot,t.epicId,j).catch(()=>{})}}async function ze(e){const t=await je(await l(e,["rev-parse","--absolute-git-dir"])),o=await je(await l(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function pt(e){const t=await O(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(p=>p.storyId===e.storyId&&p.epicId===e.epicId&&p.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await je(await l(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const d=await new Ft({projectRoot:e.projectRoot}).probe(r.leaseId);if(!d.ok||d.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=Z(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const u=r.syncedSha??r.baseSha,s=await l(e.projectRoot,["rev-parse","HEAD"]),f=`refs/heads/${e.executionBranch}`;if(s!==u||!await C(e.projectRoot,["merge-base","--is-ancestor",u,f])||!await C(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,u]))throw new Error("direct-yolo-worktree-base-divergent");if(d.value.clean!==!0||(await H(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-worktree-dirty");return{leaseId:r.leaseId,temporaryBranch:r.temporaryBranch,authorizedBase:u,headSha:s,expiresAt:r.expiresAt,binding:c}}function lt(e,t,o){return Object.freeze({...De(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Ut(e,t){const o=await pt(e),r=Ge(e.projectRoot),i=g(JSON.parse(r)),n=g(g(i?.stories)?.[e.storyId]),d=await O(e.projectRoot,{required:!0}),c=g(d.stories[e.storyId]);if(!n||!["backlog","ready_to_start"].includes(String(n.status))||n.steps_completed!==void 0&&(!Array.isArray(n.steps_completed)||n.steps_completed.length>0)||n.branch_name||n.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const u=c?.status==="branch-ready"&&c.last_step===G&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===G&&oe(c).sort().join(",")==="last_step,status,steps_completed";if(c&&oe(c).length>0&&!u)return a("direct-yolo-setup-story-progress-conflict");u||await P(e.projectRoot,p=>{const v=Oe(p,e.storyId);if(oe(v).length>0)throw new Error("direct-yolo-setup-runtime-raced");v.status="branch-ready",v.last_step=G,v.steps_completed=[G]},{expectedRevision:d.revision,preCommit:async()=>{if(Ge(e.projectRoot)!==r||await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.temporaryBranch||await l(e.projectRoot,["rev-parse","HEAD"])!==o.headSha||(await H(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}});const s=await O(e.projectRoot,{required:!0}),f=await gt(e.projectRoot,s,e.epicId,e.storyId,t);if(f?.leaseId!==o.leaseId||f.setupHeadSha!==o.headSha){const p=`setup-${Ee(32).toString("hex")}`;await or(e.projectRoot,{schemaVersion:1,kind:ht,epicId:e.epicId,ownerStoryId:e.storyId,sessionId:p,idempotencyKey:p,leaseId:o.leaseId,acquiredAt:t,expiresAt:o.expiresAt,setupHeadSha:o.headSha})}return{ok:!0,value:Object.freeze({...lt(e,o,u),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:o.headSha})}}async function Fr(e,t){const o=await U(e,t),r=await O(o.projectRoot,{required:!0}),i=Z(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Yr(e,t,o,r,i="tracked"){return re(e,t,o,r,i)}function Jr(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Ur=se,Zt="p205-wave:";function Zr(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=B(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function Qt(e){return`${Zt}${e.waveHeadSha}:${e.waveDigest}`}async function Qr(e){let t;try{t=await Ot(e.projectRoot,{headSha:e.headSha,graphRevisions:e.graphRevisions,...e.nowIso!==void 0?{nowIso:e.nowIso}:{}})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:Le(r)?r:"p205-complete-gate-failed"}}try{await e.qaRunner?.({projectRoot:e.projectRoot,storyId:e.storyId,headSha:e.headSha})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:Le(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Xr(e,t,o,r){const i=ne(t);return await l(e,["push",i,o]),Qe(e,i,o,r)}async function eo(e){try{const t=await U(e.projectRoot,e.storyId);if(e.authorizedWriteSet!==void 0&&!Te(e.authorizedWriteSet))return a("direct-yolo-write-set-invalid");const o=e.authorizedWriteSet??t.authorizedWriteSet,r=e.coverage.waveHeadSha,i=e.coverage.waveStoryIds.indexOf(e.storyId);if(i<0||e.coverage.waveCommitShas[i]!==e.headSha)return a("direct-yolo-wave-coverage-invalid");if(await l(t.projectRoot,["rev-parse","HEAD"])!==r||await l(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==r||!await C(t.projectRoot,["merge-base","--is-ancestor",e.headSha,r]))return a("direct-yolo-wave-head-raced");const n=await O(t.projectRoot,{required:!0}),d=g(n.stories[e.storyId]?.checkpoint);if(d){if(d.headSha!==e.headSha)return a("direct-yolo-checkpoint-conflict");const k=e.authorities.get(String(d.graphRevision));return await Pe(t.projectRoot,d,e.storyId,t.epicId,t.executionBranch,k??null,o)?(await de(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:d}):a("direct-yolo-replay-invalid")}const c=await ge(t,e.storyId,e.headSha,{...e.authorizedWriteSet!==void 0?{claimWriteSet:e.authorizedWriteSet}:{},...e.expectedGraphRevision!==void 0?{expectedGraphRevision:e.expectedGraphRevision}:{}});if(!c.ok)return a(c.reasonCode);const{baseSha:u,bundleDigest:s,graphRevision:f,claimRevision:p,idempotencyKey:v,governance:y}=c.value,h=i===0?void 0:e.coverage.waveCommitShas[i-1];if(h!==void 0&&u!==h)return a("direct-yolo-wave-chain-invalid");const I=e.authorities.get(f),_=it(I);if(!I||!_||_.executionHeadSha!==r||_.graphRevision!==f)return a("direct-yolo-wave-qa-unbound");const w=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:u,headSha:e.headSha,bundleDigest:s,graphRevision:f,claimRevision:p,idempotencyKey:v,qaExecution:{contract:"P205-CI-02",command:nt,manifestDigest:_.manifestDigest,gateIds:_.gateIds,resultDigest:_.resultDigest,transientAuthority:I},physicalLockOwnerDigest:pe(e.physicalLock.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Qt(e.coverage)],...y?{governance:y}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:w,remote:e.remote,expectedRevision:n.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:f,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:I,authorizedWriteSet:o,expectedHeadSha:r,keepLease:!0})?(await de(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:w}):a("direct-yolo-checkpoint-persist-failed")}catch(t){return a(K(t,"direct-yolo-wave-persist-failed"))}}async function me(e,t,o=!0){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const r=N(e),i=g(JSON.parse(Ge(r))),n=await O(r,{required:!0}),d=He(i,n),c=zt({projectRoot:r,storyId:t});if(!c.ok)throw new Error(c.reasonCode);const u=c.mode,s=g(d.stories),f=g(d.epics),p=g(s?.[t]),v=String(p?.epic_id??t.split(".")[0]),y=g(f?.[v]),h=String(y?.execution_branch??""),I=String(y?.origin_branch??""),_=String(y?.graph_revision??""),w=Array.isArray(p?.files_to_modify)?p.files_to_modify:[],E=Pt(p).filter(pr),k=[...w,...E],S=k.length>0?Be(t,k):void 0,R=S?.ok?S.scopes:[];if(!p)throw new Error("direct-yolo-story-state-missing");if(E.length>0&&R.length>at)throw new Error("direct-yolo-write-set-too-large");if(y?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!ie(h)||!await C(r,["check-ref-format","--branch",h]))throw new Error("direct-yolo-execution-branch-invalid");if(!ie(I)||!await C(r,["check-ref-format","--branch",I]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(_))throw new Error("direct-yolo-graph-revision-invalid");const j=o?await Ae({projectRoot:r,storyId:t,graphRevision:_,executionBranch:h,childPaths:R}):void 0;return{projectRoot:r,storyId:t,story:p,epicId:v,executionBranch:h,originBranch:I,graphRevision:_,authorizedWriteSet:R,rootMemoryEffect:j,governanceMode:u}}async function to(e){try{const t=await me(e.projectRoot,e.storyId);return t.governanceMode!=="runtime-store"?a("governance-capture-not-applicable"):await ze(t.projectRoot)?a("governance-capture-root-required"):{ok:!0,value:We(t).receipt}}catch(t){return a(K(t,"governance-capture-failed"))}}function Ge(e){const t=Mt(e);if(!t.ok)throw new Error(t.reasonCode);if(!t.value)throw new Error("direct-yolo-story-state-missing");return t.value.toString("utf8")}function We(e){const t=Tt(e);if(!t.ok)throw new Error(t.reasonCode);return Me(e,t.value.governanceDigest)}function Me(e,t){const o=Vt({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Kt(e.storyId));if(!r)throw new Error(ye.MISMATCH);return{receipt:o.value.receipt,review:Lt(e.storyId,r)}}async function U(e,t,o=!0){const r=await me(e,t,o);if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return r}async function we(e){const t=e.nowIso,o=await H(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=T(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=Bt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Ct({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),d=`story-qa:${n}`,c=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:d}),u=e.governance?Me(e,e.governance.governanceDigest).review:le(e.projectRoot,e.storyId,e.headSha);if(u?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const s=B(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,d,B(o),[...r].sort().join(","),u.digest].join("\0")),f=`story-review:${s}`,p=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:s,reviewArtifactDigest:u.digest,qaReceiptRef:d,verdict:"approved",reviewedAt:t,receiptRef:f}),v=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,d,f,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[],...e.governance?Gt(e.governance):[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(v),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:p,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function ve(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await P(t,n=>{const d=z(n,o.epicId);if(e.expectedLease){const f=g(d.branch_lease);if(!Re(f,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(f?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(d.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const c=Oe(n,o.storyId),u=g(c.checkpoint);if(u&&u.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=ut;const s=Array.isArray(c.steps_completed)?c.steps_completed.filter(f=>typeof f=="string"):[];c.steps_completed=[...new Set([...s,Yt,ut])],e.keepLease||(d.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await l(t,["rev-parse","HEAD"])!==n||await l(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await C(t,["merge-base","--is-ancestor",o.headSha,n]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await Pe(t,o,o.storyId,o.epicId,o.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await he(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Ke(t,r,o.branch,o.headSha):await Qe(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Ke(e,t,o,r){const i=ne(t),n=(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await C(e,["merge-base","--is-ancestor",r,n]))}function Ve(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Xt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Fe(e,t){const o=await Ne(e),r=await $e(o,"commit-plans"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function er(e,t){const o=await Fe(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`),await ee(o.path,o.parent)}async function Ye(e,t){let o;try{o=await Fe(e,t)}catch{return{state:"invalid"}}try{if(!ue(o.path))return{state:"absent"};await ee(o.path,o.parent);const r=await V(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=g(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...Xt].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!ie(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(d=>typeof d=="string"&&/^[a-f0-9]{64}$/.test(d))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const n=i;return n.idempotencyKey!==Ve({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function de(e,t){const o=await Fe(e,t);ue(o.path)&&await ct(o.parent,o.name)}function Je(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}const ht="direct-yolo-worktree-setup-reservation",tr=["schemaVersion","kind","epicId","ownerStoryId","sessionId","idempotencyKey","leaseId","acquiredAt","expiresAt","setupHeadSha"],rr=3600*1e3;async function Ue(e,t){const o=await Ne(e),r=await $e(o,"setup-reservations"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function or(e,t){const o=await Ue(e,t.ownerStoryId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),await ee(o.path,o.parent)}async function yt(e,t){try{const o=await Ue(e,t);if(!ue(o.path))return;await ee(o.path,o.parent);const r=JSON.parse(await V(o.path,"utf8"));return Object.keys(r).sort().join("\0")!==[...tr].sort().join("\0")||r.schemaVersion!==1||r.kind!==ht||r.ownerStoryId!==t||!be(r.epicId)||!be(r.leaseId)||typeof r.sessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.sessionId)||r.idempotencyKey!==r.sessionId||typeof r.setupHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.setupHeadSha)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!(Date.parse(String(r.expiresAt))>Date.parse(String(r.acquiredAt)))?void 0:r}catch{return}}async function ir(e,t){const o=await Ue(e,t);ue(o.path)&&await ct(o.parent,o.name)}async function gt(e,t,o,r,i){const n=await yt(e,r),d=Date.parse(i);if(!n||n.epicId!==o||!(Date.parse(n.expiresAt)>d))return;const c=Object.values(t.storyWorktrees?.entries??{}).find(s=>s.leaseId===n.leaseId);if(!c||c.state!=="active"||c.storyId!==r||c.epicId!==o||!(Date.parse(c.expiresAt)>d))return;const u=g(t.stories[r]);if(!(u?.checkpoint||u?.last_step!==G))return n}async function mt(e,t){const o=await Ne(e),r=await $e(o,"handoffs"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function Ze(e,t){const o=await mt(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await ee(o.path,o.parent)}async function te(e,t){try{const o=await mt(e,t);await ee(o.path,o.parent);const r=JSON.parse(await V(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function nr(e,t,o,r,i){const n=await te(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||B(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function ar(e,t,o,r,i,n){const d=await te(e,t);if(!d||d.state==="consumed"||d.fromSessionId!==o||d.token!==r||d.tokenDigest!==B(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(d.state==="consuming"){if(d.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await Ze(e,{...d,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function cr(e,t,o,r,i,n,d,c,u){const s=await te(e,o);if(s?.state==="consumed"&&s.fromSessionId===r&&s.consumedBySessionId===c)return;const f=await O(e,{required:!0}),p=g(f.epics[t]?.branch_lease),v=g(p?.handoffConsumption);if(!s||s.state!=="consuming"||s.fromSessionId!==r||s.token!==i||s.tokenDigest!==B(i)||s.bundleDigest!==n||s.claimRevision!==d||s.consumedBySessionId!==c||p?.ownerStoryId!==o||p.sessionId!==c||v?.kind!=="direct-yolo-setup-handoff-consumption"||v.state!=="consumed"||v.fromSessionId!==r||v.tokenDigest!==s.tokenDigest||v.bundleDigest!==n||v.claimRevision!==d||v.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ze(e,{schemaVersion:1,kind:s.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:s.tokenDigest,bundleDigest:s.bundleDigest,claimRevision:s.claimRevision,grantDigest:s.grantDigest,expiresAt:s.expiresAt,consumedBySessionId:c,consumedAt:u})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function sr(e){const t=g(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?B(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&dr(t.tokenDigest,r))}function dr(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&kt(o,r)}function Re(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Se(e,t,o){await P(e,r=>{const i=z(r,t),n=g(i.branch_lease);Re(n,o)&&(i.branch_lease=null)})}async function fr(e,t){const o=await O(e.projectRoot,{required:!0}),r=g(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!be(r.sessionId)||!be(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await F(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(r.sessionId),idempotencyKey:String(r.idempotencyKey),createdAt:String(r.acquiredAt),expiresAt:String(r.expiresAt),persistent:!0});if(!i.ok)return;await Y(i.path,i.owner)&&await Se(e.projectRoot,e.epicId,r)}async function Ie(e,t,o,r){const i=await $t(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=it(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:nt,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function xe(e,t,o,r){return await l(e,["rev-parse","HEAD"])!==o||await l(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await C(e,["diff","--cached","--quiet"])?!1:C(e,["diff","--quiet","HEAD","--",...r])}async function Qe(e,t,o,r){const i=ne(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function re(e,t,o,r,i="tracked"){if(e.length===0||e.some(c=>!Xe(c)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};if(i==="runtime-store")return ur(e,t,o,r);const n=t.length>0?Be(o,t):void 0;return n?.ok?[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`].every(c=>e.includes(c))?r&&(r.storyId!==o||r.childClaimRevision!==B([...n.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(c=>!Ce(n.scopes,c)&&!r?.files.some(u=>u.path===c))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}}function ur(e,t,o,r){if(e.some(Wt))return{ok:!1,reasonCode:ye.WRITE_SET_FORBIDDEN};const i=t.length>0?Be(o,t):void 0;if(!i?.ok)return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const n=`docs/stories/${o}.story.md`;return!e.includes(n)||!e.some(d=>d!==n)?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==B([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(d=>!Ce(i.scopes,d)&&!r?.files.some(c=>c.path===d))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function oe(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function pr(e){return typeof e!="string"||e.length>512||!Xe(e)||!_t(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Xe(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function be(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function ie(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function ne(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function B(e){return bt("sha256").update(e).digest("hex")}function T(e){return e.split("\0").filter(Boolean)}function q(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function lr(e,t,o,r,i){const n=g(e.expectedLease),d=n?.sessionId,c=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof d=="string"&&/^setup-[a-f0-9]{64}$/.test(d)&&n.idempotencyKey===d&&Number.isFinite(c)&&c<=i}async function hr(e,t){let o=await l(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await l(e,["rev-parse","HEAD"])!==t.originHead||await W(e)!==t.checkoutBefore)return;await l(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await l(e,["rev-parse","HEAD"])!==t.originHead||await W(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await C(e,["show-ref","--verify","--quiet",t.executionRef]))return;await l(e,["rev-parse",t.executionRef])===t.originHead&&await l(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const yr=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],gr=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function Z(e,t,o){const r=g(e);if(!r||r.originBranch!==o||r.executionBranch!==t||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt)))return;const i=Object.keys(r).sort().join("\0");if(r.schemaVersion===1)return r.capturedFromCurrentCheckout!==!0||i!==yr.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==gr.join("\0")?void 0:r}async function mr(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await C(e.projectRoot,["show-ref","--verify","--quiet",r]))return a("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await l(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return a("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await fe(e.projectRoot)).some(u=>u.branch===e.executionBranch&&N(u.path)!==e.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const d=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",d]).catch(()=>"")!==t)return a("direct-yolo-setup-physical-state-raced");const c=await et(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?a("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?a("direct-yolo-origin-ancestry-unverifiable"):{ok:!0,value:{originRef:r,binding:{schemaVersion:2,originBranch:e.originBranch,originHeadSha:i,executionBranch:e.executionBranch,capturedFrom:"branch-ref",capturedAt:o}}}}const wt=3e4,wr=3,vr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class ke extends Error{}function Rr(e,t=wt){return{timeout:t,killSignal:"SIGKILL",env:{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_HTTP_LOW_SPEED_LIMIT:"1000",GIT_HTTP_LOW_SPEED_TIME:"30",...e.GIT_SSH_COMMAND?{}:{GIT_SSH_COMMAND:vr}}}}async function Sr(e){if(!ie(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ce("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:N(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...Rr(process.env,e.fetchTimeoutMs??wt)}),{ok:!0}}catch(t){const o=String(t.stderr??"");return{ok:!1,reasonCode:/non-fast-forward|\[rejected\]/.test(o)?"origin-binding-start-fetch-non-fast-forward":"origin-binding-start-fetch-unavailable"}}}const Ir=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function ro(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=N(e),i=g(JSON.parse(await V(X(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await O(r),d=He(i,n),c=g(g(d.epics)?.[t]);if(!c)return o;const u=Rt(d,t,c),s=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,f=await vt(r,c,i),p=g(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:u,terminal:Ir.has(String(c.status??"").toLowerCase()),bound:!!Z(p,s,f),executionBranch:s,originBranch:f})}catch{return o}}async function vt(e,t,o){if(typeof t.origin_branch=="string"&&t.origin_branch.length>0)return t.origin_branch;const r=g(o.config)?.default_branch;if(r!=null&&String(r).length>0)return String(r);const i=await l(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]).catch(()=>"");if(i.startsWith("origin/")&&i.length>7)return i.slice(7);const n=[];for(const d of["main","master"])await C(e,["rev-parse","--verify","--quiet",`refs/heads/${d}^{commit}`])&&await C(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${d}^{commit}`])&&n.push(d);return n.length===1?n[0]:""}function Rt(e,t,o){if(o.branch_mode==="epic")return"recorded-epic";if(o.branch_mode!==void 0&&o.branch_mode!==null)return"not-epic";const r=g(e.stories)??{},n=At(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const u=g(r[c]);return u?[{...u,id:c}]:[]}),d=jt({...o,id:t},n);return d.mode==="epic"&&(d.source==="new-epic-default"||d.source==="epic-boundary")?"resolved-epic":"not-epic"}function St(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function oo(e){const t=q(e.nowIso),o=Date.parse(t),r=(c,u={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...u,outcome:"refused",reasonCode:c,executionRefCreated:!1,capturedAt:t});if(!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(e.epicId))return r("origin-binding-start-target-ambiguous");const i=N(e.projectRoot);let n=e.originFetch,d="origin-binding-start-raced";for(let c=0;c<wr;c+=1){let u,s={};try{const f=g(JSON.parse(await V(X(i,".neocortex/state.json"),"utf8")));if(!f)return r("origin-binding-start-state-invalid");const p=await O(i),v=He(f,p),y=g(g(v.epics)?.[e.epicId]);if(!y)return r("origin-binding-start-target-ambiguous");if(Rt(v,e.epicId,y)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const h=typeof y.execution_branch=="string"&&y.execution_branch.length>0?y.execution_branch:`epic/${e.epicId}`,I=await vt(i,y,f);if(s={executionBranch:h,originBranch:I},!ie(h)||!ie(I)||h===I||!await C(i,["check-ref-format","--branch",h])||!await C(i,["check-ref-format","--branch",I]))return r("origin-binding-start-branch-invalid",s);const _=g(p.epics[e.epicId]),w=_?.origin_binding??y.origin_binding;if(w!=null){const x=Z(w,h,I);return x?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:x.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",s)}if(St(g(_?.branch_lease??y.branch_lease),o))return r("origin-binding-start-lease-inconsistent",s);if(n??=await Sr({projectRoot:i,originBranch:I,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,s);const E=`refs/remotes/origin/${I}`,k=`refs/heads/${I}`,S=await l(i,["rev-parse","--verify","--quiet",`${k}^{commit}`]).catch(()=>""),R=await l(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(S)||S!==R)return r("origin-binding-start-origin-stale",s);if((await fe(i)).some(x=>x.branch===h&&N(x.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",s);const m=`refs/heads/${h}`,D=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(D){const x=await et(i,["merge-base","--is-ancestor",S,D]);if(x===1)return r("direct-yolo-origin-not-ancestor",s);if(x!==0)return r("direct-yolo-origin-ancestry-unverifiable",s)}const b={schemaVersion:2,originBranch:I,originHeadSha:S,executionBranch:h,capturedFrom:"branch-ref",capturedAt:t};return await P(i,x=>{const A=z(x,e.epicId);if(A.origin_binding!==void 0&&A.origin_binding!==null)throw new ke("origin-binding-start-raced");if(St(g(A.branch_lease),o))throw new ke("origin-binding-start-lease-inconsistent");A.origin_binding=b},{expectedRevision:p.revision,preCommit:async()=>{const x=await l(i,["rev-parse","--verify","--quiet",`${k}^{commit}`]).catch(()=>""),A=await l(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>""),$=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(x!==S||A!==S||$!==D)throw new ke("origin-binding-start-raced");D||(await l(i,["update-ref",m,S,""]),u={ref:m,sha:S})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:S,outcome:"captured",executionRefCreated:u!==void 0,capturedAt:t})}catch(f){if(u&&await l(i,["update-ref","-d",u.ref,u.sha]).catch(()=>{}),f instanceof Error&&f.message==="git-lifecycle-runtime-revision-conflict"){d="origin-binding-start-raced";continue}return f instanceof ke?r(f.message,s):r("origin-binding-start-failed",s)}}return r(d)}function De(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function W(e){const t=T(await H(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Xe(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await l(e,["hash-object","--no-filters","--",r])}`}));return B([await H(e,["diff","--cached","--binary","--full-index"]),await H(e,["diff","--binary","--full-index"]),await H(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function io(e){const t=N(e),o=await l(t,["rev-parse","HEAD"]),r=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await W(t);if(await l(t,["rev-parse","HEAD"])!==o||await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function fe(e){const t=[];let o;for(const r of(await H(e,["worktree","list","--porcelain","-z"])).split("\0"))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}const It=new Set(Object.values(ye));function K(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&Le(e.message)||e instanceof Error&&It.has(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function a(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function et(e,t){try{return await ce("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function l(e,t){return String((await ce("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function H(e,t){return String((await ce("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function C(e,t){try{return await ce("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Ur as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Zt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,wt as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,zr as acceptDirectYoloSetupCheckpoint,Wr as beginDirectYoloStoryCommit,io as captureDirectYoloCheckoutEvidence,to as captureDirectYoloStoryGovernance,oo as captureEpicOriginBindingAtYoloopStart,Jr as directYoloCommitIdempotencyKey,Zr as directYoloWaveQaCoverage,Qt as directYoloWaveReceiptRef,Sr as fetchOriginForYoloopStart,Mr as finalizeDirectYoloStoryCheckpoint,pr as isDirectYoloWriteSetExtensionScope,Gr as issueDirectYoloSetupLeaseHandoff,eo as persistDirectYoloWaveStoryCheckpoint,Tr as prepareDirectYoloSetup,Xr as pushDirectYoloWaveHead,ro as readYoloopStartEpic,Vr as recoverLegacyDirectYoloStoryCheckpoint,Fr as resolveDirectYoloIntegrationAuthority,Qr as runDirectYoloWaveP205,Yr as validateDirectYoloWriteSet,Kr as verifyDirectYoloIntegrationCommit,Rr as yoloopStartGitNetworkExecOptions};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recover only a missing worktree copy of an unambiguous, committed state file.
|
|
3
|
+
* The current branch and target spec must agree with that exact HEAD/index.
|
|
4
|
+
* No Git checkout operation, history search, or state synthesis participates.
|
|
5
|
+
*/
|
|
6
|
+
export declare function reconcileMissingTrackedEpicState(projectRoot: string, args: string): boolean;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{execFileSync as q}from"node:child_process";import{randomUUID as H}from"node:crypto";import{closeSync as L,fstatSync as k,fsyncSync as U,linkSync as V,lstatSync as l,openSync as W,readFileSync as X,realpathSync as m,unlinkSync as Y,writeFileSync as j}from"node:fs";import{dirname as J,join as D}from"node:path";import{parseYoloopInvocation as K}from"../yoloop/target-normalization.js";import{GOVERNANCE_RUNTIME_MAX_PROJECT_STATE_BYTES as z,GOVERNANCE_STATE_PATH as G}from"./governance-runtime-store.js";import{readGitLifecycleRuntimeSync as Z}from"./git-lifecycle-store.js";const B=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/,Q=/^@?(docs\/epics\/epic-(P[1-9][0-9]*)\.md)$/u,tt=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"];function d(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function et(n,c,u){const a=d(JSON.parse(n.toString("utf8"))),s=d(d(a?.epics)?.[c]),e=d(a?.stories);return s?.id===c&&s.branch_mode==="epic"&&s.execution_branch===u&&Array.isArray(s.stories)&&s.stories.length>0&&e!==void 0&&s.stories.every(t=>{if(typeof t!="string"||!t.startsWith(`${c}.`))return!1;const f=d(e[t]);return(f?.epic_id??f?.epic)===c})}function ft(n,c){const u=Q.exec(K(c)?.remainder??"");if(!u||tt.some(t=>process.env[t]))return!1;const a=u[1],s=u[2];let e;try{const t=m(n),f=r=>q("git",r,{cwd:t,stdio:["ignore","pipe","ignore"],timeout:3e3,maxBuffer:z,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_NO_LAZY_FETCH:"1"}}),p=r=>f(r).toString("utf8");if(m(p(["rev-parse","--show-toplevel"]).trim())!==t)return!1;const g=D(t,G),i=J(g),h=D(t,a),I=l(i),N=()=>{const r=l(h);if(!r.isFile()||m(h)!==h||r.size>z)throw new Error("unsafe-epic-spec");return X(h)};if(!I.isDirectory()||m(i)!==i||l(g,{throwIfNoEntry:!1}))return!1;const x=()=>p(["rev-parse","--verify","HEAD^{commit}"]).trim(),w=()=>p(["symbolic-ref","--quiet","HEAD"]).trim(),A=x(),b=w();if(!B.test(A)||!b.startsWith("refs/heads/"))return!1;const y=[G,a],C=()=>p(["ls-files","-v","--stage","-z","--",...y]),P=C(),$=new Set(P.split("\0").filter(Boolean)),M=p(["ls-tree","-z",A,"--",...y]).split("\0").filter(Boolean),E=new Map;for(const r of M){const o=/^(100644) blob ([a-f0-9]+)\t(.+)$/u.exec(r);if(!o||!B.test(o[2])||!y.includes(o[3])||!$.has(`H ${o[1]} ${o[2]} 0 ${o[3]}`))return!1;E.set(o[3],o[2])}if(E.size!==y.length||$.size!==y.length)return!1;const F=f(["cat-file","blob",E.get(a)]),v=N();if(!v.equals(F)&&!v.equals(Buffer.from(F.toString("utf8").replace(/\r?\n/g,`\r
|
|
2
|
+
`))))return!1;const O=f(["cat-file","blob",E.get(G)]);if(!et(O,s,b.slice(11)))return!1;try{Z(t,{required:!0})}catch(r){if(!(r instanceof Error)||r.message!=="git-lifecycle-runtime-missing")return!1}const S=D(i,`.state-recovery-${H()}.tmp`),_=W(S,"wx",384);try{e={path:S,stat:k(_)},j(_,O),U(_)}finally{L(_)}if(x()!==A||w()!==b||C()!==P)return!1;const R=l(i);if(!R.isDirectory()||R.dev!==I.dev||R.ino!==I.ino||m(i)!==i||!N().equals(v))return!1;const T=l(S);return!T.isFile()||T.dev!==e.stat.dev||T.ino!==e.stat.ino||T.size!==O.length?!1:(V(S,g),!0)}catch{return!1}finally{if(e)try{const t=l(e.path);t.dev===e.stat.dev&&t.ino===e.stat.ino&&Y(e.path)}catch{}}}export{ft as reconcileMissingTrackedEpicState};
|
|
@@ -8,6 +8,21 @@ export declare function historicalStoryQaDigest(raw: string, storyId: string): s
|
|
|
8
8
|
* returned for scheduling only after a fresh physical verification each time.
|
|
9
9
|
*/
|
|
10
10
|
export declare function reconcilePublishedStoriesForYoloop(projectRoot: string, args: string): Promise<readonly PublishedStoryReconciliation[]>;
|
|
11
|
+
type PublishedCheckpointRecovery = {
|
|
12
|
+
readonly status: 'recovered';
|
|
13
|
+
readonly storyId: string;
|
|
14
|
+
readonly headSha: string;
|
|
15
|
+
} | {
|
|
16
|
+
readonly status: 'pending';
|
|
17
|
+
readonly storyId: string;
|
|
18
|
+
readonly headSha: string;
|
|
19
|
+
readonly reasonCode: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* A published epic tip can still lack its local checkpoint after an interrupted
|
|
23
|
+
* integration. Reuse checkpoint recovery before scheduling a replacement task.
|
|
24
|
+
*/
|
|
25
|
+
export declare function recoverPublishedCheckpointForYoloop(projectRoot: string, args: string, reconciliations: readonly PublishedStoryReconciliation[]): Promise<PublishedCheckpointRecovery | undefined>;
|
|
11
26
|
/** Only server-authored story-worktree phases inherit a freshly revalidated dependency. */
|
|
12
27
|
export declare function revalidatePublishedStoriesForYolo(projectRoot: string, args: string): Promise<readonly PublishedStoryReconciliation[]>;
|
|
13
28
|
export declare function revalidatePublishedStoryDependencies(projectRoot: string, epicId: string): Promise<readonly PublishedStoryReconciliation[]>;
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`)
|
|
1
|
+
import{execFile as ae}from"node:child_process";import{createHash as se}from"node:crypto";import{realpath as M}from"node:fs/promises";import{promisify as ce}from"node:util";import{parseYoloopInvocation as Q}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as ue}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as de,resolveDirectYoloIntegrationAuthority as he,verifyDirectYoloIntegrationCommit as fe}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as z}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as le,mutateGitLifecycleRuntime as ye,publishedStoryReconciliationId as V,readGitLifecycleRuntime as B,readStoryWorktreeEvidence as we}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as me}from"./governance-runtime-store.js";import{parseNeocortexTrailers as K,trailerValue as P}from"./neocortex-trailers.js";import{StoryWorktreeManager as U}from"./story-worktree-manager.js";const X=ce(ae),T=/^[a-f0-9]{64}$/,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function Z(e){return se("sha256").update(e).digest("hex")}function v(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,o){let n;try{n=v(JSON.parse(e))}catch{return}if(!(n?.schemaVersion!==2||n.storyId!==o||n.publicSafe!==!0||n.status!=="qa-passed"||n.safeToContinueYoloop!==!0||!Array.isArray(n.blockingChecks)||n.blockingChecks.length!==0))return Z(e)}async function Ce(e,o){const n=Q(o);if(!n||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(n.remainder))return[];const t=ue(o);return!t||t.source!=="explicit"?[]:ee(e,t.epicId,!0)}async function Re(e,o,n){const t=Q(o)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const h=j(e);let I;try{const m=(await h("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await B(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==m)return;const[g,b,...N]=(await h("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
|
|
2
|
+
`);if(!g||!b||!A.test(g)||!A.test(b))return;const D=K(N.join(`
|
|
3
|
+
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!D.ok)return;const a=d=>P(D.values,d),p=a("Neocortex-Story");if(!p||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(p)||a("Neocortex-Epic")!==s||a("Neocortex-Execution-Branch")!==m||a("Neocortex-Prepared-Base")!==b||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(d=>T.test(a(d)??""))||k.stories[p]?.checkpoint||n.some(d=>d.storyId===p))return;const $=me(e);if(!$.ok||!$.value||v(v(v(JSON.parse($.value.toString("utf8")))?.stories)?.[p])?.epic_id!==s)return;I={storyId:p,headSha:g,executionBranch:m}}catch{return}const{storyId:u,headSha:f,executionBranch:S}=I;try{if(await z(h,S)!==f)return}catch{return{status:"pending",storyId:u,headSha:f,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const c=await de({projectRoot:e,storyId:u,commitSha:f});if(c.ok)return{status:"recovered",storyId:u,headSha:f};if(c.reasonCode==="direct-yolo-checkpoint-conflict"){const m=await B(e,{required:!0});if(v(m.stories[u]?.checkpoint)?.headSha===f)return}return{status:"pending",storyId:u,headSha:f,reasonCode:c.reasonCode}}function j(e){return async(...o)=>(await X("git",[...o],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Pe(e,o){const n=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(o);if(!n)return[];try{const s=(await X("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),n[1]):[]}catch{return[]}}function Se(e,o){return ee(e,o,!1)}async function ee(e,o,n){const t=j(e),s=async u=>(await t("rev-parse","--verify","--quiet",`${u}^{commit}`)).trim(),h=async(u,f)=>{try{return await t("merge-base","--is-ancestor",u,f),!0}catch{return!1}},I=[];try{const u=await M((await t("rev-parse","--absolute-git-dir")).trim()),f=await M((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(u!==f)return[];const S=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),c=await s("HEAD"),m=await B(e,{required:!0});if(m.epics[o]?.execution_branch!==S)return[];const k=Object.values(m.storyWorktrees?.entries??{}).filter(i=>i.epicId===o&&i.executionBranch===S&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const g=await B(e,{required:!0});if(g.stories[i.storyId]?.checkpoint||k.filter(r=>r.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const b=v(g.epics[o]?.branch_lease);if(b&&Date.parse(String(b.expiresAt))>Date.now())continue;const N=we(g,o)?.receipts??[];if(N.some(r=>r.kind==="integration-receipt"&&r.storyId===i.storyId))continue;const D=N.filter(r=>r.kind==="phase-one-receipt"&&r.storyId===i.storyId&&r.leaseId===i.leaseId&&r.graphRevision===i.graphRevision);if(D.length!==1)continue;const a=D[0],p=String(a.graphRevision),$=String(a.receiptId);if(!T.test(p)||!A.test(String(a.headSha))||a.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const H=N.filter(r=>r.kind==="published-story-reconciliation"&&r.storyId===i.storyId&&r.graphRevision===p);if(H.length>1||!n&&H.length===0)continue;const d=await he(e,i.storyId),x=d.originBinding;if(d.epicId!==o||d.executionBranch!==S||!x||x.originBranch===S||!await h(x.originHeadSha,c))continue;const l=await new U({projectRoot:e}).probe(i.leaseId);if(!l.ok||l.value.ownership!=="proven"||l.value.clean!==!0||!l.value.headSha||!A.test(l.value.headSha)||!await h(String(a.headSha),l.value.headSha))continue;const q=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${l.value.headSha}`,`${x.originHeadSha}..${c}`)).trim().split(`
|
|
4
|
+
`).filter(Boolean);if(q.length!==1||!A.test(q[0]))continue;const y=q[0],te=(await t("show","-s","--format=%P",y)).trim();if(!A.test(te))continue;const _=K(await t("show","-s","--format=%B",y),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||P(_.values,"Neocortex-Story-Worktree-Tip")!==l.value.headSha)continue;const E=P(_.values,"Neocortex-Graph-Revision"),W=P(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!T.test(E)||!W||!T.test(W))continue;const re=(await t("rev-parse",`${y}^{tree}`)).trim(),ie=(await t("rev-parse",`${l.value.headSha}^{tree}`)).trim();if(re!==ie)continue;const Y=await fe(d,i.storyId,y,{expectedGraphRevision:E});if(!Y.ok)continue;const oe=v(JSON.parse(await t("show",`${y}:.neocortex/state.json`))),F=v(v(oe?.stories)?.[i.storyId]);if(F?.epic_id!==o||JSON.stringify(F.depends_on??[])!==JSON.stringify(d.story.depends_on??[]))continue;const C=String(a.specRef),R=`docs/stories/${i.storyId}.story.md`;if(Z(await t("show",`${y}:${C}`))!==a.specDigest||Z(await t("show",`${c}:${C}`))!==a.specDigest||await t("show",`${y}:${R}`)!==await t("show",`${c}:${R}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R);const L=ve(await t("show",`${y}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!L)continue;const w=await z(t,x.originBranch);if(!w)continue;try{await s(w)}catch{if(!n||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",w),await s(w)!==w))continue}if(!await h(x.originHeadSha,w)||!await h(y,w))continue;const G={schemaVersion:1,kind:"published-story-reconciliation",epicId:o,storyId:i.storyId,graphRevision:p,historicalGraphRevision:E,phaseOneReceiptId:$,executionBranch:S,executionHeadSha:c,originBranch:x.originBranch,originHeadSha:w,commitSha:y,bundleDigest:Y.value.bundleDigest,historicalQaDigest:L},J=async()=>{if(await s("HEAD")!==c||await s(`refs/heads/${S}`)!==c||await z(t,x.originBranch)!==w)throw new Error("published-story-reconciliation-ref-raced");const r=await new U({projectRoot:e}).probe(i.leaseId);if(!r.ok||r.value.ownership!=="proven"||r.value.clean!==!0||r.value.headSha!==l.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R)};if(H[0]){const r=H[0],ne={...G,executionHeadSha:r.executionHeadSha,originHeadSha:r.originHeadSha};if(r.receiptId!==V(ne)||!await h(r.executionHeadSha,c)||!await h(r.originHeadSha,w)||(await J(),(await B(e,{required:!0})).revision!==g.revision))continue;I.push(r);continue}const O=Object.freeze({...G,receiptId:V(G)});if(!le(O))continue;await ye(e,r=>{pe(r,o,{receipts:[O]})},{expectedRevision:g.revision,preCommit:J}),I.push(O)}catch{}}catch{}return I}export{ve as historicalStoryQaDigest,Ce as reconcilePublishedStoriesForYoloop,Re as recoverPublishedCheckpointForYoloop,Pe as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
|