gestalt-mobile 0.58.1 → 0.59.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.
package/README.md CHANGED
@@ -621,6 +621,14 @@ browser command while lane separation is introduced; no assertions are removed.
621
621
  Maintainers should follow the [npm release operations guide](docs/releasing.md)
622
622
  when configuring GitHub, rotating credentials, or recovering a partial release.
623
623
 
624
+ ## Host-owned test suites
625
+
626
+ The optional `--test-runner-config` enables a supervisor API for tests that must
627
+ run outside an agent's shell sandbox. See [host test runner](docs/host-tests.md)
628
+ for explicit candidate authorization, start/status/cancel calls, evidence, and
629
+ the execution boundary. It is disabled by default and does not change Serena
630
+ or shell sandbox permissions.
631
+
624
632
  ## Copyright and license
625
633
 
626
634
  Copyright (C) 2026 Dyne.org foundation
@@ -29,6 +29,7 @@ Options:
29
29
  --disable-passkey-auth Disable passkey access control (unsafe on shared or network hosts)
30
30
  --data-dir <path> Directory for persistent application data
31
31
  --icon <path> SVG or PNG used as the installed PWA application icon
32
+ --test-runner-config <path> Private operator configuration for host-owned test suites
32
33
  --xerj <mode> Source discovery: auto (default, index and watch), manual, off
33
34
  --skills <profile> Use a global skill profile for every session
34
35
  --skills list List saved global skill profiles without starting the server
@@ -288,6 +289,7 @@ export async function runCli(dependencies = {}) {
288
289
  root: config.root,
289
290
  xerj: config.xerj,
290
291
  dataDir: config.dataDir,
292
+ testRunnerConfig: config.testRunnerConfig,
291
293
  relyingParty: config.relyingParty,
292
294
  passkeyAuthEnabled: config.passkeyAuthEnabled,
293
295
  staticDir: packagedClientDir(moduleUrl),
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
7
7
  import { existsSync } from 'node:fs';
8
+ import { realpath } from 'node:fs/promises';
8
9
  import { homedir } from 'node:os';
9
10
  import { FilesystemSessionDefaults } from './platform/persistence/filesystem-session-defaults.js';
10
11
  import { SessionModelConfig } from './platform/codex/session-model-config.js';
@@ -13,6 +14,10 @@ import { debuglog } from 'node:util';
13
14
  import { SqliteTransportDiagnostics } from './platform/persistence/sqlite-transport-diagnostics.js';
14
15
  import { buildApp } from './app.js';
15
16
  import { ManagedUpgrade } from './platform/maintenance/managed-upgrade.js';
17
+ import { LocalHostTestRunner } from './platform/host-tests/runner.js';
18
+ import { loadHostTestConfig, within } from './platform/host-tests/config.js';
19
+ import { handleHostTestTool } from './features/host-tests/application/handle-tool.js';
20
+ import { gestaltTestRunnerDynamicTool } from '../shared/contracts/host-tests.js';
16
21
  import { SelfDebugWorkspace } from './platform/self-debug/workspace.js';
17
22
  import { createSelfDebugSession, debugExecutionSettings, } from './features/self-debug/create-session.js';
18
23
  import { startSession } from './features/sessions/start-session/use-case.js';
@@ -108,6 +113,10 @@ export async function composeRelayApp(options) {
108
113
  if (ownerHandle && ownerHandle.length !== 32)
109
114
  throw new Error('Authorization randomness must return exactly 32 bytes');
110
115
  const root = resolve(options.root);
116
+ const hostTestSuites = options.testRunnerConfig
117
+ ? await loadHostTestConfig(options.testRunnerConfig, root)
118
+ : undefined;
119
+ let hostTests;
111
120
  const databasePath = options.dataDir
112
121
  ? join(resolve(options.dataDir), 'relay.sqlite')
113
122
  : resolveStateDatabasePath(root, process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'));
@@ -938,6 +947,20 @@ export async function composeRelayApp(options) {
938
947
  const session = withPendingInteractions(sessions.find(sessionId));
939
948
  if (!session)
940
949
  return false;
950
+ const toolCall = request.params;
951
+ if (request.method === 'item/tool/call' &&
952
+ toolCall?.tool === gestaltTestRunnerDynamicTool.name) {
953
+ const result = await handleHostTestTool(hostTests, {
954
+ sessionId,
955
+ workspace: session.workspacePath,
956
+ root: origin?.kind === 'root',
957
+ provider: session.provider,
958
+ }, toolCall.arguments);
959
+ return (runtime?.resolveServerRequest(sessionId, String(request.id), {
960
+ success: true,
961
+ contentItems: [{ type: 'inputText', text: JSON.stringify(result) }],
962
+ }) === true);
963
+ }
941
964
  if (isOrgPlanHealthCall(request)) {
942
965
  const observedPlan = supervisedPlans.find(sessionId);
943
966
  let executorBinding = observedPlan?.modelPolicyVersion === 1
@@ -1412,6 +1435,18 @@ export async function composeRelayApp(options) {
1412
1435
  }
1413
1436
  let app;
1414
1437
  try {
1438
+ if (hostTestSuites) {
1439
+ if (within(await realpath(root), await realpath(dirname(databasePath)))) {
1440
+ throw new Error('Host test evidence must be outside the agent workspace; choose a private --data-dir');
1441
+ }
1442
+ hostTests = new LocalHostTestRunner(hostTestSuites, join(dirname(databasePath), 'host-test-runs'), (sessionId, runId, observedAt) => {
1443
+ if (!sessions.find(sessionId))
1444
+ return;
1445
+ events.publish(journal.append(sessionId, 'host-test.completed', { runId, observedAt }, observedAt));
1446
+ autopilot.rootProcessCompleted(sessionId, runId);
1447
+ });
1448
+ await hostTests.initialize();
1449
+ }
1415
1450
  const transportDiagnostics = new SqliteTransportDiagnostics(database);
1416
1451
  app = await buildApp({
1417
1452
  transportDiagnostic: (id, event) => transportDiagnostics.record(id, event),
@@ -1727,8 +1762,9 @@ export async function composeRelayApp(options) {
1727
1762
  },
1728
1763
  idempotency,
1729
1764
  close: runtime || kimiRuntime
1730
- ? (id) => {
1765
+ ? async (id) => {
1731
1766
  autopilot.cancel(id, 'sessionEnded');
1767
+ await hostTests?.cancelSession(id);
1732
1768
  planMeasurementRefresh?.stop(id);
1733
1769
  dismissPendingInteractions(id, new Date().toISOString());
1734
1770
  activity.dispose(id);
@@ -2056,6 +2092,7 @@ export async function composeRelayApp(options) {
2056
2092
  });
2057
2093
  }
2058
2094
  catch (error) {
2095
+ await hostTests?.close();
2059
2096
  authorization?.close();
2060
2097
  database.close();
2061
2098
  throw error;
@@ -2110,6 +2147,7 @@ export async function composeRelayApp(options) {
2110
2147
  });
2111
2148
  app.addHook('onClose', async () => {
2112
2149
  closing = true;
2150
+ await hostTests?.close();
2113
2151
  await xerjIndexer.close();
2114
2152
  for (const [sessionId, timer] of capacityRecoveryTimers) {
2115
2153
  clearTimeout(timer);
@@ -17,6 +17,7 @@ const optionNames = new Set([
17
17
  '--skills',
18
18
  '--icon',
19
19
  '--xerj',
20
+ '--test-runner-config',
20
21
  ]);
21
22
  const flagNames = new Set(['--disable-passkey-auth']);
22
23
  export function parseConfig(args, cwd = process.cwd()) {
@@ -64,6 +65,9 @@ export function parseConfig(args, cwd = process.cwd()) {
64
65
  dataDir: values.get('--data-dir'),
65
66
  skillsProfile: values.get('--skills'),
66
67
  iconPath: values.has('--icon') ? resolveIconPath(cwd, values.get('--icon')) : undefined,
68
+ testRunnerConfig: values.has('--test-runner-config')
69
+ ? resolve(cwd, values.get('--test-runner-config'))
70
+ : undefined,
67
71
  };
68
72
  }
69
73
  function resolveIconPath(cwd, value) {
@@ -0,0 +1,23 @@
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 { hostTestRequest } from '../../../../shared/contracts/host-tests.js';
7
+ /** Authority comes from the runtime's thread binding, never from tool arguments. */
8
+ export async function handleHostTestTool(runner, context, args) {
9
+ if (!context.root || context.provider !== 'codex')
10
+ return { error: 'rootSupervisorRequired' };
11
+ const parsed = hostTestRequest.safeParse(args);
12
+ if (!parsed.success)
13
+ return { error: 'invalidRequest' };
14
+ if (!runner)
15
+ return { error: 'hostTestRunnerDisabled' };
16
+ try {
17
+ return await runner.request({ sessionId: context.sessionId, workspace: context.workspace }, parsed.data);
18
+ }
19
+ catch {
20
+ // Never put test output, environment values or raw filesystem exceptions in chat.
21
+ return { error: 'hostTestRunnerUnavailable' };
22
+ }
23
+ }
@@ -0,0 +1,6 @@
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
+ export {};
@@ -14,6 +14,7 @@ import { gestaltQuizDynamicTool } from '../../../shared/contracts/quiz.js';
14
14
  import { gestaltOrgPlanAttentionDynamicTool } from '../../../shared/contracts/org-plan-attention.js';
15
15
  import { gestaltOrgPlanCheckpointDynamicTool } from '../../../shared/contracts/org-plan-checkpoint.js';
16
16
  import { gestaltOrgPlanHealthDynamicTool } from '../../../shared/contracts/org-plan-health.js';
17
+ import { gestaltTestRunnerDynamicTool } from '../../../shared/contracts/host-tests.js';
17
18
  import { gestaltAutopilotWaitLeaseDynamicTool } from '../../../shared/contracts/autopilot-wait-lease.js';
18
19
  import { gestaltAgentCapacityRecoveryDynamicTool } from '../../../shared/contracts/agent-capacity-recovery.js';
19
20
  import { countDiffLines } from '../../../shared/contracts/file-change.js';
@@ -984,6 +985,7 @@ export class CodexSessionRuntime {
984
985
  gestaltOrgPlanAttentionDynamicTool,
985
986
  gestaltOrgPlanCheckpointDynamicTool,
986
987
  gestaltOrgPlanHealthDynamicTool,
988
+ gestaltTestRunnerDynamicTool,
987
989
  gestaltAutopilotWaitLeaseDynamicTool,
988
990
  gestaltAgentCapacityRecoveryDynamicTool,
989
991
  ],
@@ -1087,6 +1089,7 @@ export class CodexSessionRuntime {
1087
1089
  gestaltOrgPlanAttentionDynamicTool,
1088
1090
  gestaltOrgPlanCheckpointDynamicTool,
1089
1091
  gestaltOrgPlanHealthDynamicTool,
1092
+ gestaltTestRunnerDynamicTool,
1090
1093
  gestaltAutopilotWaitLeaseDynamicTool,
1091
1094
  gestaltAgentCapacityRecoveryDynamicTool,
1092
1095
  ],
@@ -0,0 +1,89 @@
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 { execFile } from 'node:child_process';
7
+ import { createHash } from 'node:crypto';
8
+ import { lstat, readFile, readlink, realpath } from 'node:fs/promises';
9
+ import { dirname, join } from 'node:path';
10
+ import { within } from './config.js';
11
+ import { promisify } from 'node:util';
12
+ const exec = promisify(execFile);
13
+ /** Git-visible inputs only; ignored dependencies and host toolchains are explicitly outside this digest. */
14
+ export async function candidate(repository) {
15
+ const git = async (...args) => (await exec('/usr/bin/git', args, {
16
+ cwd: repository,
17
+ timeout: 10_000,
18
+ maxBuffer: 16 * 1024 * 1024,
19
+ env: {
20
+ PATH: process.env.PATH,
21
+ HOME: process.env.HOME,
22
+ GIT_CONFIG_NOSYSTEM: '1',
23
+ GIT_CONFIG_GLOBAL: '/dev/null',
24
+ GIT_OPTIONAL_LOCKS: '0',
25
+ },
26
+ encoding: 'buffer',
27
+ })).stdout;
28
+ const top = (await git('rev-parse', '--show-toplevel')).toString().trim();
29
+ if ((await realpath(top)) !== repository)
30
+ throw new Error('Suite repository must be a Git root');
31
+ const hash = createHash('sha256');
32
+ const add = (value) => {
33
+ const b = Buffer.from(value);
34
+ hash.update(String(b.length) + ':');
35
+ hash.update(b);
36
+ };
37
+ add('gestalt-host-test-candidate-v1');
38
+ add(await git('rev-parse', 'HEAD'));
39
+ add(await git('symbolic-ref', '-q', 'HEAD').catch(() => Buffer.from('detached')));
40
+ // Reject submodules: their separate working trees are not represented by a gitlink alone.
41
+ const index = await git('ls-files', '--stage', '-z');
42
+ if (index
43
+ .toString()
44
+ .split('\0')
45
+ .some((line) => line.startsWith('160000 ')))
46
+ throw new Error('Submodule candidates are unsupported');
47
+ add(index);
48
+ const paths = (await git('ls-files', '--cached', '--others', '--exclude-standard', '-z'))
49
+ .toString()
50
+ .split('\0')
51
+ .filter(Boolean);
52
+ let bytes = 0;
53
+ for (const path of [...new Set(paths)].sort()) {
54
+ add(path);
55
+ const file = join(repository, path);
56
+ const parent = await realpath(dirname(file)).catch((error) => {
57
+ if (error.code === 'ENOENT')
58
+ return null;
59
+ throw error;
60
+ });
61
+ if (parent !== null && !within(repository, parent))
62
+ throw new Error('Candidate path escapes repository');
63
+ const info = await lstat(file).catch((error) => {
64
+ if (error.code === 'ENOENT')
65
+ return null;
66
+ throw error;
67
+ });
68
+ if (!info) {
69
+ add('deleted');
70
+ continue;
71
+ }
72
+ add(String(info.mode));
73
+ if (info.isSymbolicLink()) {
74
+ const target = await realpath(file);
75
+ if (!within(repository, target))
76
+ throw new Error('Candidate symlink escapes repository');
77
+ add('symlink');
78
+ add(await readlink(file));
79
+ continue;
80
+ }
81
+ if (!info.isFile())
82
+ throw new Error('Unsupported candidate entry');
83
+ bytes += info.size;
84
+ if (bytes > 128 * 1024 * 1024)
85
+ throw new Error('Candidate exceeds fingerprint budget');
86
+ add(await readFile(file));
87
+ }
88
+ return hash.digest('hex');
89
+ }
@@ -0,0 +1,58 @@
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 { lstat, readFile, realpath } from 'node:fs/promises';
7
+ import { isAbsolute, relative, sep } from 'node:path';
8
+ import { z } from 'zod';
9
+ const suiteSchema = z
10
+ .object({
11
+ id: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/),
12
+ repository: z.string().min(1),
13
+ command: z.string().min(1),
14
+ args: z.array(z.string().max(4096)).max(64),
15
+ candidate: z
16
+ .string()
17
+ .regex(/^[a-f0-9]{64}$/)
18
+ .nullable(),
19
+ timeoutMs: z.number().int().min(100).max(3_600_000),
20
+ maxOutputBytes: z.number().int().min(1024).max(16_777_216),
21
+ })
22
+ .strict();
23
+ const configSchema = z
24
+ .object({ version: z.literal(1), suites: z.array(suiteSchema).max(32) })
25
+ .strict();
26
+ export function within(root, target) {
27
+ const path = relative(root, target);
28
+ return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith('..' + sep));
29
+ }
30
+ /** Operator file, outside the workspace, loaded once. Repository files cannot grant host authority. */
31
+ export async function loadHostTestConfig(path, workspaceRoot) {
32
+ const root = await realpath(workspaceRoot);
33
+ const canonical = await realpath(path);
34
+ const info = await lstat(path);
35
+ if (within(root, canonical) ||
36
+ info.isSymbolicLink() ||
37
+ !info.isFile() ||
38
+ info.size > 65536 ||
39
+ (info.mode & 0o077) !== 0 ||
40
+ info.uid !== process.getuid?.()) {
41
+ throw new Error('Host test configuration must be a private user-owned file outside the workspace');
42
+ }
43
+ const config = configSchema.parse(JSON.parse(await readFile(canonical, 'utf8')));
44
+ const names = new Set();
45
+ for (const suite of config.suites) {
46
+ if (names.has(suite.id) || !isAbsolute(suite.repository) || !isAbsolute(suite.command)) {
47
+ throw new Error('Host test suites require unique names and absolute repository/command paths');
48
+ }
49
+ names.add(suite.id);
50
+ suite.repository = await realpath(suite.repository);
51
+ if (!within(root, suite.repository))
52
+ throw new Error('Host test repository is outside the workspace');
53
+ const executable = await lstat(suite.command);
54
+ if (!executable.isFile() && !executable.isSymbolicLink())
55
+ throw new Error('Invalid host test executable');
56
+ }
57
+ return config.suites;
58
+ }
@@ -0,0 +1,366 @@
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 { spawn } from 'node:child_process';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { closeSync, openSync, writeSync } from 'node:fs';
9
+ import { lstat, mkdir, readFile, readdir, realpath, rename, writeFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { candidate } from './candidate.js';
12
+ import { within } from './config.js';
13
+ // The host owns a lifetime pipe; even a host crash closes it. Tests cannot inherit
14
+ // that pipe or the IPC channel. The guardian reaps its own group, never a stored PID.
15
+ const guardian = `
16
+ const {spawn}=require('node:child_process');
17
+ const [command,args,cwd]=process.argv.slice(1);
18
+ let stopping=false;
19
+ function stop(){if(stopping)return;stopping=true;try{process.kill(-process.pid,'SIGTERM')}catch{}
20
+ setTimeout(()=>{try{process.kill(-process.pid,'SIGKILL')}catch{}process.exit(1)},250)}
21
+ process.on('SIGTERM',stop);process.on('SIGINT',stop);process.on('disconnect',stop);
22
+ process.stdin.resume();process.stdin.on('end',stop);
23
+ const child=spawn(command,JSON.parse(args),{cwd,env:process.env,stdio:['ignore','inherit','inherit'],shell:false});
24
+ child.once('error',()=>{if(process.connected)process.send({exitCode:127,signal:null});stop()});
25
+ child.once('exit',(exitCode,signal)=>{if(process.connected)process.send({exitCode,signal});stop()});
26
+ `;
27
+ /** One host-owned runner per relay. All suites are immutable operator configuration. */
28
+ export class LocalHostTestRunner {
29
+ suites;
30
+ evidenceRoot;
31
+ completed;
32
+ results = new Map();
33
+ active = new Map();
34
+ reservations = new Set();
35
+ requests = new Map();
36
+ sessionGenerations = new Map();
37
+ closing = false;
38
+ constructor(suites, evidenceRoot, completed = () => { }) {
39
+ this.suites = suites;
40
+ this.evidenceRoot = evidenceRoot;
41
+ this.completed = completed;
42
+ }
43
+ async initialize() {
44
+ if (process.platform !== 'linux' && process.platform !== 'darwin')
45
+ throw new Error('Host tests require POSIX process groups');
46
+ await mkdir(this.evidenceRoot, { recursive: true, mode: 0o700 });
47
+ const info = await lstat(this.evidenceRoot);
48
+ if (!info.isDirectory() ||
49
+ info.isSymbolicLink() ||
50
+ info.mode & 0o077 ||
51
+ info.uid !== process.getuid?.())
52
+ throw new Error('Private host test evidence directory required');
53
+ const entries = await readdir(this.evidenceRoot);
54
+ if (entries.length > 1000)
55
+ throw new Error('Archive host test evidence before starting more runs');
56
+ for (const id of entries) {
57
+ if (!/^[a-f0-9-]{36}$/.test(id))
58
+ continue;
59
+ try {
60
+ const path = join(this.evidenceRoot, id, 'result.json');
61
+ const stat = await lstat(path);
62
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16384)
63
+ continue;
64
+ const result = JSON.parse(await readFile(path, 'utf8'));
65
+ if (result.version !== 1 ||
66
+ result.runId !== id ||
67
+ typeof result.sessionId !== 'string' ||
68
+ typeof result.requestId !== 'string')
69
+ continue;
70
+ result.resultPath = path;
71
+ result.logPath = join(this.evidenceRoot, id, 'output.log');
72
+ if (result.state === 'running') {
73
+ result.state = 'interrupted';
74
+ result.observedAt = new Date().toISOString();
75
+ result.counts = null;
76
+ await this.persist(result);
77
+ }
78
+ this.results.set(id, result);
79
+ }
80
+ catch {
81
+ /* Incomplete crash artifacts never become a passing result. */
82
+ }
83
+ }
84
+ }
85
+ async request(owner, input) {
86
+ const generation = this.sessionGenerations.get(owner.sessionId) ?? 0;
87
+ if (input.operation !== 'start')
88
+ return this.dispatch(owner, input, generation);
89
+ const key = owner.sessionId + ':' + input.requestId;
90
+ const pending = this.requests.get(key);
91
+ if (pending) {
92
+ await pending;
93
+ return this.request(owner, input);
94
+ }
95
+ const operation = this.dispatch(owner, input, generation);
96
+ this.requests.set(key, operation);
97
+ try {
98
+ return await operation;
99
+ }
100
+ finally {
101
+ this.requests.delete(key);
102
+ }
103
+ }
104
+ async dispatch(owner, input, generation) {
105
+ if (input.operation === 'status' || input.operation === 'cancel') {
106
+ const result = this.results.get(input.runId);
107
+ if (!result || result.sessionId !== owner.sessionId)
108
+ return { error: 'runNotFound' };
109
+ if (input.operation === 'cancel')
110
+ this.active.get(result.runId)?.stop('cancelled');
111
+ return structuredClone(result);
112
+ }
113
+ const workspace = await realpath(owner.workspace);
114
+ const available = this.suites.filter((suite) => within(workspace, suite.repository));
115
+ if (input.operation === 'list')
116
+ return {
117
+ suites: available.map((suite) => ({
118
+ id: suite.id,
119
+ authorizedCandidate: suite.candidate,
120
+ timeoutMs: suite.timeoutMs,
121
+ })),
122
+ };
123
+ const suite = available.find((suite) => suite.id === input.suite);
124
+ if (!suite)
125
+ return { error: 'suiteUnavailable' };
126
+ if ((await realpath(suite.repository)) !== suite.repository)
127
+ return { error: 'repositoryChanged' };
128
+ if (input.operation === 'inspect') {
129
+ const current = await candidate(suite.repository);
130
+ return {
131
+ suite: suite.id,
132
+ candidate: current,
133
+ authorized: suite.candidate === current,
134
+ fingerprintScope: 'Git-visible files, modes, index, HEAD and branch; excludes ignored dependencies and host toolchains',
135
+ };
136
+ }
137
+ const previous = [...this.results.values()].find((result) => result.sessionId === owner.sessionId && result.requestId === input.requestId);
138
+ if (previous)
139
+ return previous.suite === suite.id && previous.candidate === input.candidate
140
+ ? structuredClone(previous)
141
+ : { error: 'requestIdConflict' };
142
+ return this.start(owner, suite, input.candidate, input.requestId, generation);
143
+ }
144
+ async start(owner, suite, expected, requestId, generation) {
145
+ if (this.closing)
146
+ return { error: 'hostShuttingDown' };
147
+ if (suite.candidate !== expected)
148
+ return { error: 'candidateNotAuthorized' };
149
+ if (this.results.size >= 1000)
150
+ return { error: 'evidenceCapacityReached' };
151
+ if (this.reservations.has(suite.repository))
152
+ return { error: 'repositoryBusy' };
153
+ if (this.reservations.size >= 2)
154
+ return { error: 'hostRunnerBusy' };
155
+ this.reservations.add(suite.repository);
156
+ try {
157
+ if ((await candidate(suite.repository)) !== expected)
158
+ return { error: 'candidateChanged' };
159
+ if (this.closing)
160
+ return { error: 'hostShuttingDown' };
161
+ const runId = randomUUID();
162
+ const directory = join(this.evidenceRoot, runId);
163
+ await mkdir(directory, { mode: 0o700 });
164
+ const now = new Date().toISOString();
165
+ const result = {
166
+ version: 1,
167
+ runId,
168
+ requestId,
169
+ sessionId: owner.sessionId,
170
+ suite: suite.id,
171
+ candidate: expected,
172
+ finalCandidate: null,
173
+ state: 'running',
174
+ startedAt: now,
175
+ processExitedAt: null,
176
+ observedAt: now,
177
+ exitCode: null,
178
+ signal: null,
179
+ counts: null,
180
+ outputBytes: 0,
181
+ outputSha256: null,
182
+ logPath: join(directory, 'output.log'),
183
+ resultPath: join(directory, 'result.json'),
184
+ };
185
+ await this.persist(result);
186
+ await writeFile(join(directory, 'invocation.json'), JSON.stringify({
187
+ repository: suite.repository,
188
+ command: suite.command,
189
+ args: suite.args,
190
+ timeoutMs: suite.timeoutMs,
191
+ maxOutputBytes: suite.maxOutputBytes,
192
+ fingerprintVersion: 1,
193
+ candidate: expected,
194
+ nodeVersion: process.version,
195
+ platform: process.platform,
196
+ arch: process.arch,
197
+ limitations: 'Ignored dependencies and host toolchains are not fingerprinted. Live checkout checked before and after, not an immutable snapshot.',
198
+ }) + '\n', { mode: 0o600 });
199
+ this.results.set(runId, result);
200
+ if (this.closing || generation !== (this.sessionGenerations.get(owner.sessionId) ?? 0)) {
201
+ result.state = this.closing ? 'interrupted' : 'cancelled';
202
+ await this.persist(result);
203
+ return structuredClone(result);
204
+ }
205
+ try {
206
+ this.launch(suite, result);
207
+ }
208
+ catch {
209
+ result.state = 'interrupted';
210
+ await this.persist(result);
211
+ }
212
+ return structuredClone(result);
213
+ }
214
+ finally {
215
+ if (![...this.active.values()].some((run) => run.result.suite === suite.id))
216
+ this.reservations.delete(suite.repository);
217
+ }
218
+ }
219
+ launch(suite, result) {
220
+ const fd = openSync(result.logPath, 'wx', 0o600);
221
+ const hash = createHash('sha256');
222
+ // No provider keys, relay tokens, hooks, NODE_OPTIONS or shell startup variables.
223
+ const env = {};
224
+ for (const key of ['PATH', 'HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL', 'TZ', 'TMPDIR']) {
225
+ if (process.env[key] !== undefined)
226
+ env[key] = process.env[key];
227
+ }
228
+ env.CI = '1';
229
+ env.NO_COLOR = '1';
230
+ let child;
231
+ try {
232
+ child = spawn(process.execPath, ['-e', guardian, suite.command, JSON.stringify(suite.args), suite.repository], {
233
+ cwd: suite.repository,
234
+ env,
235
+ detached: true,
236
+ shell: false,
237
+ stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
238
+ });
239
+ }
240
+ catch (error) {
241
+ closeSync(fd);
242
+ throw error;
243
+ }
244
+ let reason;
245
+ let finished;
246
+ const done = new Promise((resolve) => {
247
+ finished = resolve;
248
+ });
249
+ const stop = (state) => {
250
+ reason ??= state;
251
+ child.stdin?.end();
252
+ };
253
+ this.active.set(result.runId, { result, stop, done });
254
+ const timeout = setTimeout(() => stop('timedOut'), suite.timeoutMs);
255
+ let summary = '';
256
+ child.stdin?.on('error', () => { });
257
+ const output = (data) => {
258
+ const room = suite.maxOutputBytes - result.outputBytes;
259
+ const kept = data.subarray(0, Math.max(0, room));
260
+ if (kept.length) {
261
+ try {
262
+ writeSync(fd, kept);
263
+ hash.update(kept);
264
+ result.outputBytes += kept.length;
265
+ }
266
+ catch {
267
+ stop('interrupted');
268
+ }
269
+ }
270
+ summary = (summary + kept.toString('utf8')).slice(-8192);
271
+ if (data.length > room)
272
+ stop('outputLimit');
273
+ };
274
+ child.stdout?.on('data', output);
275
+ child.stderr?.on('data', output);
276
+ child.on('message', (message) => {
277
+ const value = message;
278
+ if (Number.isInteger(value?.exitCode) || value?.exitCode === null) {
279
+ result.exitCode = typeof value.exitCode === 'number' ? value.exitCode : null;
280
+ result.signal = typeof value.signal === 'string' ? value.signal.slice(0, 32) : null;
281
+ result.processExitedAt = new Date().toISOString();
282
+ }
283
+ });
284
+ child.once('error', () => {
285
+ reason ??= 'interrupted';
286
+ });
287
+ child.once('close', () => {
288
+ clearTimeout(timeout);
289
+ closeSync(fd);
290
+ void (async () => {
291
+ const terminal = structuredClone(result);
292
+ terminal.outputSha256 = hash.digest('hex');
293
+ try {
294
+ terminal.finalCandidate = await candidate(suite.repository);
295
+ }
296
+ catch {
297
+ /* Unknown candidate cannot support acceptance. */
298
+ }
299
+ terminal.state =
300
+ reason ??
301
+ (terminal.finalCandidate !== terminal.candidate
302
+ ? 'invalidated'
303
+ : terminal.exitCode === 0
304
+ ? 'passed'
305
+ : 'failed');
306
+ terminal.observedAt = new Date().toISOString();
307
+ terminal.counts = reason || result.outputBytes > 8192 ? null : parseTapCounts(summary);
308
+ try {
309
+ await this.persist(terminal);
310
+ }
311
+ catch {
312
+ terminal.state = 'interrupted';
313
+ }
314
+ this.results.set(result.runId, terminal);
315
+ this.active.delete(result.runId);
316
+ this.reservations.delete(suite.repository);
317
+ try {
318
+ this.completed(terminal.sessionId, terminal.runId, terminal.observedAt);
319
+ }
320
+ catch {
321
+ /* Durable result remains available even if the notification consumer is closing. */
322
+ }
323
+ finally {
324
+ finished();
325
+ }
326
+ })();
327
+ });
328
+ }
329
+ async persist(result) {
330
+ const temporary = result.resultPath + '.tmp';
331
+ await writeFile(temporary, JSON.stringify(result) + '\n', { mode: 0o600 });
332
+ await rename(temporary, result.resultPath);
333
+ }
334
+ async cancelSession(sessionId) {
335
+ this.sessionGenerations.set(sessionId, (this.sessionGenerations.get(sessionId) ?? 0) + 1);
336
+ await Promise.allSettled([...this.requests.entries()]
337
+ .filter(([key]) => key.startsWith(sessionId + ':'))
338
+ .map(([, pending]) => pending));
339
+ const runs = [...this.active.values()].filter((run) => run.result.sessionId === sessionId);
340
+ for (const run of runs)
341
+ run.stop('cancelled');
342
+ await Promise.all(runs.map((run) => run.done));
343
+ }
344
+ async close() {
345
+ this.closing = true;
346
+ await Promise.allSettled([...this.requests.values()]);
347
+ const runs = [...this.active.values()];
348
+ for (const run of runs)
349
+ run.stop('interrupted');
350
+ await Promise.all(runs.map((run) => run.done));
351
+ }
352
+ }
353
+ /** Unknown/mixed/truncated reporter output is not invented evidence. Exit status is independent. */
354
+ export function parseTapCounts(text) {
355
+ const names = ['tests', 'pass', 'fail', 'skipped'];
356
+ const values = names.map((name) => [
357
+ ...text.matchAll(new RegExp('^# ' + name + ' (\\d+)\\r?$', 'gm')),
358
+ ]);
359
+ if (values.some((matches) => matches.length !== 1))
360
+ return null;
361
+ const [total, passed, failed, skipped] = values.map((matches) => Number(matches[0][1]));
362
+ if (![total, passed, failed, skipped].every(Number.isSafeInteger) ||
363
+ passed + failed + skipped !== total)
364
+ return null;
365
+ return { total, passed, failed, skipped };
366
+ }
@@ -0,0 +1,39 @@
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 { z } from 'zod';
7
+ const suite = z.string().regex(/^[a-z][a-z0-9-]{0,63}$/);
8
+ const runId = z.string().uuid();
9
+ export const hostTestRequest = z.discriminatedUnion('operation', [
10
+ z.object({ operation: z.literal('list') }).strict(),
11
+ z.object({ operation: z.literal('inspect'), suite }).strict(),
12
+ z
13
+ .object({
14
+ operation: z.literal('start'),
15
+ suite,
16
+ candidate: z.string().regex(/^[a-f0-9]{64}$/),
17
+ requestId: runId,
18
+ })
19
+ .strict(),
20
+ z.object({ operation: z.literal('status'), runId }).strict(),
21
+ z.object({ operation: z.literal('cancel'), runId }).strict(),
22
+ ]);
23
+ export const gestaltTestRunnerDynamicTool = {
24
+ type: 'function',
25
+ name: 'gestalt_test_runner',
26
+ description: 'Run host-configured test suites outside the agent shell sandbox. Root supervisor only. Disabled unless the operator configures a suite and approves its exact Git-visible candidate digest. list/inspect do not execute code. start uses an idempotent requestId; status/cancel require the returned runId. Never accepts commands, environment, or paths. Results include UTC observations and private evidence paths; counts can be unknown. Does not approve milestones or resume Autopilot.',
27
+ inputSchema: {
28
+ type: 'object',
29
+ additionalProperties: false,
30
+ properties: {
31
+ operation: { type: 'string', enum: ['list', 'inspect', 'start', 'status', 'cancel'] },
32
+ suite: { type: 'string' },
33
+ candidate: { type: 'string' },
34
+ requestId: { type: 'string' },
35
+ runId: { type: 'string' },
36
+ },
37
+ required: ['operation'],
38
+ },
39
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.58.1",
3
+ "version": "0.59.0",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",