@quolu/lattice 0.61.3 → 0.62.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +6 -6
- package/bin/lattice.mjs +20 -9
- package/package.json +1 -1
- package/src/cli-help.mjs +9 -5
- package/src/project-cli.mjs +22 -71
- package/src/runtime-pull-intake.mjs +11 -5
- package/src/todo-authoring-input.mjs +183 -0
- package/src/todo-cli.mjs +367 -382
- package/src/todo-independence-contracts.mjs +11 -4
- package/src/todo-independence-guidance.mjs +4 -4
- package/src/todo-store.mjs +6 -30
- package/src/witness-scaffold.mjs +11 -4
package/README.ja.md
CHANGED
|
@@ -325,7 +325,8 @@ pidへは送りません(pid再利用で無関係のprocessを止めうるた
|
|
|
325
325
|
[ADR 0157](docs/adr/0157-dashboard-daemons-are-discoverable-by-record.md)が正です。
|
|
326
326
|
状態を書き込む`start / block / unblock / done / evidence promote / reopen / note / independence mode /
|
|
327
327
|
revise / revise-phase / revise-set / phase review|accept|reject|reopen|close-unaudited|baseline /
|
|
328
|
-
dashboard adopt`では、監査actorとして次の3
|
|
328
|
+
dashboard adopt`では、監査actorとして次の3環境変数を渡せます。未設定ならhost/`session`/USERから
|
|
329
|
+
defaultします。渡した値がidentifierとして不正なら`ACTOR_UNRESOLVED`です。
|
|
329
330
|
|
|
330
331
|
```bash
|
|
331
332
|
export LATTICE_TODO_ACTOR_HOST=<host-id>
|
|
@@ -333,12 +334,11 @@ export LATTICE_TODO_ACTOR_SESSION=<session-id>
|
|
|
333
334
|
export LATTICE_TODO_ACTOR_AGENT=<agent-id>
|
|
334
335
|
```
|
|
335
336
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
`next_action: set_required_actor_environment_and_retry`を確認し、正規値を設定して同じ操作を再試行してください。
|
|
337
|
+
`todo done`は`--evidence`にdescriptor JSONでも証拠本文でも渡せます。`--message`なら本文から
|
|
338
|
+
blobを書きます。flagの順は問いません。空の設計メモは拒否します。無策なら`NO_PLAN`と書いてください。
|
|
339
339
|
|
|
340
|
-
|
|
341
|
-
[ADR
|
|
340
|
+
authoring入口と閉じる口の契約は
|
|
341
|
+
[ADR 0181](docs/adr/0181-authoring-entry-accepts-drafts.md)を参照してください。
|
|
342
342
|
|
|
343
343
|
## 特許
|
|
344
344
|
|
package/bin/lattice.mjs
CHANGED
|
@@ -31,15 +31,26 @@ if (help !== null) {
|
|
|
31
31
|
cwd: process.cwd(), stdout: process.stdout, cliVersion: packageJson.version, error,
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
|
-
} else if (
|
|
35
|
-
&& args[2]
|
|
36
|
-
const {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
|
|
34
|
+
} else if (args[0] === 'plan' && args[1] === 'create'
|
|
35
|
+
&& args[2] !== '--schema' && args[2] !== '--schema-version') {
|
|
36
|
+
const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
|
|
37
|
+
const flags = matchFlagCommand(args, ['plan', 'create'], {
|
|
38
|
+
known: ['input', 'serialization-reviewed'],
|
|
39
|
+
required: ['input'],
|
|
40
|
+
booleans: ['serialization-reviewed'],
|
|
41
|
+
});
|
|
42
|
+
if (flags === null) {
|
|
43
|
+
process.stderr.write('lattice: unsupported command or arguments: plan create\n');
|
|
44
|
+
process.exitCode = 2;
|
|
45
|
+
} else {
|
|
46
|
+
const { projectCliFailure, runPlanCreate } = await import('../src/project-cli.mjs');
|
|
47
|
+
try {
|
|
48
|
+
process.exitCode = await runPlanCreate({
|
|
49
|
+
cwd: process.cwd(), inputRef: flags.input, stdout: process.stdout,
|
|
50
|
+
});
|
|
51
|
+
} catch (error) {
|
|
52
|
+
process.exitCode = projectCliFailure(process.stderr, error);
|
|
53
|
+
}
|
|
43
54
|
}
|
|
44
55
|
} else if (args.length === 4 && args[0] === 'plan' && args[1] === 'create'
|
|
45
56
|
&& args[2] === '--schema' && args[3] === '--json') {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.62.1",
|
|
4
4
|
"description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Quo / クオ at kitepon.dev",
|
package/src/cli-help.mjs
CHANGED
|
@@ -93,13 +93,17 @@ Write commands:
|
|
|
93
93
|
migrate --input <extraction.json> [--serialization-reviewed] [--json]
|
|
94
94
|
migrate --input <extraction.json> --dry-run --json [--serialization-reviewed]
|
|
95
95
|
# 既存storeへplanを追加する(plan createは空store初期化専用)。
|
|
96
|
+
# pretty-print・digest未計算・repo内絶対pathは機械が直す。空の設計メモは拒否する。
|
|
96
97
|
# 結果へdispatch_shapeを載せる。--serialization-reviewedは互換のため受理するだけで門ではない
|
|
97
98
|
start --plan <key> --task <id> [--parallel-frontier|--override-reason <text> [--serial-confirmed]]
|
|
98
|
-
# readyならflag
|
|
99
|
+
# readyならflagなしで着手する。flagの順は問わない。
|
|
100
|
+
# --parallel-frontierと--override-reasonは方針・理由の記録。
|
|
99
101
|
# --serial-confirmedは互換のため受理する。いずれも門ではない
|
|
100
102
|
block --plan <key> --task <id> --reason <text>
|
|
101
103
|
unblock --plan <key> --task <id>
|
|
102
|
-
done --plan <key> --task <id> --evidence <file>
|
|
104
|
+
done --plan <key> --task <id> (--evidence <file>|--message <text>)
|
|
105
|
+
# taskを閉じる。--evidenceはdescriptor JSONでも証拠本文でもよい。repo内なら絶対path可。
|
|
106
|
+
# 監査と構造finalizationは残作業であり、doneの門ではない
|
|
103
107
|
reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]
|
|
104
108
|
evidence promote --plan <key> --task <id> --evidence <file>
|
|
105
109
|
dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>
|
|
@@ -139,8 +143,8 @@ Write commands:
|
|
|
139
143
|
# 現在gate_readyかつphase eventを1つも持たないPhaseを一括でclosed_unauditedへ宣言する。
|
|
140
144
|
# 自動実行はしない(明示コマンドのみ)。--exceptで指定したplanは対象から除外する
|
|
141
145
|
|
|
142
|
-
Write commands
|
|
143
|
-
|
|
146
|
+
Write commandsはLATTICE_TODO_ACTOR_HOST / SESSION / AGENTを受理する。
|
|
147
|
+
欠落はhost/session/agentのdefaultを使う。渡した値がidentifierとして不正なら拒否する。
|
|
144
148
|
|
|
145
149
|
storeだけを書き換えるcommandの末尾へ--commit-storeを付けると、共有Git lockを取得し、
|
|
146
150
|
生じた.lattice/todoの変更だけをcommitしてreceiptを返す。
|
|
@@ -264,7 +268,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
264
268
|
'todo retract': 'todo retract --plan <key> --task <id> --reason <text>',
|
|
265
269
|
'todo block': 'todo block --plan <key> --task <id> --reason <text>',
|
|
266
270
|
'todo unblock': 'todo unblock --plan <key> --task <id>',
|
|
267
|
-
'todo done': 'todo done --plan <key> --task <id> --evidence <file> [--test-result <markdown-file>]',
|
|
271
|
+
'todo done': 'todo done --plan <key> --task <id> (--evidence <file>|--message <text>) [--test-result <markdown-file>]',
|
|
268
272
|
'todo reopen': 'todo reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]',
|
|
269
273
|
'todo evidence': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
|
|
270
274
|
'todo evidence promote': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
|
package/src/project-cli.mjs
CHANGED
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
import { gitSync } from './git-process.mjs';
|
|
2
2
|
import { constants as fsConstants } from 'node:fs';
|
|
3
|
-
import { lstat, open
|
|
3
|
+
import { lstat, open } from 'node:fs/promises';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
|
|
6
6
|
import {
|
|
7
7
|
TODO_DESIGN_MEMO_PROMPT,
|
|
8
|
-
canonicalizeTodoArtifact,
|
|
9
8
|
exactRecord,
|
|
10
9
|
explainTodoDesignMemo,
|
|
11
10
|
isTodoDesignMemo,
|
|
12
11
|
isStrictTodoTimestamp,
|
|
13
12
|
isTodoDigest,
|
|
14
13
|
isTodoIdentifier,
|
|
15
|
-
isTodoRef,
|
|
16
14
|
todoSelfDigest,
|
|
17
15
|
} from './todo-contracts.mjs';
|
|
18
16
|
import { projectTodoStatus } from './todo-status.mjs';
|
|
@@ -39,10 +37,10 @@ import {
|
|
|
39
37
|
import {
|
|
40
38
|
computeTodoDispatchShapeForPlan,
|
|
41
39
|
} from './todo-dispatch-shape.mjs';
|
|
40
|
+
import { readAuthoringJsonFile } from './todo-authoring-input.mjs';
|
|
42
41
|
|
|
43
42
|
const STORE_REF = '.lattice/todo';
|
|
44
43
|
const MANIFEST_REF = `${STORE_REF}/manifest.json`;
|
|
45
|
-
const MAX_INPUT_BYTES = 8_388_608;
|
|
46
44
|
const STATUS_SCHEMA = 'lattice.project_status.v1';
|
|
47
45
|
const SESSION_CONTEXT_SCHEMA = 'lattice.session_context.v1';
|
|
48
46
|
/** HEADが読めない環境でも投影を組めるようにする。記録があるときは実HEADで置き換わる。 */
|
|
@@ -339,15 +337,19 @@ export async function runProjectStatus({ cwd, stdout, cliVersion, env = process.
|
|
|
339
337
|
// dashboard活動の登録はdiscovery面の副作用として維持する(ADR 0131 Decision 4で
|
|
340
338
|
// session-context側だけが持たない、と決めた面である)。
|
|
341
339
|
if (state.store !== null && env.LATTICE_DASHBOARD_AUTOSTART !== '0') {
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
340
|
+
try {
|
|
341
|
+
const identity = await resolveProjectIdentity({
|
|
342
|
+
repoRoot: state.repoRoot, projectId: state.store.project_id, env,
|
|
343
|
+
});
|
|
344
|
+
const actorSession = env.LATTICE_TODO_ACTOR_SESSION;
|
|
345
|
+
await ensureDashboardActivity({
|
|
346
|
+
repoRoot: state.repoRoot, projectId: state.store.project_id,
|
|
347
|
+
displayName: identity.displayName,
|
|
348
|
+
sessionId: isTodoIdentifier(actorSession) ? actorSession : `status-${process.pid}`, env,
|
|
349
|
+
});
|
|
350
|
+
} catch {
|
|
351
|
+
// dashboardはdiscoveryの副作用。statusをdashboard故障で止めない(ADR 0181)。
|
|
352
|
+
}
|
|
351
353
|
}
|
|
352
354
|
stdout.write(`${JSON.stringify(state.result)}\n`);
|
|
353
355
|
return state.exitCode;
|
|
@@ -382,68 +384,17 @@ export async function runSessionContext({ cwd, stdout, cliVersion }) {
|
|
|
382
384
|
}
|
|
383
385
|
|
|
384
386
|
async function readCanonicalInput(repoRoot, inputRef) {
|
|
385
|
-
if (!isTodoRef(inputRef)) throw new TodoStoreError('INPUT_INVALID', 'input_ref_invalid');
|
|
386
|
-
const root = await realpath(repoRoot);
|
|
387
|
-
const absolute = path.resolve(root, inputRef);
|
|
388
|
-
if (!absolute.startsWith(`${root}${path.sep}`)) throw new TodoStoreError('INPUT_INVALID', 'input_outside_repo');
|
|
389
|
-
let cursor = root;
|
|
390
387
|
try {
|
|
391
|
-
|
|
392
|
-
cursor = path.join(cursor, part);
|
|
393
|
-
const entry = await lstat(cursor);
|
|
394
|
-
if (entry.isSymbolicLink()) throw new TodoStoreError('INPUT_INVALID', 'input_path_symlink');
|
|
395
|
-
}
|
|
388
|
+
return await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'INPUT_INVALID' });
|
|
396
389
|
} catch (error) {
|
|
397
|
-
if (error instanceof TodoStoreError
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
throw new TodoStoreError('INPUT_INVALID', 'input_path_invalid');
|
|
403
|
-
}
|
|
404
|
-
if (state.size > MAX_INPUT_BYTES) throw new TodoStoreError('INPUT_INVALID', 'input_too_large');
|
|
405
|
-
let handle;
|
|
406
|
-
let bytes;
|
|
407
|
-
try {
|
|
408
|
-
handle = await open(absolute, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
|
|
409
|
-
const opened = await handle.stat();
|
|
410
|
-
if (opened.dev !== state.dev || opened.ino !== state.ino || opened.size !== state.size
|
|
411
|
-
|| opened.mtimeMs !== state.mtimeMs || opened.ctimeMs !== state.ctimeMs || !opened.isFile()) {
|
|
412
|
-
throw new TodoStoreError('INPUT_INVALID', 'input_changed_during_validation');
|
|
413
|
-
}
|
|
414
|
-
if (opened.size > MAX_INPUT_BYTES) throw new TodoStoreError('INPUT_INVALID', 'input_too_large');
|
|
415
|
-
const capture = Buffer.allocUnsafe(MAX_INPUT_BYTES + 1);
|
|
416
|
-
let captured = 0;
|
|
417
|
-
while (captured < capture.length) {
|
|
418
|
-
const { bytesRead } = await handle.read(capture, captured, capture.length - captured, null);
|
|
419
|
-
if (bytesRead === 0) break;
|
|
420
|
-
captured += bytesRead;
|
|
421
|
-
}
|
|
422
|
-
if (captured > MAX_INPUT_BYTES) throw new TodoStoreError('INPUT_INVALID', 'input_too_large');
|
|
423
|
-
bytes = capture.subarray(0, captured);
|
|
424
|
-
const after = await lstat(absolute);
|
|
425
|
-
if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size
|
|
426
|
-
|| after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
|
|
427
|
-
|| await realpath(absolute) !== absolute) {
|
|
428
|
-
throw new TodoStoreError('INPUT_INVALID', 'input_changed_during_validation');
|
|
390
|
+
if (error instanceof TodoStoreError && [
|
|
391
|
+
'INPUT_UNREADABLE', 'INPUT_TOO_LARGE', 'INVALID_JSON',
|
|
392
|
+
].includes(error.code)) {
|
|
393
|
+
throw new TodoStoreError('INPUT_INVALID', error.detail?.reason ?? 'input_unreadable', undefined,
|
|
394
|
+
error.detail);
|
|
429
395
|
}
|
|
430
|
-
|
|
431
|
-
if (error instanceof TodoStoreError) throw error;
|
|
432
|
-
throw new TodoStoreError('INPUT_INVALID', 'input_unreadable');
|
|
433
|
-
} finally {
|
|
434
|
-
await handle?.close();
|
|
435
|
-
}
|
|
436
|
-
if (bytes.length > MAX_INPUT_BYTES) throw new TodoStoreError('INPUT_INVALID', 'input_too_large');
|
|
437
|
-
let text;
|
|
438
|
-
try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); }
|
|
439
|
-
catch { throw new TodoStoreError('INPUT_INVALID', 'input_utf8_invalid'); }
|
|
440
|
-
if (!text.endsWith('\n') || text.includes('\r') || text.slice(0, -1).includes('\n')) {
|
|
441
|
-
throw new TodoStoreError('INPUT_INVALID', 'input_bytes_noncanonical');
|
|
396
|
+
throw error;
|
|
442
397
|
}
|
|
443
|
-
let value;
|
|
444
|
-
try { value = JSON.parse(text.slice(0, -1)); } catch { throw new TodoStoreError('INPUT_INVALID', 'input_json_invalid'); }
|
|
445
|
-
if (`${canonicalizeTodoArtifact(value)}\n` !== text) throw new TodoStoreError('INPUT_INVALID', 'input_bytes_noncanonical');
|
|
446
|
-
return value;
|
|
447
398
|
}
|
|
448
399
|
|
|
449
400
|
function validateCreateInput(value) {
|
|
@@ -1082,10 +1082,16 @@ export async function detachPullWorker({ runDir, taskId, environment = process.e
|
|
|
1082
1082
|
} finally { await lock.release(); }
|
|
1083
1083
|
}
|
|
1084
1084
|
|
|
1085
|
-
function
|
|
1086
|
-
|
|
1087
|
-
entry.accepted
|
|
1088
|
-
|
|
1085
|
+
export function observationIntakes(state, includeTaskId = null) {
|
|
1086
|
+
return state.intakes.filter((entry) => {
|
|
1087
|
+
if (entry.accepted !== null) return false;
|
|
1088
|
+
if (entry.intervention.state !== 'hold') return true;
|
|
1089
|
+
return includeTaskId !== null && entry.task_id === includeTaskId;
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function observationModel(state, { includeTaskId = null } = {}) {
|
|
1094
|
+
const intakes = observationIntakes(state, includeTaskId);
|
|
1089
1095
|
const manifests = Object.fromEntries(intakes.map((entry) => [entry.task_id, entry.manifest]));
|
|
1090
1096
|
const nodes = intakes.map((entry) => ({ todo_id: entry.task_id })).sort((l, r) => l.todo_id.localeCompare(r.todo_id));
|
|
1091
1097
|
const plan = {
|
|
@@ -1154,7 +1160,7 @@ export async function acceptPullTask({ repoRoot, runDir, taskId, environment = p
|
|
|
1154
1160
|
const checkpoint = await captureWorktreeDiff({
|
|
1155
1161
|
worktreePath: intake.worktree_path, baseSha: intake.base_sha,
|
|
1156
1162
|
});
|
|
1157
|
-
const model = observationModel(state);
|
|
1163
|
+
const model = observationModel(state, { includeTaskId: taskId });
|
|
1158
1164
|
const packets = Object.fromEntries(model.intakes.map((entry) => [entry.task_id, entry.packet]));
|
|
1159
1165
|
const direct = detectCheckpointFindings({
|
|
1160
1166
|
todoId: taskId, checkpoint, packets, manifests: model.manifests,
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AIが書くauthoring入力の受理。
|
|
3
|
+
*
|
|
4
|
+
* storeへ書くbytesはこれまでどおりcanonical。入口がpretty-print・digest未計算・
|
|
5
|
+
* repo内絶対pathを拒否するのは、機械が直せるものを儀式にしている。
|
|
6
|
+
* 空の設計メモは直さない——NO_PLANは無策の明示申告であり、欠落から作らない。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { lstat, readFile, realpath } from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { parseTree } from 'jsonc-parser';
|
|
12
|
+
|
|
13
|
+
import { todoSelfDigest } from './todo-contracts.mjs';
|
|
14
|
+
import { TodoStoreError } from './todo-store.mjs';
|
|
15
|
+
|
|
16
|
+
const MAX_AUTHORING_INPUT_BYTES = 8_388_608;
|
|
17
|
+
|
|
18
|
+
export const AUTHORING_DIGEST_FIELDS = Object.freeze({
|
|
19
|
+
'lattice.todo_witness_set.v1': 'witness_set_digest',
|
|
20
|
+
'lattice.todo_witness_set.v2': 'witness_set_digest',
|
|
21
|
+
'lattice.todo_witness_set.v3': 'witness_set_digest',
|
|
22
|
+
'lattice.todo_witness_set.v4': 'witness_set_digest',
|
|
23
|
+
'lattice.todo_witness_set.v5': 'witness_set_digest',
|
|
24
|
+
'lattice.todo_extraction.v2': 'extraction_digest',
|
|
25
|
+
'lattice.todo_extraction.v3': 'extraction_digest',
|
|
26
|
+
'lattice.todo_extraction.v4': 'extraction_digest',
|
|
27
|
+
'lattice.plan_create_input.v1': 'input_digest',
|
|
28
|
+
'lattice.plan_create_input.v2': 'input_digest',
|
|
29
|
+
'lattice.plan_create_input.v3': 'input_digest',
|
|
30
|
+
'lattice.plan_create_input.v4': 'input_digest',
|
|
31
|
+
'lattice.todo_revision.v1': 'revision_digest',
|
|
32
|
+
'lattice.todo_revision.v2': 'revision_digest',
|
|
33
|
+
'lattice.phase_todo_revision.v1': 'revision_digest',
|
|
34
|
+
'lattice.phase_todo_revision.v2': 'revision_digest',
|
|
35
|
+
'lattice.phase_todo_revision.v3': 'revision_digest',
|
|
36
|
+
'lattice.todo_revision_set.v1': 'revision_set_digest',
|
|
37
|
+
'lattice.todo_revision_set.v2': 'revision_set_digest',
|
|
38
|
+
'lattice.todo_revision_set.v3': 'revision_set_digest',
|
|
39
|
+
'lattice.phase_accept_input.v1': 'input_digest',
|
|
40
|
+
'lattice.phase_reject_input.v1': 'input_digest',
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
function fail(code, reason, detail) {
|
|
44
|
+
throw new TodoStoreError(code, reason, undefined, detail);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function within(root, candidate) {
|
|
48
|
+
return candidate === root || candidate.startsWith(`${root}${path.sep}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function hasDuplicateJsonKey(node) {
|
|
52
|
+
if (node?.type === 'object') {
|
|
53
|
+
const keys = new Set();
|
|
54
|
+
for (const property of node.children ?? []) {
|
|
55
|
+
const [key, value] = property.children ?? [];
|
|
56
|
+
if (keys.has(key?.value) || hasDuplicateJsonKey(value)) return true;
|
|
57
|
+
keys.add(key?.value);
|
|
58
|
+
}
|
|
59
|
+
} else if (node?.type === 'array') {
|
|
60
|
+
return (node.children ?? []).some(hasDuplicateJsonKey);
|
|
61
|
+
}
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** CLI引数がauthoring fileを指しているか。repo相対でも絶対でもよい。 */
|
|
66
|
+
export function isAuthoringPathToken(value) {
|
|
67
|
+
return typeof value === 'string' && value.length > 0 && !value.startsWith('--');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function parseAuthoringJson(text, { invalidCode = 'INVALID_JSON' } = {}) {
|
|
71
|
+
if (typeof text !== 'string') fail(invalidCode, 'input_json_invalid');
|
|
72
|
+
const normalized = text.replace(/^\uFEFF/u, '').replace(/\r\n/gu, '\n').replace(/\r/gu, '\n');
|
|
73
|
+
const parseErrors = [];
|
|
74
|
+
const tree = parseTree(normalized, parseErrors, { allowTrailingComma: false, disallowComments: true });
|
|
75
|
+
if (parseErrors.length > 0 || tree === undefined) fail(invalidCode, 'json_parse_failed');
|
|
76
|
+
if (hasDuplicateJsonKey(tree)) fail(invalidCode, 'duplicate_key');
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(normalized);
|
|
79
|
+
} catch {
|
|
80
|
+
fail(invalidCode, 'json_parse_failed');
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function repairAuthoringArtifact(value) {
|
|
86
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
87
|
+
const field = AUTHORING_DIGEST_FIELDS[value.schema];
|
|
88
|
+
if (field === undefined) return value;
|
|
89
|
+
const next = { ...value, [field]: typeof value[field] === 'string' ? value[field] : '' };
|
|
90
|
+
next[field] = todoSelfDigest(next, field);
|
|
91
|
+
return next;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function resolveAuthoringInputPath(repoRoot, inputRef) {
|
|
95
|
+
if (typeof inputRef !== 'string' || inputRef.length === 0) {
|
|
96
|
+
fail('INPUT_UNREADABLE', 'input_ref_invalid', { input_ref: inputRef });
|
|
97
|
+
}
|
|
98
|
+
const canonicalRoot = await realpath(repoRoot);
|
|
99
|
+
const candidate = path.isAbsolute(inputRef)
|
|
100
|
+
? inputRef
|
|
101
|
+
: path.resolve(canonicalRoot, inputRef);
|
|
102
|
+
let stats;
|
|
103
|
+
try { stats = await lstat(candidate); } catch {
|
|
104
|
+
fail('INPUT_UNREADABLE', 'input_missing', { input_ref: inputRef });
|
|
105
|
+
}
|
|
106
|
+
if (stats.isSymbolicLink() || !stats.isFile()) {
|
|
107
|
+
fail('INPUT_UNREADABLE', 'unsafe_input_path', { input_ref: inputRef });
|
|
108
|
+
}
|
|
109
|
+
const resolved = await realpath(candidate);
|
|
110
|
+
if (!within(canonicalRoot, resolved) || resolved === canonicalRoot) {
|
|
111
|
+
fail('INPUT_UNREADABLE', 'input_path_outside_repo', { input_ref: inputRef });
|
|
112
|
+
}
|
|
113
|
+
if (stats.size > MAX_AUTHORING_INPUT_BYTES) fail('INPUT_TOO_LARGE', 'input_size_limit_exceeded');
|
|
114
|
+
const relative = path.relative(canonicalRoot, resolved);
|
|
115
|
+
if (relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
|
|
116
|
+
fail('INPUT_UNREADABLE', 'input_path_outside_repo', { input_ref: inputRef });
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
absolute: resolved,
|
|
120
|
+
inputRef: relative.split(path.sep).join('/'),
|
|
121
|
+
maxBytes: MAX_AUTHORING_INPUT_BYTES,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function readAuthoringJsonFile(repoRoot, inputRef, {
|
|
126
|
+
invalidCode = 'INVALID_JSON',
|
|
127
|
+
} = {}) {
|
|
128
|
+
const located = await resolveAuthoringInputPath(repoRoot, inputRef);
|
|
129
|
+
const bytes = await readFile(located.absolute);
|
|
130
|
+
if (bytes.length > located.maxBytes) fail('INPUT_TOO_LARGE', 'input_size_limit_exceeded');
|
|
131
|
+
let text;
|
|
132
|
+
try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
|
|
133
|
+
catch { fail(invalidCode, 'invalid_utf8'); }
|
|
134
|
+
const parsed = parseAuthoringJson(text, { invalidCode });
|
|
135
|
+
return repairAuthoringArtifact(parsed);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function parseFlagMap(argv) {
|
|
139
|
+
const flags = Object.create(null);
|
|
140
|
+
const rest = [];
|
|
141
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
142
|
+
const token = argv[index];
|
|
143
|
+
if (typeof token !== 'string' || !token.startsWith('--') || token === '--') {
|
|
144
|
+
rest.push(token);
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const name = token.slice(2);
|
|
148
|
+
const next = argv[index + 1];
|
|
149
|
+
if (next !== undefined && typeof next === 'string' && !next.startsWith('--')) {
|
|
150
|
+
flags[name] = next;
|
|
151
|
+
index += 1;
|
|
152
|
+
} else {
|
|
153
|
+
flags[name] = true;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { flags, rest };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function flagMapKeys(flags, expected) {
|
|
160
|
+
const actual = Object.keys(flags).sort();
|
|
161
|
+
const allowed = [...expected].sort();
|
|
162
|
+
return actual.length === allowed.length && actual.every((key, index) => key === allowed[index]);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 位置ではなくflag名でwriteコマンドを束ねる。未知flag・位置引数は受理しない。
|
|
167
|
+
* boolean flagは値がtrueのときだけ合法。requiredは非空string。
|
|
168
|
+
*/
|
|
169
|
+
export function matchFlagCommand(argv, head, { known, required = [], booleans = [] } = {}) {
|
|
170
|
+
if (!Array.isArray(argv) || !Array.isArray(head) || head.some((token, index) => argv[index] !== token)) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const { flags, rest } = parseFlagMap(argv.slice(head.length));
|
|
174
|
+
if (rest.length > 0) return null;
|
|
175
|
+
if (Object.keys(flags).some((key) => !known.includes(key))) return null;
|
|
176
|
+
for (const key of required) {
|
|
177
|
+
if (typeof flags[key] !== 'string' || flags[key].length === 0) return null;
|
|
178
|
+
}
|
|
179
|
+
for (const key of booleans) {
|
|
180
|
+
if (flags[key] !== undefined && flags[key] !== true) return null;
|
|
181
|
+
}
|
|
182
|
+
return flags;
|
|
183
|
+
}
|