jg-agent-hq 3.0.0 → 4.0.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.
Files changed (159) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +13 -13
  3. package/api/README.md +91 -102
  4. package/dist/actions/actions.js +15 -0
  5. package/dist/cli/cli.js +26 -35
  6. package/dist/cli/utilities.d.ts +1 -1
  7. package/dist/cli/utilities.js +8 -25
  8. package/dist/collaboration/dispatch/types.d.ts +2 -2
  9. package/dist/contracts/actions/types.d.ts +4 -4
  10. package/dist/contracts/browser/index.d.ts +1 -3
  11. package/dist/contracts/browser/index.js +1 -3
  12. package/dist/contracts/browser/types.d.ts +15 -1447
  13. package/dist/contracts/browser/types.js +3 -112
  14. package/dist/contracts/index.d.ts +7 -9
  15. package/dist/contracts/index.js +5 -7
  16. package/dist/contracts/plans/index.d.ts +4 -6
  17. package/dist/contracts/plans/index.js +2 -4
  18. package/dist/contracts/plans/types.d.ts +38 -905
  19. package/dist/contracts/plans/types.js +13 -139
  20. package/dist/contracts/sessions/index.d.ts +2 -0
  21. package/dist/contracts/sessions/index.js +2 -0
  22. package/dist/contracts/sessions/types.d.ts +101 -0
  23. package/dist/contracts/sessions/types.js +43 -0
  24. package/dist/contracts/types.d.ts +461 -1047
  25. package/dist/contracts/types.js +8 -0
  26. package/dist/index.d.ts +2 -4
  27. package/dist/index.js +1 -3
  28. package/dist/plans/admission.d.ts +6 -6
  29. package/dist/plans/admission.js +1 -1
  30. package/dist/plans/authority.js +15 -13
  31. package/dist/plans/documents.d.ts +3 -17
  32. package/dist/plans/documents.js +6 -62
  33. package/dist/plans/files.d.ts +2 -2
  34. package/dist/plans/files.js +2 -4
  35. package/dist/plans/finalization.d.ts +6 -8
  36. package/dist/plans/finalization.js +25 -26
  37. package/dist/plans/index.d.ts +2 -3
  38. package/dist/plans/index.js +1 -2
  39. package/dist/plans/plans.d.ts +8 -8
  40. package/dist/plans/plans.js +33 -82
  41. package/dist/plans/projections.d.ts +2 -2
  42. package/dist/plans/projections.js +44 -82
  43. package/dist/plans/revisions.d.ts +4 -5
  44. package/dist/plans/revisions.js +5 -44
  45. package/dist/plans/types.d.ts +0 -281
  46. package/dist/plans/types.js +2 -30
  47. package/dist/plans/utilities.js +2 -11
  48. package/dist/providers/claude/agents/agents.d.ts +16 -0
  49. package/dist/providers/claude/agents/agents.js +80 -0
  50. package/dist/providers/claude/agents/constants.d.ts +3 -0
  51. package/dist/providers/claude/agents/constants.js +4 -0
  52. package/dist/providers/claude/agents/index.d.ts +1 -0
  53. package/dist/providers/claude/agents/index.js +2 -0
  54. package/dist/providers/claude/agents/types.d.ts +14 -0
  55. package/dist/providers/claude/agents/types.js +9 -0
  56. package/dist/providers/claude/history/history.model.js +2 -0
  57. package/dist/providers/claude/history/types.d.ts +92 -368
  58. package/dist/providers/claude/index.d.ts +1 -0
  59. package/dist/providers/claude/index.js +2 -0
  60. package/dist/providers/codex/adapter.d.ts +1 -1
  61. package/dist/providers/codex/adapter.js +26 -3
  62. package/dist/providers/codex/codex.js +47 -18
  63. package/dist/providers/codex/events.d.ts +2 -1
  64. package/dist/providers/codex/events.js +8 -3
  65. package/dist/providers/codex/index.d.ts +1 -1
  66. package/dist/providers/codex/index.js +1 -1
  67. package/dist/providers/codex/rpc.d.ts +9 -4
  68. package/dist/providers/codex/rpc.js +109 -47
  69. package/dist/providers/codex/skill-roots/constants.d.ts +4 -0
  70. package/dist/providers/codex/skill-roots/constants.js +7 -0
  71. package/dist/providers/codex/skill-roots/index.d.ts +2 -0
  72. package/dist/providers/codex/skill-roots/index.js +4 -0
  73. package/dist/providers/codex/skill-roots/skill-roots.d.ts +35 -0
  74. package/dist/providers/codex/skill-roots/skill-roots.js +93 -0
  75. package/dist/providers/codex/transformers.d.ts +3 -1
  76. package/dist/providers/codex/transformers.js +12 -1
  77. package/dist/providers/codex/types.d.ts +4 -0
  78. package/dist/providers/codex/types.js +4 -1
  79. package/dist/providers/codex/websocket/constants.d.ts +11 -0
  80. package/dist/providers/codex/websocket/constants.js +18 -0
  81. package/dist/providers/codex/websocket/index.d.ts +1 -0
  82. package/dist/providers/codex/websocket/index.js +2 -0
  83. package/dist/providers/codex/websocket/websocket.d.ts +7 -0
  84. package/dist/providers/codex/websocket/websocket.js +219 -0
  85. package/dist/providers/index.d.ts +2 -2
  86. package/dist/providers/index.js +1 -1
  87. package/dist/providers/process.d.ts +2 -2
  88. package/dist/providers/process.js +37 -4
  89. package/dist/providers/registry/registry.js +2 -1
  90. package/dist/providers/types.d.ts +25 -2
  91. package/dist/runtime/runtime.d.ts +0 -2
  92. package/dist/runtime/runtime.js +11 -5
  93. package/dist/runtime/state/state.d.ts +1 -1
  94. package/dist/runtime/state/state.js +2 -2
  95. package/dist/runtime/types.d.ts +0 -2
  96. package/dist/runtime/types.js +0 -3
  97. package/dist/sessions/sessions.js +2 -0
  98. package/dist/snapshots/archive/archive.d.ts +29 -0
  99. package/dist/snapshots/archive/archive.js +342 -0
  100. package/dist/snapshots/archive/constants.d.ts +5 -0
  101. package/dist/snapshots/archive/constants.js +8 -0
  102. package/dist/snapshots/archive/index.d.ts +1 -0
  103. package/dist/snapshots/archive/index.js +2 -0
  104. package/dist/snapshots/artifacts.d.ts +10 -1
  105. package/dist/snapshots/artifacts.js +38 -13
  106. package/dist/snapshots/capture.d.ts +3 -2
  107. package/dist/snapshots/capture.js +29 -13
  108. package/dist/snapshots/database.d.ts +2 -2
  109. package/dist/snapshots/database.js +30 -14
  110. package/dist/snapshots/fences.d.ts +4 -9
  111. package/dist/snapshots/fences.js +9 -22
  112. package/dist/snapshots/index.d.ts +1 -2
  113. package/dist/snapshots/index.js +2 -3
  114. package/dist/snapshots/snapshots.d.ts +6 -5
  115. package/dist/snapshots/snapshots.js +13 -13
  116. package/dist/snapshots/snapshots.worker.js +1 -1
  117. package/dist/snapshots/types.d.ts +26 -5
  118. package/dist/snapshots/types.js +15 -4
  119. package/dist/storage/schema/constants.d.ts +2 -2
  120. package/dist/storage/schema/constants.js +9 -3
  121. package/dist/storage/schema/index.d.ts +2 -3
  122. package/dist/storage/schema/index.js +4 -3
  123. package/dist/storage/schema/schema.d.ts +10 -8
  124. package/dist/storage/schema/schema.js +22 -36
  125. package/dist/storage/schema/types.d.ts +1 -11
  126. package/dist/storage/schema/types.js +2 -2
  127. package/dist/storage/storage.d.ts +1 -1
  128. package/dist/storage/storage.js +2 -2
  129. package/dist/store/collaboration/collaboration.model.d.ts +2 -2
  130. package/dist/store/control/types.d.ts +16 -16
  131. package/dist/store/plans/plans.model.d.ts +3 -105
  132. package/dist/store/plans/plans.model.js +6 -46
  133. package/dist/store/schema.d.ts +0 -2
  134. package/dist/store/schema.js +6 -25
  135. package/dist/store/schema.sql +90 -16
  136. package/dist/store/sessions/index.d.ts +1 -0
  137. package/dist/store/sessions/index.js +2 -0
  138. package/dist/store/sessions/sessions.model.d.ts +28 -0
  139. package/dist/store/sessions/sessions.model.js +105 -0
  140. package/dist/store/store.d.ts +0 -2
  141. package/dist/store/store.js +13 -9
  142. package/dist/store/store.worker.js +16 -11
  143. package/dist/store/types.d.ts +134 -513
  144. package/dist/store/types.js +21 -7
  145. package/docs/recovery.md +6 -16
  146. package/errors/README.md +30 -36
  147. package/package.json +1 -1
  148. package/dist/plans/reconciliation.d.ts +0 -34
  149. package/dist/plans/reconciliation.js +0 -246
  150. package/dist/storage/schema/v1-to-v2.sql +0 -1
  151. package/dist/storage/schema/v1.sql +0 -538
  152. package/dist/storage/upgrade/index.d.ts +0 -2
  153. package/dist/storage/upgrade/index.js +0 -2
  154. package/dist/storage/upgrade/types.d.ts +0 -61
  155. package/dist/storage/upgrade/types.js +0 -42
  156. package/dist/storage/upgrade/upgrade.d.ts +0 -33
  157. package/dist/storage/upgrade/upgrade.js +0 -196
  158. package/dist/storage/upgrade/upgrade.worker.d.ts +0 -1
  159. package/dist/storage/upgrade/upgrade.worker.js +0 -220
@@ -1,33 +0,0 @@
1
- import { type IHqStorageUpgradeOptions, type IHqStorageUpgradeResult } from './types.js';
2
- /**
3
- * Upgrades existing offline storage only after a fully verified local backup.
4
- * Stop HQ/native children and all independent database/plan writers first. No owner is reclaimed.
5
- * An uncertain error requires explicit reinspection; this operation never reverses or replays DDL.
6
- * @returns The committed upgrade or an untouched current-version observation, after worker exit.
7
- * @throws
8
- * - JG_AGENT_HQ_REQUEST_INVALID: The HQ request is invalid
9
- * - JG_AGENT_HQ_STATE_DIRECTORY_UNSAFE: The HQ state directory is unsafe
10
- * - JG_AGENT_HQ_STATE_FILE_UNSAFE: The HQ state file is unsafe
11
- * - JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE: The HQ action key is unavailable
12
- * - JG_AGENT_HQ_RUNTIME_ALREADY_OWNED: The HQ runtime is already owned
13
- * - JG_AGENT_HQ_RUNTIME_OWNER_UNVERIFIABLE: The HQ runtime owner is unverifiable
14
- * - JG_AGENT_HQ_RUNTIME_NOT_RUNNING: The HQ runtime is not running
15
- * - JG_AGENT_HQ_LOCK_UNSUPPORTED_PLATFORM: The HQ lock requires Linux or macOS
16
- * - JG_AGENT_HQ_RUNTIME_DIRECTORY_INVALID: The HQ runtime directory must be a real directory
17
- * - JG_AGENT_HQ_RUNTIME_DIRECTORY_PERMISSIONS: The HQ runtime directory must be private and owned by the current user
18
- * - JG_AGENT_HQ_LOCK_FILE_INVALID: The HQ lock must be a regular file
19
- * - JG_AGENT_HQ_LOCK_FILE_PERMISSIONS: The HQ lock must be private and owned by the current user
20
- * - JG_AGENT_HQ_LOCK_OWNER_OVERSIZED: The HQ lock owner exceeds the supported size
21
- * - JG_AGENT_HQ_LOCK_OWNER_UNREADABLE: The HQ lock owner could not be read. Inspect .runtime/hq.lock
22
- * - JG_AGENT_HQ_LOCK_OWNER_INCOMPLETE: The HQ lock owner is incomplete. Inspect .runtime/hq.lock and remove it only after its owner stopped
23
- * - JG_AGENT_HQ_LOCK_OWNER_INACTIVE: The HQ lock has an inactive owner
24
- * - JG_AGENT_HQ_LOCK_OWNER_UNVERIFIABLE: The HQ lock owner could not be verified
25
- * - JG_AGENT_HQ_LOCK_TIMEOUT: Timed out waiting for the HQ lock
26
- * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
27
- * - JG_AGENT_HQ_STORAGE_VERSION_UNSUPPORTED: The HQ storage version is unsupported
28
- * - JG_AGENT_HQ_STORAGE_UPGRADE_FAILED: The HQ storage upgrade failed
29
- * - JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN: The HQ storage upgrade requires reconciliation
30
- * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
31
- * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
32
- */
33
- export declare const upgradeHqStorage: (options: IHqStorageUpgradeOptions) => Promise<IHqStorageUpgradeResult>;
@@ -1,196 +0,0 @@
1
- import { lstat, realpath } from 'node:fs/promises';
2
- import { dirname } from 'node:path';
3
- import { Worker } from 'node:worker_threads';
4
- import { hashValue } from 'jg-crypto';
5
- import { Exception, extractMessage, hasErrorCode } from 'jg-exception';
6
- import { assertPrivateDirectory } from 'jg-fs';
7
- import { isPrivateOwner } from '../../locks/index.js';
8
- import { claimRuntimeOwner, isWithinWorkspace, readExistingState, resolveAllowedRoots, } from '../../runtime/state/index.js';
9
- import { UpgradeOptionsSchema, UpgradeWorkerResponseSchema, } from './types.js';
10
- /**
11
- * Waits for actual exit, including when a worker reports an error. There is no size-based deadline.
12
- * @returns The validated result after confirmed worker shutdown.
13
- * @throws
14
- * - JG_AGENT_HQ_REQUEST_INVALID: The HQ request is invalid
15
- * - JG_AGENT_HQ_STATE_DIRECTORY_UNSAFE: The HQ state directory is unsafe
16
- * - JG_AGENT_HQ_STATE_FILE_UNSAFE: The HQ state file is unsafe
17
- * - JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE: The HQ action key is unavailable
18
- * - JG_AGENT_HQ_LOCK_UNSUPPORTED_PLATFORM: The HQ lock requires Linux or macOS
19
- * - JG_AGENT_HQ_RUNTIME_DIRECTORY_INVALID: The HQ runtime directory must be a real directory
20
- * - JG_AGENT_HQ_RUNTIME_DIRECTORY_PERMISSIONS: The HQ runtime directory must be private and owned by the current user
21
- * - JG_AGENT_HQ_LOCK_FILE_INVALID: The HQ lock must be a regular file
22
- * - JG_AGENT_HQ_LOCK_FILE_PERMISSIONS: The HQ lock must be private and owned by the current user
23
- * - JG_AGENT_HQ_LOCK_OWNER_OVERSIZED: The HQ lock owner exceeds the supported size
24
- * - JG_AGENT_HQ_LOCK_OWNER_UNREADABLE: The HQ lock owner could not be read. Inspect .runtime/hq.lock
25
- * - JG_AGENT_HQ_LOCK_OWNER_INCOMPLETE: The HQ lock owner is incomplete. Inspect .runtime/hq.lock and remove it only after its owner stopped
26
- * - JG_AGENT_HQ_LOCK_OWNER_INACTIVE: The HQ lock has an inactive owner
27
- * - JG_AGENT_HQ_LOCK_OWNER_UNVERIFIABLE: The HQ lock owner could not be verified
28
- * - JG_AGENT_HQ_LOCK_TIMEOUT: Timed out waiting for the HQ lock
29
- * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
30
- * - JG_AGENT_HQ_STORAGE_VERSION_UNSUPPORTED: The HQ storage version is unsupported
31
- * - JG_AGENT_HQ_STORAGE_UPGRADE_FAILED: The HQ storage upgrade failed
32
- * - JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN: The HQ storage upgrade requires reconciliation
33
- * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
34
- * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
35
- */
36
- const runUpgradeWorker = async (input) => {
37
- let worker;
38
- try {
39
- worker = new Worker(new URL('./upgrade.worker.js', import.meta.url), {
40
- execArgv: process.execArgv.filter((argument, index, args) => argument !== '--input-type' &&
41
- !argument.startsWith('--input-type=') &&
42
- args[index - 1] !== '--input-type'),
43
- workerData: input,
44
- });
45
- }
46
- catch (cause) {
47
- throw new Exception(`The HQ storage upgrade failed: ${extractMessage(cause)}`, {
48
- code: 'JG_AGENT_HQ_STORAGE_UPGRADE_FAILED',
49
- data: { kind: 'operation-failed', phase: 'worker-start', backupDirectory: null },
50
- cause,
51
- });
52
- }
53
- return new Promise((resolveResult, rejectResult) => {
54
- let response;
55
- let failure;
56
- let hasDuplicateResponse = false;
57
- worker.on('message', (message) => {
58
- const parsed = UpgradeWorkerResponseSchema.safeParse(message);
59
- if (response)
60
- hasDuplicateResponse = true;
61
- else if (!parsed.success)
62
- failure = parsed.error;
63
- else
64
- response = parsed.data;
65
- });
66
- worker.once('error', (cause) => {
67
- failure = cause;
68
- });
69
- worker.once('exit', (code) => {
70
- if (failure || hasDuplicateResponse || code !== 0 || !response)
71
- rejectResult(new Exception(`The HQ storage upgrade requires reconciliation: ${failure ? extractMessage(failure) : hasDuplicateResponse ? 'Duplicate upgrade worker result' : `Worker exited (${code})`}`, {
72
- code: 'JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN',
73
- data: {
74
- kind: 'operation-failed',
75
- phase: 'worker-exit',
76
- backupDirectory: input.backupDirectory,
77
- },
78
- cause: failure,
79
- }));
80
- else if (response.kind === 'error')
81
- rejectResult(new Exception(response.message, {
82
- code: response.code,
83
- data: response.data,
84
- cause: response.cause,
85
- }));
86
- else
87
- resolveResult(response.result);
88
- });
89
- });
90
- };
91
- /**
92
- * Upgrades existing offline storage only after a fully verified local backup.
93
- * Stop HQ/native children and all independent database/plan writers first. No owner is reclaimed.
94
- * An uncertain error requires explicit reinspection; this operation never reverses or replays DDL.
95
- * @returns The committed upgrade or an untouched current-version observation, after worker exit.
96
- * @throws
97
- * - JG_AGENT_HQ_REQUEST_INVALID: The HQ request is invalid
98
- * - JG_AGENT_HQ_STATE_DIRECTORY_UNSAFE: The HQ state directory is unsafe
99
- * - JG_AGENT_HQ_STATE_FILE_UNSAFE: The HQ state file is unsafe
100
- * - JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE: The HQ action key is unavailable
101
- * - JG_AGENT_HQ_RUNTIME_ALREADY_OWNED: The HQ runtime is already owned
102
- * - JG_AGENT_HQ_RUNTIME_OWNER_UNVERIFIABLE: The HQ runtime owner is unverifiable
103
- * - JG_AGENT_HQ_RUNTIME_NOT_RUNNING: The HQ runtime is not running
104
- * - JG_AGENT_HQ_LOCK_UNSUPPORTED_PLATFORM: The HQ lock requires Linux or macOS
105
- * - JG_AGENT_HQ_RUNTIME_DIRECTORY_INVALID: The HQ runtime directory must be a real directory
106
- * - JG_AGENT_HQ_RUNTIME_DIRECTORY_PERMISSIONS: The HQ runtime directory must be private and owned by the current user
107
- * - JG_AGENT_HQ_LOCK_FILE_INVALID: The HQ lock must be a regular file
108
- * - JG_AGENT_HQ_LOCK_FILE_PERMISSIONS: The HQ lock must be private and owned by the current user
109
- * - JG_AGENT_HQ_LOCK_OWNER_OVERSIZED: The HQ lock owner exceeds the supported size
110
- * - JG_AGENT_HQ_LOCK_OWNER_UNREADABLE: The HQ lock owner could not be read. Inspect .runtime/hq.lock
111
- * - JG_AGENT_HQ_LOCK_OWNER_INCOMPLETE: The HQ lock owner is incomplete. Inspect .runtime/hq.lock and remove it only after its owner stopped
112
- * - JG_AGENT_HQ_LOCK_OWNER_INACTIVE: The HQ lock has an inactive owner
113
- * - JG_AGENT_HQ_LOCK_OWNER_UNVERIFIABLE: The HQ lock owner could not be verified
114
- * - JG_AGENT_HQ_LOCK_TIMEOUT: Timed out waiting for the HQ lock
115
- * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
116
- * - JG_AGENT_HQ_STORAGE_VERSION_UNSUPPORTED: The HQ storage version is unsupported
117
- * - JG_AGENT_HQ_STORAGE_UPGRADE_FAILED: The HQ storage upgrade failed
118
- * - JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN: The HQ storage upgrade requires reconciliation
119
- * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
120
- * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
121
- */
122
- export const upgradeHqStorage = async (options) => {
123
- const parsed = UpgradeOptionsSchema.safeParse(options);
124
- if (!parsed.success)
125
- throw new Exception('The HQ request is invalid', {
126
- code: 'JG_AGENT_HQ_REQUEST_INVALID',
127
- data: { kind: 'invalid-request' },
128
- cause: parsed.error,
129
- });
130
- const selected = parsed.data;
131
- const state = await readExistingState(selected.stateRoot);
132
- const allowedRoots = await resolveAllowedRoots(selected.allowedRoots);
133
- const coordinationRoot = selected.coordinationRoot
134
- ? (await resolveAllowedRoots([selected.coordinationRoot]))[0]
135
- : state.stateRoot;
136
- try {
137
- await assertPrivateDirectory(dirname(selected.backupDirectory));
138
- if ((await realpath(dirname(selected.backupDirectory))) !== dirname(selected.backupDirectory) ||
139
- !isPrivateOwner(await lstat(dirname(selected.backupDirectory))) ||
140
- isWithinWorkspace(state.stateRoot, selected.backupDirectory) ||
141
- isWithinWorkspace(selected.backupDirectory, state.stateRoot))
142
- throw new Exception('The HQ snapshot is invalid', {
143
- code: 'JG_AGENT_HQ_SNAPSHOT_INVALID',
144
- data: { kind: 'invalid-request' },
145
- });
146
- }
147
- catch (cause) {
148
- if (hasErrorCode(cause, 'JG_AGENT_HQ_SNAPSHOT_INVALID'))
149
- throw cause;
150
- throw new Exception(`The HQ snapshot is invalid: ${extractMessage(cause)}`, {
151
- code: 'JG_AGENT_HQ_SNAPSHOT_INVALID',
152
- data: { kind: 'invalid-request' },
153
- cause,
154
- });
155
- }
156
- const ownership = await claimRuntimeOwner(state.stateRoot, 'upgrade-storage');
157
- let result;
158
- let failure;
159
- try {
160
- const current = await readExistingState(state.stateRoot);
161
- if (hashValue(current.actionKey) !== hashValue(state.actionKey))
162
- throw new Exception('The HQ action key is unavailable', {
163
- code: 'JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE',
164
- data: { kind: 'state-conflict' },
165
- });
166
- result = await runUpgradeWorker({
167
- ...selected,
168
- allowedRoots,
169
- coordinationRoot,
170
- actionKeyHash: hashValue(current.actionKey),
171
- });
172
- }
173
- catch (cause) {
174
- failure = cause;
175
- }
176
- try {
177
- // runUpgradeWorker settles only after exit; a worker that has not exited keeps this owner
178
- await ownership.release();
179
- }
180
- catch (cause) {
181
- throw new Exception(`The HQ storage upgrade requires reconciliation: ${extractMessage(cause)}`, {
182
- code: 'JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN',
183
- data: {
184
- kind: 'operation-failed',
185
- phase: 'owner-release',
186
- backupDirectory: result?.backupDirectory ?? selected.backupDirectory,
187
- },
188
- cause: failure
189
- ? new AggregateError([failure, cause], 'Upgrade owner release failed')
190
- : cause,
191
- });
192
- }
193
- if (failure)
194
- throw failure;
195
- return result;
196
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,220 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { DatabaseSync, backup } from 'node:sqlite';
3
- import { parentPort, workerData } from 'node:worker_threads';
4
- import { hashValue } from 'jg-crypto';
5
- import { Exception, extractMessage, isException } from 'jg-exception';
6
- import { z } from 'zod';
7
- import { getErrorKind } from '../../errors/index.js';
8
- import { acquireHqLock } from '../../locks/index.js';
9
- import { isWithinWorkspace, readExistingState } from '../../runtime/state/index.js';
10
- import { captureSnapshot, verifySnapshot } from '../../snapshots/index.js';
11
- import { CURRENT_SCHEMA_VERSION, STORAGE_MIGRATIONS, STORAGE_SCHEMAS, readStorageSchema, } from '../schema/index.js';
12
- import { STORAGE_CONNECTION_SETTINGS } from '../constants.js';
13
- import { UpgradeWorkerInputSchema, UpgradeResultSchema, } from './types.js';
14
- const port = parentPort;
15
- if (!port)
16
- throw new Exception('The HQ storage upgrade failed', {
17
- code: 'JG_AGENT_HQ_STORAGE_UPGRADE_FAILED',
18
- });
19
- let phase = 'preflight';
20
- let verifiedBackup = null;
21
- let database;
22
- let release;
23
- let hasCommitted = false;
24
- let result;
25
- let failure;
26
- try {
27
- const input = UpgradeWorkerInputSchema.parse(workerData);
28
- const state = await readExistingState(input.stateRoot);
29
- if (hashValue(state.actionKey) !== input.actionKeyHash)
30
- throw new Exception('The HQ action key is unavailable', {
31
- code: 'JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE',
32
- data: { kind: 'state-conflict' },
33
- });
34
- database = new DatabaseSync(state.databasePath, {
35
- readOnly: true,
36
- enableForeignKeyConstraints: true,
37
- timeout: STORAGE_CONNECTION_SETTINGS.busyTimeoutMs,
38
- });
39
- const observed = readStorageSchema(database, input.actionKeyHash);
40
- if (!observed)
41
- throw new Exception('The HQ storage is invalid', {
42
- code: 'JG_AGENT_HQ_STORAGE_INVALID',
43
- data: { kind: 'state-conflict' },
44
- });
45
- const target = STORAGE_SCHEMAS.find((entry) => entry.version === CURRENT_SCHEMA_VERSION);
46
- const base = {
47
- stateRoot: state.stateRoot,
48
- fromVersion: observed.schema.version,
49
- toVersion: target.version,
50
- fromSchemaHash: observed.schema.hash,
51
- toSchemaHash: target.hash,
52
- };
53
- if (observed.schema.version === target.version) {
54
- result = { ...base, state: 'current', backupDirectory: null };
55
- }
56
- else {
57
- // validate every selected source before reserving output; pages remain bounded for growing registries
58
- let after = '';
59
- for (;;) {
60
- const page = database
61
- .prepare('SELECT directory FROM hq_plan_registration WHERE directory > ? ORDER BY directory LIMIT 128')
62
- .all(after);
63
- for (const row of page) {
64
- const directory = z.string().parse(row.directory);
65
- if (isWithinWorkspace(input.backupDirectory, directory) ||
66
- isWithinWorkspace(directory, input.backupDirectory))
67
- throw new Exception('The HQ snapshot is invalid', {
68
- code: 'JG_AGENT_HQ_SNAPSHOT_INVALID',
69
- data: { kind: 'invalid-request' },
70
- });
71
- after = directory;
72
- }
73
- if (page.length < 128)
74
- break;
75
- }
76
- database.close();
77
- database = undefined;
78
- phase = 'metadata-lock';
79
- release = await acquireHqLock(input.coordinationRoot ?? state.stateRoot, 'upgrade-storage', {
80
- waitTimeoutMs: 0,
81
- });
82
- const checkpoint = await readExistingState(state.stateRoot);
83
- if (hashValue(checkpoint.actionKey) !== input.actionKeyHash)
84
- throw new Exception('The HQ action key is unavailable', {
85
- code: 'JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE',
86
- data: { kind: 'state-conflict' },
87
- });
88
- database = new DatabaseSync(state.databasePath, {
89
- enableForeignKeyConstraints: true,
90
- timeout: STORAGE_CONNECTION_SETTINGS.busyTimeoutMs,
91
- });
92
- database.exec(`PRAGMA journal_mode = ${STORAGE_CONNECTION_SETTINGS.journalMode}; PRAGMA synchronous = ${STORAGE_CONNECTION_SETTINGS.synchronous}; BEGIN IMMEDIATE`);
93
- const locked = readStorageSchema(database, input.actionKeyHash);
94
- if (locked?.schema.version !== observed.schema.version ||
95
- locked.schema.hash !== observed.schema.hash)
96
- throw new Exception('The HQ storage is invalid', {
97
- code: 'JG_AGENT_HQ_STORAGE_INVALID',
98
- data: { kind: 'state-conflict' },
99
- });
100
- phase = 'backup';
101
- const writer = database;
102
- await captureSnapshot({
103
- stateRoot: state.stateRoot,
104
- coordinationRoot: input.coordinationRoot ?? state.stateRoot,
105
- allowedRoots: input.allowedRoots,
106
- actionKeyHash: input.actionKeyHash,
107
- schemaHash: observed.schema.hash,
108
- readPlans: async (cursor) => writer
109
- .prepare('SELECT directory FROM hq_plan_registration WHERE directory > ? ORDER BY directory LIMIT 128')
110
- .all(cursor)
111
- .map((row) => z.string().parse(row.directory)),
112
- backupDatabase: async (destination) => {
113
- // an active writer cannot be the source of sqlite3_backup; readers see the locked committed state
114
- const source = new DatabaseSync(state.databasePath, {
115
- readOnly: true,
116
- enableForeignKeyConstraints: true,
117
- });
118
- try {
119
- await backup(source, destination);
120
- }
121
- finally {
122
- source.close();
123
- }
124
- const copy = new DatabaseSync(destination);
125
- try {
126
- copy.exec('PRAGMA journal_mode = DELETE');
127
- }
128
- finally {
129
- copy.close();
130
- }
131
- },
132
- verify: verifySnapshot,
133
- }, input.backupDirectory);
134
- verifiedBackup = input.backupDirectory;
135
- phase = 'migration';
136
- const edge = STORAGE_MIGRATIONS.find((entry) => entry.fromVersion === observed.schema.version && entry.toVersion === target.version);
137
- if (!edge)
138
- throw new Exception('The HQ storage version is unsupported', {
139
- code: 'JG_AGENT_HQ_STORAGE_VERSION_UNSUPPORTED',
140
- data: { kind: 'state-conflict' },
141
- });
142
- database.exec(await readFile(edge.source, 'utf8'));
143
- database
144
- .prepare('UPDATE hq_schema SET schema_version = ?, schema_hash = ? WHERE id = 1')
145
- .run(target.version, target.hash);
146
- const migrated = readStorageSchema(database, input.actionKeyHash);
147
- if (migrated?.schema.version !== target.version || migrated.schema.hash !== target.hash)
148
- throw new Exception('The HQ storage is invalid', {
149
- code: 'JG_AGENT_HQ_STORAGE_INVALID',
150
- data: { kind: 'state-conflict' },
151
- });
152
- const integrity = database.prepare('PRAGMA integrity_check').all();
153
- if (integrity.length !== 1 ||
154
- integrity[0]?.integrity_check !== 'ok' ||
155
- database.prepare('PRAGMA foreign_key_check').get())
156
- throw new Exception('The HQ storage is invalid', {
157
- code: 'JG_AGENT_HQ_STORAGE_INVALID',
158
- data: { kind: 'state-conflict' },
159
- });
160
- phase = 'commit';
161
- database.exec('COMMIT');
162
- hasCommitted = true;
163
- result = { ...base, state: 'upgraded', backupDirectory: verifiedBackup };
164
- }
165
- }
166
- catch (cause) {
167
- failure = cause;
168
- // a post-COMMIT exception can precede the assignment above; autocommit distinguishes that uncertainty
169
- if (phase === 'commit' && database && !database.isTransaction)
170
- hasCommitted = true;
171
- if (database?.isTransaction) {
172
- try {
173
- database.exec('ROLLBACK');
174
- }
175
- catch (cleanup) {
176
- hasCommitted = true;
177
- failure = new AggregateError([cause, cleanup], 'Upgrade rollback could not be confirmed');
178
- }
179
- }
180
- }
181
- finally {
182
- try {
183
- database?.close();
184
- await release?.();
185
- }
186
- catch (cause) {
187
- hasCommitted = true;
188
- failure = failure ? new AggregateError([failure, cause], 'Upgrade cleanup failed') : cause;
189
- phase = 'cleanup';
190
- }
191
- }
192
- try {
193
- if (failure) {
194
- const error = hasCommitted
195
- ? new Exception(`The HQ storage upgrade requires reconciliation: ${extractMessage(failure)}`, {
196
- code: 'JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN',
197
- data: { kind: 'operation-failed' },
198
- cause: failure,
199
- })
200
- : isException(failure) && failure.code.startsWith('JG_AGENT_HQ_')
201
- ? failure
202
- : new Exception(`The HQ storage upgrade failed: ${extractMessage(failure)}`, {
203
- code: 'JG_AGENT_HQ_STORAGE_UPGRADE_FAILED',
204
- data: { kind: 'operation-failed' },
205
- cause: failure,
206
- });
207
- port.postMessage({
208
- kind: 'error',
209
- code: error.code,
210
- message: extractMessage(error),
211
- cause: failure instanceof Error ? failure : undefined,
212
- data: { kind: getErrorKind(error), phase, backupDirectory: verifiedBackup },
213
- });
214
- }
215
- else
216
- port.postMessage({ kind: 'result', result: UpgradeResultSchema.parse(result) });
217
- }
218
- finally {
219
- port.close();
220
- }