agentxchain 2.33.1 → 2.34.2
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/bin/agentxchain.js +7 -0
- package/package.json +1 -1
- package/src/commands/restart.js +222 -0
- package/src/lib/export.js +1 -0
- package/src/lib/governed-state.js +12 -0
- package/src/lib/repo-observer.js +1 -0
- package/src/lib/session-checkpoint.js +92 -0
package/bin/agentxchain.js
CHANGED
|
@@ -76,6 +76,7 @@ import { approveCompletionCommand } from '../src/commands/approve-completion.js'
|
|
|
76
76
|
import { dashboardCommand } from '../src/commands/dashboard.js';
|
|
77
77
|
import { exportCommand } from '../src/commands/export.js';
|
|
78
78
|
import { restoreCommand } from '../src/commands/restore.js';
|
|
79
|
+
import { restartCommand } from '../src/commands/restart.js';
|
|
79
80
|
import { reportCommand } from '../src/commands/report.js';
|
|
80
81
|
import {
|
|
81
82
|
pluginInstallCommand,
|
|
@@ -146,6 +147,12 @@ program
|
|
|
146
147
|
.requiredOption('--input <path>', 'Path to a prior run export artifact')
|
|
147
148
|
.action(restoreCommand);
|
|
148
149
|
|
|
150
|
+
program
|
|
151
|
+
.command('restart')
|
|
152
|
+
.description('Restart a governed run from the last checkpoint (cross-session recovery)')
|
|
153
|
+
.option('--role <role>', 'Override the next role assignment')
|
|
154
|
+
.action(restartCommand);
|
|
155
|
+
|
|
149
156
|
program
|
|
150
157
|
.command('report')
|
|
151
158
|
.description('Render a human-readable governance summary from an export artifact')
|
package/package.json
CHANGED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agentxchain restart — governed-only command.
|
|
3
|
+
*
|
|
4
|
+
* Reconstructs dispatch context from durable checkpoint state and assigns the
|
|
5
|
+
* next turn. Unlike `resume` (which assumes the caller has session context),
|
|
6
|
+
* `restart` assumes the caller has NO session context and rebuilds everything
|
|
7
|
+
* from .agentxchain/session.json + .agentxchain/state.json.
|
|
8
|
+
*
|
|
9
|
+
* Use case: terminal died mid-run, machine restarted, new agent session
|
|
10
|
+
* picking up a long-horizon governed run.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import chalk from 'chalk';
|
|
14
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
|
|
15
|
+
import { join, dirname } from 'path';
|
|
16
|
+
import { loadProjectContext, loadProjectState } from '../lib/config.js';
|
|
17
|
+
import {
|
|
18
|
+
assignGovernedTurn,
|
|
19
|
+
getActiveTurns,
|
|
20
|
+
getActiveTurnCount,
|
|
21
|
+
reactivateGovernedRun,
|
|
22
|
+
STATE_PATH,
|
|
23
|
+
HISTORY_PATH,
|
|
24
|
+
LEDGER_PATH,
|
|
25
|
+
} from '../lib/governed-state.js';
|
|
26
|
+
import { readSessionCheckpoint, SESSION_PATH } from '../lib/session-checkpoint.js';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Generate a session recovery report summarizing the run state
|
|
30
|
+
* so a new agent session can orient quickly.
|
|
31
|
+
*/
|
|
32
|
+
function generateRecoveryReport(root, state, checkpoint) {
|
|
33
|
+
const lines = [
|
|
34
|
+
'# Session Recovery Report',
|
|
35
|
+
'',
|
|
36
|
+
`> Auto-generated by \`agentxchain restart\` at ${new Date().toISOString()}`,
|
|
37
|
+
'',
|
|
38
|
+
'## Run Identity',
|
|
39
|
+
'',
|
|
40
|
+
`- **Run ID**: \`${state.run_id}\``,
|
|
41
|
+
`- **Project**: \`${state.project_id || 'unknown'}\``,
|
|
42
|
+
`- **Status**: ${state.status}`,
|
|
43
|
+
`- **Phase**: ${state.phase || state.current_phase || 'unknown'}`,
|
|
44
|
+
'',
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
if (checkpoint) {
|
|
48
|
+
lines.push(
|
|
49
|
+
'## Last Checkpoint',
|
|
50
|
+
'',
|
|
51
|
+
`- **Session**: \`${checkpoint.session_id}\``,
|
|
52
|
+
`- **Last turn**: \`${checkpoint.last_turn_id || 'none'}\``,
|
|
53
|
+
`- **Last role**: ${checkpoint.last_role || 'unknown'}`,
|
|
54
|
+
`- **Reason**: ${checkpoint.checkpoint_reason}`,
|
|
55
|
+
`- **Time**: ${checkpoint.last_checkpoint_at}`,
|
|
56
|
+
'',
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Recent decisions from ledger
|
|
61
|
+
const ledgerPath = join(root, LEDGER_PATH);
|
|
62
|
+
if (existsSync(ledgerPath)) {
|
|
63
|
+
try {
|
|
64
|
+
const entries = readFileSync(ledgerPath, 'utf8')
|
|
65
|
+
.trim()
|
|
66
|
+
.split('\n')
|
|
67
|
+
.filter(Boolean)
|
|
68
|
+
.map(l => JSON.parse(l));
|
|
69
|
+
const recent = entries.slice(-5);
|
|
70
|
+
if (recent.length > 0) {
|
|
71
|
+
lines.push('## Recent Decisions', '');
|
|
72
|
+
for (const entry of recent) {
|
|
73
|
+
lines.push(`- \`${entry.decision_id || entry.id || 'unknown'}\`: ${entry.summary || entry.description || JSON.stringify(entry).slice(0, 100)}`);
|
|
74
|
+
}
|
|
75
|
+
lines.push('');
|
|
76
|
+
}
|
|
77
|
+
} catch {
|
|
78
|
+
// Non-fatal
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Turn history summary
|
|
83
|
+
const historyPath = join(root, HISTORY_PATH);
|
|
84
|
+
if (existsSync(historyPath)) {
|
|
85
|
+
try {
|
|
86
|
+
const entries = readFileSync(historyPath, 'utf8')
|
|
87
|
+
.trim()
|
|
88
|
+
.split('\n')
|
|
89
|
+
.filter(Boolean)
|
|
90
|
+
.map(l => JSON.parse(l));
|
|
91
|
+
lines.push(`## Turn History`, '', `Total turns completed: ${entries.length}`, '');
|
|
92
|
+
const recent = entries.slice(-3);
|
|
93
|
+
if (recent.length > 0) {
|
|
94
|
+
lines.push('### Last 3 Turns', '');
|
|
95
|
+
for (const entry of recent) {
|
|
96
|
+
lines.push(`- **${entry.turn_id}** (${entry.role}, phase: ${entry.phase}): ${entry.status}`);
|
|
97
|
+
}
|
|
98
|
+
lines.push('');
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
// Non-fatal
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
lines.push('## Next Steps', '', 'The next turn has been assigned. Check the dispatch bundle for context.', '');
|
|
106
|
+
|
|
107
|
+
return lines.join('\n');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function restartCommand(opts) {
|
|
111
|
+
const context = loadProjectContext();
|
|
112
|
+
if (!context) {
|
|
113
|
+
console.log(chalk.red('No agentxchain.json found. Run `agentxchain init` first.'));
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const { root, config } = context;
|
|
118
|
+
|
|
119
|
+
if (config.protocol_mode !== 'governed') {
|
|
120
|
+
console.log(chalk.red('The restart command is only available for governed projects.'));
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Load state
|
|
125
|
+
const statePath = join(root, STATE_PATH);
|
|
126
|
+
if (!existsSync(statePath)) {
|
|
127
|
+
console.log(chalk.red('No governed run found. Use `agentxchain resume` or `agentxchain run` to start.'));
|
|
128
|
+
process.exit(1);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const state = JSON.parse(readFileSync(statePath, 'utf8'));
|
|
132
|
+
|
|
133
|
+
// Load checkpoint (optional — restart can work without it, just with less context)
|
|
134
|
+
const checkpoint = readSessionCheckpoint(root);
|
|
135
|
+
|
|
136
|
+
// Validate run_id agreement if checkpoint exists
|
|
137
|
+
if (checkpoint && checkpoint.run_id !== state.run_id) {
|
|
138
|
+
console.log(chalk.red(`Checkpoint run_id mismatch: session.json has ${checkpoint.run_id}, state.json has ${state.run_id}`));
|
|
139
|
+
console.log(chalk.dim('The checkpoint is stale. Proceeding with state.json as ground truth.'));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Check terminal states
|
|
143
|
+
if (state.status === 'completed') {
|
|
144
|
+
console.log(chalk.red('Run is in terminal state: completed.'));
|
|
145
|
+
console.log(chalk.dim(`Run ${state.run_id} completed at ${state.completed_at || 'unknown'}.`));
|
|
146
|
+
process.exit(1);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (state.status === 'failed') {
|
|
150
|
+
console.log(chalk.red('Run is in terminal state: failed.'));
|
|
151
|
+
process.exit(1);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (state.status === 'blocked') {
|
|
155
|
+
console.log(chalk.red('Run is blocked. Resolve the blocker first.'));
|
|
156
|
+
if (state.blocked_reason) {
|
|
157
|
+
console.log(chalk.dim(`Reason: ${typeof state.blocked_reason === 'string' ? state.blocked_reason : JSON.stringify(state.blocked_reason)}`));
|
|
158
|
+
}
|
|
159
|
+
console.log(chalk.dim('Use `agentxchain step --resume` or resolve the blocker, then try again.'));
|
|
160
|
+
process.exit(1);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Handle abandoned active turns (assigned but never completed)
|
|
164
|
+
const activeTurns = getActiveTurns(state);
|
|
165
|
+
const activeTurnCount = getActiveTurnCount(state);
|
|
166
|
+
if (activeTurnCount > 0 && state.status === 'active') {
|
|
167
|
+
const turnIds = Object.keys(activeTurns);
|
|
168
|
+
console.log(chalk.yellow(`Warning: ${activeTurnCount} turn(s) were assigned but never completed: ${turnIds.join(', ')}`));
|
|
169
|
+
console.log(chalk.dim('These turns will be available for the next agent to complete.'));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// If paused, reactivate
|
|
173
|
+
if (state.status === 'paused' || state.status === 'idle') {
|
|
174
|
+
const reactivated = reactivateGovernedRun(root, state, {
|
|
175
|
+
reason: 'session_restart',
|
|
176
|
+
});
|
|
177
|
+
if (!reactivated.ok) {
|
|
178
|
+
console.log(chalk.red(`Failed to reactivate run: ${reactivated.error}`));
|
|
179
|
+
process.exit(1);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Determine role from option or routing
|
|
184
|
+
const phase = state.phase || state.current_phase;
|
|
185
|
+
const routing = config.routing?.[phase];
|
|
186
|
+
const roleId = opts.role || routing?.entry_role || Object.keys(config.roles || {})[0] || null;
|
|
187
|
+
|
|
188
|
+
if (!roleId) {
|
|
189
|
+
console.log(chalk.red('Cannot determine which role to assign. Use --role to specify.'));
|
|
190
|
+
process.exit(1);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Assign next turn if no active turn exists
|
|
194
|
+
if (activeTurnCount === 0) {
|
|
195
|
+
const assignment = assignGovernedTurn(root, config, roleId);
|
|
196
|
+
if (!assignment.ok) {
|
|
197
|
+
console.log(chalk.red(`Failed to assign turn: ${assignment.error}`));
|
|
198
|
+
process.exit(1);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
console.log(chalk.green(`✓ Restarted run ${state.run_id}`));
|
|
202
|
+
console.log(chalk.dim(` Phase: ${phase}`));
|
|
203
|
+
console.log(chalk.dim(` Turn: ${assignment.turn?.id || 'assigned'}`));
|
|
204
|
+
console.log(chalk.dim(` Role: ${assignment.turn?.role || roleId || 'routing default'}`));
|
|
205
|
+
if (checkpoint) {
|
|
206
|
+
console.log(chalk.dim(` Last checkpoint: ${checkpoint.checkpoint_reason} at ${checkpoint.last_checkpoint_at}`));
|
|
207
|
+
}
|
|
208
|
+
} else {
|
|
209
|
+
console.log(chalk.green(`✓ Reconnected to run ${state.run_id}`));
|
|
210
|
+
console.log(chalk.dim(` Phase: ${phase}`));
|
|
211
|
+
console.log(chalk.dim(` Active turns: ${Object.keys(activeTurns).join(', ')}`));
|
|
212
|
+
console.log(chalk.dim(' Complete the active turn(s) with `agentxchain accept-turn` or `agentxchain step`.'));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Write session recovery report
|
|
216
|
+
const recoveryReport = generateRecoveryReport(root, state, checkpoint);
|
|
217
|
+
const recoveryPath = join(root, '.agentxchain/SESSION_RECOVERY.md');
|
|
218
|
+
const recoveryDir = dirname(recoveryPath);
|
|
219
|
+
if (!existsSync(recoveryDir)) mkdirSync(recoveryDir, { recursive: true });
|
|
220
|
+
writeFileSync(recoveryPath, recoveryReport);
|
|
221
|
+
console.log(chalk.dim(` Recovery report: .agentxchain/SESSION_RECOVERY.md`));
|
|
222
|
+
}
|
package/src/lib/export.js
CHANGED
|
@@ -35,6 +35,7 @@ import { getMaxConcurrentTurns } from './normalized-config.js';
|
|
|
35
35
|
import { getTurnStagingResultPath, getTurnStagingDir, getDispatchTurnDir, getReviewArtifactPath } from './turn-paths.js';
|
|
36
36
|
import { runHooks } from './hook-runner.js';
|
|
37
37
|
import { emitNotifications } from './notification-runner.js';
|
|
38
|
+
import { writeSessionCheckpoint } from './session-checkpoint.js';
|
|
38
39
|
|
|
39
40
|
// ── Constants ────────────────────────────────────────────────────────────────
|
|
40
41
|
|
|
@@ -2483,6 +2484,11 @@ function _acceptGovernedTurnLocked(root, config, opts) {
|
|
|
2483
2484
|
}, currentTurn);
|
|
2484
2485
|
}
|
|
2485
2486
|
|
|
2487
|
+
// Session checkpoint — non-fatal, written after every successful acceptance
|
|
2488
|
+
writeSessionCheckpoint(root, updatedState, 'turn_accepted', {
|
|
2489
|
+
role: historyEntry?.role,
|
|
2490
|
+
});
|
|
2491
|
+
|
|
2486
2492
|
return {
|
|
2487
2493
|
ok: true,
|
|
2488
2494
|
state: attachLegacyCurrentTurnAlias(updatedState),
|
|
@@ -2791,6 +2797,9 @@ export function approvePhaseTransition(root, config) {
|
|
|
2791
2797
|
|
|
2792
2798
|
writeState(root, updatedState);
|
|
2793
2799
|
|
|
2800
|
+
// Session checkpoint — non-fatal
|
|
2801
|
+
writeSessionCheckpoint(root, updatedState, 'phase_approved');
|
|
2802
|
+
|
|
2794
2803
|
return {
|
|
2795
2804
|
ok: true,
|
|
2796
2805
|
state: attachLegacyCurrentTurnAlias(updatedState),
|
|
@@ -2889,6 +2898,9 @@ export function approveRunCompletion(root, config) {
|
|
|
2889
2898
|
requested_by_turn: completion.requested_by_turn || null,
|
|
2890
2899
|
}, completion.requested_by_turn ? getActiveTurns(state)[completion.requested_by_turn] || null : null);
|
|
2891
2900
|
|
|
2901
|
+
// Session checkpoint — non-fatal
|
|
2902
|
+
writeSessionCheckpoint(root, updatedState, 'run_completed');
|
|
2903
|
+
|
|
2892
2904
|
return {
|
|
2893
2905
|
ok: true,
|
|
2894
2906
|
state: attachLegacyCurrentTurnAlias(updatedState),
|
package/src/lib/repo-observer.js
CHANGED
|
@@ -34,6 +34,7 @@ const OPERATIONAL_PATH_PREFIXES = [
|
|
|
34
34
|
// These are written exclusively by the orchestrator (§4.1 State Ownership Rule).
|
|
35
35
|
const ORCHESTRATOR_STATE_FILES = [
|
|
36
36
|
'.agentxchain/state.json',
|
|
37
|
+
'.agentxchain/session.json',
|
|
37
38
|
'.agentxchain/history.jsonl',
|
|
38
39
|
'.agentxchain/decision-ledger.jsonl',
|
|
39
40
|
'.agentxchain/lock.json',
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session checkpoint — automatic state markers for cross-session restart.
|
|
3
|
+
*
|
|
4
|
+
* Writes .agentxchain/session.json at every governance boundary
|
|
5
|
+
* (turn acceptance, phase transition, gate approval, run completion)
|
|
6
|
+
* so that `agentxchain restart` can reconstruct dispatch context
|
|
7
|
+
* without any in-memory session state.
|
|
8
|
+
*
|
|
9
|
+
* Design rules:
|
|
10
|
+
* - Checkpoint writes are non-fatal: failures log a warning and do not
|
|
11
|
+
* block the governance operation.
|
|
12
|
+
* - The file is always overwritten, not appended.
|
|
13
|
+
* - run_id in session.json must agree with state.json; mismatch is a
|
|
14
|
+
* corruption signal.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs';
|
|
18
|
+
import { join, dirname } from 'path';
|
|
19
|
+
import { randomBytes } from 'crypto';
|
|
20
|
+
|
|
21
|
+
const SESSION_PATH = '.agentxchain/session.json';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Generate a new session ID.
|
|
25
|
+
*/
|
|
26
|
+
function generateSessionId() {
|
|
27
|
+
return `session_${randomBytes(8).toString('hex')}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Read the current session checkpoint, or null if none exists.
|
|
32
|
+
*/
|
|
33
|
+
export function readSessionCheckpoint(root) {
|
|
34
|
+
const filePath = join(root, SESSION_PATH);
|
|
35
|
+
if (!existsSync(filePath)) return null;
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(readFileSync(filePath, 'utf8'));
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Write or update the session checkpoint.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} root - project root
|
|
47
|
+
* @param {object} state - current governed state (from state.json)
|
|
48
|
+
* @param {string} reason - checkpoint reason (e.g. 'turn_accepted', 'phase_approved', 'run_completed')
|
|
49
|
+
* @param {object} [extra] - optional extra context fields
|
|
50
|
+
*/
|
|
51
|
+
export function writeSessionCheckpoint(root, state, reason, extra = {}) {
|
|
52
|
+
const filePath = join(root, SESSION_PATH);
|
|
53
|
+
try {
|
|
54
|
+
// Read existing session to preserve session_id across checkpoints in the same session
|
|
55
|
+
const existing = readSessionCheckpoint(root);
|
|
56
|
+
const sessionId = (existing && existing.run_id === state.run_id)
|
|
57
|
+
? existing.session_id
|
|
58
|
+
: generateSessionId();
|
|
59
|
+
|
|
60
|
+
const currentTurn = state.current_turn || null;
|
|
61
|
+
const lastTurnId = currentTurn?.id || currentTurn?.turn_id || state.last_completed_turn_id || null;
|
|
62
|
+
const lastRole = currentTurn?.role || currentTurn?.assigned_role || extra.role || null;
|
|
63
|
+
const lastPhase = state.current_phase || state.phase || null;
|
|
64
|
+
|
|
65
|
+
const checkpoint = {
|
|
66
|
+
session_id: sessionId,
|
|
67
|
+
run_id: state.run_id,
|
|
68
|
+
started_at: existing?.started_at || new Date().toISOString(),
|
|
69
|
+
last_checkpoint_at: new Date().toISOString(),
|
|
70
|
+
last_turn_id: lastTurnId,
|
|
71
|
+
last_phase: lastPhase,
|
|
72
|
+
last_role: lastRole,
|
|
73
|
+
run_status: state.status || null,
|
|
74
|
+
checkpoint_reason: reason,
|
|
75
|
+
agent_context: {
|
|
76
|
+
adapter: extra.adapter || null,
|
|
77
|
+
dispatch_dir: extra.dispatch_dir || null,
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const dir = dirname(filePath);
|
|
82
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
83
|
+
writeFileSync(filePath, JSON.stringify(checkpoint, null, 2) + '\n');
|
|
84
|
+
} catch (err) {
|
|
85
|
+
// Non-fatal — warn but do not block governance operations
|
|
86
|
+
if (process.env.AGENTXCHAIN_DEBUG) {
|
|
87
|
+
console.error(`[session-checkpoint] Warning: failed to write checkpoint: ${err.message}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export { SESSION_PATH };
|