instar 1.3.1983 → 1.3.1985

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/core/QuotaAwareScheduler.d.ts.map +1 -1
  2. package/dist/core/QuotaAwareScheduler.js +4 -26
  3. package/dist/core/QuotaAwareScheduler.js.map +1 -1
  4. package/dist/core/SessionManager.d.ts.map +1 -1
  5. package/dist/core/SessionManager.js +473 -443
  6. package/dist/core/SessionManager.js.map +1 -1
  7. package/dist/core/SubscriptionPool.d.ts +2 -1
  8. package/dist/core/SubscriptionPool.d.ts.map +1 -1
  9. package/dist/core/SubscriptionPool.js +10 -3
  10. package/dist/core/SubscriptionPool.js.map +1 -1
  11. package/dist/core/UsageWallRescue.d.ts +2 -1
  12. package/dist/core/UsageWallRescue.d.ts.map +1 -1
  13. package/dist/core/UsageWallRescue.js +4 -3
  14. package/dist/core/UsageWallRescue.js.map +1 -1
  15. package/dist/core/windowAwareChoice.d.ts +3 -0
  16. package/dist/core/windowAwareChoice.d.ts.map +1 -1
  17. package/dist/core/windowAwareChoice.js +18 -20
  18. package/dist/core/windowAwareChoice.js.map +1 -1
  19. package/dist/data/standards-guard-index.json +1 -1
  20. package/dist/data/standards-guard-index.meta.json +2 -2
  21. package/dist/data/standards-registry.meta.json +1 -1
  22. package/dist/native/InstarWedgeCanary.app/Contents/MacOS/InstarWedgeCanary +0 -0
  23. package/dist/native/instar-desktop-host +0 -0
  24. package/package.json +1 -1
  25. package/src/data/awareness/codex-weekly-reset-routing.md +12 -0
  26. package/src/data/builtin-manifest.json +3 -3
  27. package/src/data/standards-guard-index.json +1 -1
  28. package/src/data/standards-guard-index.meta.json +2 -2
  29. package/src/data/standards-registry.meta.json +1 -1
  30. package/upgrades/1.3.1984.md +22 -0
  31. package/upgrades/1.3.1985.md +20 -0
  32. package/upgrades/side-effects/codex-weekly-reset-routing.md +77 -0
  33. package/upgrades/side-effects/internal-codex-reset-first.md +48 -0
@@ -4538,7 +4538,7 @@ rm() { "${shimRunner}" rm "$@"; }
4538
4538
  modelSource: options.model ? 'explicit' : requestedModel ? 'config-default' : 'unknown',
4539
4539
  sessionName: tmuxSession,
4540
4540
  }) ?? null)
4541
- : headlessFramework === 'codex-cli'
4541
+ : headlessFramework === 'codex-cli' && !options.codexLocalProvider
4542
4542
  ? this.codexHeadlessPlacement()
4543
4543
  : null;
4544
4544
  if (pinnedAccount) {
@@ -7728,461 +7728,484 @@ rm() { "${shimRunner}" rm "$@"; }
7728
7728
  // Overload admission (Part C2): while overloaded, an operator session starts
7729
7729
  // only by taking the one host-wide recovery slot.
7730
7730
  this.checkAdmission(options?.admissionKind ?? 'operator', tmuxSession);
7731
- // Generate session ID before tmux spawn so we can pass it as env var
7732
- const interactiveSessionId = this.generateId();
7733
- // Resolve which framework this session runs under. Precedence:
7734
- // 1. per-call override (options.framework)
7735
- // 2. the agent's resolved runtime framework (config.framework,
7736
- // derived at load from sessions.framework | enabledFrameworks[0]
7737
- // | INSTAR_FRAMEWORK)
7738
- // 3. INSTAR_FRAMEWORK env (defense-in-depth if config.framework
7739
- // wasn't populated by an older Config.load)
7740
- // 4. 'claude-code' (historical default)
7741
- // Before config.framework existed this hardcoded 'claude-code',
7742
- // which made a codex-cli-only agent spawn a Claude session every
7743
- // time the user messaged it (the interactive path is what handles
7744
- // Telegram/Slack messages).
7745
- const framework = resolveInteractiveFramework({
7746
- perCall: options?.framework,
7747
- configFramework: this.config.framework,
7748
- envFramework: frameworkFromEnv(),
7749
- });
7750
- // Memory privacy: decide the audience before anything else, and drop a resume
7751
- // whose transcript was read by a different audience.
7752
- const memoryPlan = this.planMemorySession(framework, tmuxSession, {
7753
- telegramTopicId: options?.telegramTopicId,
7754
- slackChannelId: options?.slackChannelId,
7755
- memoryPlaceKey: options?.memoryPlaceKey,
7756
- memoryPlace: options?.memoryPlace,
7757
- });
7758
- // A caller that shaped its message for one audience gets it reshaped if a grant changed that.
7759
- const actualAudience = memoryPlan?.audience.kind ?? 'open';
7760
- if (initialMessage && options?.reshapeForAudience && options.shapedForAudience !== undefined && options.shapedForAudience !== actualAudience) {
7761
- initialMessage = options.reshapeForAudience(actualAudience, initialMessage);
7762
- }
7763
- if (memoryPlan?.dropResume && options?.resumeSessionId) {
7764
- options = { ...options, resumeSessionId: undefined };
7765
- }
7766
- // Shared impersonation fence (spec §2.0) — see resolveFrameworkBinaryPath.
7767
- const configuredBinaryPath = resolveFrameworkBinaryPath({
7768
- framework,
7769
- frameworkBinaryPaths: this.config.frameworkBinaryPaths,
7770
- claudePath: this.config.claudePath,
7771
- configuredFramework: this.config.framework,
7772
- });
7773
- if (!configuredBinaryPath) {
7774
- throw new Error(`No binary path available for framework "${framework}"`);
7775
- }
7776
- // CMT-798: launch claude-code from its retained per-version copy.
7777
- const binaryPath = this.resolveLaunchBinary(framework, configuredBinaryPath);
7778
- // Per-call defaultModel override (used by /local-model to set Codex's
7779
- // local model id) wins over config defaults. Config defaults survive
7780
- // for cloud-Codex topics that haven't been customized.
7781
- const defaultModel = options?.defaultModel ?? this.config.frameworkDefaultModels?.[framework];
7782
- // Codex rate-limit model-swap (see resolveCodexLaunchModel) — applies to the
7783
- // interactive (user-facing) codex session too, not just headless spawns.
7784
- const launchDefaultModel = await this.resolveCodexLaunchModel(framework, defaultModel, options?.codexLocalProvider);
7785
- // Subscription-pool pinning for the INTERACTIVE (user-facing) lane (B1).
7786
- // Mirrors the headless lane (spawnSession): when pinSessionsToPool wired the
7787
- // spawn-account resolver, launch this claude-code session under the
7788
- // scheduler-picked optimal account's config home and TAG it. That makes the
7789
- // user's own conversation first-class for auto-swap — it can be moved when
7790
- // its account walls — instead of riding the default login untagged, where
7791
- // only ProactiveSwapMonitor's default-login fallback could rescue it.
7792
- // • An explicit caller-supplied configHome ALWAYS wins (the account-swap
7793
- // path, SessionRefresh, passes one) — the resolver is only consulted when
7794
- // the caller didn't pin a home itself.
7795
- // • claude-code only: the pool holds claude logins; a pool configHome is
7796
- // meaningless for a codex/pi launch.
7797
- // • No-op unless the resolver is wired (pinSessionsToPool) and returns an
7798
- // account → default-login behavior is exactly unchanged when off.
7799
- const explicitConfigHome = options?.configHome;
7800
- const pinnedAccount = (!explicitConfigHome && framework === 'claude-code')
7801
- ? (this.poolAccountForSpawn({
7802
- model: launchDefaultModel ?? null,
7803
- modelSource: options?.defaultModel ? 'explicit' : launchDefaultModel ? 'config-default' : 'unknown',
7804
- sessionName: tmuxSession,
7805
- }) ?? null)
7806
- : null;
7807
- // Census #6: when the home comes from a pinned pool account, resolve its LIVE slot through the
7808
- // ledger gate (an explicit caller-supplied home — the account-swap / SessionRefresh path — is a
7809
- // deliberate pin and always wins, unchanged).
7810
- const effectiveConfigHome = explicitConfigHome ?? (pinnedAccount ? this.resolvePinnedSpawnHome(pinnedAccount) : undefined);
7811
- const effectiveAccountId = options?.subscriptionAccountId ?? pinnedAccount?.accountId;
7812
- // §2.10 provenance — SINGLE SOURCE OF TRUTH: the SAME `(anthropicApiKey ?? '') !== ''`
7813
- // predicate that selects the Anthropic env block in the execFileSync below. Only meaningful
7814
- // for the claude-code lane (the only one whose env block claude-code actually reads).
7815
- const interactiveCredentialSource = framework === 'claude-code'
7816
- ? ((this.config.anthropicApiKey ?? '') !== '' ? 'env' : 'store')
7817
- : undefined;
7818
- // This interactive session is about to launch under a pool account's config
7819
- // home — seed the onboarding flags first or a headless-enrolled home wedges
7820
- // it on the first-launch onboarding wizard (2026-06-09 incident). Applies to
7821
- // both the explicit account-swap target and a resolver-pinned home.
7822
- if (effectiveConfigHome && framework === 'claude-code') {
7823
- this.ensurePinnedHomeInteractiveReady(effectiveConfigHome, explicitConfigHome ? 'interactive account-swap' : 'interactive pin');
7824
- }
7825
- // Resume Follows the Account (docs/specs/resume-follows-account.md §3.1).
7826
- // Claude opens a resume transcript only from the login folder it runs
7827
- // under. When a topic conversation is launched under a pool/swap login,
7828
- // place the freshest copy there first; if none exists (or the id is an
7829
- // internal one-shot call), launch fresh instead of letting Claude exit
7830
- // with "No conversation found".
7831
- let resumeReopenFailed = false;
7832
- if (options?.resumeSessionId &&
7833
- framework === 'claude-code' &&
7834
- effectiveConfigHome &&
7835
- (options.telegramTopicId !== undefined || options.slackChannelId) &&
7836
- this.resumeFollowsAccountEnabled()) {
7837
- const outcome = await placeResumeTranscript(options.resumeSessionId, effectiveConfigHome);
7838
- console.log(`[SessionManager] Resume placement for "${tmuxSession}": ${outcome} (uuid=${options.resumeSessionId}, home=${effectiveConfigHome})`);
7839
- if (outcome === 'not-found' || outcome === 'one-shot') {
7840
- resumeReopenFailed = true;
7841
- options = { ...options, resumeSessionId: undefined };
7731
+ // Every refusal after acquiring admission, including account selection or
7732
+ // resume placement before tmux exists, must give the recovery slot back.
7733
+ let interactiveTmuxCreated = false;
7734
+ try {
7735
+ // Generate session ID before tmux spawn so we can pass it as env var
7736
+ const interactiveSessionId = this.generateId();
7737
+ // Resolve which framework this session runs under. Precedence:
7738
+ // 1. per-call override (options.framework)
7739
+ // 2. the agent's resolved runtime framework (config.framework,
7740
+ // derived at load from sessions.framework | enabledFrameworks[0]
7741
+ // | INSTAR_FRAMEWORK)
7742
+ // 3. INSTAR_FRAMEWORK env (defense-in-depth if config.framework
7743
+ // wasn't populated by an older Config.load)
7744
+ // 4. 'claude-code' (historical default)
7745
+ // Before config.framework existed this hardcoded 'claude-code',
7746
+ // which made a codex-cli-only agent spawn a Claude session every
7747
+ // time the user messaged it (the interactive path is what handles
7748
+ // Telegram/Slack messages).
7749
+ const framework = resolveInteractiveFramework({
7750
+ perCall: options?.framework,
7751
+ configFramework: this.config.framework,
7752
+ envFramework: frameworkFromEnv(),
7753
+ });
7754
+ // Memory privacy: decide the audience before anything else, and drop a resume
7755
+ // whose transcript was read by a different audience.
7756
+ const memoryPlan = this.planMemorySession(framework, tmuxSession, {
7757
+ telegramTopicId: options?.telegramTopicId,
7758
+ slackChannelId: options?.slackChannelId,
7759
+ memoryPlaceKey: options?.memoryPlaceKey,
7760
+ memoryPlace: options?.memoryPlace,
7761
+ });
7762
+ // A caller that shaped its message for one audience gets it reshaped if a grant changed that.
7763
+ const actualAudience = memoryPlan?.audience.kind ?? 'open';
7764
+ if (initialMessage && options?.reshapeForAudience && options.shapedForAudience !== undefined && options.shapedForAudience !== actualAudience) {
7765
+ initialMessage = options.reshapeForAudience(actualAudience, initialMessage);
7842
7766
  }
7843
- if (outcome === 'not-found' || outcome === 'one-shot' || outcome === 'forked') {
7844
- DegradationReporter.getInstance().report({
7845
- feature: 'SessionManager.resumePlacement',
7846
- primary: 'Place the topic conversation in the login the session launches under',
7847
- fallback: outcome === 'forked'
7848
- ? 'A diverged copy in the target login was set aside and the freshest copy placed'
7849
- : 'The session launched without its earlier conversation',
7850
- reason: `Why: resume placement outcome ${outcome}`,
7851
- impact: outcome === 'forked'
7852
- ? 'No data lost; the diverged copy is kept beside the transcript'
7853
- : 'The session starts from recent topic messages instead of the full conversation',
7854
- });
7767
+ if (memoryPlan?.dropResume && options?.resumeSessionId) {
7768
+ options = { ...options, resumeSessionId: undefined };
7855
7769
  }
7856
- }
7857
- // The Codex half of Resume Follows the Account. `codex resume <thread>` reads the
7858
- // conversation only from the CODEX_HOME it runs under, so before relaunching a
7859
- // Codex conversation under an account's home, place the freshest copy there.
7860
- // Without it the launch below (which now honours the home) would stop at
7861
- // "no rollout found"; the earlier code avoided that only by ignoring the home
7862
- // and running on the default login under another account's name (2026-11-18).
7863
- // A relaunch WITHOUT an account home runs on the default login, and is placed
7864
- // too: after a swap the conversation continued in the account's home, and the
7865
- // default home holds only the older copy, so resuming there would silently drop
7866
- // every turn taken on the account. There, a conversation found nowhere keeps
7867
- // today's behaviour (the default home is where it was always looked for).
7868
- const defaultCodexHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
7869
- const codexPlacementHome = explicitConfigHome ?? defaultCodexHome;
7870
- // The thread id names a file copied between homes, so it is checked here too. This is
7871
- // a file-copy guard, not a launch flag: the --resume flag keeps its own guard in the builder.
7872
- const codexThreadToPlace = options?.resumeSessionId;
7873
- if (codexThreadToPlace &&
7874
- framework === CODEX_CLI_FRAMEWORK &&
7875
- (explicitConfigHome || this.codexAccountHomesResolver) &&
7876
- isSafeSessionRef(codexThreadToPlace)) {
7877
- let outcome;
7878
- try {
7879
- const sources = [defaultCodexHome, ...(this.codexAccountHomesResolver?.() ?? [])];
7880
- outcome = (await placeCodexResumeRollout(codexThreadToPlace, codexPlacementHome, sources)).outcome;
7770
+ // Shared impersonation fence (spec §2.0) — see resolveFrameworkBinaryPath.
7771
+ const configuredBinaryPath = resolveFrameworkBinaryPath({
7772
+ framework,
7773
+ frameworkBinaryPaths: this.config.frameworkBinaryPaths,
7774
+ claudePath: this.config.claudePath,
7775
+ configuredFramework: this.config.framework,
7776
+ });
7777
+ if (!configuredBinaryPath) {
7778
+ throw new Error(`No binary path available for framework "${framework}"`);
7779
+ }
7780
+ // CMT-798: launch claude-code from its retained per-version copy.
7781
+ const binaryPath = this.resolveLaunchBinary(framework, configuredBinaryPath);
7782
+ // Per-call defaultModel override (used by /local-model to set Codex's
7783
+ // local model id) wins over config defaults. Config defaults survive
7784
+ // for cloud-Codex topics that haven't been customized.
7785
+ const defaultModel = options?.defaultModel ?? this.config.frameworkDefaultModels?.[framework];
7786
+ // Codex rate-limit model-swap (see resolveCodexLaunchModel) — applies to the
7787
+ // interactive (user-facing) codex session too, not just headless spawns.
7788
+ const launchDefaultModel = await this.resolveCodexLaunchModel(framework, defaultModel, options?.codexLocalProvider);
7789
+ // Subscription-pool pinning for the INTERACTIVE (user-facing) lane (B1).
7790
+ // Mirrors the headless lane (spawnSession): when pinSessionsToPool wired the
7791
+ // spawn-account resolver, launch this claude-code session under the
7792
+ // scheduler-picked optimal account's config home and TAG it. That makes the
7793
+ // user's own conversation first-class for auto-swap — it can be moved when
7794
+ // its account walls — instead of riding the default login untagged, where
7795
+ // only ProactiveSwapMonitor's default-login fallback could rescue it.
7796
+ // • An explicit caller-supplied configHome ALWAYS wins (the account-swap
7797
+ // path, SessionRefresh, passes one) — the resolver is only consulted when
7798
+ // the caller didn't pin a home itself.
7799
+ // • Codex cloud sessions use their own resolver, never a Claude home.
7800
+ // Local models keep their local provider and do not select a paid login.
7801
+ // • No-op unless the resolver is wired (pinSessionsToPool) and returns an
7802
+ // account → default-login behavior is exactly unchanged when off.
7803
+ const explicitConfigHome = options?.configHome;
7804
+ if (framework === CODEX_CLI_FRAMEWORK && options?.subscriptionAccountId && !explicitConfigHome) {
7805
+ throw new Error('A Codex account pin requires its config home; refusing a tag without a matching launch home.');
7806
+ }
7807
+ const pinnedAccount = explicitConfigHome
7808
+ ? null
7809
+ : framework === 'claude-code'
7810
+ ? (this.poolAccountForSpawn({
7811
+ model: launchDefaultModel ?? null,
7812
+ modelSource: options?.defaultModel ? 'explicit' : launchDefaultModel ? 'config-default' : 'unknown',
7813
+ sessionName: tmuxSession,
7814
+ }) ?? null)
7815
+ : framework === CODEX_CLI_FRAMEWORK && !options?.codexLocalProvider
7816
+ ? this.codexHeadlessPlacement()
7817
+ : null;
7818
+ // Census #6: when the home comes from a pinned pool account, resolve its LIVE slot through the
7819
+ // ledger gate (an explicit caller-supplied home — the account-swap / SessionRefresh path — is a
7820
+ // deliberate pin and always wins, unchanged).
7821
+ const effectiveConfigHome = explicitConfigHome ?? (pinnedAccount ? this.resolvePinnedSpawnHome(pinnedAccount) : undefined);
7822
+ const effectiveAccountId = options?.subscriptionAccountId ?? pinnedAccount?.accountId;
7823
+ // §2.10 provenance — SINGLE SOURCE OF TRUTH: the SAME `(anthropicApiKey ?? '') !== ''`
7824
+ // predicate that selects the Anthropic env block in the execFileSync below. Only meaningful
7825
+ // for the claude-code lane (the only one whose env block claude-code actually reads).
7826
+ const interactiveCredentialSource = framework === 'claude-code'
7827
+ ? ((this.config.anthropicApiKey ?? '') !== '' ? 'env' : 'store')
7828
+ : undefined;
7829
+ // This interactive session is about to launch under a pool account's config
7830
+ // home — seed the onboarding flags first or a headless-enrolled home wedges
7831
+ // it on the first-launch onboarding wizard (2026-06-09 incident). Applies to
7832
+ // both the explicit account-swap target and a resolver-pinned home.
7833
+ if (effectiveConfigHome && framework === 'claude-code') {
7834
+ this.ensurePinnedHomeInteractiveReady(effectiveConfigHome, explicitConfigHome ? 'interactive account-swap' : 'interactive pin');
7835
+ }
7836
+ // Resume Follows the Account (docs/specs/resume-follows-account.md §3.1).
7837
+ // Claude opens a resume transcript only from the login folder it runs
7838
+ // under. When a topic conversation is launched under a pool/swap login,
7839
+ // place the freshest copy there first; if none exists (or the id is an
7840
+ // internal one-shot call), launch fresh instead of letting Claude exit
7841
+ // with "No conversation found".
7842
+ let resumeReopenFailed = false;
7843
+ if (options?.resumeSessionId &&
7844
+ framework === 'claude-code' &&
7845
+ effectiveConfigHome &&
7846
+ (options.telegramTopicId !== undefined || options.slackChannelId) &&
7847
+ this.resumeFollowsAccountEnabled()) {
7848
+ const outcome = await placeResumeTranscript(options.resumeSessionId, effectiveConfigHome);
7849
+ console.log(`[SessionManager] Resume placement for "${tmuxSession}": ${outcome} (uuid=${options.resumeSessionId}, home=${effectiveConfigHome})`);
7850
+ if (outcome === 'not-found' || outcome === 'one-shot') {
7851
+ resumeReopenFailed = true;
7852
+ options = { ...options, resumeSessionId: undefined };
7853
+ }
7854
+ if (outcome === 'not-found' || outcome === 'one-shot' || outcome === 'forked') {
7855
+ DegradationReporter.getInstance().report({
7856
+ feature: 'SessionManager.resumePlacement',
7857
+ primary: 'Place the topic conversation in the login the session launches under',
7858
+ fallback: outcome === 'forked'
7859
+ ? 'A diverged copy in the target login was set aside and the freshest copy placed'
7860
+ : 'The session launched without its earlier conversation',
7861
+ reason: `Why: resume placement outcome ${outcome}`,
7862
+ impact: outcome === 'forked'
7863
+ ? 'No data lost; the diverged copy is kept beside the transcript'
7864
+ : 'The session starts from recent topic messages instead of the full conversation',
7865
+ });
7866
+ }
7881
7867
  }
7882
- catch (err) {
7883
- // @silent-fallback-ok — reported below; the session launches fresh instead of failing.
7884
- console.warn(`[SessionManager] Codex resume placement failed for "${tmuxSession}": ${err instanceof Error ? err.message : String(err)}`);
7885
- outcome = 'error';
7868
+ // The Codex half of Resume Follows the Account. `codex resume <thread>` reads the
7869
+ // conversation only from the CODEX_HOME it runs under, so before relaunching a
7870
+ // Codex conversation under an account's home, place the freshest copy there.
7871
+ // Without it the launch below (which now honours the home) would stop at
7872
+ // "no rollout found"; the earlier code avoided that only by ignoring the home
7873
+ // and running on the default login under another account's name (2026-11-18).
7874
+ // A relaunch WITHOUT an account home runs on the default login, and is placed
7875
+ // too: after a swap the conversation continued in the account's home, and the
7876
+ // default home holds only the older copy, so resuming there would silently drop
7877
+ // every turn taken on the account. There, a conversation found nowhere keeps
7878
+ // today's behaviour (the default home is where it was always looked for).
7879
+ const defaultCodexHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
7880
+ const codexPlacementHome = effectiveConfigHome ?? defaultCodexHome;
7881
+ // The thread id names a file copied between homes, so it is checked here too. This is
7882
+ // a file-copy guard, not a launch flag: the --resume flag keeps its own guard in the builder.
7883
+ const codexThreadToPlace = options?.resumeSessionId;
7884
+ if (codexThreadToPlace &&
7885
+ framework === CODEX_CLI_FRAMEWORK &&
7886
+ (effectiveConfigHome || this.codexAccountHomesResolver) &&
7887
+ isSafeSessionRef(codexThreadToPlace)) {
7888
+ let outcome;
7889
+ try {
7890
+ const sources = [defaultCodexHome, ...(this.codexAccountHomesResolver?.() ?? [])];
7891
+ outcome = (await placeCodexResumeRollout(codexThreadToPlace, codexPlacementHome, sources)).outcome;
7892
+ }
7893
+ catch (err) {
7894
+ // @silent-fallback-ok — reported below; the session launches fresh instead of failing.
7895
+ console.warn(`[SessionManager] Codex resume placement failed for "${tmuxSession}": ${err instanceof Error ? err.message : String(err)}`);
7896
+ outcome = 'error';
7897
+ }
7898
+ console.log(`[SessionManager] Codex resume placement for "${tmuxSession}": ${outcome} (thread=${codexThreadToPlace}, home=${codexPlacementHome})`);
7899
+ if (pinnedAccount && (outcome === 'not-found' || outcome === 'error')) {
7900
+ throw new Error('codex-account-resume-unavailable: the saved conversation could not be placed in the selected account; no fresh conversation was started.');
7901
+ }
7902
+ if (explicitConfigHome && (outcome === 'not-found' || outcome === 'error')) {
7903
+ resumeReopenFailed = true;
7904
+ options = { ...options, resumeSessionId: undefined };
7905
+ DegradationReporter.getInstance().report({
7906
+ feature: 'SessionManager.codexResumePlacement',
7907
+ primary: 'Place the Codex conversation in the account home the session launches under',
7908
+ fallback: 'The session launched without its earlier conversation',
7909
+ reason: `Why: Codex resume placement outcome ${outcome}`,
7910
+ impact: 'The session starts from recent topic messages instead of the full conversation',
7911
+ });
7912
+ }
7886
7913
  }
7887
- console.log(`[SessionManager] Codex resume placement for "${tmuxSession}": ${outcome} (thread=${codexThreadToPlace}, home=${codexPlacementHome})`);
7888
- if (explicitConfigHome && (outcome === 'not-found' || outcome === 'error')) {
7889
- resumeReopenFailed = true;
7890
- options = { ...options, resumeSessionId: undefined };
7891
- DegradationReporter.getInstance().report({
7892
- feature: 'SessionManager.codexResumePlacement',
7893
- primary: 'Place the Codex conversation in the account home the session launches under',
7894
- fallback: 'The session launched without its earlier conversation',
7895
- reason: `Why: Codex resume placement outcome ${outcome}`,
7896
- impact: 'The session starts from recent topic messages instead of the full conversation',
7897
- });
7914
+ if (resumeReopenFailed && effectiveInitialMessage) {
7915
+ effectiveInitialMessage = `${RESUME_REOPEN_FAILED_NOTE}\n\n${effectiveInitialMessage}`;
7898
7916
  }
7899
- }
7900
- if (resumeReopenFailed && effectiveInitialMessage) {
7901
- effectiveInitialMessage = `${RESUME_REOPEN_FAILED_NOTE}\n\n${effectiveInitialMessage}`;
7902
- }
7903
- assertBrowserMcpProfilesSafe(options?.cwd ?? this.config.projectDir, framework, effectiveConfigHome, this.config.projectDir);
7904
- const { plan: interactiveThreadline, mcpFlags: interactiveMcpFlags, tag: interactiveTransportTag } = this.planInteractiveThreadlineMcp(framework, binaryPath, options); // threadline-mcp-local-http D3
7905
- const launchSpec = buildInteractiveLaunch(framework, {
7906
- binaryPath,
7907
- ...(options?.resumeSessionId ? { resumeSessionId: options.resumeSessionId } : {}),
7908
- ...(launchDefaultModel ? { defaultModel: launchDefaultModel } : {}),
7909
- // Warm-session A2A: pin a deterministic --session-id (claude-only, ignored
7910
- // when resuming) so eviction mid-thread falls back to --resume losslessly.
7911
- ...(options?.sessionId && !options?.resumeSessionId ? { sessionId: options.sessionId } : {}),
7912
- ...(options?.codexLocalProvider ? { codexLocalProvider: options.codexLocalProvider } : {}),
7913
- // Subscription & Auth Standard P1.3: per-account config home → CLAUDE_CONFIG_DIR
7914
- // (claude-code) or CODEX_HOME (codex-cli) for the launched session.
7915
- // effectiveConfigHome = explicit caller home, else the resolver-pinned one.
7916
- ...(effectiveConfigHome ? { configHome: effectiveConfigHome } : {}),
7917
- // Per-agent codex threadline MCP override (ignored by non-codex builders).
7918
- ...(this.config.codexThreadlineMcp ? { codexThreadlineMcp: this.config.codexThreadlineMcp } : {}),
7919
- ...(interactiveThreadline.transport === 'http' && interactiveThreadline.codexArgs
7920
- ? { codexThreadlineHttpArgs: interactiveThreadline.codexArgs } : {}),
7921
- // Dynamic MCP Lifecycle (claude-code only): launch with a lean/explicit MCP
7922
- // subset when resolved. Fail-safe to [] (full .mcp.json) — a no-op while the
7923
- // feature is dark, and never strands a launch. Ignored by other frameworks.
7924
- // Threadline HTTP (when chosen and dynamic MCP is off) rides the same flag slot.
7925
- ...(interactiveMcpFlags.length > 0 ? { mcpFlags: interactiveMcpFlags } : {}),
7926
- // pi-cli: pin session transcripts into the agent state dir so they are
7927
- // durable + discoverable (PI-HARNESS-INTEGRATION-SPEC §2.2). Ignored by
7928
- // every other framework's builder.
7929
- ...(framework === 'pi-cli'
7930
- ? { piSessionDir: path.join(this.config.projectDir, '.instar', 'state', 'pi-sessions') }
7931
- : {}),
7932
- // grok-build interactive step-3 gate (grok-build spec §7 round-8):
7933
- // enabledFrameworks is the reviewer lever; interactive sessions need
7934
- // the DISTINCT sessions.grokInteractiveSessions opt-in.
7935
- ...(framework === 'grok-build'
7936
- ? {
7937
- grokInteractiveOptIn: computeGrokInteractiveOptIn({
7938
- ...(this.config.enabledFrameworks
7939
- ? { enabledFrameworks: this.config.enabledFrameworks }
7940
- : {}),
7941
- ...(this.config.grokInteractiveSessions !== undefined
7942
- ? { grokInteractiveSessions: this.config.grokInteractiveSessions }
7943
- : {}),
7944
- }),
7945
- }
7946
- : {}),
7947
- // Topic Profile §6: per-topic thinking mode (claude --effort / codex
7948
- // model_reasoning_effort; strict no-op on gemini/pi).
7949
- ...(options?.thinkingMode ? { thinkingMode: options.thinkingMode } : {}),
7950
- // Topic Profile: direct per-topic Claude `--effort` pin (claude-code
7951
- // only; the builder validates the enum + drops an unknown value).
7952
- ...(options?.effort ? { effort: options.effort } : {}),
7953
- });
7954
- // Never-Silent Conversation §1.5: a session in a folder its engine home never trusted can stop
7955
- // at a "trust this folder?" dialog and never answer. Record the agent's own launch folder first,
7956
- // through the engine's own seeder (adapter table). Under vitest the default home is skipped: it is
7957
- // the operator's real home.
7958
- const trustSeeder = PROJECT_TRUST_SEEDERS[framework];
7959
- if (trustSeeder) {
7960
- const seeded = trustSeeder(launchSpec.envOverrides, options?.cwd ?? this.config.projectDir, { allowDefaultHome: !process.env.VITEST });
7961
- if (seeded.result.patched)
7962
- console.log(`[SessionManager] ${framework}: trusted the launch folder in ${seeded.home}`);
7963
- else if (seeded.result.reason !== 'already-recorded' && seeded.result.reason !== 'no-home') {
7964
- console.warn(`[SessionManager] ${framework}: could not record folder trust in ${seeded.home} — ${seeded.result.reason}`);
7965
- }
7966
- }
7967
- const memoryScoped = Boolean(memoryPlan?.scopeDir && memoryPlan.settingsPath);
7968
- if (memoryScoped) {
7969
- applyMemorySessionLaunch(launchSpec.argv, memoryPlan.settingsPath, memoryPlan.scopeDir);
7970
- }
7971
- else {
7972
- this.linkAgentOwnedMemory(framework, launchSpec.envOverrides, options?.cwd ?? this.config.projectDir);
7973
- }
7974
- const memoryToken = memoryScoped
7975
- ? this.memoryPrivacyWiring.privacy.issueSessionToken(interactiveSessionId, memoryPlan.audience, memoryPlan.placeKey)
7976
- : null;
7977
- const memoryScopeEnv = memoryPlan ? memoryScopeEnvValue(memoryPlan.audience) : null;
7978
- // Linux: the sandboxed shell reaches the agent server only through the sandbox proxy.
7979
- const memoryCurlHome = memoryScoped ? prepareSessionCurlHome(memoryPlan.scopeDir) : null;
7980
- // Spawn the framework CLI in tmux — no bash -c shell intermediary.
7981
- // Uses tmux -e flags to set/unset env vars directly, matching spawnSession pattern.
7982
- // This avoids shell injection risks and handles binary paths with spaces.
7983
- try {
7984
- const tmuxArgs = [
7985
- 'new-session', '-d',
7986
- '-s', tmuxSession,
7987
- '-c', options?.cwd ?? this.config.projectDir,
7988
- '-x', '200', '-y', '50',
7989
- // Opt-in: raise Claude Code's own retry count so it rides out transient
7990
- // throttle/overload longer before surfacing to the RateLimitSentinel.
7991
- ...(this.config.claudeCodeMaxRetries != null
7992
- ? ['-e', `CLAUDE_CODE_MAX_RETRIES=${this.config.claudeCodeMaxRetries}`]
7993
- : []),
7994
- '-e', `INSTAR_SESSION_ID=${interactiveSessionId}`,
7995
- ...await this.originTokenEnvFlags({
7996
- sessionId: interactiveSessionId, harnessId: framework, projectDir: options?.cwd ?? this.config.projectDir,
7997
- configuredModel: resolveInteractiveLaunchModel(framework, launchDefaultModel, options?.codexLocalProvider),
7998
- nativeSessionId: options?.resumeSessionId ?? (framework === 'claude-code' ? options?.sessionId : undefined),
7999
- configHome: this.originConfigHome(framework, launchSpec.envOverrides),
8000
- }), // Expose instar session ID to hook events
8001
- '-e', `INSTAR_SESSION_NAME=${tmuxSession}`, // Threadline binding: attributes a relay-send to its origin session
8002
- ...this.telemetryIdentityEnvFlags(options?.telegramTopicId), // skill-learning slice 0: INSTAR_MACHINE_ID / INSTAR_TOPIC_ID
8003
- '-e', `INSTAR_SERVER_URL=http://localhost:${this.config.port}`,
8004
- '-e', `INSTAR_AUTH_TOKEN=${memoryToken ?? this.config.authToken}`,
8005
- ...(memoryScopeEnv ? ['-e', `INSTAR_MEMORY_SCOPE=${memoryScopeEnv}`] : []),
8006
- ...(memoryScoped ? [
8007
- '-e', `INSTAR_PORT=${this.config.port}`,
8008
- '-e', `CLAUDE_CODE_TMPDIR=${path.join(memoryPlan.scopeDir, 'tmp')}`,
8009
- '-e', `TMPDIR=${path.join(memoryPlan.scopeDir, 'tmp')}`,
8010
- ] : []),
8011
- ...(memoryCurlHome ? ['-e', `CURL_HOME=${memoryCurlHome}`] : []),
8012
- ...(memoryScoped ? [] : interactiveThreadline.secretEnvFlags), // threadline-mcp-local-http D2 (flag on only)
8013
- ...(framework === 'claude-code' ? CLAUDE_MCP_TOOL_TIMEOUT_ENV_FLAGS : []), // long waits
8014
- '-e', `INSTAR_AGENT_ID=${this.config.projectName}`,
8015
- // The agent HOME (the `.instar` PARENT), distinct from CLAUDE_PROJECT_DIR.
8016
- // A worktree session's project dir has no `.instar/config.json` and no
8017
- // `.instar/state/`, so any hook that resolved those from the project dir
8018
- // silently no-opped for exactly the sessions doing mutating work. Hooks
8019
- // resolve agent-scoped files as `<INSTAR_AGENT_HOME>/.instar/...` — the
8020
- // `.instar` segment is part of every such path, never implied.
8021
- '-e', `INSTAR_AGENT_HOME=${this.config.projectDir}`,
8022
- '-e', `INSTAR_FRAMEWORK=${framework}`,
8023
- // durable-conversation-identity §7: per-session bind token scoping
8024
- // durable-state opens to this spawn's bootstrap conversation set
8025
- // (Telegram topic, or the Slack dispatch's minted conversation id).
8026
- ...this.bindTokenEnvFlags(tmuxSession, options?.bootstrapConversationIds ??
8027
- (typeof options?.telegramTopicId === 'number' ? [options.telegramTopicId] : [])),
8028
- ...(memoryScoped ? [] : this.ghTokenEnvFlags()), // P3b: per-agent vault GitHub token (empty when no vault token)
8029
- // Framework-specific env additions/clears (e.g., CLAUDECODE=)
8030
- ...Object.entries(launchSpec.envOverrides).flatMap(([k, v]) => ['-e', `${k}=${v}`]),
8031
- // OAuth tokens (sk-ant-oat01-...) go in CLAUDE_CODE_OAUTH_TOKEN to enable
8032
- // interactive mode auth via subscription. API keys (sk-ant-api03-...) go in
8033
- // ANTHROPIC_API_KEY for direct API billing. Codex reads its own
8034
- // OPENAI_API_KEY but harmless to pass these — Codex ignores them.
8035
- ...((this.config.anthropicApiKey ?? '').startsWith('sk-ant-oat')
8036
- ? ['-e', `CLAUDE_CODE_OAUTH_TOKEN=${this.config.anthropicApiKey}`, '-e', 'ANTHROPIC_API_KEY=']
8037
- : ['-e', `ANTHROPIC_API_KEY=${this.config.anthropicApiKey ?? ''}`, '-e', 'CLAUDE_CODE_OAUTH_TOKEN=']),
8038
- '-e', `ANTHROPIC_BASE_URL=${this.config.anthropicBaseUrl ?? ''}`,
8039
- // Isolate database credentials — spawned sessions must never inherit production
8040
- // database URLs from the parent shell. (Learned from Portal incident 2026-02-22)
8041
- '-e', 'DATABASE_URL=',
8042
- '-e', 'DIRECT_DATABASE_URL=',
8043
- // Round-18 (security): the round-17 scrub landed on the LEAST-exposed
8044
- // of the spawn sites — the 10-minute scoped triage pane — while the
8045
- // long-lived interactive panes, where the agent runs arbitrary Bash and
8046
- // can invoke grok directly, inherited the metered key from the tmux
8047
- // server env. Found by grepping the codebase's OWN scrub convention:
8048
- // DATABASE_URL_PROD= appears at every spawn site, XAI_API_KEY= at one.
8049
- '-e', 'XAI_API_KEY=',
8050
- '-e', 'GROK_DEPLOYMENT_KEY=',
8051
- '-e', 'DATABASE_URL_PROD=',
8052
- '-e', 'DATABASE_URL_DEV=',
8053
- '-e', 'DATABASE_URL_TEST=',
8054
- ];
8055
- if (options?.telegramTopicId) {
8056
- tmuxArgs.push('-e', `INSTAR_TELEGRAM_TOPIC=${options.telegramTopicId}`);
8057
- }
8058
- if (options?.slackChannelId) {
8059
- tmuxArgs.push('-e', `INSTAR_SLACK_CHANNEL=${options.slackChannelId}`);
8060
- }
8061
- // Thread→session (§5.3): when this session belongs to a Slack thread, carry the
8062
- // thread_ts so the session's reply path can thread its replies. Absent for
8063
- // channel-level sessions (today's behavior unchanged).
8064
- if (options?.slackThreadTs) {
8065
- tmuxArgs.push('-e', `INSTAR_SLACK_THREAD_TS=${options.slackThreadTs}`);
8066
- }
8067
- // ── slack-followthrough-generalization §4.4: channel-neutral conversation id
8068
- // for the Action-Claim Stop hook. Resolved IDENTICALLY to the bind token's
8069
- // bootstrap set above (bootstrapConversationIds[0] ?? telegramTopicId), so
8070
- // the id the hook posts is ALWAYS in the token's set (§4.3 gate never 403s
8071
- // its own session). 1:1 GUARD (R2-EXT-C1): injected ONLY for a session that
8072
- // is 1:1 with the conversation — NEVER on the shared `lifeline` session, which
8073
- // serves both the Telegram system topic AND Slack DMs. On the lifeline the
8074
- // hook (which keys ONLY on INSTAR_CONVERSATION_ID, no fallback) registers
8075
- // nothing — a genuine untracked miss, never a cross-channel mis-delivery.
8076
- if (name !== 'lifeline') {
8077
- const conversationEnvId = options?.bootstrapConversationIds?.[0] ??
8078
- (typeof options?.telegramTopicId === 'number' ? options.telegramTopicId : undefined);
8079
- if (typeof conversationEnvId === 'number') {
8080
- tmuxArgs.push('-e', `INSTAR_CONVERSATION_ID=${conversationEnvId}`);
7917
+ assertBrowserMcpProfilesSafe(options?.cwd ?? this.config.projectDir, framework, effectiveConfigHome, this.config.projectDir);
7918
+ const { plan: interactiveThreadline, mcpFlags: interactiveMcpFlags, tag: interactiveTransportTag } = this.planInteractiveThreadlineMcp(framework, binaryPath, { ...options, configHome: effectiveConfigHome }); // threadline-mcp-local-http D3
7919
+ const launchSpec = buildInteractiveLaunch(framework, {
7920
+ binaryPath,
7921
+ ...(options?.resumeSessionId ? { resumeSessionId: options.resumeSessionId } : {}),
7922
+ ...(launchDefaultModel ? { defaultModel: launchDefaultModel } : {}),
7923
+ // Warm-session A2A: pin a deterministic --session-id (claude-only, ignored
7924
+ // when resuming) so eviction mid-thread falls back to --resume losslessly.
7925
+ ...(options?.sessionId && !options?.resumeSessionId ? { sessionId: options.sessionId } : {}),
7926
+ ...(options?.codexLocalProvider ? { codexLocalProvider: options.codexLocalProvider } : {}),
7927
+ // Subscription & Auth Standard P1.3: per-account config home → CLAUDE_CONFIG_DIR
7928
+ // (claude-code) or CODEX_HOME (codex-cli) for the launched session.
7929
+ // effectiveConfigHome = explicit caller home, else the resolver-pinned one.
7930
+ ...(effectiveConfigHome ? { configHome: effectiveConfigHome } : {}),
7931
+ // Per-agent codex threadline MCP override (ignored by non-codex builders).
7932
+ ...(this.config.codexThreadlineMcp ? { codexThreadlineMcp: this.config.codexThreadlineMcp } : {}),
7933
+ ...(interactiveThreadline.transport === 'http' && interactiveThreadline.codexArgs
7934
+ ? { codexThreadlineHttpArgs: interactiveThreadline.codexArgs } : {}),
7935
+ // Dynamic MCP Lifecycle (claude-code only): launch with a lean/explicit MCP
7936
+ // subset when resolved. Fail-safe to [] (full .mcp.json) — a no-op while the
7937
+ // feature is dark, and never strands a launch. Ignored by other frameworks.
7938
+ // Threadline HTTP (when chosen and dynamic MCP is off) rides the same flag slot.
7939
+ ...(interactiveMcpFlags.length > 0 ? { mcpFlags: interactiveMcpFlags } : {}),
7940
+ // pi-cli: pin session transcripts into the agent state dir so they are
7941
+ // durable + discoverable (PI-HARNESS-INTEGRATION-SPEC §2.2). Ignored by
7942
+ // every other framework's builder.
7943
+ ...(framework === 'pi-cli'
7944
+ ? { piSessionDir: path.join(this.config.projectDir, '.instar', 'state', 'pi-sessions') }
7945
+ : {}),
7946
+ // grok-build interactive step-3 gate (grok-build spec §7 round-8):
7947
+ // enabledFrameworks is the reviewer lever; interactive sessions need
7948
+ // the DISTINCT sessions.grokInteractiveSessions opt-in.
7949
+ ...(framework === 'grok-build'
7950
+ ? {
7951
+ grokInteractiveOptIn: computeGrokInteractiveOptIn({
7952
+ ...(this.config.enabledFrameworks
7953
+ ? { enabledFrameworks: this.config.enabledFrameworks }
7954
+ : {}),
7955
+ ...(this.config.grokInteractiveSessions !== undefined
7956
+ ? { grokInteractiveSessions: this.config.grokInteractiveSessions }
7957
+ : {}),
7958
+ }),
7959
+ }
7960
+ : {}),
7961
+ // Topic Profile §6: per-topic thinking mode (claude --effort / codex
7962
+ // model_reasoning_effort; strict no-op on gemini/pi).
7963
+ ...(options?.thinkingMode ? { thinkingMode: options.thinkingMode } : {}),
7964
+ // Topic Profile: direct per-topic Claude `--effort` pin (claude-code
7965
+ // only; the builder validates the enum + drops an unknown value).
7966
+ ...(options?.effort ? { effort: options.effort } : {}),
7967
+ });
7968
+ // Never-Silent Conversation §1.5: a session in a folder its engine home never trusted can stop
7969
+ // at a "trust this folder?" dialog and never answer. Record the agent's own launch folder first,
7970
+ // through the engine's own seeder (adapter table). Under vitest the default home is skipped: it is
7971
+ // the operator's real home.
7972
+ const trustSeeder = PROJECT_TRUST_SEEDERS[framework];
7973
+ if (trustSeeder) {
7974
+ const seeded = trustSeeder(launchSpec.envOverrides, options?.cwd ?? this.config.projectDir, { allowDefaultHome: !process.env.VITEST });
7975
+ if (seeded.result.patched)
7976
+ console.log(`[SessionManager] ${framework}: trusted the launch folder in ${seeded.home}`);
7977
+ else if (seeded.result.reason !== 'already-recorded' && seeded.result.reason !== 'no-home') {
7978
+ console.warn(`[SessionManager] ${framework}: could not record folder trust in ${seeded.home} — ${seeded.result.reason}`);
8081
7979
  }
8082
7980
  }
8083
- tmuxArgs.push(...launchSpec.argv);
8084
- if (options?.resumeSessionId) {
8085
- console.log(`[SessionManager] Resuming session: ${options.resumeSessionId} (framework: ${framework})`);
7981
+ const memoryScoped = Boolean(memoryPlan?.scopeDir && memoryPlan.settingsPath);
7982
+ if (memoryScoped) {
7983
+ applyMemorySessionLaunch(launchSpec.argv, memoryPlan.settingsPath, memoryPlan.scopeDir);
8086
7984
  }
8087
7985
  else {
8088
- console.log(`[SessionManager] Spawning interactive session "${tmuxSession}" (framework: ${framework})`);
8089
- }
8090
- withSyncOp(() => execFileSync(this.config.tmuxPath, tmuxArgs, { encoding: 'utf-8' }));
8091
- this.retainFailedExitStatus(tmuxSession);
8092
- // Increase tmux scrollback buffer for dashboard history support
7986
+ this.linkAgentOwnedMemory(framework, launchSpec.envOverrides, options?.cwd ?? this.config.projectDir);
7987
+ }
7988
+ const memoryToken = memoryScoped
7989
+ ? this.memoryPrivacyWiring.privacy.issueSessionToken(interactiveSessionId, memoryPlan.audience, memoryPlan.placeKey)
7990
+ : null;
7991
+ const memoryScopeEnv = memoryPlan ? memoryScopeEnvValue(memoryPlan.audience) : null;
7992
+ // Linux: the sandboxed shell reaches the agent server only through the sandbox proxy.
7993
+ const memoryCurlHome = memoryScoped ? prepareSessionCurlHome(memoryPlan.scopeDir) : null;
7994
+ // Spawn the framework CLI in tmux — no bash -c shell intermediary.
7995
+ // Uses tmux -e flags to set/unset env vars directly, matching spawnSession pattern.
7996
+ // This avoids shell injection risks and handles binary paths with spaces.
8093
7997
  try {
8094
- withSyncOp(() => execFileSync(this.config.tmuxPath, [
8095
- 'set-option', '-t', `=${tmuxSession}:`, 'history-limit', '50000',
8096
- ], { encoding: 'utf-8', timeout: 5000 }));
7998
+ const tmuxArgs = [
7999
+ 'new-session', '-d',
8000
+ '-s', tmuxSession,
8001
+ '-c', options?.cwd ?? this.config.projectDir,
8002
+ '-x', '200', '-y', '50',
8003
+ // Opt-in: raise Claude Code's own retry count so it rides out transient
8004
+ // throttle/overload longer before surfacing to the RateLimitSentinel.
8005
+ ...(this.config.claudeCodeMaxRetries != null
8006
+ ? ['-e', `CLAUDE_CODE_MAX_RETRIES=${this.config.claudeCodeMaxRetries}`]
8007
+ : []),
8008
+ '-e', `INSTAR_SESSION_ID=${interactiveSessionId}`,
8009
+ ...await this.originTokenEnvFlags({
8010
+ sessionId: interactiveSessionId, harnessId: framework, projectDir: options?.cwd ?? this.config.projectDir,
8011
+ configuredModel: resolveInteractiveLaunchModel(framework, launchDefaultModel, options?.codexLocalProvider),
8012
+ nativeSessionId: options?.resumeSessionId ?? (framework === 'claude-code' ? options?.sessionId : undefined),
8013
+ configHome: this.originConfigHome(framework, launchSpec.envOverrides),
8014
+ }), // Expose instar session ID to hook events
8015
+ '-e', `INSTAR_SESSION_NAME=${tmuxSession}`, // Threadline binding: attributes a relay-send to its origin session
8016
+ ...this.telemetryIdentityEnvFlags(options?.telegramTopicId), // skill-learning slice 0: INSTAR_MACHINE_ID / INSTAR_TOPIC_ID
8017
+ '-e', `INSTAR_SERVER_URL=http://localhost:${this.config.port}`,
8018
+ '-e', `INSTAR_AUTH_TOKEN=${memoryToken ?? this.config.authToken}`,
8019
+ ...(memoryScopeEnv ? ['-e', `INSTAR_MEMORY_SCOPE=${memoryScopeEnv}`] : []),
8020
+ ...(memoryScoped ? [
8021
+ '-e', `INSTAR_PORT=${this.config.port}`,
8022
+ '-e', `CLAUDE_CODE_TMPDIR=${path.join(memoryPlan.scopeDir, 'tmp')}`,
8023
+ '-e', `TMPDIR=${path.join(memoryPlan.scopeDir, 'tmp')}`,
8024
+ ] : []),
8025
+ ...(memoryCurlHome ? ['-e', `CURL_HOME=${memoryCurlHome}`] : []),
8026
+ ...(memoryScoped ? [] : interactiveThreadline.secretEnvFlags), // threadline-mcp-local-http D2 (flag on only)
8027
+ ...(framework === 'claude-code' ? CLAUDE_MCP_TOOL_TIMEOUT_ENV_FLAGS : []), // long waits
8028
+ '-e', `INSTAR_AGENT_ID=${this.config.projectName}`,
8029
+ // The agent HOME (the `.instar` PARENT), distinct from CLAUDE_PROJECT_DIR.
8030
+ // A worktree session's project dir has no `.instar/config.json` and no
8031
+ // `.instar/state/`, so any hook that resolved those from the project dir
8032
+ // silently no-opped for exactly the sessions doing mutating work. Hooks
8033
+ // resolve agent-scoped files as `<INSTAR_AGENT_HOME>/.instar/...` — the
8034
+ // `.instar` segment is part of every such path, never implied.
8035
+ '-e', `INSTAR_AGENT_HOME=${this.config.projectDir}`,
8036
+ '-e', `INSTAR_FRAMEWORK=${framework}`,
8037
+ // durable-conversation-identity §7: per-session bind token scoping
8038
+ // durable-state opens to this spawn's bootstrap conversation set
8039
+ // (Telegram topic, or the Slack dispatch's minted conversation id).
8040
+ ...this.bindTokenEnvFlags(tmuxSession, options?.bootstrapConversationIds ??
8041
+ (typeof options?.telegramTopicId === 'number' ? [options.telegramTopicId] : [])),
8042
+ ...(memoryScoped ? [] : this.ghTokenEnvFlags()), // P3b: per-agent vault GitHub token (empty when no vault token)
8043
+ // Framework-specific env additions/clears (e.g., CLAUDECODE=)
8044
+ ...Object.entries(launchSpec.envOverrides).flatMap(([k, v]) => ['-e', `${k}=${v}`]),
8045
+ // OAuth tokens (sk-ant-oat01-...) go in CLAUDE_CODE_OAUTH_TOKEN to enable
8046
+ // interactive mode auth via subscription. API keys (sk-ant-api03-...) go in
8047
+ // ANTHROPIC_API_KEY for direct API billing. Codex reads its own
8048
+ // OPENAI_API_KEY but harmless to pass these — Codex ignores them.
8049
+ ...((this.config.anthropicApiKey ?? '').startsWith('sk-ant-oat')
8050
+ ? ['-e', `CLAUDE_CODE_OAUTH_TOKEN=${this.config.anthropicApiKey}`, '-e', 'ANTHROPIC_API_KEY=']
8051
+ : ['-e', `ANTHROPIC_API_KEY=${this.config.anthropicApiKey ?? ''}`, '-e', 'CLAUDE_CODE_OAUTH_TOKEN=']),
8052
+ '-e', `ANTHROPIC_BASE_URL=${this.config.anthropicBaseUrl ?? ''}`,
8053
+ // Isolate database credentials — spawned sessions must never inherit production
8054
+ // database URLs from the parent shell. (Learned from Portal incident 2026-02-22)
8055
+ '-e', 'DATABASE_URL=',
8056
+ '-e', 'DIRECT_DATABASE_URL=',
8057
+ // Round-18 (security): the round-17 scrub landed on the LEAST-exposed
8058
+ // of the spawn sites — the 10-minute scoped triage pane — while the
8059
+ // long-lived interactive panes, where the agent runs arbitrary Bash and
8060
+ // can invoke grok directly, inherited the metered key from the tmux
8061
+ // server env. Found by grepping the codebase's OWN scrub convention:
8062
+ // DATABASE_URL_PROD= appears at every spawn site, XAI_API_KEY= at one.
8063
+ '-e', 'XAI_API_KEY=',
8064
+ '-e', 'GROK_DEPLOYMENT_KEY=',
8065
+ '-e', 'DATABASE_URL_PROD=',
8066
+ '-e', 'DATABASE_URL_DEV=',
8067
+ '-e', 'DATABASE_URL_TEST=',
8068
+ ];
8069
+ if (options?.telegramTopicId) {
8070
+ tmuxArgs.push('-e', `INSTAR_TELEGRAM_TOPIC=${options.telegramTopicId}`);
8071
+ }
8072
+ if (options?.slackChannelId) {
8073
+ tmuxArgs.push('-e', `INSTAR_SLACK_CHANNEL=${options.slackChannelId}`);
8074
+ }
8075
+ // Thread→session (§5.3): when this session belongs to a Slack thread, carry the
8076
+ // thread_ts so the session's reply path can thread its replies. Absent for
8077
+ // channel-level sessions (today's behavior unchanged).
8078
+ if (options?.slackThreadTs) {
8079
+ tmuxArgs.push('-e', `INSTAR_SLACK_THREAD_TS=${options.slackThreadTs}`);
8080
+ }
8081
+ // ── slack-followthrough-generalization §4.4: channel-neutral conversation id
8082
+ // for the Action-Claim Stop hook. Resolved IDENTICALLY to the bind token's
8083
+ // bootstrap set above (bootstrapConversationIds[0] ?? telegramTopicId), so
8084
+ // the id the hook posts is ALWAYS in the token's set (§4.3 gate never 403s
8085
+ // its own session). 1:1 GUARD (R2-EXT-C1): injected ONLY for a session that
8086
+ // is 1:1 with the conversation — NEVER on the shared `lifeline` session, which
8087
+ // serves both the Telegram system topic AND Slack DMs. On the lifeline the
8088
+ // hook (which keys ONLY on INSTAR_CONVERSATION_ID, no fallback) registers
8089
+ // nothing — a genuine untracked miss, never a cross-channel mis-delivery.
8090
+ if (name !== 'lifeline') {
8091
+ const conversationEnvId = options?.bootstrapConversationIds?.[0] ??
8092
+ (typeof options?.telegramTopicId === 'number' ? options.telegramTopicId : undefined);
8093
+ if (typeof conversationEnvId === 'number') {
8094
+ tmuxArgs.push('-e', `INSTAR_CONVERSATION_ID=${conversationEnvId}`);
8095
+ }
8096
+ }
8097
+ tmuxArgs.push(...launchSpec.argv);
8098
+ if (options?.resumeSessionId) {
8099
+ console.log(`[SessionManager] Resuming session: ${options.resumeSessionId} (framework: ${framework})`);
8100
+ }
8101
+ else {
8102
+ console.log(`[SessionManager] Spawning interactive session "${tmuxSession}" (framework: ${framework})`);
8103
+ }
8104
+ withSyncOp(() => execFileSync(this.config.tmuxPath, tmuxArgs, { encoding: 'utf-8' }));
8105
+ interactiveTmuxCreated = true;
8106
+ this.retainFailedExitStatus(tmuxSession);
8107
+ // Increase tmux scrollback buffer for dashboard history support
8108
+ try {
8109
+ withSyncOp(() => execFileSync(this.config.tmuxPath, [
8110
+ 'set-option', '-t', `=${tmuxSession}:`, 'history-limit', '50000',
8111
+ ], { encoding: 'utf-8', timeout: 5000 }));
8112
+ }
8113
+ catch {
8114
+ // @silent-fallback-ok — history-limit is a nice-to-have
8115
+ }
8097
8116
  }
8098
- catch {
8099
- // @silent-fallback-ok — history-limit is a nice-to-have
8117
+ catch (err) {
8118
+ this.revokeOriginSession(interactiveSessionId);
8119
+ this.releaseAdmissionFor(tmuxSession); // a failed spawn must not hold the recovery slot
8120
+ throw new Error(`Failed to create interactive tmux session: ${this.originSpawnError(err)}`);
8121
+ }
8122
+ // Track it in state (with default timeout — interactive sessions shouldn't hang forever)
8123
+ const session = {
8124
+ id: interactiveSessionId,
8125
+ name: name || tmuxSession,
8126
+ ...(options?.telegramTopicId !== undefined ? { telegramTopicId: options.telegramTopicId } : {}),
8127
+ status: 'running',
8128
+ tmuxSession,
8129
+ startedAt: new Date().toISOString(),
8130
+ // Carry the framework so the dashboard renders engine-aware (a Codex
8131
+ // interactive session must not display as a Claude one). Model is the
8132
+ // framework-resolved model THIS session was actually launched with —
8133
+ // we use launchDefaultModel (post Codex rate-limit swap), not the raw
8134
+ // config default, so GET /sessions reports the real running model and an
8135
+ // operator can confirm what a session picked up after a config change.
8136
+ // Left undefined only when no model was pinned (the CLI uses its own
8137
+ // account default).
8138
+ framework,
8139
+ ...(resolveInteractiveLaunchModel(framework, launchDefaultModel, options?.codexLocalProvider)
8140
+ ? { model: resolveInteractiveLaunchModel(framework, launchDefaultModel, options?.codexLocalProvider) }
8141
+ : {}),
8142
+ // P1.3: which subscription-pool account this session runs under (an explicit
8143
+ // quota-aware swap/placement, OR the resolver-pinned account for B1 — the
8144
+ // user-facing interactive lane is now tagged just like the headless lane).
8145
+ // Undefined for single-account agents (resolver unwired → no pin).
8146
+ ...(effectiveAccountId ? { subscriptionAccountId: effectiveAccountId } : {}),
8147
+ // §2.10 credential provenance — derived from the SAME predicate as the env block.
8148
+ ...(interactiveCredentialSource ? { credentialSource: interactiveCredentialSource } : {}),
8149
+ ...(memoryPlan ? { memoryAudience: audienceKey(memoryPlan.audience) } : {}),
8150
+ ...(memoryPlan?.scopeDir ? { memoryScopeDir: memoryPlan.scopeDir, memorySettingsPath: memoryPlan.settingsPath ?? undefined } : {}),
8151
+ ...(memoryPlan ? { memoryPlaceInput: {
8152
+ telegramTopicId: options?.telegramTopicId, slackChannelId: options?.slackChannelId,
8153
+ memoryPlaceKey: options?.memoryPlaceKey, memoryPlace: options?.memoryPlace,
8154
+ } } : {}),
8155
+ ...(options?.slackChannelId ? { slackChannelId: options.slackChannelId } : {}),
8156
+ ...(options?.triggeredBy ? { triggeredBy: options.triggeredBy } : {}),
8157
+ prompt: effectiveInitialMessage,
8158
+ maxDurationMinutes: this.effectiveMaxDurationMinutes,
8159
+ // R2.8/L13: record the spawn cwd so a resume-queue entry can revive
8160
+ // this session in ITS tree (worktree round-trip).
8161
+ cwd: options?.cwd ?? this.config.projectDir,
8162
+ ...interactiveTransportTag,
8163
+ };
8164
+ this.state.saveSession(session);
8165
+ // Wait for Claude to be ready, then send the initial message.
8166
+ // Resume sessions load large JONSLs which trigger TUI redraws — use longer timeout
8167
+ // and a stabilization delay to avoid injecting text that gets wiped by the redraw.
8168
+ // Fresh sessions also get a generous timeout (90s) to handle slow API auth,
8169
+ // large CLAUDE.md loading, and session-start hook execution.
8170
+ const readyTimeout = options?.resumeSessionId ? 120_000 : 90_000;
8171
+ if (effectiveInitialMessage) {
8172
+ // DURABILITY (finding 8d300555): the inject below happens after an async
8173
+ // readiness wait — codex can take tens of seconds to boot, and a server
8174
+ // restart in that window used to silently drop the message (the pending
8175
+ // inject was process-local; tmux survived idle, the bootstrap file sat
8176
+ // unconsumed, the operator waited on nothing). Record the pending inject
8177
+ // BEFORE the wait; handleReadyAndInject clears it only after the inject
8178
+ // actually runs; recoverPendingInjects sweeps survivors at boot.
8179
+ this.pendingInjects.record({
8180
+ tmuxSession,
8181
+ // SEC-137: record the text exactly as rawInject will type it, so the
8182
+ // Stage-B first-message match compares like with like.
8183
+ initialMessage: sanitizeTypedText(effectiveInitialMessage),
8184
+ telegramTopicId: options?.telegramTopicId,
8185
+ conversationId: options?.bootstrapConversationIds?.[0] ?? options?.telegramTopicId,
8186
+ // Only a genuinely fresh Codex spawn may use the narrow offset-zero
8187
+ // bootstrap lane. Resume/recovery records and records written by old
8188
+ // binaries remain fail-closed even if session state is incomplete.
8189
+ freshPreRolloutBootstrap: framework === 'codex-cli' && !options?.resumeSessionId,
8190
+ });
8191
+ const injection = this.handleReadyAndInject(tmuxSession, name, effectiveInitialMessage, readyTimeout, framework === CODEX_CLI_FRAMEWORK && pinnedAccount && options?.resumeSessionId
8192
+ ? { ...options, strictCodexResume: true }
8193
+ : options);
8194
+ if (options?.awaitInitialInjection) {
8195
+ await injection;
8196
+ }
8197
+ else
8198
+ injection.catch((err) => {
8199
+ console.error(`[SessionManager] Error during ready-and-inject for "${tmuxSession}": ${err}`);
8200
+ });
8100
8201
  }
8202
+ return tmuxSession;
8101
8203
  }
8102
8204
  catch (err) {
8103
- this.revokeOriginSession(interactiveSessionId);
8104
- this.releaseAdmissionFor(tmuxSession); // a failed spawn must not hold the recovery slot
8105
- throw new Error(`Failed to create interactive tmux session: ${this.originSpawnError(err)}`);
8106
- }
8107
- // Track it in state (with default timeout — interactive sessions shouldn't hang forever)
8108
- const session = {
8109
- id: interactiveSessionId,
8110
- name: name || tmuxSession,
8111
- ...(options?.telegramTopicId !== undefined ? { telegramTopicId: options.telegramTopicId } : {}),
8112
- status: 'running',
8113
- tmuxSession,
8114
- startedAt: new Date().toISOString(),
8115
- // Carry the framework so the dashboard renders engine-aware (a Codex
8116
- // interactive session must not display as a Claude one). Model is the
8117
- // framework-resolved model THIS session was actually launched with —
8118
- // we use launchDefaultModel (post Codex rate-limit swap), not the raw
8119
- // config default, so GET /sessions reports the real running model and an
8120
- // operator can confirm what a session picked up after a config change.
8121
- // Left undefined only when no model was pinned (the CLI uses its own
8122
- // account default).
8123
- framework,
8124
- ...(resolveInteractiveLaunchModel(framework, launchDefaultModel, options?.codexLocalProvider)
8125
- ? { model: resolveInteractiveLaunchModel(framework, launchDefaultModel, options?.codexLocalProvider) }
8126
- : {}),
8127
- // P1.3: which subscription-pool account this session runs under (an explicit
8128
- // quota-aware swap/placement, OR the resolver-pinned account for B1 — the
8129
- // user-facing interactive lane is now tagged just like the headless lane).
8130
- // Undefined for single-account agents (resolver unwired → no pin).
8131
- ...(effectiveAccountId ? { subscriptionAccountId: effectiveAccountId } : {}),
8132
- // §2.10 credential provenance — derived from the SAME predicate as the env block.
8133
- ...(interactiveCredentialSource ? { credentialSource: interactiveCredentialSource } : {}),
8134
- ...(memoryPlan ? { memoryAudience: audienceKey(memoryPlan.audience) } : {}),
8135
- ...(memoryPlan?.scopeDir ? { memoryScopeDir: memoryPlan.scopeDir, memorySettingsPath: memoryPlan.settingsPath ?? undefined } : {}),
8136
- ...(memoryPlan ? { memoryPlaceInput: {
8137
- telegramTopicId: options?.telegramTopicId, slackChannelId: options?.slackChannelId,
8138
- memoryPlaceKey: options?.memoryPlaceKey, memoryPlace: options?.memoryPlace,
8139
- } } : {}),
8140
- ...(options?.slackChannelId ? { slackChannelId: options.slackChannelId } : {}),
8141
- ...(options?.triggeredBy ? { triggeredBy: options.triggeredBy } : {}),
8142
- prompt: effectiveInitialMessage,
8143
- maxDurationMinutes: this.effectiveMaxDurationMinutes,
8144
- // R2.8/L13: record the spawn cwd so a resume-queue entry can revive
8145
- // this session in ITS tree (worktree round-trip).
8146
- cwd: options?.cwd ?? this.config.projectDir,
8147
- ...interactiveTransportTag,
8148
- };
8149
- this.state.saveSession(session);
8150
- // Wait for Claude to be ready, then send the initial message.
8151
- // Resume sessions load large JONSLs which trigger TUI redraws — use longer timeout
8152
- // and a stabilization delay to avoid injecting text that gets wiped by the redraw.
8153
- // Fresh sessions also get a generous timeout (90s) to handle slow API auth,
8154
- // large CLAUDE.md loading, and session-start hook execution.
8155
- const readyTimeout = options?.resumeSessionId ? 120_000 : 90_000;
8156
- if (effectiveInitialMessage) {
8157
- // DURABILITY (finding 8d300555): the inject below happens after an async
8158
- // readiness wait — codex can take tens of seconds to boot, and a server
8159
- // restart in that window used to silently drop the message (the pending
8160
- // inject was process-local; tmux survived idle, the bootstrap file sat
8161
- // unconsumed, the operator waited on nothing). Record the pending inject
8162
- // BEFORE the wait; handleReadyAndInject clears it only after the inject
8163
- // actually runs; recoverPendingInjects sweeps survivors at boot.
8164
- this.pendingInjects.record({
8165
- tmuxSession,
8166
- // SEC-137: record the text exactly as rawInject will type it, so the
8167
- // Stage-B first-message match compares like with like.
8168
- initialMessage: sanitizeTypedText(effectiveInitialMessage),
8169
- telegramTopicId: options?.telegramTopicId,
8170
- conversationId: options?.bootstrapConversationIds?.[0] ?? options?.telegramTopicId,
8171
- // Only a genuinely fresh Codex spawn may use the narrow offset-zero
8172
- // bootstrap lane. Resume/recovery records and records written by old
8173
- // binaries remain fail-closed even if session state is incomplete.
8174
- freshPreRolloutBootstrap: framework === 'codex-cli' && !options?.resumeSessionId,
8175
- });
8176
- const injection = this.handleReadyAndInject(tmuxSession, name, effectiveInitialMessage, readyTimeout, options);
8177
- if (options?.awaitInitialInjection) {
8178
- await injection;
8179
- }
8180
- else
8181
- injection.catch((err) => {
8182
- console.error(`[SessionManager] Error during ready-and-inject for "${tmuxSession}": ${err}`);
8183
- });
8205
+ if (!interactiveTmuxCreated)
8206
+ this.releaseAdmissionFor(tmuxSession);
8207
+ throw err;
8184
8208
  }
8185
- return tmuxSession;
8186
8209
  }
8187
8210
  /**
8188
8211
  * Wait for Claude to be ready, inject the initial message, and — when the
@@ -8241,14 +8264,16 @@ rm() { "${shimRunner}" rm "$@"; }
8241
8264
  }
8242
8265
  const stillAlive = sessionExists && !paneDead;
8243
8266
  if (!stillAlive && options?.resumeSessionId) {
8244
- console.warn(`[SessionManager] Resume failed for "${tmuxSession}" (UUID ${options.resumeSessionId}) — tmux died during startup. Falling back to fresh spawn.`);
8267
+ console.warn(options.strictCodexResume
8268
+ ? `[SessionManager] Codex resume failed for "${tmuxSession}" — saved conversation retained for recovery.`
8269
+ : `[SessionManager] Resume failed for "${tmuxSession}" (UUID ${options.resumeSessionId}) — tmux died during startup. Falling back to fresh spawn.`);
8245
8270
  // Mark the failed session BEFORE emitting the event. A concurrent
8246
8271
  // monitor tick that reads state in between would otherwise see a dead
8247
8272
  // pane still flagged `running`. Also matters because some
8248
8273
  // resumeFailed listeners may consult listRunningSessions to confirm
8249
8274
  // the failure shape.
8250
8275
  try {
8251
- const failed = this.listRunningSessions().find(s => s.tmuxSession === tmuxSession);
8276
+ const failed = this.state.listSessions({ status: 'running' }).find(s => s.tmuxSession === tmuxSession);
8252
8277
  if (failed) {
8253
8278
  failed.status = 'failed';
8254
8279
  failed.endedAt = new Date().toISOString();
@@ -8257,6 +8282,11 @@ rm() { "${shimRunner}" rm "$@"; }
8257
8282
  }
8258
8283
  catch { /* state cleanup is best-effort */ }
8259
8284
  this.releaseAdmissionFor(tmuxSession); // the fresh respawn below re-admits on its own
8285
+ if (options.strictCodexResume) {
8286
+ // Do not emit resumeFailed: its consumer removes the saved resume id.
8287
+ // The pending bootstrap and rollout remain available for recovery.
8288
+ throw new Error('codex-account-resume-failed: the resumed conversation exited; saved rollouts were preserved and no fresh conversation was started.');
8289
+ }
8260
8290
  this.emit('resumeFailed', {
8261
8291
  tmuxSession,
8262
8292
  resumeSessionId: options.resumeSessionId,