gestalt-mobile 0.58.1 → 0.60.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 +9 -0
- package/dist/server/server/cli.js +2 -0
- package/dist/server/server/composition.js +37 -1
- package/dist/server/server/config.js +2 -1
- package/dist/server/server/features/host-tests/application/handle-tool.js +23 -0
- package/dist/server/server/features/host-tests/application/ports.js +6 -0
- package/dist/server/server/platform/codex/session-runtime.js +3 -0
- package/dist/server/server/platform/host-tests/candidate.js +89 -0
- package/dist/server/server/platform/host-tests/config.js +61 -0
- package/dist/server/server/platform/host-tests/runner.js +369 -0
- package/dist/server/shared/contracts/host-tests.js +37 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -621,6 +621,15 @@ 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 host test runner is enabled by default. Root supervisors configure suites at
|
|
627
|
+
runtime in the session workspace's `.gestalt/host-tests.json` and run them as the
|
|
628
|
+
host user, outside the agent shell sandbox, without fingerprint approval or a
|
|
629
|
+
restart. See [host test runner](docs/host-tests.md) for configuration, calls,
|
|
630
|
+
evidence and the execution boundary. Use `--disable-test-runner` to turn it off.
|
|
631
|
+
Serena's own sandbox checks remain in place.
|
|
632
|
+
|
|
624
633
|
## Copyright and license
|
|
625
634
|
|
|
626
635
|
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
|
+
--disable-test-runner Disable host tests (default: runtime .gestalt/host-tests.json 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
|
+
testRunnerEnabled: config.testRunnerEnabled,
|
|
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 { loadWorkspaceHostTestConfig, 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,7 @@ 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
|
+
let hostTests;
|
|
111
117
|
const databasePath = options.dataDir
|
|
112
118
|
? join(resolve(options.dataDir), 'relay.sqlite')
|
|
113
119
|
: resolveStateDatabasePath(root, process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'));
|
|
@@ -938,6 +944,20 @@ export async function composeRelayApp(options) {
|
|
|
938
944
|
const session = withPendingInteractions(sessions.find(sessionId));
|
|
939
945
|
if (!session)
|
|
940
946
|
return false;
|
|
947
|
+
const toolCall = request.params;
|
|
948
|
+
if (request.method === 'item/tool/call' &&
|
|
949
|
+
toolCall?.tool === gestaltTestRunnerDynamicTool.name) {
|
|
950
|
+
const result = await handleHostTestTool(hostTests, {
|
|
951
|
+
sessionId,
|
|
952
|
+
workspace: session.workspacePath,
|
|
953
|
+
root: origin?.kind === 'root',
|
|
954
|
+
provider: session.provider,
|
|
955
|
+
}, toolCall.arguments);
|
|
956
|
+
return (runtime?.resolveServerRequest(sessionId, String(request.id), {
|
|
957
|
+
success: true,
|
|
958
|
+
contentItems: [{ type: 'inputText', text: JSON.stringify(result) }],
|
|
959
|
+
}) === true);
|
|
960
|
+
}
|
|
941
961
|
if (isOrgPlanHealthCall(request)) {
|
|
942
962
|
const observedPlan = supervisedPlans.find(sessionId);
|
|
943
963
|
let executorBinding = observedPlan?.modelPolicyVersion === 1
|
|
@@ -1412,6 +1432,19 @@ export async function composeRelayApp(options) {
|
|
|
1412
1432
|
}
|
|
1413
1433
|
let app;
|
|
1414
1434
|
try {
|
|
1435
|
+
if (options.testRunnerEnabled !== false) {
|
|
1436
|
+
hostTests = new LocalHostTestRunner(join(dirname(databasePath), 'host-test-runs'), (sessionId, runId, observedAt) => {
|
|
1437
|
+
if (!sessions.find(sessionId))
|
|
1438
|
+
return;
|
|
1439
|
+
events.publish(journal.append(sessionId, 'host-test.completed', { runId, observedAt }, observedAt));
|
|
1440
|
+
autopilot.rootProcessCompleted(sessionId, runId);
|
|
1441
|
+
}, async (workspace) => {
|
|
1442
|
+
if (!within(await realpath(root), await realpath(workspace)))
|
|
1443
|
+
throw new Error('Host test workspace is outside the configured root');
|
|
1444
|
+
return loadWorkspaceHostTestConfig(workspace);
|
|
1445
|
+
});
|
|
1446
|
+
await hostTests.initialize();
|
|
1447
|
+
}
|
|
1415
1448
|
const transportDiagnostics = new SqliteTransportDiagnostics(database);
|
|
1416
1449
|
app = await buildApp({
|
|
1417
1450
|
transportDiagnostic: (id, event) => transportDiagnostics.record(id, event),
|
|
@@ -1727,8 +1760,9 @@ export async function composeRelayApp(options) {
|
|
|
1727
1760
|
},
|
|
1728
1761
|
idempotency,
|
|
1729
1762
|
close: runtime || kimiRuntime
|
|
1730
|
-
? (id) => {
|
|
1763
|
+
? async (id) => {
|
|
1731
1764
|
autopilot.cancel(id, 'sessionEnded');
|
|
1765
|
+
await hostTests?.cancelSession(id);
|
|
1732
1766
|
planMeasurementRefresh?.stop(id);
|
|
1733
1767
|
dismissPendingInteractions(id, new Date().toISOString());
|
|
1734
1768
|
activity.dispose(id);
|
|
@@ -2056,6 +2090,7 @@ export async function composeRelayApp(options) {
|
|
|
2056
2090
|
});
|
|
2057
2091
|
}
|
|
2058
2092
|
catch (error) {
|
|
2093
|
+
await hostTests?.close();
|
|
2059
2094
|
authorization?.close();
|
|
2060
2095
|
database.close();
|
|
2061
2096
|
throw error;
|
|
@@ -2110,6 +2145,7 @@ export async function composeRelayApp(options) {
|
|
|
2110
2145
|
});
|
|
2111
2146
|
app.addHook('onClose', async () => {
|
|
2112
2147
|
closing = true;
|
|
2148
|
+
await hostTests?.close();
|
|
2113
2149
|
await xerjIndexer.close();
|
|
2114
2150
|
for (const [sessionId, timer] of capacityRecoveryTimers) {
|
|
2115
2151
|
clearTimeout(timer);
|
|
@@ -18,7 +18,7 @@ const optionNames = new Set([
|
|
|
18
18
|
'--icon',
|
|
19
19
|
'--xerj',
|
|
20
20
|
]);
|
|
21
|
-
const flagNames = new Set(['--disable-passkey-auth']);
|
|
21
|
+
const flagNames = new Set(['--disable-passkey-auth', '--disable-test-runner']);
|
|
22
22
|
export function parseConfig(args, cwd = process.cwd()) {
|
|
23
23
|
const values = new Map();
|
|
24
24
|
const flags = new Set();
|
|
@@ -64,6 +64,7 @@ export function parseConfig(args, cwd = process.cwd()) {
|
|
|
64
64
|
dataDir: values.get('--data-dir'),
|
|
65
65
|
skillsProfile: values.get('--skills'),
|
|
66
66
|
iconPath: values.has('--icon') ? resolveIconPath(cwd, values.get('--icon')) : undefined,
|
|
67
|
+
testRunnerEnabled: !flags.has('--disable-test-runner'),
|
|
67
68
|
};
|
|
68
69
|
}
|
|
69
70
|
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
|
+
}
|
|
@@ -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,61 @@
|
|
|
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, join, 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
|
+
timeoutMs: z.number().int().min(100).max(3_600_000),
|
|
16
|
+
maxOutputBytes: z.number().int().min(1024).max(16_777_216),
|
|
17
|
+
})
|
|
18
|
+
.strict();
|
|
19
|
+
const configSchema = z
|
|
20
|
+
.object({ version: z.literal(1), suites: z.array(suiteSchema).max(32) })
|
|
21
|
+
.strict();
|
|
22
|
+
export function within(root, target) {
|
|
23
|
+
const path = relative(root, target);
|
|
24
|
+
return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith('..' + sep));
|
|
25
|
+
}
|
|
26
|
+
/** Reload agent-editable workspace suites on demand. Absence permits later creation. */
|
|
27
|
+
export async function loadWorkspaceHostTestConfig(workspaceRoot) {
|
|
28
|
+
const root = await realpath(workspaceRoot);
|
|
29
|
+
const path = join(root, '.gestalt', 'host-tests.json');
|
|
30
|
+
let info;
|
|
31
|
+
try {
|
|
32
|
+
info = await lstat(path);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error.code === 'ENOENT')
|
|
36
|
+
return [];
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
const canonical = await realpath(path);
|
|
40
|
+
if (!within(root, canonical) || info.isSymbolicLink() || !info.isFile() || info.size > 65536) {
|
|
41
|
+
throw new Error('Host test configuration must be a bounded regular file within the workspace');
|
|
42
|
+
}
|
|
43
|
+
const config = configSchema.parse(JSON.parse(await readFile(canonical, 'utf8')));
|
|
44
|
+
return validateSuites(config.suites, root);
|
|
45
|
+
}
|
|
46
|
+
async function validateSuites(suites, root) {
|
|
47
|
+
const names = new Set();
|
|
48
|
+
for (const suite of suites) {
|
|
49
|
+
if (names.has(suite.id) || !isAbsolute(suite.repository) || !isAbsolute(suite.command)) {
|
|
50
|
+
throw new Error('Host test suites require unique names and absolute repository/command paths');
|
|
51
|
+
}
|
|
52
|
+
names.add(suite.id);
|
|
53
|
+
suite.repository = await realpath(suite.repository);
|
|
54
|
+
if (!within(root, suite.repository))
|
|
55
|
+
throw new Error('Host test repository is outside the workspace');
|
|
56
|
+
const executable = await lstat(suite.command);
|
|
57
|
+
if (!executable.isFile() && !executable.isSymbolicLink())
|
|
58
|
+
throw new Error('Invalid host test executable');
|
|
59
|
+
}
|
|
60
|
+
return suites;
|
|
61
|
+
}
|
|
@@ -0,0 +1,369 @@
|
|
|
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 { loadWorkspaceHostTestConfig, 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. Each run retains its resolved configuration. */
|
|
28
|
+
export class LocalHostTestRunner {
|
|
29
|
+
evidenceRoot;
|
|
30
|
+
completed;
|
|
31
|
+
workspaceSuites;
|
|
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(evidenceRoot, completed = () => { }, workspaceSuites = loadWorkspaceHostTestConfig) {
|
|
39
|
+
this.evidenceRoot = evidenceRoot;
|
|
40
|
+
this.completed = completed;
|
|
41
|
+
this.workspaceSuites = workspaceSuites;
|
|
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
|
+
if (input.operation === 'start') {
|
|
114
|
+
const previous = [...this.results.values()].find((result) => result.sessionId === owner.sessionId && result.requestId === input.requestId);
|
|
115
|
+
if (previous) {
|
|
116
|
+
return previous.suite === input.suite
|
|
117
|
+
? structuredClone(previous)
|
|
118
|
+
: { error: 'requestIdConflict' };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const workspace = await realpath(owner.workspace);
|
|
122
|
+
if (within(workspace, await realpath(this.evidenceRoot)))
|
|
123
|
+
return { error: 'evidenceInsideWorkspace' };
|
|
124
|
+
const suites = await this.workspaceSuites(workspace);
|
|
125
|
+
const available = suites.filter((suite) => within(workspace, suite.repository));
|
|
126
|
+
if (input.operation === 'list')
|
|
127
|
+
return {
|
|
128
|
+
suites: available.map((suite) => ({
|
|
129
|
+
id: suite.id,
|
|
130
|
+
repository: suite.repository,
|
|
131
|
+
timeoutMs: suite.timeoutMs,
|
|
132
|
+
})),
|
|
133
|
+
};
|
|
134
|
+
const suite = available.find((suite) => suite.id === input.suite);
|
|
135
|
+
if (!suite)
|
|
136
|
+
return { error: 'suiteUnavailable' };
|
|
137
|
+
if ((await realpath(suite.repository)) !== suite.repository)
|
|
138
|
+
return { error: 'repositoryChanged' };
|
|
139
|
+
if (input.operation === 'inspect') {
|
|
140
|
+
const current = await candidate(suite.repository);
|
|
141
|
+
return {
|
|
142
|
+
suite: suite.id,
|
|
143
|
+
repository: suite.repository,
|
|
144
|
+
candidate: current,
|
|
145
|
+
fingerprintScope: 'Git-visible files, modes, index, HEAD and branch; excludes ignored dependencies and host toolchains',
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return this.start(owner, suite, input.requestId, generation);
|
|
149
|
+
}
|
|
150
|
+
async start(owner, suite, requestId, generation) {
|
|
151
|
+
if (this.closing)
|
|
152
|
+
return { error: 'hostShuttingDown' };
|
|
153
|
+
if (this.results.size >= 1000)
|
|
154
|
+
return { error: 'evidenceCapacityReached' };
|
|
155
|
+
if (this.reservations.has(suite.repository))
|
|
156
|
+
return { error: 'repositoryBusy' };
|
|
157
|
+
if (this.reservations.size >= 2)
|
|
158
|
+
return { error: 'hostRunnerBusy' };
|
|
159
|
+
this.reservations.add(suite.repository);
|
|
160
|
+
try {
|
|
161
|
+
const current = await candidate(suite.repository);
|
|
162
|
+
if (this.closing)
|
|
163
|
+
return { error: 'hostShuttingDown' };
|
|
164
|
+
const runId = randomUUID();
|
|
165
|
+
const directory = join(this.evidenceRoot, runId);
|
|
166
|
+
await mkdir(directory, { mode: 0o700 });
|
|
167
|
+
const now = new Date().toISOString();
|
|
168
|
+
const result = {
|
|
169
|
+
version: 1,
|
|
170
|
+
runId,
|
|
171
|
+
requestId,
|
|
172
|
+
sessionId: owner.sessionId,
|
|
173
|
+
suite: suite.id,
|
|
174
|
+
candidate: current,
|
|
175
|
+
finalCandidate: null,
|
|
176
|
+
state: 'running',
|
|
177
|
+
startedAt: now,
|
|
178
|
+
processExitedAt: null,
|
|
179
|
+
observedAt: now,
|
|
180
|
+
exitCode: null,
|
|
181
|
+
signal: null,
|
|
182
|
+
counts: null,
|
|
183
|
+
outputBytes: 0,
|
|
184
|
+
outputSha256: null,
|
|
185
|
+
logPath: join(directory, 'output.log'),
|
|
186
|
+
resultPath: join(directory, 'result.json'),
|
|
187
|
+
};
|
|
188
|
+
await this.persist(result);
|
|
189
|
+
await writeFile(join(directory, 'invocation.json'), JSON.stringify({
|
|
190
|
+
repository: suite.repository,
|
|
191
|
+
command: suite.command,
|
|
192
|
+
args: suite.args,
|
|
193
|
+
timeoutMs: suite.timeoutMs,
|
|
194
|
+
maxOutputBytes: suite.maxOutputBytes,
|
|
195
|
+
fingerprintVersion: 1,
|
|
196
|
+
candidate: current,
|
|
197
|
+
nodeVersion: process.version,
|
|
198
|
+
platform: process.platform,
|
|
199
|
+
arch: process.arch,
|
|
200
|
+
limitations: 'Ignored dependencies and host toolchains are not fingerprinted. Live checkout checked before and after, not an immutable snapshot.',
|
|
201
|
+
}) + '\n', { mode: 0o600 });
|
|
202
|
+
this.results.set(runId, result);
|
|
203
|
+
if (this.closing || generation !== (this.sessionGenerations.get(owner.sessionId) ?? 0)) {
|
|
204
|
+
result.state = this.closing ? 'interrupted' : 'cancelled';
|
|
205
|
+
await this.persist(result);
|
|
206
|
+
return structuredClone(result);
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
this.launch(suite, result);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
result.state = 'interrupted';
|
|
213
|
+
await this.persist(result);
|
|
214
|
+
}
|
|
215
|
+
return structuredClone(result);
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
if (![...this.active.values()].some((run) => run.repository === suite.repository))
|
|
219
|
+
this.reservations.delete(suite.repository);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
launch(suite, result) {
|
|
223
|
+
const fd = openSync(result.logPath, 'wx', 0o600);
|
|
224
|
+
const hash = createHash('sha256');
|
|
225
|
+
// No provider keys, relay tokens, hooks, NODE_OPTIONS or shell startup variables.
|
|
226
|
+
const env = {};
|
|
227
|
+
for (const key of ['PATH', 'HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL', 'TZ', 'TMPDIR']) {
|
|
228
|
+
if (process.env[key] !== undefined)
|
|
229
|
+
env[key] = process.env[key];
|
|
230
|
+
}
|
|
231
|
+
env.CI = '1';
|
|
232
|
+
env.NO_COLOR = '1';
|
|
233
|
+
let child;
|
|
234
|
+
try {
|
|
235
|
+
child = spawn(process.execPath, ['-e', guardian, suite.command, JSON.stringify(suite.args), suite.repository], {
|
|
236
|
+
cwd: suite.repository,
|
|
237
|
+
env,
|
|
238
|
+
detached: true,
|
|
239
|
+
shell: false,
|
|
240
|
+
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
closeSync(fd);
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
let reason;
|
|
248
|
+
let finished;
|
|
249
|
+
const done = new Promise((resolve) => {
|
|
250
|
+
finished = resolve;
|
|
251
|
+
});
|
|
252
|
+
const stop = (state) => {
|
|
253
|
+
reason ??= state;
|
|
254
|
+
child.stdin?.end();
|
|
255
|
+
};
|
|
256
|
+
this.active.set(result.runId, { result, repository: suite.repository, stop, done });
|
|
257
|
+
const timeout = setTimeout(() => stop('timedOut'), suite.timeoutMs);
|
|
258
|
+
let summary = '';
|
|
259
|
+
child.stdin?.on('error', () => { });
|
|
260
|
+
const output = (data) => {
|
|
261
|
+
const room = suite.maxOutputBytes - result.outputBytes;
|
|
262
|
+
const kept = data.subarray(0, Math.max(0, room));
|
|
263
|
+
if (kept.length) {
|
|
264
|
+
try {
|
|
265
|
+
writeSync(fd, kept);
|
|
266
|
+
hash.update(kept);
|
|
267
|
+
result.outputBytes += kept.length;
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
stop('interrupted');
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
summary = (summary + kept.toString('utf8')).slice(-8192);
|
|
274
|
+
if (data.length > room)
|
|
275
|
+
stop('outputLimit');
|
|
276
|
+
};
|
|
277
|
+
child.stdout?.on('data', output);
|
|
278
|
+
child.stderr?.on('data', output);
|
|
279
|
+
child.on('message', (message) => {
|
|
280
|
+
const value = message;
|
|
281
|
+
if (Number.isInteger(value?.exitCode) || value?.exitCode === null) {
|
|
282
|
+
result.exitCode = typeof value.exitCode === 'number' ? value.exitCode : null;
|
|
283
|
+
result.signal = typeof value.signal === 'string' ? value.signal.slice(0, 32) : null;
|
|
284
|
+
result.processExitedAt = new Date().toISOString();
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
child.once('error', () => {
|
|
288
|
+
reason ??= 'interrupted';
|
|
289
|
+
});
|
|
290
|
+
child.once('close', () => {
|
|
291
|
+
clearTimeout(timeout);
|
|
292
|
+
closeSync(fd);
|
|
293
|
+
void (async () => {
|
|
294
|
+
const terminal = structuredClone(result);
|
|
295
|
+
terminal.outputSha256 = hash.digest('hex');
|
|
296
|
+
try {
|
|
297
|
+
terminal.finalCandidate = await candidate(suite.repository);
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
/* Unknown candidate cannot support acceptance. */
|
|
301
|
+
}
|
|
302
|
+
terminal.state =
|
|
303
|
+
reason ??
|
|
304
|
+
(terminal.finalCandidate !== terminal.candidate
|
|
305
|
+
? 'invalidated'
|
|
306
|
+
: terminal.exitCode === 0
|
|
307
|
+
? 'passed'
|
|
308
|
+
: 'failed');
|
|
309
|
+
terminal.observedAt = new Date().toISOString();
|
|
310
|
+
terminal.counts = reason || result.outputBytes > 8192 ? null : parseTapCounts(summary);
|
|
311
|
+
try {
|
|
312
|
+
await this.persist(terminal);
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
terminal.state = 'interrupted';
|
|
316
|
+
}
|
|
317
|
+
this.results.set(result.runId, terminal);
|
|
318
|
+
this.active.delete(result.runId);
|
|
319
|
+
this.reservations.delete(suite.repository);
|
|
320
|
+
try {
|
|
321
|
+
this.completed(terminal.sessionId, terminal.runId, terminal.observedAt);
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
/* Durable result remains available even if the notification consumer is closing. */
|
|
325
|
+
}
|
|
326
|
+
finally {
|
|
327
|
+
finished();
|
|
328
|
+
}
|
|
329
|
+
})();
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
async persist(result) {
|
|
333
|
+
const temporary = result.resultPath + '.tmp';
|
|
334
|
+
await writeFile(temporary, JSON.stringify(result) + '\n', { mode: 0o600 });
|
|
335
|
+
await rename(temporary, result.resultPath);
|
|
336
|
+
}
|
|
337
|
+
async cancelSession(sessionId) {
|
|
338
|
+
this.sessionGenerations.set(sessionId, (this.sessionGenerations.get(sessionId) ?? 0) + 1);
|
|
339
|
+
await Promise.allSettled([...this.requests.entries()]
|
|
340
|
+
.filter(([key]) => key.startsWith(sessionId + ':'))
|
|
341
|
+
.map(([, pending]) => pending));
|
|
342
|
+
const runs = [...this.active.values()].filter((run) => run.result.sessionId === sessionId);
|
|
343
|
+
for (const run of runs)
|
|
344
|
+
run.stop('cancelled');
|
|
345
|
+
await Promise.all(runs.map((run) => run.done));
|
|
346
|
+
}
|
|
347
|
+
async close() {
|
|
348
|
+
this.closing = true;
|
|
349
|
+
await Promise.allSettled([...this.requests.values()]);
|
|
350
|
+
const runs = [...this.active.values()];
|
|
351
|
+
for (const run of runs)
|
|
352
|
+
run.stop('interrupted');
|
|
353
|
+
await Promise.all(runs.map((run) => run.done));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/** Unknown/mixed/truncated reporter output is not invented evidence. Exit status is independent. */
|
|
357
|
+
export function parseTapCounts(text) {
|
|
358
|
+
const names = ['tests', 'pass', 'fail', 'skipped'];
|
|
359
|
+
const values = names.map((name) => [
|
|
360
|
+
...text.matchAll(new RegExp('^# ' + name + ' (\\d+)\\r?$', 'gm')),
|
|
361
|
+
]);
|
|
362
|
+
if (values.some((matches) => matches.length !== 1))
|
|
363
|
+
return null;
|
|
364
|
+
const [total, passed, failed, skipped] = values.map((matches) => Number(matches[0][1]));
|
|
365
|
+
if (![total, passed, failed, skipped].every(Number.isSafeInteger) ||
|
|
366
|
+
passed + failed + skipped !== total)
|
|
367
|
+
return null;
|
|
368
|
+
return { total, passed, failed, skipped };
|
|
369
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
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
|
+
requestId: runId,
|
|
17
|
+
})
|
|
18
|
+
.strict(),
|
|
19
|
+
z.object({ operation: z.literal('status'), runId }).strict(),
|
|
20
|
+
z.object({ operation: z.literal('cancel'), runId }).strict(),
|
|
21
|
+
]);
|
|
22
|
+
export const gestaltTestRunnerDynamicTool = {
|
|
23
|
+
type: 'function',
|
|
24
|
+
name: 'gestalt_test_runner',
|
|
25
|
+
description: 'Run workspace test suites outside the agent shell sandbox as the host user. Enabled by default; root supervisor only. Create or edit .gestalt/host-tests.json in the session workspace using normal file tools; suites reload at runtime without restart or fingerprint approval. list/inspect do not execute code. start requires suite and an idempotent requestId; status/cancel require runId. Tool arguments never accept commands, environment, or paths. Results retain automatic source fingerprints, UTC observations and private evidence; counts can be unknown. Keep the writer idle during tests. Does not approve milestones or resume Autopilot.',
|
|
26
|
+
inputSchema: {
|
|
27
|
+
type: 'object',
|
|
28
|
+
additionalProperties: false,
|
|
29
|
+
properties: {
|
|
30
|
+
operation: { type: 'string', enum: ['list', 'inspect', 'start', 'status', 'cancel'] },
|
|
31
|
+
suite: { type: 'string' },
|
|
32
|
+
requestId: { type: 'string' },
|
|
33
|
+
runId: { type: 'string' },
|
|
34
|
+
},
|
|
35
|
+
required: ['operation'],
|
|
36
|
+
},
|
|
37
|
+
};
|