gestalt-mobile 0.71.5 → 0.72.1

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 (47) hide show
  1. package/README.md +15 -48
  2. package/dist/client/assets/index-CwgSPgbi.css +1 -0
  3. package/dist/client/assets/index-ME1MRi_3.js +182 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/client/features/chat/activity-summary.js +11 -0
  6. package/dist/server/client/features/chat/chat-projection.js +6 -2
  7. package/dist/server/server/cli.js +0 -3
  8. package/dist/server/server/composition.contracts.js +0 -2
  9. package/dist/server/server/composition.js +8 -25
  10. package/dist/server/server/config.js +2 -5
  11. package/dist/server/server/features/agent-activity/registry.js +42 -15
  12. package/dist/server/server/features/catalog/get-bootstrap/use-case.js +0 -1
  13. package/dist/server/server/features/catalog/register-routes.js +0 -3
  14. package/dist/server/server/features/sessions/forget-session/use-case.js +6 -0
  15. package/dist/server/server/features/skills/list-available/endpoint.js +1 -1
  16. package/dist/server/server/features/skills/model/skill-profile.js +2 -3
  17. package/dist/server/server/platform/codex/capability-deadline.js +26 -0
  18. package/dist/server/server/platform/codex/codex-capabilities.js +23 -56
  19. package/dist/server/server/platform/codex/codex-playwright.js +3 -3
  20. package/dist/server/server/platform/codex/codex-serena.js +1 -1
  21. package/dist/server/server/platform/codex/mcp-startup-failure.js +0 -25
  22. package/dist/server/server/platform/codex/normalizer.js +0 -17
  23. package/dist/server/server/platform/codex/retired-capability-migration.js +105 -0
  24. package/dist/server/server/platform/codex/session-runtime.js +4 -52
  25. package/dist/server/server/platform/codex/startup-guidance.fixture.js +3 -3
  26. package/dist/server/server/platform/kimi/kimi-skill-catalog.js +2 -8
  27. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -7
  28. package/dist/server/server/platform/scratch/containment-fence.js +76 -20
  29. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +139 -13
  30. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +20 -11
  31. package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +64 -8
  32. package/dist/server/server/platform/scratch/managed-scratch-owner.js +17 -1
  33. package/dist/server/server/platform/scratch/runtime-root.js +147 -0
  34. package/dist/server/server/platform/scratch/workspace-publication.js +67 -0
  35. package/dist/server/server/platform/skills/codex-skill-catalog.js +9 -7
  36. package/dist/server/shared/contracts/mcp-startup-failure.js +5 -30
  37. package/package.json +1 -1
  38. package/dist/client/assets/index-BOJci8Jh.css +0 -1
  39. package/dist/client/assets/index-Cb4qCgbe.js +0 -183
  40. package/dist/server/server/features/catalog/get-xerj-status/endpoint.js +0 -13
  41. package/dist/server/server/platform/retrieval/codex-xerj.js +0 -205
  42. package/dist/server/server/platform/retrieval/managed-xerj.js +0 -196
  43. package/dist/server/server/platform/retrieval/xerj-index-config.js +0 -70
  44. package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +0 -124
  45. package/dist/server/server/platform/retrieval/xerj-indexer.js +0 -399
  46. package/dist/server/shared/contracts/xerj-startup.js +0 -76
  47. /package/dist/server/{shared/contracts/xerj-status.js → server/platform/codex/capability-contracts.js} +0 -0
@@ -5,7 +5,6 @@
5
5
  */
6
6
  import { parseMcpStartupFailure, parseMcpStartupStatus, startupIdentifier, startupServers, } from '../../../shared/contracts/mcp-startup-failure.js';
7
7
  import { randomUUID } from 'node:crypto';
8
- import { parseXerjStartupReason } from '../../../shared/contracts/xerj-startup.js';
9
8
  /**
10
9
  * Codex 0.164.0 generated experimental schema: McpServerStatusUpdatedNotification.
11
10
  * Upstream supplies error prose and one structured failure reason, but no child
@@ -44,30 +43,6 @@ export function observedMcpStartupFailure(correlation, observation) {
44
43
  export class McpStartupTracker {
45
44
  runtimeId = randomUUID();
46
45
  attempts = new Map();
47
- /** Trusted local observation only; upstream notifications cannot supply this phase. */
48
- observeReadiness(status, reason) {
49
- const observation = this.observe({
50
- method: 'mcpServer/statusUpdated',
51
- params: { name: 'gestalt-xerj', status },
52
- });
53
- if (!observation)
54
- return undefined;
55
- const local = parseMcpStartupStatus({
56
- ...observation,
57
- phase: 'readiness',
58
- failure: observation.failure
59
- ? {
60
- ...observation.failure,
61
- phase: 'readiness',
62
- code: 'readiness-failed',
63
- readinessReason: parseXerjStartupReason(reason),
64
- }
65
- : null,
66
- });
67
- if (local)
68
- this.attempts.set(JSON.stringify([null, 'gestalt-xerj']), local);
69
- return local;
70
- }
71
46
  observe(notification) {
72
47
  if (!['mcpServer/startupStatus/updated', 'mcpServer/statusUpdated'].includes(notification.method ?? '') ||
73
48
  !notification.params ||
@@ -74,23 +74,6 @@ export function normalizeCodexNotification(sessionId, sequence, occurredAt, noti
74
74
  },
75
75
  };
76
76
  }
77
- if (notification.method === 'mcpServer/statusUpdated' &&
78
- !connection?.threadId &&
79
- connection?.name === 'gestalt-xerj' &&
80
- ['failed', 'cancelled'].includes(String(connection.status))) {
81
- return {
82
- sessionId,
83
- sequence,
84
- occurredAt,
85
- type: 'activity.updated',
86
- payload: {
87
- id: 'gestalt-xerj-availability',
88
- label: 'Xerj unavailable',
89
- detail: 'Retrieval is unavailable. Check gestalt xerj status. Use rg and current source reads; readiness will be checked when the runtime resumes.',
90
- ...(activeTurnId ? { turnId: activeTurnId } : {}),
91
- },
92
- };
93
- }
94
77
  if (notification.method === 'mcpServer/statusUpdated' &&
95
78
  !connection?.threadId &&
96
79
  connection?.name === 'gestalt-serena' &&
@@ -0,0 +1,105 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { constants } from 'node:fs';
7
+ import { access, realpath } from 'node:fs/promises';
8
+ import { isAbsolute, join } from 'node:path';
9
+ /** In-memory retirement only: never change native configuration or user data. */
10
+ export function retireLegacyCapabilityInstructions(instructions) {
11
+ const stack = [];
12
+ let start = 0;
13
+ let nested = false;
14
+ let copied = 0;
15
+ let retained = '';
16
+ for (const marker of instructions.matchAll(/<(\/?)gestalt_xerj_(capability|unavailable)>/gu)) {
17
+ const [, closing, kind] = marker;
18
+ if (!closing) {
19
+ if (stack.length === 0) {
20
+ start = marker.index;
21
+ nested = false;
22
+ }
23
+ else
24
+ nested = true;
25
+ stack.push(kind);
26
+ }
27
+ else if (stack.length) {
28
+ // Mismatched or nested markers leave their entire enclosing region intact.
29
+ if (stack.at(-1) !== kind) {
30
+ nested = true;
31
+ continue;
32
+ }
33
+ stack.pop();
34
+ if (stack.length === 0 && !nested) {
35
+ retained += instructions.slice(copied, start);
36
+ copied = marker.index + marker[0].length;
37
+ }
38
+ }
39
+ }
40
+ // Unclosed regions are copied verbatim, including any complete inner markers.
41
+ return retained + instructions.slice(copied);
42
+ }
43
+ function managedArguments(value) {
44
+ if (!Array.isArray(value) || value[0] !== 'xerj' || value[1] !== 'mcp')
45
+ return false;
46
+ if (value.length === 2)
47
+ return true;
48
+ // Earlier Mobile thread overrides used this exact loopback endpoint form.
49
+ if (value.length !== 4 || value[2] !== '--url' || typeof value[3] !== 'string')
50
+ return false;
51
+ if (!/^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/.test(value[3]))
52
+ return false;
53
+ try {
54
+ const port = Number(new URL(value[3]).port || 80);
55
+ return port >= 1 && port <= 65535;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /**
62
+ * A mixed-version installation must migrate before a native thread can launch
63
+ * a retired managed service. Names alone never establish ownership. Unresolved
64
+ * executables, custom arguments and user transports remain native-owned.
65
+ */
66
+ export async function assertNoLegacyManagedConnection(servers, environment = process.env) {
67
+ if (!servers || typeof servers !== 'object' || Array.isArray(servers))
68
+ return;
69
+ const candidates = Object.values(servers).filter((server) => !!server &&
70
+ typeof server === 'object' &&
71
+ !Array.isArray(server) &&
72
+ server.enabled !== false &&
73
+ !server.url &&
74
+ typeof server.command === 'string' &&
75
+ isAbsolute(server.command) &&
76
+ managedArguments(server.args));
77
+ if (!candidates.length)
78
+ return;
79
+ const paths = environment.GESTALT_MANAGER_BIN
80
+ ? [environment.GESTALT_MANAGER_BIN]
81
+ : (environment.PATH ?? '')
82
+ .split(':')
83
+ .filter(Boolean)
84
+ .map((path) => join(path, 'gestalt'));
85
+ let manager;
86
+ for (const path of paths) {
87
+ if (!isAbsolute(path))
88
+ continue;
89
+ try {
90
+ await access(path, constants.X_OK);
91
+ manager = await realpath(path);
92
+ break;
93
+ }
94
+ catch {
95
+ /* Missing manager identity grants no migration authority. */
96
+ }
97
+ }
98
+ if (!manager)
99
+ return;
100
+ for (const server of candidates) {
101
+ const executable = await realpath(String(server.command)).catch(() => undefined);
102
+ if (executable === manager)
103
+ throw new Error('Retired Gestalt-managed Xerj connection requires migration. Run gestalt update, then reopen the session. Configuration and user data are unchanged.');
104
+ }
105
+ }
@@ -25,7 +25,7 @@ import { threadPlanName } from './thread-plan-name.js';
25
25
  import { WriterAcquisitionError, } from '../../features/sessions/application/writer-acquisition.js';
26
26
  import { CodexJsonRpcError, isCodexThreadWriterBusy, isMissingCodexThreadRollout, } from './json-rpc-client.js';
27
27
  import { resolvedServerRequestId } from './server-request.js';
28
- import { xerjDeadline } from '../retrieval/managed-xerj.js';
28
+ import { capabilityDeadline } from './capability-deadline.js';
29
29
  import { McpStartupTracker } from './mcp-startup-failure.js';
30
30
  /** Sticky thread config keeps skill paths out of the app-server process argv. */
31
31
  export function threadSkillConfig(skillsConfig, modelConfig = {}) {
@@ -81,10 +81,9 @@ class SessionResource {
81
81
  this.onDisposed = onDisposed;
82
82
  }
83
83
  retrieval;
84
- retrievalFailureReported = false;
85
84
  capabilityFailuresReported = new Set();
86
85
  readinessPublished = new Map();
87
- readinessDeadline = xerjDeadline();
86
+ readinessDeadline = capabilityDeadline();
88
87
  dispose() {
89
88
  if (this.disposed)
90
89
  return false;
@@ -1570,7 +1569,7 @@ export class CodexSessionRuntime {
1570
1569
  if (purpose === 'execution')
1571
1570
  this.scratch?.reserveRuntime?.(session);
1572
1571
  this.confirmedWorkspaceReleases.delete(session.id);
1573
- const deadline = xerjDeadline();
1572
+ const deadline = capabilityDeadline();
1574
1573
  const lease = purpose === 'execution' && this.planStatusSource
1575
1574
  ? await this.planStatusSource.open({ id: session.id, workspacePath: session.workspacePath }, (update) => this.onPlanStatus?.(session.id, update))
1576
1575
  : undefined;
@@ -1692,13 +1691,6 @@ export class CodexSessionRuntime {
1692
1691
  return;
1693
1692
  resource.capabilityFailuresReported.add(status.name);
1694
1693
  }
1695
- if (!asRecord(notification.params)?.threadId &&
1696
- status?.name === 'gestalt-xerj' &&
1697
- ['failed', 'cancelled'].includes(status.status ?? '')) {
1698
- if (resource.retrievalFailureReported)
1699
- return;
1700
- resource.retrievalFailureReported = true;
1701
- }
1702
1694
  }
1703
1695
  const childModel = decodeThreadSettingsModel(notification);
1704
1696
  if (childModel &&
@@ -1769,9 +1761,7 @@ export class CodexSessionRuntime {
1769
1761
  ...skill,
1770
1762
  enabled: Boolean(resource.retrieval.capabilities.find((capability) => capability.skillName === skill.name)?.ready),
1771
1763
  }
1772
- : skill.name === 'gestalt:xerj'
1773
- ? { ...skill, enabled: resource.retrieval.ready }
1774
- : skill),
1764
+ : skill),
1775
1765
  },
1776
1766
  };
1777
1767
  }
@@ -1782,34 +1772,10 @@ export class CodexSessionRuntime {
1782
1772
  resource.retrieval = state;
1783
1773
  resource.skillsConfig = state.skillsConfig;
1784
1774
  resource.modelConfig = state.config;
1785
- if (state.backendPreparation) {
1786
- const status = state.backendPreparation.status === 'starting' ? 'starting' : 'failed';
1787
- this.publishStartupStatus(resource, resource.mcpStartup.observeReadiness(status, state.backendPreparation.reason));
1788
- if (status === 'failed') {
1789
- resource.retrievalFailureReported = true;
1790
- this.onNotification?.(session.id, {
1791
- method: 'mcpServer/statusUpdated',
1792
- params: { name: 'gestalt-xerj', status },
1793
- }, { kind: 'root' });
1794
- }
1795
- }
1796
1775
  this.reportCapabilityFailures(resource, session);
1797
- if (state.diagnostic && !state.backendPreparation && !resource.retrievalFailureReported) {
1798
- resource.retrievalFailureReported = true;
1799
- this.publishMcpStartup(resource, {
1800
- method: 'mcpServer/statusUpdated',
1801
- params: { name: 'gestalt-xerj', status: 'failed' },
1802
- });
1803
- this.onNotification?.(session.id, {
1804
- method: 'mcpServer/statusUpdated',
1805
- params: { name: 'gestalt-xerj', status: 'failed' },
1806
- }, { kind: 'root' });
1807
- }
1808
1776
  }
1809
1777
  reportCapabilityFailures(resource, session) {
1810
1778
  for (const capability of resource.retrieval?.capabilities ?? []) {
1811
- if (capability.serverName === 'gestalt-xerj' && resource.retrieval?.backendPreparation)
1812
- continue;
1813
1779
  if (!capability.diagnostic || resource.capabilityFailuresReported.has(capability.serverName))
1814
1780
  continue;
1815
1781
  resource.capabilityFailuresReported.add(capability.serverName);
@@ -1842,20 +1808,6 @@ export class CodexSessionRuntime {
1842
1808
  }
1843
1809
  state.fallback();
1844
1810
  this.reportCapabilityFailures(resource, session);
1845
- if (!state.capabilities && !resource.retrievalFailureReported) {
1846
- resource.retrievalFailureReported = true;
1847
- this.publishMcpStartup(resource, {
1848
- method: 'mcpServer/statusUpdated',
1849
- params: { name: 'gestalt-xerj', status: 'failed' },
1850
- });
1851
- this.onNotification?.(session.id, {
1852
- method: 'mcpServer/statusUpdated',
1853
- params: {
1854
- name: 'gestalt-xerj',
1855
- status: 'failed',
1856
- },
1857
- }, { kind: 'root' });
1858
- }
1859
1811
  resource.skillsConfig = state.skillsConfig;
1860
1812
  resource.modelConfig = state.config;
1861
1813
  // A fresh Codex thread has no durable rollout until its first turn, so it
@@ -18,7 +18,7 @@ export const startupDescriptor = {
18
18
  maxWords: 350,
19
19
  };
20
20
  export async function installStartupFixture(root, version = '0.0.1') {
21
- for (const path of ['.codex-plugin', 'startup', 'skills/coding', 'skills/xerj', 'skills/serena'])
21
+ for (const path of ['.codex-plugin', 'startup', 'skills/coding', 'skills/serena'])
22
22
  await mkdir(join(root, path), { recursive: true });
23
23
  await writeFile(join(root, '.codex-plugin/plugin.json'), JSON.stringify({
24
24
  name: 'gestalt',
@@ -28,9 +28,9 @@ export async function installStartupFixture(root, version = '0.0.1') {
28
28
  }));
29
29
  await writeFile(join(root, 'gestalt-startup-contract.json'), JSON.stringify(startupDescriptor));
30
30
  await writeFile(join(root, 'startup/bootstrap.md'), syntheticBootstrap);
31
- for (const name of ['coding', 'xerj', 'serena'])
31
+ for (const name of ['coding', 'serena'])
32
32
  await writeFile(join(root, `skills/${name}/SKILL.md`), `---\nname: ${name}\ndescription: Synthetic ${name} fixture\n---\nSYNTHETIC_${name.toUpperCase()}_GUIDANCE\n`);
33
- return ['coding', 'xerj', 'serena'].map((name) => ({
33
+ return ['coding', 'serena'].map((name) => ({
34
34
  name: `gestalt:${name}`,
35
35
  path: join(root, `skills/${name}/SKILL.md`),
36
36
  enabled: true,
@@ -71,15 +71,9 @@ export class KimiSkillCatalog {
71
71
  const skill = wire;
72
72
  if (!skill || typeof skill !== 'object' || typeof skill.name !== 'string')
73
73
  continue;
74
- // kimi web workers accept only global MCP configuration and expose no
75
- // per-session native connection readiness gate. Never materialize
76
- // conditional retrieval guidance without that verified connection.
77
- if (skill.name === 'gestalt:xerj') {
78
- errors.push({
79
- message: 'Xerj retrieval is unavailable for Kimi web: native session readiness is unsupported.',
80
- });
74
+ // Compatibility only: do not advertise the retired managed skill from old installations.
75
+ if (skill.name === 'gestalt:xerj')
81
76
  continue;
82
- }
83
77
  // The shared catalog contract canonicalizes skill paths as absolute
84
78
  // filesystem paths (profile snapshots and overrides resolve against
85
79
  // them). kimi built-ins report no path and cannot be materialized per
@@ -9,7 +9,7 @@ import { createHash, randomUUID } from 'node:crypto';
9
9
  import { readFile, realpath, stat } from 'node:fs/promises';
10
10
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
11
  import { promisify } from 'node:util';
12
- import { beforeDeadline } from './codex-xerj.js';
12
+ import { beforeDeadline } from '../codex/capability-deadline.js';
13
13
  import { ReadinessEvidence } from './readiness-evidence.js';
14
14
  import { hasUnrestrictedReadAuthority } from './read-authority.js';
15
15
  const execute = promisify(execFile);
@@ -137,12 +137,7 @@ async function capture(workspace, cwd, path, configuration, authorize) {
137
137
  builds.push(hash(JSON.stringify([build, item])));
138
138
  }
139
139
  }
140
- for (const name of [
141
- '.serena/project.yml',
142
- '.xerjignore',
143
- 'CMakePresets.json',
144
- 'CMakeUserPresets.json',
145
- ]) {
140
+ for (const name of ['.serena/project.yml', 'CMakePresets.json', 'CMakeUserPresets.json']) {
146
141
  const content = await read(join(repository, name), true);
147
142
  metadata.push([name, content ? hash(content) : null]);
148
143
  }
@@ -6,8 +6,10 @@
6
6
  import { constants } from 'node:fs';
7
7
  import { lstat, mkdir, open, realpath, rmdir } from 'node:fs/promises';
8
8
  import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
9
- import { canonicalScratchWorkspace, readManagedScratchAttribution, readManagedScratchLeases, } from './managed-scratch-owner.js';
9
+ import { canonicalScratchWorkspace, readManagedScratchAttribution, readManagedScratchLeases, readRuntimeScratchAttribution, } from './managed-scratch-owner.js';
10
10
  import { privateDirectory } from './scratch-filesystem.js';
11
+ import { runtimeContainer } from './runtime-root.js';
12
+ import { assertParentPublications, claimWorkspacePublication } from './workspace-publication.js';
11
13
  export const containmentFenceName = '.containment-lock';
12
14
  const same = (left, right) => left.dev === right.dev && left.ino === right.ino && left.birth === right.birth;
13
15
  async function directoryIdentity(path) {
@@ -32,6 +34,7 @@ async function ancestorIdentity(directory, allowRetired) {
32
34
  return {
33
35
  directory,
34
36
  ownerId: owner.ownerId,
37
+ workspacePath: owner.workspacePath,
35
38
  identity: await directoryIdentity(directory),
36
39
  provenance: JSON.stringify([
37
40
  marker.schemaVersion,
@@ -43,6 +46,9 @@ async function ancestorIdentity(directory, allowRetired) {
43
46
  marker.authority.kind,
44
47
  marker.authority.sessionId ?? null,
45
48
  marker.authority.leaseId ?? null,
49
+ marker.runtime
50
+ ? [marker.runtime.directory, marker.runtime.token, marker.runtime.identity]
51
+ : null,
46
52
  ]),
47
53
  };
48
54
  }
@@ -84,27 +90,43 @@ async function releaseClaims(claims) {
84
90
  throw failure;
85
91
  }
86
92
  /** Interoperates with Launcher scratchWithContainment; no PID/age recovery. */
87
- export async function claimScratchContainment(workspace, cleanupOwnerId) {
93
+ export async function claimScratchContainment(workspace, cleanupOwnerId, inherited) {
88
94
  let selected = await canonicalScratchWorkspace(workspace);
89
95
  const selectedIdentity = await directoryIdentity(selected);
90
96
  const ancestors = [];
91
- const parts = selected.slice(parse(selected).root.length).split(sep).filter(Boolean);
92
- let directory = parse(selected).root;
93
- for (let index = 0; index < parts.length; index++) {
94
- directory = join(directory, parts[index]);
95
- if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
96
- if (ancestors.length >= 64)
97
- throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
98
- const ancestor = await ancestorIdentity(directory, directory === selected && cleanupOwnerId !== undefined);
99
- if (directory === selected &&
100
- cleanupOwnerId !== undefined &&
101
- ancestor.ownerId !== cleanupOwnerId)
102
- throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
103
- ancestors.push(ancestor);
97
+ const visiting = new Set();
98
+ const runtimeBase = process.getuid ? await runtimeContainer() : undefined;
99
+ const discover = async (path) => {
100
+ if (visiting.has(path) || visiting.size >= 64)
101
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
102
+ visiting.add(path);
103
+ const parts = path.slice(parse(path).root.length).split(sep).filter(Boolean);
104
+ let directory = parse(path).root;
105
+ for (let index = 0; index < parts.length; index++) {
106
+ directory = join(directory, parts[index]);
107
+ if (dirname(directory) === runtimeBase) {
108
+ const owner = await readRuntimeScratchAttribution(directory);
109
+ await discover(owner.directory);
110
+ }
111
+ if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
112
+ if (ancestors.some((ancestor) => ancestor.directory === directory))
113
+ continue;
114
+ if (ancestors.length >= 64)
115
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
116
+ const ancestor = await ancestorIdentity(directory, directory === selected && cleanupOwnerId !== undefined);
117
+ if (directory === selected &&
118
+ cleanupOwnerId !== undefined &&
119
+ ancestor.ownerId !== cleanupOwnerId)
120
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
121
+ ancestors.push(ancestor);
122
+ }
104
123
  }
105
- }
124
+ visiting.delete(path);
125
+ };
126
+ await discover(selected);
106
127
  const claims = [];
107
128
  const revalidate = async () => {
129
+ await inherited?.revalidate();
108
130
  await canonicalScratchWorkspace(selected);
109
131
  if (!same(selectedIdentity, await directoryIdentity(selected)))
110
132
  throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
@@ -121,6 +143,10 @@ export async function claimScratchContainment(workspace, cleanupOwnerId) {
121
143
  // Ancestors are discovered in path order. Containment always precedes the
122
144
  // owner's controller/association operation, and never spans a service lifetime.
123
145
  for (const ancestor of ancestors) {
146
+ if (inherited?.owns(ancestor.directory)) {
147
+ await inherited.revalidate();
148
+ continue;
149
+ }
124
150
  const path = join(ancestor.directory, containmentFenceName);
125
151
  try {
126
152
  await mkdir(path, { mode: 0o700 });
@@ -153,6 +179,9 @@ export async function claimScratchContainment(workspace, cleanupOwnerId) {
153
179
  throw error;
154
180
  }
155
181
  return {
182
+ publicationParents: ancestors.map((ancestor) => ancestor.workspacePath),
183
+ owns: (directory) => claims.some((claim) => !claim.attempted && claim.directory === directory) ||
184
+ !!inherited?.owns(directory),
156
185
  revalidate,
157
186
  async relocate(from, to) {
158
187
  const ancestor = ancestors.find((value) => value.directory === from);
@@ -182,12 +211,31 @@ export async function claimScratchContainment(workspace, cleanupOwnerId) {
182
211
  };
183
212
  }
184
213
  export async function withScratchContainment(workspace, publish) {
185
- const guard = await claimScratchContainment(workspace);
214
+ const releaseWorkspace = await claimWorkspacePublication(workspace);
215
+ let guard;
216
+ let failed = false;
186
217
  try {
187
- return await publish();
218
+ guard = await claimScratchContainment(workspace);
219
+ await assertParentPublications(workspace, guard.publicationParents);
220
+ const result = await publish();
221
+ await assertParentPublications(workspace, guard.publicationParents);
222
+ return result;
223
+ }
224
+ catch (error) {
225
+ failed = true;
226
+ throw error;
188
227
  }
189
228
  finally {
190
- await guard.release();
229
+ try {
230
+ await guard?.release();
231
+ }
232
+ finally {
233
+ // Preserve the first failed boundary when the selected workspace changed.
234
+ if (failed)
235
+ await releaseWorkspace().catch(() => { });
236
+ else
237
+ await releaseWorkspace();
238
+ }
191
239
  }
192
240
  }
193
241
  /** Detached history may outlive its cwd; publishing it never allocates scratch. */
@@ -241,8 +289,13 @@ export async function withHistoryScratchContainment(workspace, publish) {
241
289
  let ownerCount = 0;
242
290
  const parts = workspace.slice(parse(workspace).root.length).split(sep).filter(Boolean);
243
291
  let directory = parse(workspace).root;
292
+ const runtimeBase = process.getuid ? await runtimeContainer() : undefined;
244
293
  for (let index = 0; index < parts.length; index++) {
245
294
  directory = join(directory, parts[index]);
295
+ if (dirname(directory) === runtimeBase) {
296
+ await readRuntimeScratchAttribution(directory);
297
+ deepestOwner = directory;
298
+ }
246
299
  if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
247
300
  if (++ownerCount > 64)
248
301
  throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
@@ -254,7 +307,10 @@ export async function withHistoryScratchContainment(workspace, publish) {
254
307
  const guard = deepestOwner ? await claimScratchContainment(deepestOwner) : undefined;
255
308
  try {
256
309
  await revalidate();
257
- return await publish();
310
+ await assertParentPublications(workspace, guard?.publicationParents);
311
+ const result = await publish();
312
+ await assertParentPublications(workspace, guard?.publicationParents);
313
+ return result;
258
314
  }
259
315
  finally {
260
316
  await guard?.release();