hoi4-agent-tools 4.20.3 → 4.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
- package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
- package/dist/hoi4_agent_tools/core/configuration.js +6 -0
- package/dist/hoi4_agent_tools/core/engine.js +67 -21
- package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
- package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
- package/dist/hoi4_agent_tools/core/transactions.js +6 -0
- package/dist/hoi4_agent_tools/core/workspace.js +14 -1
- package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
- package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
- package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
- package/dist/hoi4_agent_tools/event/graph.js +3 -3
- package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
- package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
- package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
- package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/gui/assets.js +3 -13
- package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/gui/layout.js +2 -4
- package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
- package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
- package/dist/hoi4_agent_tools/gui/studio.js +31 -0
- package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
- package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
- package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
- package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/map/model.js +17 -3
- package/dist/hoi4_agent_tools/map/validation.js +12 -18
- package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
- package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/runtime.js +4 -2
- package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
- package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
- package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/operations.js +1 -2
- package/dist/hoi4_agent_tools/technology/service.js +30 -59
- package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +11 -10
- package/docs/troubleshooting.md +11 -11
- package/engine/bin/darwin-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-x64/hoi4-engine +0 -0
- package/engine/bin/manifest.json +8 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -2
- package/schemas/configuration.schema.json +143 -134
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +1 -1
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +1 -1
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +1 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
1
2
|
import { compareCodeUnits, hashCanonical } from './canonical.js';
|
|
2
3
|
import { installedEffectCommands } from './game-documentation.js';
|
|
3
4
|
import { SymbolIndex } from './index.js';
|
|
@@ -107,7 +108,13 @@ export class CoreEngine {
|
|
|
107
108
|
#scanAdmissionQueue = [];
|
|
108
109
|
#activeScanAdmissions = new Set();
|
|
109
110
|
#recovery;
|
|
111
|
+
#startupWork;
|
|
110
112
|
#startup;
|
|
113
|
+
/** Set by {@link recoverOnDemand}: each workspace recovers on its first use. */
|
|
114
|
+
#recoverOnDemand = false;
|
|
115
|
+
#recoveries = new Map();
|
|
116
|
+
/** Marks the work of a recovery, which reads its own workspace and must not wait for itself. */
|
|
117
|
+
#inRecovery = new AsyncLocalStorage();
|
|
111
118
|
constructor(resolver, services = {}) {
|
|
112
119
|
this.resolver = resolver;
|
|
113
120
|
const state = resolver.serverState();
|
|
@@ -144,39 +151,78 @@ export class CoreEngine {
|
|
|
144
151
|
return recovery;
|
|
145
152
|
}
|
|
146
153
|
/**
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
154
|
+
* Set the work that loads the workspaces, to run when {@link recovered} is first asked for. A
|
|
155
|
+
* stdio server answers its handshake and tool list without it; the transport asks for
|
|
156
|
+
* {@link recovered} when the first request that needs a workspace arrives, so an idle server
|
|
157
|
+
* never loads one. The work reports its own failure (for example through
|
|
150
158
|
* `resolver.failStartup`); a rejection here only ends the wait.
|
|
151
159
|
*/
|
|
152
160
|
deferStartup(work) {
|
|
153
|
-
this.#
|
|
161
|
+
this.#startupWork = work;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Recover each workspace on its first use instead of every workspace at once: before its
|
|
165
|
+
* first file access through the resolver, before its first job is submitted and before its
|
|
166
|
+
* first rewrite is planned or applied. A failed recovery is recorded as with
|
|
167
|
+
* {@link initialize}: reads go on and rewrites are refused with
|
|
168
|
+
* `TRANSACTION_RECOVERY_REQUIRED`.
|
|
169
|
+
*/
|
|
170
|
+
recoverOnDemand() {
|
|
171
|
+
this.#recoverOnDemand = true;
|
|
172
|
+
this.resolver.onWorkspaceUse((workspaceId) => this.ensureRecovered(workspaceId));
|
|
173
|
+
this.transactions.setRecoveryGate((workspaceId) => {
|
|
174
|
+
try {
|
|
175
|
+
return this.ensureRecovered(this.resolver.get(workspaceId).id);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
// An unknown workspace is refused by the caller's own lookup.
|
|
179
|
+
return Promise.resolve();
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Recover `workspaceId` once when {@link recoverOnDemand} is on; otherwise, and for the
|
|
185
|
+
* recovery's own file access, it returns at once. It never rejects.
|
|
186
|
+
*/
|
|
187
|
+
ensureRecovered(workspaceId) {
|
|
188
|
+
if (!this.#recoverOnDemand || this.#inRecovery.getStore() === true)
|
|
189
|
+
return Promise.resolve();
|
|
190
|
+
let recovery = this.#recoveries.get(workspaceId);
|
|
191
|
+
if (recovery === undefined) {
|
|
192
|
+
recovery = this.#inRecovery.run(true, () => this.#recoverWorkspace(workspaceId));
|
|
193
|
+
this.#recoveries.set(workspaceId, recovery);
|
|
194
|
+
}
|
|
195
|
+
return recovery;
|
|
154
196
|
}
|
|
155
197
|
/**
|
|
156
198
|
* Settles when the deferred startup and the latest {@link initialize} have finished, at once
|
|
157
|
-
* when neither was
|
|
199
|
+
* when neither was set. The first call starts the deferred startup.
|
|
158
200
|
*/
|
|
159
201
|
async recovered() {
|
|
202
|
+
if (this.#startupWork !== undefined)
|
|
203
|
+
this.#startup ??= this.#startupWork().catch(() => undefined);
|
|
160
204
|
await this.#startup;
|
|
161
205
|
await this.#recovery;
|
|
162
206
|
}
|
|
163
207
|
async #recoverWorkspaces() {
|
|
164
|
-
for (const workspace of this.resolver.list())
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
208
|
+
for (const workspace of this.resolver.list())
|
|
209
|
+
await this.#recoverWorkspace(workspace.id);
|
|
210
|
+
}
|
|
211
|
+
async #recoverWorkspace(workspaceId) {
|
|
212
|
+
// Recovery repairs an interrupted internal rewrite before the workspace is exposed. A
|
|
213
|
+
// journal that cannot be recovered blocks rewrites of its own workspace, not the server.
|
|
214
|
+
try {
|
|
215
|
+
await this.transactions.recover(workspaceId);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
this.transactions.recordRecoveryFailure(workspaceId, error);
|
|
219
|
+
process.stderr.write(`${JSON.stringify({
|
|
220
|
+
level: 'error',
|
|
221
|
+
event: 'transaction_recovery_blocked',
|
|
222
|
+
workspaceId,
|
|
223
|
+
code: error instanceof ServiceError ? error.code : 'TRANSACTION_RECOVERY_FAILED',
|
|
224
|
+
message: error instanceof Error ? error.message : String(error),
|
|
225
|
+
})}\n`);
|
|
180
226
|
}
|
|
181
227
|
}
|
|
182
228
|
status(workspaceId, principal) {
|
|
@@ -96,3 +96,10 @@ export class IdleCacheLifetime {
|
|
|
96
96
|
this.release();
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* The cache lifetime of one group of operations on `engine`: its caches are released after the
|
|
101
|
+
* configured `idleCacheReleaseSeconds` without a call (default 30 s).
|
|
102
|
+
*/
|
|
103
|
+
export function idleCacheLifetime(engine, releaseCaches) {
|
|
104
|
+
return new IdleCacheLifetime(releaseCaches, engine.resolver.config().idleCacheReleaseSeconds * 1000);
|
|
105
|
+
}
|
|
@@ -131,7 +131,9 @@ export class OperationTaskService {
|
|
|
131
131
|
? validatedArguments.relativePath
|
|
132
132
|
: undefined, requestSignal)
|
|
133
133
|
: await resolveOperationWorkspaceId(this.engine, context, requestedWorkspaceId, requestSignal);
|
|
134
|
-
this
|
|
134
|
+
// A server that recovers on demand repairs this workspace's interrupted rewrite before
|
|
135
|
+
// the call reads or rewrites it; a failure is recorded and refuses rewrites only.
|
|
136
|
+
await this.engine.ensureRecovered(this.engine.resolver.get(workspaceId, context.principal).id);
|
|
135
137
|
requestSignal?.throwIfAborted();
|
|
136
138
|
}
|
|
137
139
|
catch (error) {
|
|
@@ -212,7 +212,13 @@ export class TransactionManager {
|
|
|
212
212
|
recordRecoveryFailure(workspaceId, error) {
|
|
213
213
|
this.#recoveryFailures.set(workspaceId, error instanceof Error ? error.message : 'Rewrite journal recovery failed');
|
|
214
214
|
}
|
|
215
|
+
#recoveryGate;
|
|
216
|
+
/** Run `gate` before a rewrite of a workspace is planned or applied; the engine recovers on demand. */
|
|
217
|
+
setRecoveryGate(gate) {
|
|
218
|
+
this.#recoveryGate = gate;
|
|
219
|
+
}
|
|
215
220
|
async assertRecovered(workspaceId, signal) {
|
|
221
|
+
await this.#recoveryGate?.(workspaceId);
|
|
216
222
|
if (!this.#recoveryFailures.has(workspaceId))
|
|
217
223
|
return;
|
|
218
224
|
try {
|
|
@@ -389,6 +389,7 @@ export class WorkspaceResolver {
|
|
|
389
389
|
#state = 'prepared';
|
|
390
390
|
#population;
|
|
391
391
|
#startupError;
|
|
392
|
+
#useHook;
|
|
392
393
|
constructor(configuration) {
|
|
393
394
|
this.configuration = configuration;
|
|
394
395
|
}
|
|
@@ -503,6 +504,14 @@ export class WorkspaceResolver {
|
|
|
503
504
|
: new ServiceError('INTERNAL_ERROR', error instanceof Error ? error.message : String(error));
|
|
504
505
|
return this.#startupError;
|
|
505
506
|
}
|
|
507
|
+
/**
|
|
508
|
+
* Run `hook` with the workspace's ID before each file access through this resolver
|
|
509
|
+
* (`refreshDescriptors`, `resolvePath`, `resolvePathInRoot`). The engine uses it to
|
|
510
|
+
* recover a workspace on its first use.
|
|
511
|
+
*/
|
|
512
|
+
onWorkspaceUse(hook) {
|
|
513
|
+
this.#useHook = hook;
|
|
514
|
+
}
|
|
506
515
|
/** The reason the server could not start, when it could not. */
|
|
507
516
|
startupError() {
|
|
508
517
|
return this.#startupError;
|
|
@@ -723,6 +732,7 @@ export class WorkspaceResolver {
|
|
|
723
732
|
*/
|
|
724
733
|
async refreshDescriptors(workspaceId, principal) {
|
|
725
734
|
const workspace = this.get(workspaceId, principal);
|
|
735
|
+
await this.#useHook?.(workspace.id);
|
|
726
736
|
if (workspace.registration.kind === 'game')
|
|
727
737
|
return;
|
|
728
738
|
const dependencies = workspace.registration.dependencies;
|
|
@@ -809,13 +819,16 @@ export class WorkspaceResolver {
|
|
|
809
819
|
* workspace lookup when it was TypeScript.
|
|
810
820
|
*/
|
|
811
821
|
async getAfterPathCheck(workspaceId, relativePath, principal) {
|
|
822
|
+
let workspace;
|
|
812
823
|
try {
|
|
813
|
-
|
|
824
|
+
workspace = this.get(workspaceId, principal);
|
|
814
825
|
}
|
|
815
826
|
catch (error) {
|
|
816
827
|
await refuseUnsafeRelativePath(relativePath);
|
|
817
828
|
throw error;
|
|
818
829
|
}
|
|
830
|
+
await this.#useHook?.(workspace.id);
|
|
831
|
+
return workspace;
|
|
819
832
|
}
|
|
820
833
|
allowedWorkspaceIds(principal) {
|
|
821
834
|
const token = this.configuration.http.tokens.find((entry) => entry.principal === principal);
|
|
@@ -38,7 +38,7 @@ function newDecisionFilePath(file) {
|
|
|
38
38
|
return path;
|
|
39
39
|
}
|
|
40
40
|
/** The file the operation writes: the one named, the one that defines the decision, or the one with the category. */
|
|
41
|
-
function targetFile(snapshot, input) {
|
|
41
|
+
async function targetFile(snapshot, input) {
|
|
42
42
|
const files = modDecisionFiles(snapshot);
|
|
43
43
|
if (input.file !== undefined) {
|
|
44
44
|
const named = files.find(({ relativePath }) => normalized(relativePath) === normalized(input.file));
|
|
@@ -63,7 +63,8 @@ function targetFile(snapshot, input) {
|
|
|
63
63
|
if (input.category === undefined)
|
|
64
64
|
fail('DECISION_WRITE_CATEGORY_REQUIRED', 'add needs the category block the decision goes in');
|
|
65
65
|
const category = input.category;
|
|
66
|
-
const
|
|
66
|
+
const categoriesByFile = await Promise.all(files.map(({ bytes, relativePath }) => decisionCategories({ bytes, path: relativePath })));
|
|
67
|
+
const holding = files.filter((_, index) => categoriesByFile[index].includes(category));
|
|
67
68
|
if (holding.length === 0) {
|
|
68
69
|
if (input.createCategory === true) {
|
|
69
70
|
if (files.length === 1)
|
|
@@ -74,9 +75,7 @@ function targetFile(snapshot, input) {
|
|
|
74
75
|
}
|
|
75
76
|
fail('DECISION_WRITE_CATEGORY_NOT_FOUND', `No common/decisions file of the mod has a ${category} category; pass createCategory: true to create it`, {
|
|
76
77
|
category,
|
|
77
|
-
categories: [
|
|
78
|
-
...new Set(files.flatMap(({ bytes, relativePath }) => decisionCategories({ bytes, path: relativePath }))),
|
|
79
|
-
],
|
|
78
|
+
categories: [...new Set(categoriesByFile.flat())],
|
|
80
79
|
});
|
|
81
80
|
}
|
|
82
81
|
if (holding.length > 1)
|
|
@@ -121,7 +120,7 @@ function referencesOf(id, body) {
|
|
|
121
120
|
}
|
|
122
121
|
export async function computeDecisionWrite(engine, input, context, applied) {
|
|
123
122
|
const snapshot = await engine.scan(context.workspaceId, { patterns: WRITE_PATTERNS }, context.principal, context.signal);
|
|
124
|
-
const target = targetFile(snapshot, input);
|
|
123
|
+
const target = await targetFile(snapshot, input);
|
|
125
124
|
const planInput = {
|
|
126
125
|
operation: input.operation,
|
|
127
126
|
id: input.id,
|
|
@@ -133,7 +132,7 @@ export async function computeDecisionWrite(engine, input, context, applied) {
|
|
|
133
132
|
let plan;
|
|
134
133
|
if ('file' in target) {
|
|
135
134
|
file = target.file;
|
|
136
|
-
plan = planDecisionWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
135
|
+
plan = await planDecisionWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
137
136
|
}
|
|
138
137
|
else {
|
|
139
138
|
const inMod = snapshot.index
|
|
@@ -144,7 +143,7 @@ export async function computeDecisionWrite(engine, input, context, applied) {
|
|
|
144
143
|
id: input.id,
|
|
145
144
|
path: inMod.path,
|
|
146
145
|
});
|
|
147
|
-
plan = planNewDecisionFile(target.newPath, planInput);
|
|
146
|
+
plan = await planNewDecisionFile(target.newPath, planInput);
|
|
148
147
|
}
|
|
149
148
|
const missing = { localisation: [], icon: [], category: [] };
|
|
150
149
|
const diagnostics = [];
|
|
@@ -1,252 +1,32 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
function
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
: []);
|
|
21
|
-
}
|
|
22
|
-
/** One level of indentation, read from the file's own decisions, tabs when it has none. */
|
|
23
|
-
function indentUnit(document, located) {
|
|
24
|
-
for (const { decision, category } of located) {
|
|
25
|
-
const outer = lineIndent(document.text, category.start);
|
|
26
|
-
const inner = lineIndent(document.text, decision.start);
|
|
27
|
-
if (inner.length > outer.length && inner.startsWith(outer))
|
|
28
|
-
return inner.slice(outer.length);
|
|
29
|
-
}
|
|
30
|
-
return '\t';
|
|
31
|
-
}
|
|
32
|
-
/** The body, checked on its own as the block it will become. */
|
|
33
|
-
function assertBodyIsOneBlock(id, body) {
|
|
34
|
-
const probe = parseClausewitz(Buffer.from(`${id} = {\n${body}\n}\n`, 'utf8'), 'decision-body');
|
|
35
|
-
const only = probe.root.entries;
|
|
36
|
-
const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === id;
|
|
37
|
-
if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
|
|
38
|
-
fail('DECISION_WRITE_BODY_INVALID', 'The body must be the text between the braces of one decision: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
|
|
39
|
-
if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
|
|
40
|
-
fail('DECISION_WRITE_BODY_INVALID', 'The body of a decision cannot be empty');
|
|
41
|
-
}
|
|
42
|
-
function definitionTexts(document, skip) {
|
|
43
|
-
const byKey = new Map();
|
|
44
|
-
for (const { decision, category } of definitions(document)) {
|
|
45
|
-
if (decision.start === skip?.start)
|
|
46
|
-
continue;
|
|
47
|
-
const key = `${category.key.value}:${decision.key.value}`;
|
|
48
|
-
byKey.set(key, [...(byKey.get(key) ?? []), document.text.slice(decision.start, decision.end)]);
|
|
49
|
-
}
|
|
50
|
-
return byKey;
|
|
51
|
-
}
|
|
52
|
-
function checkRequest(input) {
|
|
53
|
-
if (!ID_PATTERN.test(input.id))
|
|
54
|
-
fail('DECISION_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid decision id`, {
|
|
55
|
-
id: input.id,
|
|
56
|
-
});
|
|
57
|
-
if (input.operation === 'remove' && input.body !== undefined)
|
|
58
|
-
fail('DECISION_WRITE_BODY_UNEXPECTED', 'remove takes no body');
|
|
59
|
-
if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
|
|
60
|
-
fail('DECISION_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the decision`);
|
|
61
|
-
if (input.operation !== 'add' && input.createCategory === true)
|
|
62
|
-
fail('DECISION_WRITE_CATEGORY_UNEXPECTED', 'createCategory applies to add only');
|
|
63
|
-
if (input.category !== undefined && !ID_PATTERN.test(input.category))
|
|
64
|
-
fail('DECISION_WRITE_CATEGORY_INVALID', `${JSON.stringify(input.category)} is not a valid category name`, { category: input.category });
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { callSourceQuery, callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
|
|
3
|
+
const planSchema = z.object({
|
|
4
|
+
operation: z.enum(['add', 'replace', 'remove']),
|
|
5
|
+
id: z.string(),
|
|
6
|
+
category: z.string(),
|
|
7
|
+
path: z.string(),
|
|
8
|
+
edit: replacementSchema,
|
|
9
|
+
untouchedDefinitions: z.number().int().nonnegative(),
|
|
10
|
+
});
|
|
11
|
+
async function plan(path, input, source) {
|
|
12
|
+
const answer = await callWritePlan({
|
|
13
|
+
op: 'decision_write.plan',
|
|
14
|
+
path,
|
|
15
|
+
input: { ...input },
|
|
16
|
+
...(source === undefined ? {} : { source }),
|
|
17
|
+
result: planSchema,
|
|
18
|
+
});
|
|
19
|
+
return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
|
|
65
20
|
}
|
|
66
|
-
/**
|
|
67
|
-
* The plan that creates a new `common/decisions` file holding one category block with one new
|
|
68
|
-
* decision, for `createFile: true`. The file is UTF-8 without a byte order mark and uses tabs and LF.
|
|
69
|
-
*/
|
|
21
|
+
/** The plan that creates a new file holding one new decision, for `createFile: true`. */
|
|
70
22
|
export function planNewDecisionFile(path, input) {
|
|
71
|
-
|
|
72
|
-
if (input.operation !== 'add')
|
|
73
|
-
fail('DECISION_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
|
|
74
|
-
if (input.category === undefined)
|
|
75
|
-
fail('DECISION_WRITE_CATEGORY_REQUIRED', 'a new file needs the category block the decision goes in');
|
|
76
|
-
assertBodyIsOneBlock(input.id, input.body);
|
|
77
|
-
const text = [
|
|
78
|
-
`${input.category} = {`,
|
|
79
|
-
`\t${input.id} = {`,
|
|
80
|
-
indentedBody(input.body, '\t\t', '\n'),
|
|
81
|
-
'\t}',
|
|
82
|
-
'}',
|
|
83
|
-
'',
|
|
84
|
-
].join('\n');
|
|
85
|
-
const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
|
|
86
|
-
if (hasBlockingDiagnostics(written.diagnostics))
|
|
87
|
-
fail('DECISION_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
|
|
88
|
-
diagnosticCodes: written.diagnostics.map(({ code }) => code),
|
|
89
|
-
});
|
|
90
|
-
return {
|
|
91
|
-
operation: 'add',
|
|
92
|
-
id: input.id,
|
|
93
|
-
category: input.category,
|
|
94
|
-
path,
|
|
95
|
-
text,
|
|
96
|
-
bytes: Buffer.from(text, 'utf8'),
|
|
97
|
-
edit: { start: 0, end: 0, text, description: `create ${path} with ${input.id}` },
|
|
98
|
-
diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
|
|
99
|
-
untouchedDefinitions: 0,
|
|
100
|
-
};
|
|
23
|
+
return plan(path, input, undefined);
|
|
101
24
|
}
|
|
102
25
|
export function planDecisionWrite(source, input) {
|
|
103
|
-
|
|
104
|
-
const document = parseClausewitz(source.bytes, source.path);
|
|
105
|
-
if (hasBlockingDiagnostics(document.diagnostics))
|
|
106
|
-
fail('DECISION_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', { path: source.path, diagnosticCodes: document.diagnostics.map(({ code }) => code) });
|
|
107
|
-
const text = document.text;
|
|
108
|
-
const newline = document.newline;
|
|
109
|
-
const located = definitions(document);
|
|
110
|
-
if (input.body !== undefined)
|
|
111
|
-
assertBodyIsOneBlock(input.id, input.body);
|
|
112
|
-
const unit = indentUnit(document, located);
|
|
113
|
-
const existing = located.filter(({ decision }) => decision.key.value === input.id);
|
|
114
|
-
let edit;
|
|
115
|
-
let category;
|
|
116
|
-
let skip;
|
|
117
|
-
if (input.operation === 'add') {
|
|
118
|
-
if (existing.length > 0)
|
|
119
|
-
fail('DECISION_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
|
|
120
|
-
id: input.id,
|
|
121
|
-
category: existing[0]?.category.key.value,
|
|
122
|
-
line: existing[0]?.decision.key.token.line,
|
|
123
|
-
});
|
|
124
|
-
if (input.category === undefined)
|
|
125
|
-
fail('DECISION_WRITE_CATEGORY_REQUIRED', 'add needs the category block the decision goes in');
|
|
126
|
-
const wanted = input.category;
|
|
127
|
-
const matching = categoryBlocks(document).filter(({ key }) => key.value === wanted);
|
|
128
|
-
if (matching.length === 0 && input.createCategory !== true)
|
|
129
|
-
fail('DECISION_WRITE_CATEGORY_NOT_FOUND', `The file has no ${wanted} category block; pass createCategory: true to create it`, {
|
|
130
|
-
category: wanted,
|
|
131
|
-
categories: [...new Set(categoryBlocks(document).map(({ key }) => key.value))],
|
|
132
|
-
});
|
|
133
|
-
if (matching.length > 1)
|
|
134
|
-
fail('DECISION_WRITE_CATEGORY_AMBIGUOUS', `The file has ${matching.length} ${wanted} category blocks`, { category: wanted, lines: matching.map(({ key }) => key.token.line) });
|
|
135
|
-
if (matching.length === 0) {
|
|
136
|
-
const lead = text === '' ? '' : `${text.endsWith('\n') ? '' : newline}${newline}`;
|
|
137
|
-
edit = {
|
|
138
|
-
start: text.length,
|
|
139
|
-
end: text.length,
|
|
140
|
-
text: `${lead}${wanted} = {${newline}${unit}${input.id} = {${newline}${indentedBody(input.body, unit + unit, newline)}${newline}${unit}}${newline}}${newline}`,
|
|
141
|
-
description: `add ${input.id} in the new category ${wanted}`,
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
else {
|
|
145
|
-
const target = matching[0];
|
|
146
|
-
const block = target.value;
|
|
147
|
-
const close = block.close;
|
|
148
|
-
if (close === undefined)
|
|
149
|
-
fail('DECISION_WRITE_LAYOUT_UNSUPPORTED', `The ${wanted} category has no closing brace`);
|
|
150
|
-
const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
|
|
151
|
-
if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
|
|
152
|
-
fail('DECISION_WRITE_LAYOUT_UNSUPPORTED', `The closing brace of ${wanted} shares its line with other text, so the new decision has no line to go on`, { category: wanted, line: close.line });
|
|
153
|
-
const decisionIndent = lineIndent(text, target.start) + unit;
|
|
154
|
-
const decisionText = `${decisionIndent}${input.id} = {${newline}${indentedBody(input.body, decisionIndent + unit, newline)}${newline}${decisionIndent}}${newline}`;
|
|
155
|
-
edit = {
|
|
156
|
-
start: closeLineStart,
|
|
157
|
-
end: closeLineStart,
|
|
158
|
-
text: `${block.entries.length > 0 ? newline : ''}${decisionText}`,
|
|
159
|
-
description: `add ${input.id} to ${wanted}`,
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
category = wanted;
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
if (existing.length === 0)
|
|
166
|
-
fail('DECISION_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, {
|
|
167
|
-
id: input.id,
|
|
168
|
-
});
|
|
169
|
-
if (existing.length > 1)
|
|
170
|
-
fail('DECISION_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, { id: input.id, lines: existing.map(({ decision }) => decision.key.token.line) });
|
|
171
|
-
const found = existing[0];
|
|
172
|
-
category = found.category.key.value;
|
|
173
|
-
if (input.category !== undefined && input.category !== category)
|
|
174
|
-
fail('DECISION_WRITE_CATEGORY_MISMATCH', `${input.id} is in ${category}, and moving a decision to another category is not supported`, { id: input.id, category });
|
|
175
|
-
skip = found.decision;
|
|
176
|
-
const decisionIndent = lineIndent(text, found.decision.start);
|
|
177
|
-
if (input.operation === 'replace') {
|
|
178
|
-
edit = {
|
|
179
|
-
start: found.decision.start,
|
|
180
|
-
end: found.decision.end,
|
|
181
|
-
text: `${input.id} = {${newline}${indentedBody(input.body, decisionIndent + unit, newline)}${newline}${decisionIndent}}`,
|
|
182
|
-
description: `replace ${input.id}`,
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
else {
|
|
186
|
-
const lineStart = text.lastIndexOf('\n', found.decision.start - 1) + 1;
|
|
187
|
-
const lineEndAt = text.indexOf('\n', found.decision.end);
|
|
188
|
-
const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
|
|
189
|
-
const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.decision.start)) &&
|
|
190
|
-
/^[ \t]*\r?$/u.test(text.slice(found.decision.end, lineEndAt === -1 ? text.length : lineEndAt));
|
|
191
|
-
if (!alone) {
|
|
192
|
-
edit = {
|
|
193
|
-
start: found.decision.start,
|
|
194
|
-
end: found.decision.end,
|
|
195
|
-
text: '',
|
|
196
|
-
description: `remove ${input.id}`,
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
else {
|
|
200
|
-
// A blank line that only separated this decision from the one before it goes with it.
|
|
201
|
-
const before = text.slice(0, lineStart);
|
|
202
|
-
const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
|
|
203
|
-
const after = text.slice(lineEnd);
|
|
204
|
-
const nextIsBlankOrClose = /^[ \t]*(?:\r?\n|\})/u.test(after) || after === '';
|
|
205
|
-
let start = lineStart;
|
|
206
|
-
if (blankBefore && nextIsBlankOrClose)
|
|
207
|
-
start = before.lastIndexOf('\n', before.length - 2) + 1;
|
|
208
|
-
edit = { start, end: lineEnd, text: '', description: `remove ${input.id}` };
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
const bytes = applyReplacements(document, [edit]);
|
|
213
|
-
const after = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
214
|
-
const written = parseClausewitz(bytes, source.path);
|
|
215
|
-
if (hasBlockingDiagnostics(written.diagnostics))
|
|
216
|
-
fail('DECISION_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
|
|
217
|
-
diagnosticCodes: written.diagnostics.map(({ code }) => code),
|
|
218
|
-
});
|
|
219
|
-
const before = definitionTexts(document, skip);
|
|
220
|
-
const afterTexts = definitionTexts(written, undefined);
|
|
221
|
-
let untouched = 0;
|
|
222
|
-
for (const [key, texts] of before) {
|
|
223
|
-
const now = afterTexts.get(key) ?? [];
|
|
224
|
-
for (const textOfDecision of texts)
|
|
225
|
-
if (now.includes(textOfDecision))
|
|
226
|
-
untouched += 1;
|
|
227
|
-
else
|
|
228
|
-
fail('DECISION_WRITE_RESULT_INVALID', `The edit would change ${key}, which it must not touch`, { key });
|
|
229
|
-
}
|
|
230
|
-
if (written.text !== after)
|
|
231
|
-
fail('DECISION_WRITE_RESULT_INVALID', 'The written file does not match the planned edit');
|
|
232
|
-
return {
|
|
233
|
-
operation: input.operation,
|
|
234
|
-
id: input.id,
|
|
235
|
-
category,
|
|
236
|
-
path: source.path,
|
|
237
|
-
text: after,
|
|
238
|
-
bytes,
|
|
239
|
-
edit,
|
|
240
|
-
diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
|
|
241
|
-
context: DIFF_CONTEXT_LINES,
|
|
242
|
-
}),
|
|
243
|
-
untouchedDefinitions: untouched,
|
|
244
|
-
};
|
|
26
|
+
return plan(source.path, input, source.bytes);
|
|
245
27
|
}
|
|
246
28
|
/** The category blocks of a `common/decisions` file, or none when the file cannot be parsed. */
|
|
247
|
-
export function decisionCategories(source) {
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
return [];
|
|
251
|
-
return [...new Set(categoryBlocks(document).map(({ key }) => key.value))];
|
|
29
|
+
export async function decisionCategories(source) {
|
|
30
|
+
const answer = await callSourceQuery('decision_write.categories', source.path, source.bytes, z.object({ categories: z.array(z.string()) }));
|
|
31
|
+
return answer.categories;
|
|
252
32
|
}
|
|
@@ -146,7 +146,7 @@ export async function computeDoctrineWrite(engine, input, context, applied) {
|
|
|
146
146
|
let plan;
|
|
147
147
|
if ('file' in target) {
|
|
148
148
|
file = target.file;
|
|
149
|
-
plan = planDoctrineWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
149
|
+
plan = await planDoctrineWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
150
150
|
}
|
|
151
151
|
else {
|
|
152
152
|
const inMod = snapshot.index
|
|
@@ -157,7 +157,7 @@ export async function computeDoctrineWrite(engine, input, context, applied) {
|
|
|
157
157
|
id: input.id,
|
|
158
158
|
path: inMod.path,
|
|
159
159
|
});
|
|
160
|
-
plan = planNewDoctrineFile(target.newPath, planInput);
|
|
160
|
+
plan = await planNewDoctrineFile(target.newPath, planInput);
|
|
161
161
|
}
|
|
162
162
|
const missing = {
|
|
163
163
|
localisation: [],
|