gestalt-mobile 0.65.7 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +22 -0
  2. package/dist/client/assets/index-BDsGojoG.js +128 -0
  3. package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/cli.js +2 -1
  6. package/dist/server/server/composition.contracts.js +179 -84
  7. package/dist/server/server/composition.js +65 -5
  8. package/dist/server/server/features/autopilot/application/service.js +19 -2
  9. package/dist/server/server/features/autopilot/domain/supervision-protocol.js +3 -0
  10. package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
  11. package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
  12. package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
  13. package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
  14. package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
  15. package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
  16. package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
  17. package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
  18. package/dist/server/server/features/sessions/register-routes.js +29 -2
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
  20. package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
  21. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
  22. package/dist/server/server/platform/codex/codex-playwright.js +41 -3
  23. package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
  24. package/dist/server/server/platform/codex/codex-serena.js +2 -1
  25. package/dist/server/server/platform/codex/managed-playwright.js +48 -36
  26. package/dist/server/server/platform/codex/session-runtime.js +134 -4
  27. package/dist/server/server/platform/git/command.js +7 -1
  28. package/dist/server/server/platform/host-tests/runner.js +47 -6
  29. package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
  30. package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
  31. package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
  32. package/dist/server/server/platform/persistence/migrate.js +24 -0
  33. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
  34. package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
  35. package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
  36. package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
  37. package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
  38. package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
  39. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
  40. package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +72 -2
  41. package/dist/server/server/platform/retrieval/xerj-indexer.js +104 -48
  42. package/dist/server/server/platform/scratch/child-environment.js +21 -0
  43. package/dist/server/server/platform/scratch/containment-fence.js +262 -0
  44. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +245 -0
  45. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
  46. package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
  47. package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
  48. package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
  49. package/dist/server/server/platform/scratch/owner-fence.js +27 -0
  50. package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
  51. package/dist/server/server/platform/self-debug/workspace.js +3 -0
  52. package/dist/server/shared/contracts/session-forget.js +6 -0
  53. package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
  54. package/package.json +1 -1
  55. package/dist/client/assets/index-CKJWzSwH.js +0 -128
@@ -28,6 +28,30 @@ function migrateWorkspaceGitDefaults(database) {
28
28
  }
29
29
  export function migrate(database) {
30
30
  database.exec(schema);
31
+ database.exec(`CREATE TABLE IF NOT EXISTS session_forget_operations (
32
+ session_id TEXT PRIMARY KEY CHECK(length(session_id) BETWEEN 1 AND 256),
33
+ operation_id TEXT NOT NULL UNIQUE CHECK(length(operation_id) = 36),
34
+ phase TEXT NOT NULL CHECK(phase IN ('stopping','cleaning','finalizing','failed','completed')),
35
+ updated_at TEXT NOT NULL CHECK(length(updated_at) <= 32),
36
+ failure_code TEXT CHECK(failure_code IS NULL OR failure_code IN ('SESSION_RELEASE_UNCONFIRMED','SESSION_CLEANUP_FAILED','SESSION_FORGET_FAILED'))
37
+ );
38
+ CREATE TRIGGER IF NOT EXISTS forget_fence_insert BEFORE INSERT ON relay_sessions
39
+ WHEN EXISTS (SELECT 1 FROM session_forget_operations WHERE session_id = NEW.id)
40
+ BEGIN SELECT RAISE(IGNORE); END;
41
+ CREATE TRIGGER IF NOT EXISTS forget_fence_update BEFORE UPDATE ON relay_sessions
42
+ WHEN EXISTS (SELECT 1 FROM session_forget_operations WHERE session_id = NEW.id)
43
+ BEGIN SELECT RAISE(IGNORE); END;`);
44
+ database.exec(`CREATE TABLE IF NOT EXISTS scratch_known_workspaces (
45
+ workspace_path TEXT PRIMARY KEY
46
+ ); INSERT OR IGNORE INTO scratch_known_workspaces (workspace_path)
47
+ SELECT DISTINCT workspace_path FROM relay_sessions;
48
+ CREATE TRIGGER IF NOT EXISTS scratch_workspace_on_insert AFTER INSERT ON relay_sessions
49
+ BEGIN INSERT INTO scratch_known_workspaces VALUES (NEW.workspace_path)
50
+ ON CONFLICT(workspace_path) DO NOTHING; END;
51
+ CREATE TRIGGER IF NOT EXISTS scratch_workspace_on_update AFTER UPDATE OF workspace_path ON relay_sessions
52
+ WHEN NEW.workspace_path IS NOT OLD.workspace_path
53
+ BEGIN INSERT INTO scratch_known_workspaces VALUES (NEW.workspace_path)
54
+ ON CONFLICT(workspace_path) DO NOTHING; END;`);
31
55
  database.exec('CREATE TABLE IF NOT EXISTS org_plan_retired_supervisors (plan_identity TEXT NOT NULL, session_id TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(plan_identity, session_id))');
32
56
  database.exec('CREATE TABLE IF NOT EXISTS org_plan_takeovers (plan_identity TEXT PRIMARY KEY, session_id TEXT NOT NULL, epoch INTEGER NOT NULL, phase TEXT NOT NULL)');
33
57
  database.exec('CREATE TABLE IF NOT EXISTS tool_efficiency (session_id TEXT PRIMARY KEY REFERENCES relay_sessions(id) ON DELETE CASCADE, state_json TEXT NOT NULL)');
@@ -0,0 +1,67 @@
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 { randomUUID } from 'node:crypto';
7
+ export class SqliteForgetOperationStore {
8
+ db;
9
+ constructor(db) {
10
+ this.db = db;
11
+ }
12
+ find(id) {
13
+ const row = this.db
14
+ .prepare('SELECT * FROM session_forget_operations WHERE session_id = ?')
15
+ .get(id);
16
+ return row
17
+ ? {
18
+ operationId: row.operation_id,
19
+ sessionId: row.session_id,
20
+ phase: row.phase,
21
+ updatedAt: row.updated_at,
22
+ ...(row.failure_code ? { failureCode: row.failure_code } : {}),
23
+ }
24
+ : null;
25
+ }
26
+ assertAvailable(id) {
27
+ if (this.find(id))
28
+ throw new Error('SESSION_FORGET_IN_PROGRESS');
29
+ }
30
+ pendingIds() {
31
+ return this.db
32
+ .prepare("SELECT session_id FROM session_forget_operations WHERE phase != 'completed'")
33
+ .all().map((row) => row.session_id);
34
+ }
35
+ begin(id) {
36
+ this.db
37
+ .prepare(`INSERT INTO session_forget_operations (session_id, operation_id, phase, updated_at)
38
+ SELECT id, ?, 'stopping', ? FROM relay_sessions WHERE id = ?
39
+ ON CONFLICT(session_id) DO NOTHING`)
40
+ .run(randomUUID(), new Date().toISOString(), id);
41
+ return this.find(id);
42
+ }
43
+ update(operation) {
44
+ this.db
45
+ .prepare(`UPDATE session_forget_operations SET phase = ?, updated_at = ?, failure_code = ?
46
+ WHERE session_id = ? AND operation_id = ? AND phase != 'completed'`)
47
+ .run(operation.phase, operation.updatedAt, operation.failureCode ?? null, operation.sessionId, operation.operationId);
48
+ return this.find(operation.sessionId);
49
+ }
50
+ finalize(operation) {
51
+ this.db.exec('BEGIN IMMEDIATE');
52
+ try {
53
+ const current = this.find(operation.sessionId);
54
+ if (current?.operationId !== operation.operationId ||
55
+ !['finalizing', 'completed'].includes(current.phase))
56
+ throw new Error('SESSION_FORGET_OPERATION_CHANGED');
57
+ this.db.prepare('DELETE FROM relay_sessions WHERE id = ?').run(operation.sessionId);
58
+ this.update({ ...operation, phase: 'completed' });
59
+ this.db.exec('COMMIT');
60
+ return this.find(operation.sessionId);
61
+ }
62
+ catch (error) {
63
+ this.db.exec('ROLLBACK');
64
+ throw error;
65
+ }
66
+ }
67
+ }
@@ -23,6 +23,10 @@ export class SqliteSessionRepository {
23
23
  list() {
24
24
  return this.db.prepare('SELECT * FROM relay_sessions ORDER BY updated_at DESC').all().map(map);
25
25
  }
26
+ /** Workspace locators outlive Forget; they never grant deletion authority. */
27
+ knownWorkspacePaths() {
28
+ return this.db.prepare('SELECT workspace_path FROM scratch_known_workspaces').all().map((row) => row.workspace_path);
29
+ }
26
30
  remove(id) {
27
31
  this.db.prepare('DELETE FROM relay_sessions WHERE id = ?').run(id);
28
32
  }
@@ -5,11 +5,13 @@
5
5
  */
6
6
  import { execFile } from 'node:child_process';
7
7
  import { promisify } from 'node:util';
8
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
8
9
  const execute = promisify(execFile);
9
10
  async function run(command, args, cwd) {
10
11
  try {
11
12
  const result = await execute(command, [...args], {
12
13
  cwd,
14
+ env: withoutSessionScratch(),
13
15
  encoding: 'utf8',
14
16
  maxBuffer: 64 * 1024 * 1024,
15
17
  timeout: 30_000,
@@ -5,13 +5,17 @@
5
5
  */
6
6
  import { execFile } from 'node:child_process';
7
7
  import { promisify } from 'node:util';
8
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
8
9
  import { ORG_PLAN_CAPABILITIES } from './org-plan-capabilities.js';
9
10
  const execute = promisify(execFile);
10
11
  export const PLAN_MEASUREMENT_COMMAND_TIMEOUT_MS = 15_000;
11
12
  /** Invokes the explicitly configured Org Plan helper without a shell. */
12
13
  export async function checkpointPlanMeasurement(helperPath, planPath, stepId, snapshot) {
13
14
  await execute(helperPath, ['measure', 'checkpoint', planPath, stepId, JSON.stringify(snapshot)], {
14
- env: { ...process.env, GESTALT_MOBILE_ORG_PLAN_CAPABILITIES: ORG_PLAN_CAPABILITIES },
15
+ env: {
16
+ ...withoutSessionScratch(),
17
+ GESTALT_MOBILE_ORG_PLAN_CAPABILITIES: ORG_PLAN_CAPABILITIES,
18
+ },
15
19
  shell: false,
16
20
  timeout: PLAN_MEASUREMENT_COMMAND_TIMEOUT_MS,
17
21
  });
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { readFile } from 'node:fs/promises';
7
+ import { sessionScratchEnvironmentKeys } from '../scratch/child-environment.js';
7
8
  import { parseXerjStartupReason, } from '../../../shared/contracts/xerj-startup.js';
8
9
  import { ReadinessEvidence } from './readiness-evidence.js';
9
10
  export const xerjServerName = 'gestalt-xerj';
@@ -115,7 +116,13 @@ export class CodexXerj {
115
116
  command: ready.manager,
116
117
  args: ['xerj', 'mcp', '--url', ready.endpoint],
117
118
  cwd: input.cwd,
118
- env_vars: ['CODEX_HOME', 'GESTALT_HOME', 'XERJ_API_KEY', 'XERJ_AUTH'],
119
+ env_vars: [
120
+ 'CODEX_HOME',
121
+ 'GESTALT_HOME',
122
+ 'XERJ_API_KEY',
123
+ 'XERJ_AUTH',
124
+ ...sessionScratchEnvironmentKeys,
125
+ ],
119
126
  enabled: true,
120
127
  required: false,
121
128
  startup_readiness: 'connection',
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { spawn } from 'node:child_process';
7
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
7
8
  import { access } from 'node:fs/promises';
8
9
  import { constants } from 'node:fs';
9
10
  import { isAbsolute, join } from 'node:path';
@@ -66,7 +67,7 @@ export class ManagedXerj {
66
67
  return new Promise((resolve) => {
67
68
  const child = spawn(manager, ['xerj', operation], {
68
69
  cwd,
69
- env: { ...this.environment, XERJ_READY_TIMEOUT_MS: String(timeout) },
70
+ env: { ...withoutSessionScratch(this.environment), XERJ_READY_TIMEOUT_MS: String(timeout) },
70
71
  shell: false,
71
72
  stdio: ['ignore', 'pipe', 'ignore'],
72
73
  });
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { execFile } from 'node:child_process';
7
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
7
8
  import { createHash, randomUUID } from 'node:crypto';
8
9
  import { readFile, realpath, stat } from 'node:fs/promises';
9
10
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
@@ -48,7 +49,7 @@ async function git(cwd, args) {
48
49
  cwd,
49
50
  timeout: 2000,
50
51
  maxBuffer: 262144,
51
- env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
52
+ env: { ...withoutSessionScratch(), GIT_OPTIONAL_LOCKS: '0' },
52
53
  })).stdout;
53
54
  }
54
55
  /** Read only the requested source, known metadata and bounded dirty tracked inputs, on demand. */
@@ -6,9 +6,78 @@
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
7
  import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
8
8
  import { join } from 'node:path';
9
- /** Classify bounded native prose; never retain it or copy arbitrary native fields. */
9
+ /** Read only error-bearing fields, never request bodies or arbitrary object values. */
10
+ function errorText(value, depth = 0) {
11
+ if (depth > 5)
12
+ return '';
13
+ if (typeof value === 'string') {
14
+ const text = value.slice(0, 16_384).trim();
15
+ if (text.startsWith('{') || (text.startsWith('[') && !/^\[[\w-]+\]\s+/.test(text))) {
16
+ try {
17
+ return errorText(JSON.parse(text), depth + 1);
18
+ }
19
+ catch {
20
+ return ''; // A partial structured payload is not safe display text.
21
+ }
22
+ }
23
+ return text;
24
+ }
25
+ if (!value || typeof value !== 'object' || Array.isArray(value))
26
+ return '';
27
+ const error = value;
28
+ for (const key of ['caused_by', 'error', 'reason', 'message']) {
29
+ const text = errorText(error[key], depth + 1);
30
+ if (text)
31
+ return text;
32
+ }
33
+ return '';
34
+ }
35
+ /** Reduce an error to one cause before persisting or publishing any native prose. */
36
+ export function xerjErrorSummary(message) {
37
+ let text = errorText(message)
38
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
39
+ .replace(/-----BEGIN [^-]+-----[\s\S]*?(?:-----END [^-]+-----|$)/g, '[redacted]');
40
+ const lines = text.split(/[\r\n]+/).map((line) => line.trim());
41
+ const causeIndex = lines.findLastIndex((line) => /^(?:\d+:\s*)?caused by:/i.test(line));
42
+ text =
43
+ causeIndex >= 0
44
+ ? lines[causeIndex].replace(/^(?:\d+:\s*)?caused by:\s*/i, '') ||
45
+ lines.slice(causeIndex + 1).find(Boolean) ||
46
+ ''
47
+ : (lines.find((line) => line && !/^at\s+\S+/.test(line)) ?? '');
48
+ text = text
49
+ .replace(/^watch:\s*pass \d+ FAILED after [\d.]+s:\s*/i, '')
50
+ .replace(/^(?:(?:\d+:\s*)?(?:error|fatal|warning|caused by):\s*)+/i, '')
51
+ .replace(/\b(?:still watching|waiting for (?:a |the )?(?:source |file )?change)[\s\S]*$/i, '')
52
+ // Payloads can contain indexed text, prompts and model output. Drop the tail.
53
+ .replace(/\b(?:request|response|headers|body|payload|document|source|prompt|model output|environment|preview of (?:field'?s? )?value)\s*[:=][\s\S]*$/i, '')
54
+ .replace(/\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*[:=][\s\S]*$/i, '')
55
+ .replace(/\b(?:password|passwd|token|access[_-]?token|api[_ -]?key|secret|client[_-]?secret|credentials?)\s*[:=][\s\S]*$/gi, '[redacted]')
56
+ .replace(/\b(?:Bearer|Basic|ApiKey)\s+[^\s,;]+/gi, '[redacted]')
57
+ .replace(/\b[A-Z][A-Z0-9_]+\s*=\s*(?:"[^"\n]*"|'[^'\n]*'|[^\s,;]+)/g, '[redacted]')
58
+ .replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s<>"']+/gi, '[endpoint]')
59
+ .replace(/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`]*`)/g, '[redacted]')
60
+ .replace(/(?:[A-Za-z]:[\\/]|~?\/)[^\s,:;)"']*(?::\d+(?::\d+)?)?/g, '[path]')
61
+ .replace(/\b(file|path|directory)\s+[^\s:;,]+(?=:)/gi, '$1 [path]')
62
+ .replace(/\b[^\s@]+@[^\s@]+\.[^\s,;]+/g, '[redacted]')
63
+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g, '[endpoint]')
64
+ .replace(/\b(?:sk-[\w-]+|gh[pousr]_[\w]+|github_pat_[\w]+|AKIA[A-Z0-9]+)\b/g, '[redacted]')
65
+ .replace(/\b[A-Za-z0-9_+/=-]{32,}\b/g, '[redacted]')
66
+ .replace(/\b\d{4}-\d\d-\d\d[T ][\d:.]+(?:Z|[+-]\d\d:\d\d)?\b/g, '')
67
+ .replace(/\b(?:request|trace|correlation)[_-]?id\s*[:=]\s*[^\s,;]+/gi, '')
68
+ .replace(/\b(?:after|in|elapsed|duration|took)\s*[:=]?\s*\d+(?:\.\d+)?\s*(?:ms|s|secs?|seconds?|minutes?)\b/gi, '')
69
+ .replace(/\b\d+(?:\.\d+)?\s*(?:ms|s|secs?|seconds?|minutes?)\b/gi, '')
70
+ .replace(/[\x00-\x1f\x7f]/g, '')
71
+ .replace(/\s+/g, ' ')
72
+ .replace(/^[\s:;,.-]+|[\s:;,.-]+$/g, '');
73
+ if (!/[a-z]/i.test(text.replace(/\[(?:redacted|path|endpoint)\]/g, '')))
74
+ return undefined;
75
+ return text.length <= 200 ? text : `${text.slice(0, 197).replace(/\s+\S*$/, '')}…`;
76
+ }
77
+ /** Classify bounded errors; retain only the reduced, redacted cause. */
10
78
  export function xerjIndexDiagnostic(message) {
11
- const text = typeof message === 'string' ? message.slice(0, 16_384) : '';
79
+ const text = errorText(message);
80
+ const summary = xerjErrorSummary(message);
12
81
  const pass = /^watch: pass (\d+) FAILED after (\d+(?:\.\d+)?)s:/.exec(text);
13
82
  const number = pass ? Number(pass[1]) : Number.NaN;
14
83
  const durationSeconds = pass ? Number(pass[2]) : Number.NaN;
@@ -35,6 +104,7 @@ export function xerjIndexDiagnostic(message) {
35
104
  occurredAt: new Date().toISOString(),
36
105
  code,
37
106
  messageDigest: text ? createHash('sha256').update(text).digest('hex') : null,
107
+ ...(summary ? { summary } : {}),
38
108
  ...(Number.isSafeInteger(number) && Number.isFinite(durationSeconds)
39
109
  ? { watchPass: { number, durationSeconds } }
40
110
  : {}),
@@ -4,6 +4,8 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { spawn } from 'node:child_process';
7
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
8
+ import { stopOwnedProcessGroup } from '../scratch/owned-process-group.js';
7
9
  import { createHash } from 'node:crypto';
8
10
  import { realpath, writeFile } from 'node:fs/promises';
9
11
  import { join } from 'node:path';
@@ -60,9 +62,11 @@ export class XerjIndexer {
60
62
  capability;
61
63
  environment;
62
64
  report;
65
+ serviceScratch;
63
66
  value;
64
67
  evidence = new ReadinessEvidence();
65
68
  child;
69
+ scratch;
66
70
  task;
67
71
  closed = false;
68
72
  saveConfiguration;
@@ -70,10 +74,13 @@ export class XerjIndexer {
70
74
  diagnosticDirectory;
71
75
  pendingDiagnostic;
72
76
  diagnosticSaved;
73
- constructor(root, mode, capability, environment = process.env, report = console.warn) {
77
+ diskBudgetRefused = false;
78
+ currentFailure;
79
+ constructor(root, mode, capability, environment = process.env, report = console.warn, serviceScratch) {
74
80
  this.capability = capability;
75
81
  this.environment = environment;
76
82
  this.report = report;
83
+ this.serviceScratch = serviceScratch;
77
84
  this.value = { root, mode, state: mode === 'off' ? 'disabled' : 'starting' };
78
85
  }
79
86
  status() {
@@ -82,9 +89,9 @@ export class XerjIndexer {
82
89
  start() {
83
90
  if (this.task || this.closed || this.value.mode === 'off')
84
91
  return;
85
- this.task = this.launch().catch(() => {
92
+ this.task = this.launch().catch((error) => {
86
93
  if (!this.closed)
87
- this.fail('Could not start XERJ indexing. Check root access and run gestalt doctor.');
94
+ this.reportFailure(error);
88
95
  });
89
96
  }
90
97
  fail(message) {
@@ -92,6 +99,23 @@ export class XerjIndexer {
92
99
  this.value = { ...this.value, state: 'error', phase: undefined, percent: undefined, message };
93
100
  this.report(message);
94
101
  }
102
+ rememberDiagnostic(diagnostic) {
103
+ this.currentFailure = diagnostic;
104
+ this.value = { ...this.value, diagnostic };
105
+ this.pendingDiagnostic = diagnostic;
106
+ this.diagnosticSaved ??= this.saveDiagnostics();
107
+ }
108
+ reportFailure(message) {
109
+ const diagnostic = xerjIndexDiagnostic(message);
110
+ if (this.currentFailure?.summary && this.genericFailure(diagnostic))
111
+ return;
112
+ this.rememberDiagnostic(diagnostic);
113
+ this.fail(`XERJ indexing failed: ${diagnostic.summary ?? 'No error cause was supplied'}. Index freshness is unverified.`);
114
+ }
115
+ genericFailure(diagnostic) {
116
+ return (!diagnostic.summary ||
117
+ /^(?:needs-decision|unknown (?:error|cause)|(?:indexing|autoindex|operation|pass) failed)$/i.test(diagnostic.summary));
118
+ }
95
119
  async launch() {
96
120
  const root = await realpath(this.value.root);
97
121
  const namespace = `ax-${createHash('sha256').update(root).digest('hex').slice(0, 16)}`;
@@ -146,6 +170,11 @@ export class XerjIndexer {
146
170
  }
147
171
  if (this.closed)
148
172
  return;
173
+ this.scratch = await this.serviceScratch?.();
174
+ if (this.closed) {
175
+ await this.scratch?.release();
176
+ return;
177
+ }
149
178
  const child = spawn(ready.manager, [
150
179
  'xerj',
151
180
  'autoindex',
@@ -167,27 +196,38 @@ export class XerjIndexer {
167
196
  '2000',
168
197
  '--progress',
169
198
  'json',
170
- ], { cwd: root, env: this.environment, shell: false, stdio: ['ignore', 'ignore', 'pipe'] });
199
+ ], {
200
+ cwd: root,
201
+ env: { ...withoutSessionScratch(this.environment), ...this.scratch?.environment },
202
+ shell: false,
203
+ detached: true,
204
+ stdio: ['ignore', 'pipe', 'pipe'],
205
+ });
171
206
  this.child = child;
172
207
  this.value = { ...this.value, state: 'indexing' };
173
- // Never retain raw tool output or filenames. The status contains only an
174
- // allowlist of counters/phases; bound even a malformed unterminated line.
175
- let pending = '';
176
- child.stderr?.on('data', (data) => {
177
- pending += data.toString();
178
- const lines = pending.split('\n');
179
- pending = lines.pop() ?? '';
180
- if (pending.length > 16_384)
181
- pending = '';
182
- for (const line of lines)
183
- this.progress(line);
184
- });
185
- child.once('error', () => {
208
+ // Retain only redacted error summaries and allowlisted counters/phases;
209
+ // bound even a malformed unterminated line.
210
+ // Native budget decisions use stdout; progress and watch failures use stderr.
211
+ // Keep separate line buffers so interleaved streams cannot corrupt JSON.
212
+ for (const stream of [child.stdout, child.stderr]) {
213
+ let pending = '';
214
+ stream?.on('data', (data) => {
215
+ pending += data.toString();
216
+ const lines = pending.split('\n');
217
+ pending = lines.pop() ?? '';
218
+ if (pending.length > 16_384)
219
+ pending = '';
220
+ for (const line of lines)
221
+ if (line.length <= 16_384)
222
+ this.progress(line);
223
+ });
224
+ }
225
+ child.once('error', (error) => {
186
226
  if (!this.closed)
187
- this.fail('Could not launch XERJ. Check the Gestalt manager and flock/setpriv installation.');
227
+ this.reportFailure(error);
188
228
  });
189
229
  child.once('close', (code) => {
190
- this.child = undefined;
230
+ // Retain the live-owned group handle: leader exit does not prove descendants stopped.
191
231
  if (this.closed)
192
232
  return;
193
233
  if (code === 75) {
@@ -199,7 +239,7 @@ export class XerjIndexer {
199
239
  };
200
240
  }
201
241
  else {
202
- this.fail(`XERJ watcher stopped (exit ${code ?? 'signal'}). Run gestalt doctor; verify flock and setpriv are installed, then restart Mobile.`);
242
+ this.fail(`XERJ watcher stopped${this.currentFailure?.summary ? `: ${this.currentFailure.summary}` : ` (exit ${code ?? 'signal'})`}. Run gestalt doctor before restarting Mobile.`);
203
243
  }
204
244
  });
205
245
  }
@@ -208,7 +248,26 @@ export class XerjIndexer {
208
248
  return;
209
249
  try {
210
250
  const event = JSON.parse(line);
211
- if (event.event === 'progress') {
251
+ if (event.xerj === 'autoindex-budget' && event.decision_required === true) {
252
+ const disk = event.disk;
253
+ if (disk?.threshold_enabled === true &&
254
+ typeof disk.used_percent === 'number' &&
255
+ typeof disk.flood_stage === 'number' &&
256
+ disk.flood_stage > 0 &&
257
+ disk.used_percent <= 100 &&
258
+ disk.used_percent >= disk.flood_stage) {
259
+ this.diskBudgetRefused = true;
260
+ const diagnostic = xerjIndexDiagnostic('no space left: disk flood-stage budget');
261
+ this.rememberDiagnostic(diagnostic);
262
+ this.fail('XERJ indexing refused: disk flood-stage threshold reached. Free space or move the index to a larger volume. Index freshness is unverified.');
263
+ }
264
+ else {
265
+ this.reportFailure(event.error ?? event.refused ?? 'Indexing requires an operator decision');
266
+ }
267
+ }
268
+ else if (event.event === 'progress') {
269
+ this.diskBudgetRefused = false;
270
+ this.currentFailure = undefined;
212
271
  this.evidence.invalidate();
213
272
  this.evidence.connection('ready');
214
273
  this.evidence.coverage(this.value.lastUpdate ? 'stale' : 'unknown');
@@ -228,7 +287,11 @@ export class XerjIndexer {
228
287
  }
229
288
  else if (event.event === 'done') {
230
289
  if (event.ok !== true) {
231
- this.fail('XERJ indexing failed. Check the index with gestalt xerj autoindex status; the next source change retries it.');
290
+ if (this.diskBudgetRefused)
291
+ return;
292
+ const detail = event.error ?? event.message;
293
+ if (detail || !this.currentFailure)
294
+ this.reportFailure(detail ?? event.reason);
232
295
  return;
233
296
  }
234
297
  if (this.saveConfiguration && !this.configurationSaved) {
@@ -246,19 +309,23 @@ export class XerjIndexer {
246
309
  ...(count(event.files) !== undefined ? { files: count(event.files) } : {}),
247
310
  ...(count(event.records) !== undefined ? { records: count(event.records) } : {}),
248
311
  };
312
+ this.diskBudgetRefused = false;
313
+ this.currentFailure = undefined;
249
314
  const records = count(event.records);
250
315
  this.evidence.coverage(records === undefined ? 'unknown' : records === 0 ? 'unavailable' : 'ready', {
251
316
  files: count(event.files),
252
317
  records,
253
318
  });
254
319
  }
255
- else if (event.event === 'warning') {
256
- const diagnostic = xerjIndexDiagnostic(event.message);
257
- this.value = { ...this.value, diagnostic };
258
- this.pendingDiagnostic = diagnostic;
259
- this.diagnosticSaved ??= this.saveDiagnostics();
260
- const reference = ` Diagnostic: ${diagnostic.id} (${diagnostic.code}).`;
320
+ else if (event.event === 'warning' || event.event === 'error') {
321
+ const diagnostic = xerjIndexDiagnostic(event.error ?? event.message ?? event.reason);
322
+ if ((this.currentFailure?.summary && this.genericFailure(diagnostic)) ||
323
+ (this.diskBudgetRefused &&
324
+ ['watch-pass-failed', 'unknown-warning'].includes(diagnostic.code)))
325
+ return;
326
+ this.rememberDiagnostic(diagnostic);
261
327
  if (diagnostic.code === 'watch-rescan') {
328
+ this.currentFailure = undefined;
262
329
  // Native XERJ already schedules a full pass after dropped watch events.
263
330
  // This invalidates coverage, but is not a failed pass or lost connection.
264
331
  this.evidence.coverage(this.value.lastUpdate ? 'stale' : 'unknown');
@@ -272,13 +339,11 @@ export class XerjIndexer {
272
339
  return;
273
340
  }
274
341
  if (diagnostic.code === 'rebuild-required') {
275
- this.fail('XERJ cannot update the saved index with the current indexing configuration. A new index generation is required; source changes alone cannot repair it. See the XERJ recovery guide.' +
276
- reference);
342
+ this.fail(`XERJ indexing failed: ${diagnostic.summary ?? 'Saved index configuration changed'}. A new index generation is required; source changes alone cannot repair it.`);
277
343
  return;
278
344
  }
279
345
  if (diagnostic.code === 'ambiguous-assignment') {
280
- this.fail('XERJ incremental dataset assignment failed; the index is stale. See the XERJ recovery guide for this upstream limitation.' +
281
- reference);
346
+ this.fail(`XERJ indexing failed: ${diagnostic.summary ?? 'Ambiguous dataset assignment'}. The index is stale; see the XERJ recovery guide.`);
282
347
  return;
283
348
  }
284
349
  const cause = {
@@ -289,17 +354,14 @@ export class XerjIndexer {
289
354
  'watch-pass-failed': 'The underlying cause could not be classified.',
290
355
  'unknown-warning': 'The warning could not be classified.',
291
356
  }[diagnostic.code];
292
- const pass = diagnostic.watchPass;
293
- this.fail((pass
294
- ? `XERJ watch pass ${pass.number} failed after ${pass.durationSeconds}s. `
295
- : 'XERJ indexing reported a warning. ') +
296
- cause +
297
- ' The watcher is still running and is waiting for a source change to retry; index coverage is unverified until an update succeeds.' +
298
- reference);
357
+ this.fail(`XERJ indexing failed: ${diagnostic.summary ?? cause.replace(/\.$/, '')}. The watcher is still running; index freshness is unverified.`);
299
358
  }
300
359
  }
301
360
  catch {
302
- /* Native diagnostics are not public status or application logs. */
361
+ // Ignore ordinary stdout and partial payloads. Only explicit error lines
362
+ // are eligible for redaction and display.
363
+ if (/^\s*(?:error|fatal|caused by):/i.test(line))
364
+ this.reportFailure(line);
303
365
  }
304
366
  }
305
367
  async saveDiagnostics() {
@@ -326,14 +388,8 @@ export class XerjIndexer {
326
388
  await this.configurationSaved;
327
389
  await this.diagnosticSaved;
328
390
  const child = this.child;
329
- if (child && child.exitCode === null && child.signalCode === null) {
330
- await new Promise((resolve) => {
331
- child.once('close', resolve);
332
- child.kill('SIGTERM');
333
- const timer = setTimeout(() => child.kill('SIGKILL'), 2_000).unref();
334
- child.once('close', () => clearTimeout(timer));
335
- });
336
- }
391
+ if (child && (await stopOwnedProcessGroup(child)))
392
+ await this.scratch?.release();
337
393
  this.value = { ...this.value, state: this.value.mode === 'off' ? 'disabled' : 'stopped' };
338
394
  this.evidence.connection('unavailable');
339
395
  }
@@ -0,0 +1,21 @@
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
+ /** Unrelated children must never borrow the relay's ambient owning session. */
7
+ export const sessionScratchEnvironmentKeys = [
8
+ 'TMPDIR',
9
+ 'TMP',
10
+ 'TEMP',
11
+ 'GESTALT_SESSION_TMP_CONTEXT',
12
+ ];
13
+ export function withoutSessionScratch(environment = process.env) {
14
+ const inherited = { ...environment };
15
+ // An ordinary operator TMPDIR may name the host's only executable scratch.
16
+ // Its presence alone is not evidence of owning-session context.
17
+ if (environment.GESTALT_SESSION_TMP_CONTEXT !== undefined)
18
+ for (const key of sessionScratchEnvironmentKeys)
19
+ delete inherited[key];
20
+ return inherited;
21
+ }