gestalt-mobile 0.71.5 → 0.72.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +15 -48
  2. package/dist/client/assets/index-CwgSPgbi.css +1 -0
  3. package/dist/client/assets/index-ME1MRi_3.js +182 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/client/features/chat/activity-summary.js +11 -0
  6. package/dist/server/client/features/chat/chat-projection.js +6 -2
  7. package/dist/server/server/cli.js +0 -3
  8. package/dist/server/server/composition.contracts.js +0 -2
  9. package/dist/server/server/composition.js +8 -25
  10. package/dist/server/server/config.js +2 -5
  11. package/dist/server/server/features/agent-activity/registry.js +42 -15
  12. package/dist/server/server/features/catalog/get-bootstrap/use-case.js +0 -1
  13. package/dist/server/server/features/catalog/register-routes.js +0 -3
  14. package/dist/server/server/features/sessions/forget-session/use-case.js +6 -0
  15. package/dist/server/server/features/skills/list-available/endpoint.js +1 -1
  16. package/dist/server/server/features/skills/model/skill-profile.js +2 -3
  17. package/dist/server/server/platform/codex/capability-deadline.js +26 -0
  18. package/dist/server/server/platform/codex/codex-capabilities.js +23 -56
  19. package/dist/server/server/platform/codex/codex-playwright.js +3 -3
  20. package/dist/server/server/platform/codex/codex-serena.js +1 -1
  21. package/dist/server/server/platform/codex/mcp-startup-failure.js +0 -25
  22. package/dist/server/server/platform/codex/normalizer.js +0 -17
  23. package/dist/server/server/platform/codex/retired-capability-migration.js +105 -0
  24. package/dist/server/server/platform/codex/session-runtime.js +4 -52
  25. package/dist/server/server/platform/codex/startup-guidance.fixture.js +3 -3
  26. package/dist/server/server/platform/kimi/kimi-skill-catalog.js +2 -8
  27. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -7
  28. package/dist/server/server/platform/scratch/containment-fence.js +76 -20
  29. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +139 -13
  30. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +20 -11
  31. package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +64 -8
  32. package/dist/server/server/platform/scratch/managed-scratch-owner.js +17 -1
  33. package/dist/server/server/platform/scratch/runtime-root.js +147 -0
  34. package/dist/server/server/platform/scratch/workspace-publication.js +67 -0
  35. package/dist/server/server/platform/skills/codex-skill-catalog.js +9 -7
  36. package/dist/server/shared/contracts/mcp-startup-failure.js +5 -30
  37. package/package.json +1 -1
  38. package/dist/client/assets/index-BOJci8Jh.css +0 -1
  39. package/dist/client/assets/index-Cb4qCgbe.js +0 -183
  40. package/dist/server/server/features/catalog/get-xerj-status/endpoint.js +0 -13
  41. package/dist/server/server/platform/retrieval/codex-xerj.js +0 -205
  42. package/dist/server/server/platform/retrieval/managed-xerj.js +0 -196
  43. package/dist/server/server/platform/retrieval/xerj-index-config.js +0 -70
  44. package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +0 -124
  45. package/dist/server/server/platform/retrieval/xerj-indexer.js +0 -399
  46. package/dist/server/shared/contracts/xerj-startup.js +0 -76
  47. /package/dist/server/{shared/contracts/xerj-status.js → server/platform/codex/capability-contracts.js} +0 -0
@@ -1,13 +0,0 @@
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 { unknownReadiness } from '../../../../shared/contracts/retrieval-readiness.js';
7
- export function registerXerjStatus(app, status) {
8
- app.get('/api/xerj', async (_request, reply) => {
9
- reply.header('Cache-Control', 'no-store');
10
- const current = status();
11
- return { ...current, readiness: current.readiness ?? unknownReadiness() };
12
- });
13
- }
@@ -1,205 +0,0 @@
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 { readFile } from 'node:fs/promises';
7
- import { sessionScratchEnvironmentKeys } from '../scratch/child-environment.js';
8
- import { parseXerjStartupReason, } from '../../../shared/contracts/xerj-startup.js';
9
- import { ReadinessEvidence } from './readiness-evidence.js';
10
- import { withCapabilityInstructions } from '../codex/instruction-blocks.js';
11
- export const xerjServerName = 'gestalt-xerj';
12
- export const xerjTools = ['xerj_search', 'xerj_map', 'xerj_code_search'];
13
- const connectionTimeoutMs = 5_000;
14
- /** Ephemeral native thread configuration; no installation or daemon ownership. */
15
- export class CodexXerj {
16
- capability;
17
- constructor(capability) {
18
- this.capability = capability;
19
- }
20
- async prepare(input) {
21
- const skill = input.skills.find((entry) => entry.name === 'gestalt:xerj');
22
- const evidence = new ReadinessEvidence();
23
- const state = {
24
- evidence,
25
- get readiness() {
26
- return evidence.snapshot();
27
- },
28
- ready: false,
29
- deadline: input.deadline,
30
- config: { ...input.config },
31
- skillsConfig: input.skillsConfig.map((entry) => ({
32
- ...entry,
33
- enabled: entry.path === skill?.path ? false : entry.enabled,
34
- })),
35
- fallback: () => { },
36
- };
37
- let native = {};
38
- let compatible = false;
39
- try {
40
- const read = input.nativeConfig !== undefined
41
- ? { config: input.nativeConfig ?? undefined }
42
- : (await beforeDeadline(input.rpc.request('config/read', { cwd: input.cwd, includeLayers: false }), input.deadline));
43
- native = read.config ?? {};
44
- compatible = read.config !== undefined;
45
- }
46
- catch {
47
- /* An incompatible runtime cannot safely advertise retrieval. */
48
- }
49
- const servers = native.mcp_servers && typeof native.mcp_servers === 'object'
50
- ? native.mcp_servers
51
- : {};
52
- const mcp = {};
53
- // Disable aliases of the managed connection without disturbing unrelated MCP.
54
- for (const [name, server] of Object.entries(servers)) {
55
- if (server?.args?.[0] === 'xerj' && server.args[1] === 'mcp')
56
- mcp[name] = { ...server, enabled: false, required: false };
57
- }
58
- const instructions = typeof input.config.developer_instructions === 'string'
59
- ? input.config.developer_instructions
60
- : typeof native.developer_instructions === 'string'
61
- ? native.developer_instructions
62
- : '';
63
- state.fallback = () => {
64
- evidence.connection('unavailable');
65
- state.ready = false;
66
- state.skillsConfig = state.skillsConfig.map((entry) => ({
67
- ...entry,
68
- enabled: entry.path === skill?.path ? false : entry.enabled,
69
- }));
70
- state.instructionBlock =
71
- '<gestalt_xerj_unavailable>\nXerj retrieval is unavailable in this runtime. Earlier retrieval guidance is inactive; use rg and current source reads.\n</gestalt_xerj_unavailable>';
72
- state.config = {
73
- ...input.config,
74
- skills: { config: [{ name: 'gestalt:xerj', enabled: false }] },
75
- mcp_servers: {
76
- ...mcp,
77
- [xerjServerName]: {
78
- command: 'gestalt',
79
- args: ['xerj', 'mcp'],
80
- enabled: false,
81
- required: false,
82
- },
83
- },
84
- developer_instructions: withCapabilityInstructions(instructions, 'xerj', state.instructionBlock),
85
- };
86
- };
87
- state.fallback();
88
- if (!compatible || !skill || Date.now() >= input.deadline)
89
- return state;
90
- try {
91
- const ready = await this.capability.check({
92
- cwd: input.cwd,
93
- deadline: input.deadline,
94
- start: input.start,
95
- });
96
- if (ready.status !== 'ready') {
97
- if (ready.status === 'starting')
98
- state.backendPreparation = { status: 'starting' };
99
- if (ready.status === 'unavailable') {
100
- state.diagnostic = 'backend-unavailable';
101
- state.backendPreparation = {
102
- status: 'unavailable',
103
- reason: parseXerjStartupReason(ready.reason),
104
- };
105
- }
106
- return state;
107
- }
108
- const guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
109
- if (guidance.length > 16_384)
110
- return state;
111
- // Backend preparation must not leave the native MCP handshake with only
112
- // a few milliseconds. These are separate, individually bounded phases.
113
- state.deadline = Date.now() + connectionTimeoutMs;
114
- state.verificationTimeoutMs = connectionTimeoutMs;
115
- state.skillsConfig = state.skillsConfig.map((entry) => ({
116
- ...entry,
117
- enabled: entry.path === skill.path ? true : entry.enabled,
118
- }));
119
- state.instructionBlock = `<gestalt_xerj_capability>\nWorkspace index counts do not establish coverage or freshness for a selected repository. Verify hit identity and current source before relying on it.\n${guidance}\n</gestalt_xerj_capability>`;
120
- state.config = {
121
- ...input.config,
122
- skills: { config: [{ name: 'gestalt:xerj', enabled: true }] },
123
- mcp_servers: {
124
- ...mcp,
125
- [xerjServerName]: {
126
- command: ready.manager,
127
- args: ['xerj', 'mcp', '--url', ready.endpoint],
128
- cwd: input.cwd,
129
- env_vars: [
130
- 'CODEX_HOME',
131
- 'GESTALT_HOME',
132
- 'XERJ_API_KEY',
133
- 'XERJ_AUTH',
134
- ...sessionScratchEnvironmentKeys,
135
- ],
136
- enabled: true,
137
- required: false,
138
- startup_readiness: 'connection',
139
- startup_timeout_ms: connectionTimeoutMs,
140
- enabled_tools: xerjTools,
141
- default_tools_approval_mode: 'approve',
142
- },
143
- },
144
- developer_instructions: withCapabilityInstructions(instructions, 'xerj', state.instructionBlock),
145
- };
146
- state.ready = true;
147
- evidence.connection('unknown');
148
- }
149
- catch {
150
- state.fallback();
151
- state.diagnostic = 'connection-unavailable';
152
- }
153
- return state;
154
- }
155
- async verify(rpc, threadId, state) {
156
- if (!state.ready)
157
- return false;
158
- // thread/start can consume the handshake allowance before this method runs.
159
- const deadline = state.verificationTimeoutMs
160
- ? Date.now() + state.verificationTimeoutMs
161
- : state.deadline;
162
- try {
163
- while (Date.now() < deadline) {
164
- const result = (await beforeDeadline(rpc.request('mcpServerStatus/list', {
165
- threadId,
166
- serverName: xerjServerName,
167
- detail: 'full',
168
- }), deadline));
169
- const server = result.data?.find((entry) => entry.name === xerjServerName);
170
- if (server?.runtimeStatus === 'connected' &&
171
- !server.toolsError &&
172
- xerjTools.every((tool) => Object.hasOwn(server.tools ?? {}, tool))) {
173
- state.evidence?.connection('ready');
174
- return true;
175
- }
176
- if (server?.runtimeStatus !== 'starting') {
177
- state.evidence?.connection('unavailable');
178
- return false;
179
- }
180
- await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)), deadline);
181
- }
182
- state.evidence?.connection('unavailable');
183
- return false;
184
- }
185
- catch {
186
- state.evidence?.connection('unavailable');
187
- return false;
188
- }
189
- }
190
- }
191
- export async function beforeDeadline(promise, deadline) {
192
- let timer;
193
- try {
194
- return await Promise.race([
195
- promise,
196
- new Promise((_, reject) => {
197
- timer = setTimeout(() => reject(new Error('XERJ_READINESS_TIMEOUT')), Math.max(0, deadline - Date.now()));
198
- }),
199
- ]);
200
- }
201
- finally {
202
- if (timer)
203
- clearTimeout(timer);
204
- }
205
- }
@@ -1,196 +0,0 @@
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 { withoutSessionScratch } from '../scratch/child-environment.js';
8
- import { access } from 'node:fs/promises';
9
- import { constants } from 'node:fs';
10
- import { isAbsolute, join } from 'node:path';
11
- import { parseXerjStartupReason } from '../../../shared/contracts/xerj-startup.js';
12
- /** The manager alone owns backend identity, authentication and shared lifetime. */
13
- export class ManagedXerj {
14
- environment;
15
- startup;
16
- probes = new Set();
17
- closed = false;
18
- constructor(environment = process.env) {
19
- this.environment = environment;
20
- }
21
- async check(input) {
22
- if (this.closed)
23
- return { status: 'unavailable', reason: 'cancelled' };
24
- const manager = await this.manager();
25
- if (this.closed)
26
- return { status: 'unavailable', reason: 'cancelled' };
27
- if (!manager)
28
- return { status: 'absent' };
29
- const remaining = input.deadline - Date.now();
30
- if (this.startup?.manager === manager)
31
- return this.wait(this.startup.result, Math.max(0, remaining));
32
- // The shipped manager rejects sub-100ms operations because it reserves
33
- // cleanup time inside the overall deadline. Do not spend the remaining
34
- // budget spawning a request that cannot satisfy that contract.
35
- if (remaining < minimumXerjTimeoutMs)
36
- return { status: 'unavailable', reason: 'readiness-timeout' };
37
- // A short-lived session waiter never owns the shared startup process.
38
- // Read-only discovery can observe an existing startup but cannot initiate one.
39
- if (!input.start)
40
- return this.run(manager, input.cwd, 'probe', Math.min(remaining, maximumXerjTimeoutMs));
41
- const startup = {
42
- manager,
43
- result: this.run(manager, input.cwd, 'ensure-ready', xerjStartupTimeout(this.environment)),
44
- };
45
- this.startup = startup;
46
- void startup.result.then(() => {
47
- if (this.startup === startup)
48
- this.startup = undefined;
49
- });
50
- return this.wait(startup.result, remaining);
51
- }
52
- async wait(result, timeout) {
53
- let timer;
54
- try {
55
- return await Promise.race([
56
- result,
57
- new Promise((resolve) => {
58
- timer = setTimeout(() => resolve({ status: 'starting' }), timeout);
59
- }),
60
- ]);
61
- }
62
- finally {
63
- clearTimeout(timer);
64
- }
65
- }
66
- run(manager, cwd, operation, timeout) {
67
- return new Promise((resolve) => {
68
- const child = spawn(manager, ['xerj', operation], {
69
- cwd,
70
- env: { ...withoutSessionScratch(this.environment), XERJ_READY_TIMEOUT_MS: String(timeout) },
71
- shell: false,
72
- stdio: ['ignore', 'pipe', 'ignore'],
73
- });
74
- let output = '';
75
- let finished = false;
76
- let failure;
77
- let escalation;
78
- let closed;
79
- const probe = {
80
- stop: () => stop('cancelled'),
81
- closed: new Promise((resolve) => {
82
- closed = resolve;
83
- }),
84
- };
85
- this.probes.add(probe);
86
- const settle = (result) => {
87
- if (finished)
88
- return;
89
- finished = true;
90
- clearTimeout(timer);
91
- clearTimeout(escalation);
92
- this.probes.delete(probe);
93
- closed();
94
- resolve(result);
95
- };
96
- const unavailable = (reason) => ({
97
- status: 'unavailable',
98
- reason,
99
- });
100
- const stop = (reason) => {
101
- if (finished || failure)
102
- return;
103
- failure = unavailable(reason);
104
- // Reap only our manager client; its lifecycle contract owns launch cleanup.
105
- child.kill('SIGTERM');
106
- escalation = setTimeout(() => child.kill('SIGKILL'), 100).unref();
107
- };
108
- const timer = setTimeout(() => stop('readiness-timeout'), timeout);
109
- child.on('error', () => {
110
- failure = unavailable('manager-unavailable');
111
- });
112
- child.stdout.on('data', (data) => {
113
- if (failure)
114
- return;
115
- output += data.toString();
116
- if (output.length > 16_384) {
117
- stop('invalid-manager-response');
118
- }
119
- });
120
- child.once('close', (code) => {
121
- if (failure)
122
- return settle(failure);
123
- try {
124
- const value = JSON.parse(output);
125
- if (code !== 0 || value.schemaVersion !== 1)
126
- throw new Error();
127
- if (value.status === 'absent')
128
- return settle({ status: 'absent' });
129
- if (value.status === 'unavailable')
130
- return settle(unavailable(parseXerjStartupReason(value.reason)));
131
- if (value.status !== 'ready' ||
132
- typeof value.version !== 'string' ||
133
- !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.version) ||
134
- typeof value.endpoint !== 'string' ||
135
- !/^http:\/\/(127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/.test(value.endpoint))
136
- throw new Error();
137
- const url = new URL(value.endpoint);
138
- if (Number(url.port || 80) < 1 || Number(url.port || 80) > 65535)
139
- throw new Error();
140
- settle({ status: 'ready', manager, endpoint: value.endpoint });
141
- }
142
- catch {
143
- settle(unavailable('invalid-manager-response'));
144
- }
145
- });
146
- }).catch(() => ({ status: 'unavailable', reason: 'manager-unavailable' }));
147
- }
148
- async close() {
149
- this.closed = true;
150
- const probes = [...this.probes];
151
- for (const probe of probes)
152
- probe.stop();
153
- await Promise.all(probes.map((probe) => probe.closed));
154
- }
155
- async manager() {
156
- const explicit = this.environment.GESTALT_MANAGER_BIN;
157
- const paths = explicit
158
- ? [explicit]
159
- : (this.environment.PATH ?? '')
160
- .split(':')
161
- .filter(Boolean)
162
- .map((path) => join(path, 'gestalt'));
163
- for (const path of paths) {
164
- if (!isAbsolute(path))
165
- continue;
166
- try {
167
- await access(path, constants.X_OK);
168
- return path;
169
- }
170
- catch {
171
- /* Try next established executable path. */
172
- }
173
- }
174
- return undefined;
175
- }
176
- }
177
- export function xerjDeadline(environment = process.env) {
178
- const configured = Number(environment.XERJ_READY_TIMEOUT_MS);
179
- return (Date.now() +
180
- (Number.isInteger(configured) &&
181
- configured >= minimumXerjTimeoutMs &&
182
- configured <= maximumXerjTimeoutMs
183
- ? configured
184
- : defaultXerjTimeoutMs));
185
- }
186
- const minimumXerjTimeoutMs = 100;
187
- const maximumXerjTimeoutMs = 60_000;
188
- const defaultXerjTimeoutMs = 5_000;
189
- export function xerjStartupTimeout(environment = process.env) {
190
- const configured = Number(environment.XERJ_STARTUP_TIMEOUT_MS);
191
- return Number.isInteger(configured) &&
192
- configured >= minimumXerjTimeoutMs &&
193
- configured <= maximumXerjTimeoutMs
194
- ? configured
195
- : 30_000;
196
- }
@@ -1,70 +0,0 @@
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 { createHash, randomUUID } from 'node:crypto';
7
- import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
8
- import { join } from 'node:path';
9
- // Content-affecting settings. Reused in the command and fingerprint so
10
- // changing an operational setting cannot accidentally require a rebuild.
11
- export const xerjContentArguments = [
12
- '--no-graph',
13
- '--no-semantic',
14
- '--max-file-gb',
15
- '1',
16
- '--sample',
17
- '500',
18
- '--pdf-timeout-secs',
19
- '120',
20
- ];
21
- export function xerjIndexConfig(root, prefix, endpoint) {
22
- const settings = {
23
- root,
24
- prefix,
25
- endpoint,
26
- contentArguments: xerjContentArguments,
27
- followSymlinks: false,
28
- label: null,
29
- };
30
- return {
31
- schemaVersion: 1,
32
- fingerprint: createHash('sha256').update(JSON.stringify(settings)).digest('hex'),
33
- settings,
34
- };
35
- }
36
- const filename = '.gestalt-index-config.json';
37
- /** Unknown legacy indexes still undergo native validation; never bless them early. */
38
- export async function checkXerjIndexConfig(directory, expected) {
39
- try {
40
- const saved = JSON.parse(await readFile(join(directory, filename), 'utf8'));
41
- // Older fingerprints included a pinned version. Validate their integrity
42
- // before comparing content settings; native XERJ owns index compatibility.
43
- const settings = { ...saved.settings };
44
- delete settings.nativeVersion;
45
- return saved.schemaVersion === expected.schemaVersion &&
46
- createHash('sha256').update(JSON.stringify(settings)).digest('hex') ===
47
- expected.fingerprint &&
48
- createHash('sha256').update(JSON.stringify(saved.settings)).digest('hex') ===
49
- saved.fingerprint
50
- ? 'compatible'
51
- : 'incompatible';
52
- }
53
- catch (error) {
54
- if (error.code === 'ENOENT')
55
- return 'missing';
56
- return 'incompatible';
57
- }
58
- }
59
- /** Record only after a successful native generation, atomically and without credentials. */
60
- export async function saveXerjIndexConfig(directory, config) {
61
- await mkdir(directory, { recursive: true, mode: 0o700 });
62
- const temporary = join(directory, `${filename}.${randomUUID()}.tmp`);
63
- try {
64
- await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
65
- await rename(temporary, join(directory, filename));
66
- }
67
- finally {
68
- await rm(temporary, { force: true });
69
- }
70
- }
@@ -1,124 +0,0 @@
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 { createHash, randomUUID } from 'node:crypto';
7
- import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
8
- import { join } from 'node:path';
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. */
78
- export function xerjIndexDiagnostic(message) {
79
- const text = errorText(message);
80
- const summary = xerjErrorSummary(message);
81
- const pass = /^watch: pass (\d+) FAILED after (\d+(?:\.\d+)?)s:/.exec(text);
82
- const number = pass ? Number(pass[1]) : Number.NaN;
83
- const durationSeconds = pass ? Number(pass[2]) : Number.NaN;
84
- const code = text.includes('refusing ambiguous assignment')
85
- ? 'ambiguous-assignment'
86
- : /\b(timeout|timed out)\b/i.test(text)
87
- ? 'timeout'
88
- : /\b(unauthorized|forbidden|authentication)\b/i.test(text)
89
- ? 'authentication'
90
- : /\b(connection refused|connection reset|unreachable)\b/i.test(text)
91
- ? 'connection'
92
- : /\b(out of memory|no space left|disk full)\b/i.test(text)
93
- ? 'capacity'
94
- : text.includes('rebuild with a new --state-dir and a new --prefix')
95
- ? 'rebuild-required'
96
- : /^watch: pass \d+ FAILED after [\d.]+s:/.test(text)
97
- ? 'watch-pass-failed'
98
- : text ===
99
- 'watch: the platform reported dropped events (watch queue overflow); re-hashing the whole tree for this pass'
100
- ? 'watch-rescan'
101
- : 'unknown-warning';
102
- return {
103
- id: randomUUID(),
104
- occurredAt: new Date().toISOString(),
105
- code,
106
- messageDigest: text ? createHash('sha256').update(text).digest('hex') : null,
107
- ...(summary ? { summary } : {}),
108
- ...(Number.isSafeInteger(number) && Number.isFinite(durationSeconds)
109
- ? { watchPass: { number, durationSeconds } }
110
- : {}),
111
- };
112
- }
113
- /** One private atomic record per root; repeated warnings cannot grow a log. */
114
- export async function saveXerjIndexDiagnostic(directory, diagnostic) {
115
- await mkdir(directory, { recursive: true, mode: 0o700 });
116
- const temporary = join(directory, `.gestalt-index-diagnostic.${randomUUID()}.tmp`);
117
- try {
118
- await writeFile(temporary, `${JSON.stringify(diagnostic)}\n`, { flag: 'wx', mode: 0o600 });
119
- await rename(temporary, join(directory, '.gestalt-index-diagnostic.json'));
120
- }
121
- finally {
122
- await rm(temporary, { force: true });
123
- }
124
- }