maka-agent 0.2.0-dev.26.20260909 → 0.2.0-dev.27.20260910

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 (62) hide show
  1. package/dist/cli-core.js +21 -0
  2. package/dist/runtime-host-cli.js +43 -3
  3. package/dist/runtime-host-handoff-surface.js +10 -8
  4. package/dist/runtime-host-lifecycle-transaction.js +28 -3
  5. package/dist/runtime-host-local-source-retirement.js +1 -1
  6. package/dist/runtime-host-setup-command.js +29 -6
  7. package/dist/runtime-host-update-command.js +49 -5
  8. package/dist/session-export-command.js +72 -0
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@maka/core/dist/usage-stats/types.js +2 -0
  11. package/node_modules/@maka/core/dist/workhub-routing.js +126 -0
  12. package/node_modules/@maka/core/package.json +2 -1
  13. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +7 -3
  14. package/node_modules/@maka/runtime/dist/builtin-tools.js +21 -2
  15. package/node_modules/@maka/runtime/dist/plugin-agent-service.js +131 -0
  16. package/node_modules/@maka/runtime/dist/plugin-approval-service.js +33 -0
  17. package/node_modules/@maka/runtime/dist/plugin-attachment-service.js +53 -0
  18. package/node_modules/@maka/runtime/dist/plugin-command-service.js +100 -0
  19. package/node_modules/@maka/runtime/dist/plugin-data-services.js +332 -0
  20. package/node_modules/@maka/runtime/dist/plugin-fs-service.js +62 -0
  21. package/node_modules/@maka/runtime/dist/plugin-goal-service.js +61 -0
  22. package/node_modules/@maka/runtime/dist/plugin-invocation-signal.js +24 -0
  23. package/node_modules/@maka/runtime/dist/plugin-llm-service.js +85 -0
  24. package/node_modules/@maka/runtime/dist/plugin-lsp-service.js +94 -0
  25. package/node_modules/@maka/runtime/dist/plugin-scope-registry.js +91 -0
  26. package/node_modules/@maka/runtime/dist/plugin-session-query-service.js +71 -0
  27. package/node_modules/@maka/runtime/dist/plugin-shell-env-service.js +87 -0
  28. package/node_modules/@maka/runtime/dist/plugin-shell-service.js +74 -0
  29. package/node_modules/@maka/runtime/dist/plugin-skill-service.js +93 -0
  30. package/node_modules/@maka/runtime/dist/plugin-system-prompt-service.js +346 -0
  31. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +18 -52
  32. package/node_modules/@maka/runtime/dist/plugin-user-question-service.js +43 -0
  33. package/node_modules/@maka/runtime/dist/plugin-web-service.js +69 -0
  34. package/node_modules/@maka/runtime/dist/session-export.js +177 -0
  35. package/node_modules/@maka/runtime/package.json +18 -0
  36. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +67 -18
  37. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +46 -12
  38. package/node_modules/@maka/runtime-host/dist/operator/setup-frame.js +31 -21
  39. package/node_modules/@maka/runtime-host/dist/protocol/index.js +9 -1
  40. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +30 -5
  41. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +25 -23
  42. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +62 -4
  43. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +452 -7
  44. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +74 -0
  45. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +2 -2
  46. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +30 -0
  47. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +79 -16
  48. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +25 -4
  49. package/node_modules/@maka/runtime-host/dist/server/plugin-data-runtime.js +234 -0
  50. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  51. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +12 -0
  52. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +189 -92
  53. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -35
  54. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +92 -10
  55. package/node_modules/@maka/storage/dist/agent-run-store.js +54 -10
  56. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +13 -6
  57. package/node_modules/@maka/storage/dist/execution-stores.js +1 -1
  58. package/node_modules/@maka/storage/dist/session-bundle-policy.js +333 -30
  59. package/node_modules/@maka/storage/dist/session-store.js +2 -2
  60. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +12 -5
  61. package/node_modules/@maka/storage/package.json +2 -0
  62. package/package.json +1 -1
@@ -16,7 +16,8 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { copyFile, lstat, mkdir, readdir, realpath, rename, rm } from 'node:fs/promises';
19
+ import { lstat, mkdir, open, readdir, realpath, rename, rm, writeFile, } from 'node:fs/promises';
20
+ import { constants } from 'node:fs';
20
21
  import { randomUUID } from 'node:crypto';
21
22
  import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
22
23
  import { DatabaseSync } from 'node:sqlite';
@@ -24,7 +25,8 @@ import { decodeArtifactRecordJsons } from './artifact-metadata-codec.js';
24
25
  import { withArtifactWriterLock } from './artifact-writer-lock.js';
25
26
  import { withOfflineContextSnapshot, copyContextSnapshot, validateContextSnapshot, planContextSnapshotFiles, } from './context-offload-snapshot.js';
26
27
  import { CONTEXT_OFFLOAD_DATABASE_NAME, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME, } from './sqlite-context-offload-store.js';
27
- import { acquireOperationalStateDatabase, OPERATIONAL_STATE_DATABASE_NAME, } from './operational-state-store.js';
28
+ import { acquireOperationalStateDatabase, inspectOperationalStateSchema, OPERATIONAL_STATE_DATABASE_NAME, } from './operational-state-store.js';
29
+ import { TERMINAL_RUNTIME_EVENT_SQL } from './runtime-transcript-query.js';
28
30
  import { isSafeStorageId } from './storage-id.js';
29
31
  export const SESSION_BUNDLE_STATE_ENTRIES = [
30
32
  'artifacts',
@@ -54,10 +56,18 @@ export async function planSessionBundleExport(input) {
54
56
  assertRootsSeparate(stateRoot, configRoot, input.allowShared === true);
55
57
  assertRootsSeparate(stateRoot, destinationRoot, false);
56
58
  assertRootsSeparate(configRoot, destinationRoot, false);
57
- const databasePath = resolve(stateRoot, OPERATIONAL_STATE_DATABASE_NAME);
59
+ // Everything below is derived from `input.databasePath` -- the private copy
60
+ // the caller has already taken -- and never from the live database. The
61
+ // artifact and context locks do not fence ordinary Session and runtime
62
+ // writers, so a subtree, an artifact list and a manifest read from the live
63
+ // file would describe a different moment than the database that ships.
64
+ const databasePath = input.databasePath ?? resolve(stateRoot, OPERATIONAL_STATE_DATABASE_NAME);
58
65
  await assertRegularFile(databasePath, OPERATIONAL_STATE_DATABASE_NAME);
59
66
  const database = new DatabaseSync(databasePath, { readOnly: true });
60
67
  let artifacts;
68
+ let sessionIds;
69
+ let sourceSchema;
70
+ let connection;
61
71
  try {
62
72
  const session = database
63
73
  .prepare('SELECT 1 AS present FROM session_metadata WHERE session_id = ?')
@@ -65,10 +75,23 @@ export async function planSessionBundleExport(input) {
65
75
  if (!session) {
66
76
  throw new SessionBundleExportError('invalid_root', `Session bundle session does not exist: ${input.sessionId}`);
67
77
  }
78
+ sourceSchema = assertPortableSourceSchema(database);
79
+ sessionIds =
80
+ input.includeSubtree === true
81
+ ? collectSubagentSessionTree(database, input.sessionId)
82
+ : [input.sessionId];
83
+ const placeholders = sessionIds.map(() => '?').join(', ');
68
84
  const rows = database
69
- .prepare('SELECT record_json FROM artifact_records WHERE session_id = ? ORDER BY created_at, artifact_id')
70
- .all(input.sessionId);
85
+ .prepare(`SELECT record_json FROM artifact_records WHERE session_id IN (${placeholders}) ORDER BY created_at, artifact_id`)
86
+ .all(...sessionIds);
71
87
  artifacts = decodeArtifactRecordJsons(rows.map((row) => row.record_json));
88
+ const route = database
89
+ .prepare('SELECT llm_connection_slug, model FROM session_metadata WHERE session_id = ?')
90
+ .get(input.sessionId);
91
+ connection = {
92
+ llmConnectionSlug: String(route?.llm_connection_slug ?? ''),
93
+ model: String(route?.model ?? ''),
94
+ };
72
95
  }
73
96
  finally {
74
97
  database.close();
@@ -84,16 +107,24 @@ export async function planSessionBundleExport(input) {
84
107
  if (artifacts.length > 0) {
85
108
  entries.push({ relativePath: 'artifacts', kind: 'directory', source: 'copy' });
86
109
  for (const artifact of artifacts) {
87
- if (!isArtifactPathForSession(artifact.relativePath, input.sessionId)) {
88
- throw new SessionBundleExportError('path_escape', `Artifact path does not belong to session ${input.sessionId}: ${artifact.relativePath}`);
110
+ if (!sessionIds.some((id) => isArtifactPathForSession(artifact.relativePath, id))) {
111
+ throw new SessionBundleExportError('path_escape', `Artifact path does not belong to the exported subtree: ${artifact.relativePath}`);
89
112
  }
90
113
  const relativePath = `artifacts/${artifact.relativePath}`;
91
- await assertRegularFile(resolve(stateRoot, relativePath), relativePath);
114
+ // A record naming bytes the workspace does not have would produce a
115
+ // bundle whose own metadata points at nothing. Reported apart from a
116
+ // missing state root, which is a different mistake entirely.
117
+ await assertRegularFile(resolve(stateRoot, relativePath), relativePath).catch((error) => {
118
+ if (error instanceof SessionBundleExportError && error.code === 'invalid_root') {
119
+ throw new SessionBundleExportError('missing_entry', error.message, { cause: error });
120
+ }
121
+ throw error;
122
+ });
92
123
  entries.push({ relativePath, kind: 'file', source: 'copy' });
93
124
  }
94
125
  includedEntries.push('artifacts');
95
126
  }
96
- const contextFiles = await planContextSnapshotFiles(stateRoot, input.sessionId);
127
+ const contextFiles = await planContextSnapshotFiles(stateRoot, sessionIds);
97
128
  for (const relativePath of contextFiles) {
98
129
  entries.push({ relativePath, kind: 'file', source: 'context_snapshot' });
99
130
  }
@@ -108,6 +139,9 @@ export async function planSessionBundleExport(input) {
108
139
  configRoot,
109
140
  destinationRoot,
110
141
  sessionId: input.sessionId,
142
+ sessionIds,
143
+ sourceSchema,
144
+ connection,
111
145
  includedEntries,
112
146
  excludedEntries,
113
147
  entries,
@@ -115,28 +149,35 @@ export async function planSessionBundleExport(input) {
115
149
  }
116
150
  export async function exportSessionBundleState(input) {
117
151
  return withOfflineContextSnapshot(input.stateRoot, (contextLocked) => withArtifactWriterLock(input.stateRoot, async (stateRoot) => {
118
- const plan = await planSessionBundleExport({ ...input, stateRoot });
119
- await assertDestinationMissing(plan.destinationRoot);
120
- const stagingRoot = `${plan.destinationRoot}.${process.pid}.${randomUUID()}.tmp`;
152
+ const destinationRoot = resolve(input.destinationRoot);
153
+ await assertDestinationMissing(destinationRoot);
154
+ const stagingRoot = `${destinationRoot}.${process.pid}.${randomUUID()}.tmp`;
121
155
  try {
122
156
  await mkdir(stagingRoot, { recursive: true, mode: 0o700 });
157
+ // Take the private copy BEFORE anything is read. `lease.backup()` is
158
+ // what freezes the content; every decision after this -- schema, the
159
+ // subtree, the artifact list, quiescence, the manifest -- is made
160
+ // against this one file, so the bundle cannot describe two moments.
161
+ const databasePath = resolveInside(stagingRoot, OPERATIONAL_STATE_DATABASE_NAME);
162
+ await backupOperationalState(stateRoot, databasePath);
163
+ const plan = await planSessionBundleExport({ ...input, stateRoot, databasePath });
123
164
  for (const entry of plan.entries) {
124
- if (entry.source === 'context_snapshot')
165
+ if (entry.source === 'context_snapshot' || entry.source === 'filtered_runtime_sqlite') {
125
166
  continue;
167
+ }
126
168
  const destination = resolveInside(stagingRoot, entry.relativePath);
127
169
  if (entry.kind === 'directory') {
128
170
  await mkdir(destination, { recursive: true });
129
171
  continue;
130
172
  }
131
173
  await mkdir(dirname(destination), { recursive: true });
132
- if (entry.source === 'copy') {
133
- await copyFile(resolveInside(plan.stateRoot, entry.relativePath), destination);
134
- }
135
- else {
136
- await exportFilteredDatabase(plan.stateRoot, destination, plan.sessionId);
137
- }
174
+ await copyArtifactFile(plan.stateRoot, entry.relativePath, destination);
138
175
  }
139
- await copyContextSnapshot(stateRoot, stagingRoot, contextLocked, plan.sessionId);
176
+ await filterBackedUpDatabase(databasePath, plan.sessionIds, {
177
+ omitDiagnostics: input.omitDiagnostics === true,
178
+ requireQuiescent: input.requireQuiescent === true,
179
+ });
180
+ await copyContextSnapshot(stateRoot, stagingRoot, contextLocked, plan.sessionIds);
140
181
  await validateContextSnapshot(stagingRoot);
141
182
  await mkdir(dirname(plan.destinationRoot), { recursive: true });
142
183
  await rename(stagingRoot, plan.destinationRoot);
@@ -148,16 +189,90 @@ export async function exportSessionBundleState(input) {
148
189
  }
149
190
  }));
150
191
  }
151
- async function exportFilteredDatabase(stateRoot, destinationPath, sessionId) {
152
- const lease = acquireOperationalStateDatabase(stateRoot);
192
+ /**
193
+ * Take the private copy the whole export is derived from.
194
+ *
195
+ * `require_current` because an export must not migrate what it reads: opening
196
+ * the live database the ordinary way upgrades it in place, which turns a
197
+ * read-only operation into a write to someone else's workspace and leaves the
198
+ * manifest describing a version the source no longer has.
199
+ */
200
+ /**
201
+ * Copy one artifact without leaving the state root.
202
+ *
203
+ * Checking the final component is not enough: `artifacts/<sessionId>` can
204
+ * itself be a symlink, and `copyFile` follows ancestors — an artifact record
205
+ * that decodes perfectly can then pull in a file from outside the workspace.
206
+ * Every segment is checked, the final open refuses to follow a link, and the
207
+ * bytes are read from that descriptor rather than from the name.
208
+ *
209
+ * Node has no `openat`, so a segment swapped between its check and the open is
210
+ * not closed here. That window is narrowed, not eliminated; closing it needs a
211
+ * directory-relative open this runtime does not expose.
212
+ */
213
+ async function copyArtifactFile(stateRoot, relativePath, destination) {
214
+ const segments = relativePath.split('/').filter((segment) => segment.length > 0);
215
+ let walked = stateRoot;
216
+ for (const segment of segments) {
217
+ if (segment === '.' || segment === '..') {
218
+ throw new SessionBundleExportError('path_escape', `Artifact path segment is not safe`);
219
+ }
220
+ walked = resolveInside(walked, segment);
221
+ const metadata = await lstat(walked).catch((error) => {
222
+ if (error.code === 'ENOENT')
223
+ return undefined;
224
+ throw error;
225
+ });
226
+ if (!metadata) {
227
+ throw new SessionBundleExportError('missing_entry', `Missing ${relativePath}`);
228
+ }
229
+ if (metadata.isSymbolicLink()) {
230
+ throw new SessionBundleExportError('symlink', `Artifact path crosses a symlink at ${segment}`);
231
+ }
232
+ }
233
+ const handle = await open(walked, constants.O_RDONLY | constants.O_NOFOLLOW);
234
+ try {
235
+ const stats = await handle.stat();
236
+ if (!stats.isFile()) {
237
+ throw new SessionBundleExportError('unsupported_entry', `${relativePath} is not a regular file`);
238
+ }
239
+ await writeFile(destination, handle.createReadStream());
240
+ }
241
+ finally {
242
+ await handle.close().catch(() => { });
243
+ }
244
+ }
245
+ async function backupOperationalState(stateRoot, destinationPath) {
246
+ // A directory with no state database is not a workspace, which is a different
247
+ // mistake from a workspace whose schema this build cannot read.
248
+ await assertRegularFile(resolveInside(stateRoot, OPERATIONAL_STATE_DATABASE_NAME), OPERATIONAL_STATE_DATABASE_NAME);
249
+ let lease;
250
+ try {
251
+ lease = acquireOperationalStateDatabase(stateRoot, { schemaMigration: 'require_current' });
252
+ }
253
+ catch (error) {
254
+ throw new SessionBundleExportError('schema_unsupported', 'Session bundle source is not at the current schema', { cause: error });
255
+ }
153
256
  try {
154
257
  await lease.backup(destinationPath);
155
258
  }
156
259
  finally {
157
260
  lease.close();
158
261
  }
262
+ }
263
+ async function filterBackedUpDatabase(destinationPath, sessionIds, options) {
159
264
  const database = new DatabaseSync(destinationPath);
160
265
  try {
266
+ // Quiescence is asserted here, on the copy, not on the live database.
267
+ // `lease.backup()` is what freezes the content; a check made before it
268
+ // describes a state the bundle may no longer carry, and the artifact and
269
+ // context locks held around this do not keep a turn from starting. This is
270
+ // the only place where "what was checked" and "what ships" are the same
271
+ // bytes.
272
+ if (options.requireQuiescent) {
273
+ for (const sessionId of sessionIds)
274
+ assertSessionQuiescent(database, sessionId);
275
+ }
161
276
  database.exec('PRAGMA foreign_keys = OFF; BEGIN IMMEDIATE');
162
277
  const tables = database
163
278
  .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
@@ -171,19 +286,47 @@ async function exportFilteredDatabase(stateRoot, destinationPath, sessionId) {
171
286
  const names = new Set(columns
172
287
  .map((column) => column.name)
173
288
  .filter((name) => typeof name === 'string'));
174
- const sessionColumns = ['session_id', 'source_session_id', 'target_session_id'].filter((name) => names.has(name));
289
+ const sessionColumns = names.has(SESSION_ROW_OWNER_COLUMN)
290
+ ? [SESSION_ROW_OWNER_COLUMN]
291
+ : SESSION_LINK_COLUMNS.filter((name) => names.has(name));
175
292
  if (sessionColumns.length > 0) {
293
+ // Delete what the subtree does not own, keeping the original
294
+ // predicate's shape: a row survives only when EVERY session column it
295
+ // has names an exported Session. A link table row with one end outside
296
+ // the bundle would otherwise arrive pointing at a Session that is not
297
+ // there -- the reference is what makes it a link.
298
+ const placeholders = sessionIds.map(() => '?').join(', ');
176
299
  const predicate = sessionColumns
177
- .map((name) => `${quoteIdentifier(name)} <> ?`)
300
+ .map((name) => name === SESSION_ROW_OWNER_COLUMN
301
+ ? // An owner that is NULL owns nothing. Such a row cannot be
302
+ // attributed to any Session, so it is not this bundle's to
303
+ // carry -- keeping it shipped an unattributed usage row.
304
+ `(${quoteIdentifier(name)} IS NULL OR ${quoteIdentifier(name)} NOT IN (${placeholders}))`
305
+ : // A link endpoint that is NULL names no counterpart, which is
306
+ // not the same as naming one outside the bundle.
307
+ `(${quoteIdentifier(name)} IS NOT NULL AND ${quoteIdentifier(name)} NOT IN (${placeholders}))`)
178
308
  .join(' OR ');
179
309
  database
180
310
  .prepare(`DELETE FROM ${quoteIdentifier(row.name)} WHERE ${predicate}`)
181
- .run(...sessionColumns.map(() => sessionId));
311
+ .run(...sessionColumns.flatMap(() => sessionIds));
182
312
  }
183
313
  else if (!PORTABLE_DERIVED_TABLES.has(row.name)) {
184
314
  database.exec(`DELETE FROM ${quoteIdentifier(row.name)}`);
185
315
  }
186
316
  }
317
+ // Operational rows that describe a REQUEST rather than the conversation.
318
+ // None of them reach the model, and in a real Session they are the large
319
+ // majority of this table. The two record kinds that do decide what the
320
+ // model reads -- history_compact_checkpoint_recorded and
321
+ // model_projection_transition_recorded -- are deliberately not here.
322
+ if (options.omitDiagnostics) {
323
+ database
324
+ .prepare(`
325
+ DELETE FROM core_agent_run_events
326
+ WHERE event_type IN (${SESSION_BUNDLE_OMITTED_EVENT_TYPES.map(() => '?').join(', ')})
327
+ `)
328
+ .run(...SESSION_BUNDLE_OMITTED_EVENT_TYPES);
329
+ }
187
330
  database
188
331
  .prepare(`
189
332
  DELETE FROM tool_journal_events
@@ -224,11 +367,17 @@ async function exportFilteredDatabase(stateRoot, destinationPath, sessionId) {
224
367
  const foreignKeyViolation = database.prepare('PRAGMA foreign_key_check').get();
225
368
  if (foreignKeyViolation)
226
369
  throw new Error('Filtered session database has dangling references');
227
- const session = database
228
- .prepare('SELECT 1 AS present FROM session_metadata WHERE session_id = ?')
229
- .get(sessionId);
230
- if (!session)
231
- throw new Error(`Filtered session is missing: ${sessionId}`);
370
+ // DELETE frees pages, it does not erase them. Without this the bundle ships
371
+ // a file whose freelist still holds the excluded Sessions' bytes -- readable
372
+ // by anyone who opens it with something other than SQL.
373
+ database.exec('VACUUM');
374
+ for (const sessionId of sessionIds) {
375
+ const session = database
376
+ .prepare('SELECT 1 AS present FROM session_metadata WHERE session_id = ?')
377
+ .get(sessionId);
378
+ if (!session)
379
+ throw new Error(`Filtered session is missing: ${sessionId}`);
380
+ }
232
381
  database.exec('PRAGMA journal_mode = DELETE');
233
382
  }
234
383
  catch (error) {
@@ -242,6 +391,57 @@ async function exportFilteredDatabase(stateRoot, destinationPath, sessionId) {
242
391
  database.close();
243
392
  }
244
393
  }
394
+ /**
395
+ * `core_agent_run_events` types the bundle drops.
396
+ *
397
+ * They record how a request was shaped and how a stream behaved -- diagnostics
398
+ * for the machine that produced them, not the conversation. Any type absent
399
+ * from this list is carried, including one a later build introduces: an export
400
+ * moves rows, it does not interpret them.
401
+ */
402
+ export const SESSION_BUNDLE_OMITTED_EVENT_TYPES = [
403
+ 'provider_request_attempt_recorded',
404
+ 'provider_request_captured',
405
+ 'model_call_attempt_recorded',
406
+ 'model_stream_started',
407
+ 'model_stream_completed',
408
+ 'model_stream_failed',
409
+ 'send_diagnostics_recorded',
410
+ 'plan_context_resolved',
411
+ 'skill_catalog_built',
412
+ 'skill_searched',
413
+ 'skill_loaded',
414
+ 'skill_load_failed',
415
+ 'tool_searched',
416
+ 'request_composition_resolved',
417
+ 'trace_write_failed',
418
+ ];
419
+ /**
420
+ * Ownership, which is not the same thing as naming a Session.
421
+ *
422
+ * `session_id` says whose row this is. Everything else in this list is a
423
+ * Session column only on tables that have no `session_id` -- link tables, whose
424
+ * whole content is the pair they join, and which are meaningless when one end
425
+ * is outside the bundle.
426
+ *
427
+ * Keeping the two apart matters. `session_metadata.parent_session_id` is a
428
+ * lineage POINTER, not ownership: treating it as ownership deleted the very
429
+ * Session being exported whenever its branch source lay outside the subtree.
430
+ * And a link table whose columns are spelled `parent_session_id` /
431
+ * `child_session_id` -- `subagent_spawns`, the record of which tool call
432
+ * spawned each child -- looked Session-less and was emptied wholesale.
433
+ *
434
+ * Nullable columns count only when set, so a row that names no counterpart is
435
+ * not deleted for failing to name one.
436
+ */
437
+ const SESSION_ROW_OWNER_COLUMN = 'session_id';
438
+ const SESSION_LINK_COLUMNS = [
439
+ 'source_session_id',
440
+ 'target_session_id',
441
+ 'parent_session_id',
442
+ 'child_session_id',
443
+ 'root_session_id',
444
+ ];
245
445
  const PORTABLE_GLOBAL_TABLES = new Set([
246
446
  'operational_schema_migrations',
247
447
  'session_metadata_schema',
@@ -254,6 +454,109 @@ const PORTABLE_DERIVED_TABLES = new Set([
254
454
  'runtime_partial_segments',
255
455
  'core_interaction_outcomes',
256
456
  ]);
457
+ /**
458
+ * The Session and its subagent descendants, root first, siblings by id.
459
+ *
460
+ * `subagent_parent_session_id` is an ordinary column, not a constrained tree:
461
+ * nothing stops a row naming itself or an ancestor. Membership is tracked
462
+ * rather than assumed, so a cycle ends the walk instead of hanging it, and a
463
+ * Session reachable twice is exported once.
464
+ */
465
+ /**
466
+ * Refuse a source whose schema this build does not read.
467
+ *
468
+ * The filter runs `DELETE` over whatever tables the database happens to have,
469
+ * so a schema this build cannot read produces a bundle whose shape will not
470
+ * match what its manifest claims. The operational store is the authority on
471
+ * what "current" means -- a private list here went stale the moment a scope was
472
+ * added, and reported versions the source did not have.
473
+ */
474
+ function assertPortableSourceSchema(database) {
475
+ // The inspector validates every scope and says whether a migration is owed.
476
+ // It reports only some of them, so the manifest's numbers come from the
477
+ // registry the database keeps -- validated by the authority, reported from
478
+ // the source, and neither of them this build's constants.
479
+ const inspection = inspectOperationalStateSchema(database);
480
+ if (inspection.status !== 'current') {
481
+ throw new SessionBundleExportError('schema_unsupported', 'Session bundle source schema is not current');
482
+ }
483
+ const registered = {};
484
+ for (const row of database
485
+ .prepare('SELECT scope, version FROM operational_schema_migrations ORDER BY scope')
486
+ .all()) {
487
+ if (typeof row.scope === 'string' && typeof row.version === 'number') {
488
+ registered[row.scope] = row.version;
489
+ }
490
+ }
491
+ return registered;
492
+ }
493
+ /**
494
+ * Refuse a Session that is mid-turn.
495
+ *
496
+ * The writer locks around this export keep other writers out from here on, but
497
+ * they say nothing about work that was already in flight when it started. A
498
+ * partial stream snapshot, a tool dispatched without a settled result, or an
499
+ * invocation that never reached a terminal event each mean the bundle would
500
+ * carry half of something -- and half a turn is not a Session.
501
+ */
502
+ function assertSessionQuiescent(database, sessionId) {
503
+ const partials = database
504
+ .prepare('SELECT COUNT(*) AS count FROM runtime_partial_snapshots WHERE session_id = ?')
505
+ .get(sessionId);
506
+ if (Number(partials.count ?? 0) > 0) {
507
+ throw new SessionBundleExportError('session_active', `Session has a partial stream snapshot: ${sessionId}`);
508
+ }
509
+ // A tool that crossed the dispatch boundary and never settled. Its
510
+ // invocation can carry a terminal event -- the run failed -- while the
511
+ // operation itself is still prepared, so an invocation check does not see it.
512
+ // Same predicate the runtime store uses, so "unsettled" means one thing.
513
+ const unsettledOperations = database
514
+ .prepare(`
515
+ SELECT COUNT(*) AS count FROM tool_operations
516
+ WHERE current_state = 'prepared'
517
+ AND result_event_id IS NULL
518
+ AND dispatch_event_id IS NOT NULL
519
+ AND call_event_id IN (SELECT event_id FROM runtime_events WHERE session_id = ?)
520
+ `)
521
+ .get(sessionId);
522
+ if (Number(unsettledOperations.count ?? 0) > 0) {
523
+ throw new SessionBundleExportError('session_active', `Session has an unsettled tool operation: ${sessionId}`);
524
+ }
525
+ const openInvocations = database
526
+ .prepare(`
527
+ SELECT COUNT(*) AS count FROM (
528
+ SELECT DISTINCT invocation_id FROM runtime_events AS invocations
529
+ WHERE session_id = ?
530
+ AND NOT EXISTS (
531
+ SELECT 1 FROM runtime_events AS terminal
532
+ WHERE terminal.invocation_id = invocations.invocation_id
533
+ AND ${TERMINAL_RUNTIME_EVENT_SQL}
534
+ )
535
+ )
536
+ `)
537
+ .get(sessionId);
538
+ if (Number(openInvocations.count ?? 0) > 0) {
539
+ throw new SessionBundleExportError('session_active', `Session has an invocation with no terminal event: ${sessionId}`);
540
+ }
541
+ }
542
+ function collectSubagentSessionTree(database, rootSessionId) {
543
+ const ordered = [];
544
+ const seen = new Set([rootSessionId]);
545
+ const queue = [rootSessionId];
546
+ const children = database.prepare('SELECT session_id FROM session_metadata WHERE subagent_parent_session_id = ? ORDER BY session_id');
547
+ while (queue.length > 0) {
548
+ const sessionId = queue.shift();
549
+ ordered.push(sessionId);
550
+ for (const row of children.all(sessionId)) {
551
+ const childId = row.session_id;
552
+ if (typeof childId !== 'string' || seen.has(childId))
553
+ continue;
554
+ seen.add(childId);
555
+ queue.push(childId);
556
+ }
557
+ }
558
+ return ordered;
559
+ }
257
560
  export function isArtifactPathForSession(relativePath, sessionId) {
258
561
  const parts = relativePath.split(/[\\/]+/);
259
562
  return (parts.length >= 2 &&
@@ -446,9 +446,9 @@ class SqliteSessionStore {
446
446
  await this.ensureReady();
447
447
  await this.metadata.updateMessageAdmission(admission);
448
448
  }
449
- async reorderMessageAdmissions(sessionId, messageIds) {
449
+ async reorderMessageAdmissions(sessionId, messageIds, disposition = 'followup') {
450
450
  await this.ensureReady();
451
- await this.metadata.reorderMessageAdmissions(sessionId, messageIds);
451
+ await this.metadata.reorderMessageAdmissions(sessionId, messageIds, disposition);
452
452
  }
453
453
  async cancelMessageAdmissions(sessionId, messageIds) {
454
454
  await this.ensureReady();
@@ -1799,7 +1799,7 @@ export class SqliteSessionMetadataStore {
1799
1799
  }
1800
1800
  });
1801
1801
  }
1802
- async reorderMessageAdmissions(sessionId, messageIds) {
1802
+ async reorderMessageAdmissions(sessionId, messageIds, disposition = 'followup') {
1803
1803
  this.assertOpen();
1804
1804
  assertSafeSessionId(sessionId);
1805
1805
  const unique = [...new Set(messageIds)];
@@ -1813,13 +1813,13 @@ export class SqliteSessionMetadataStore {
1813
1813
  .prepare(`
1814
1814
  SELECT message_id
1815
1815
  FROM message_admissions
1816
- WHERE session_id = ? AND disposition = 'followup'
1816
+ WHERE session_id = ? AND disposition = ?
1817
1817
  ORDER BY queue_order, sequence
1818
1818
  `)
1819
- .all(sessionId);
1819
+ .all(sessionId, disposition);
1820
1820
  const current = rows.map((row) => row.message_id);
1821
1821
  const currentIds = new Set(current);
1822
- if (current.length !== unique.length ||
1822
+ if ((disposition === 'followup' && current.length !== unique.length) ||
1823
1823
  unique.some((messageId) => !currentIds.has(messageId))) {
1824
1824
  throw new SessionMetadataConflictError('Message admission reorder identity conflict');
1825
1825
  }
@@ -1828,7 +1828,14 @@ export class SqliteSessionMetadataStore {
1828
1828
  SET queue_order = ?
1829
1829
  WHERE session_id = ? AND message_id = ?
1830
1830
  `);
1831
- unique.forEach((messageId, index) => update.run(index, sessionId, messageId));
1831
+ // Older steering may already be in flight. Keep those entries in their
1832
+ // slots so recovery never interleaves them with a newly reordered batch.
1833
+ const selected = new Set(unique);
1834
+ let next = 0;
1835
+ current.forEach((messageId, index) => {
1836
+ const orderedId = selected.has(messageId) ? unique[next++] : messageId;
1837
+ update.run(index, sessionId, orderedId);
1838
+ });
1832
1839
  });
1833
1840
  }
1834
1841
  async readCoordinationTranscriptIndexState() {
@@ -43,6 +43,8 @@
43
43
  "./scheduled-task-store": "./dist/scheduled-task-store.js",
44
44
  "./quiescent-session-snapshot": "./dist/quiescent-session-snapshot.js",
45
45
  "./production-session-snapshot": "./dist/production-session-snapshot.js",
46
+ "./session-bundle-contract": "./dist/session-bundle-contract.js",
47
+ "./session-bundle-file-service": "./dist/session-bundle-file-service.js",
46
48
  "./session-bundle-policy": "./dist/session-bundle-policy.js",
47
49
  "./session-copy-cleanup": "./dist/session-copy-cleanup.js",
48
50
  "./session-todo-authority": "./dist/session-todo-authority.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maka-agent",
3
- "version": "0.2.0-dev.26.20260909",
3
+ "version": "0.2.0-dev.27.20260910",
4
4
  "description": "Apache Maka (Incubating) developer snapshot; not an Apache release.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",