@quolu/lattice 0.83.0 → 0.84.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.
@@ -807,20 +807,16 @@ async function durableReplaceBytes(directory, name, bytes) {
807
807
  async function withLifecycleLock(runDir, action) {
808
808
  // managed mutationの正本lockはdurable supervisorが所有する。これはunmanaged/launch CLI競合だけを塞ぐ。
809
809
  const lockPath = path.join(runDir, '.cli-lifecycle.lock');
810
- let handle;
811
- try {
812
- handle = await open(lockPath, 'wx', 0o600);
813
- } catch (error) {
814
- if (error?.code === 'EEXIST') {
815
- throw new CliContractError('RUN_BUSY', 'run lifecycle操作が既に進行中');
816
- }
817
- throw error;
818
- }
810
+ const lock = await acquireRuntimeLifecycleLock({
811
+ lockPath,
812
+ sessionNonceDigest: digestArtifact({ run_dir: runDir, lock: '.cli-lifecycle.lock' }),
813
+ operation: 'cli-lifecycle',
814
+ requestId: randomUUID(),
815
+ });
819
816
  try {
820
817
  return await action();
821
818
  } finally {
822
- await handle.close();
823
- await unlink(lockPath).catch(() => {});
819
+ await lock.release();
824
820
  }
825
821
  }
826
822
 
@@ -646,12 +646,14 @@ async function releaseIntakeRecorded(runDir, current, intake, actor, reason, det
646
646
  /**
647
647
  * Retracting a start releases every unaccepted intake bound to it and records that (u03 C11).
648
648
  * Release happens before Plan's event, so a failed append leaves a start that can be intaken again.
649
+ * Retiring an in-progress task uses the same release with `releaseReason: 'task_retired'` (u03 A14r).
649
650
  */
650
651
  export async function withStartRetractionGuard({
651
652
  repoRoot, planKey, taskId, activationEventDigest, action, environment = process.env,
653
+ releaseReason = 'start_retracted',
652
654
  }) {
653
655
  if (!identifier(planKey) || !identifier(taskId) || !sha256(activationEventDigest)
654
- || typeof action !== 'function') {
656
+ || typeof action !== 'function' || !['start_retracted', 'task_retired'].includes(releaseReason)) {
655
657
  fail('INVALID_START_RETRACTION', 'start retraction guard入力が不正');
656
658
  }
657
659
  const binding = { planKey, taskId, activationEventDigest };
@@ -665,7 +667,7 @@ export async function withStartRetractionGuard({
665
667
  const current = await readPullStore(runDir);
666
668
  const intake = boundIntake(project(current.events, current.meta), binding);
667
669
  if (intake !== undefined) {
668
- await releaseIntakeRecorded(runDir, current, intake, actor, 'start_retracted', {
670
+ await releaseIntakeRecorded(runDir, current, intake, actor, releaseReason, {
669
671
  target_start_digest: activationEventDigest,
670
672
  });
671
673
  }
@@ -10,10 +10,47 @@ import { lstat, readFile, realpath } from 'node:fs/promises';
10
10
  import path from 'node:path';
11
11
  import { parseTree } from 'jsonc-parser';
12
12
 
13
- import { canonicalizeTodoArtifact, todoSelfDigest } from './todo-contracts.mjs';
13
+ import { canonicalizeTodoArtifact, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
14
+ import { readOrCreateTerminalIdSync, terminalPublicLabel } from './terminal-identity.mjs';
15
+ import { resolveSeatIdentity } from './seat-identity.mjs';
14
16
  import { TodoStoreError } from './todo-store.mjs';
15
17
 
16
18
  const MAX_AUTHORING_INPUT_BYTES = 8_388_608;
19
+ function sanitizeActorIdentifier(raw, fallback) {
20
+ const compact = String(raw ?? '').replace(/[^0-9A-Za-z._-]/gu, '-').replace(/^-+/u, '').slice(0, 128);
21
+ return isTodoIdentifier(compact) ? compact : fallback;
22
+ }
23
+
24
+ /**
25
+ * 名乗りの無い操作のhost(ADR 0197)。journalは公開repositoryへcommitされるので、OSのhost名は
26
+ * 書かない——host名はOSが決めた自由文で、持ち主の名前を含むことがある。端末ごとの識別子から
27
+ * 一方向に導いたlabelを使い、端末の区別は保つ。識別子を読めず作れない端末は`host`になる。
28
+ */
29
+ function defaultActorHost(env) {
30
+ const terminalId = readOrCreateTerminalIdSync({ env });
31
+ return terminalId === null ? 'host' : terminalPublicLabel(terminalId);
32
+ }
33
+
34
+ function seatAgent(env) {
35
+ const { seat_id } = resolveSeatIdentity(env);
36
+ return isTodoIdentifier(seat_id) ? seat_id : null;
37
+ }
38
+
39
+ // u03s A57: a set but non-identifier value is treated like an unset one (no refusal).
40
+ export function resolveTodoActor(env) {
41
+ return {
42
+ host: isTodoIdentifier(env.LATTICE_TODO_ACTOR_HOST)
43
+ ? env.LATTICE_TODO_ACTOR_HOST
44
+ : defaultActorHost(env),
45
+ session: isTodoIdentifier(env.LATTICE_TODO_ACTOR_SESSION)
46
+ ? env.LATTICE_TODO_ACTOR_SESSION
47
+ : 'session',
48
+ // Seats on one machine share USER; the seat id keeps their `own` tasks apart (seat-contract).
49
+ agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
50
+ ? env.LATTICE_TODO_ACTOR_AGENT
51
+ : seatAgent(env) ?? sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'),
52
+ };
53
+ }
17
54
 
18
55
  export const AUTHORING_DIGEST_FIELDS = Object.freeze({
19
56
  'lattice.plan_backchain.v1': 'chain_digest',
@@ -108,12 +145,15 @@ function sortUnique(list, key) {
108
145
 
109
146
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
110
147
 
148
+ const CREATE_INPUT_SCHEMA = /^lattice\.plan_create_input\.v[1-5]$/u;
149
+
111
150
  /**
112
- * plan_create_input.v5だけ: 並びに作成者の意味が無い集合を、入力順に依らず正準形へ寄せる。
113
- * tasksと他の配列は並べ替えない。形が壊れていれば触らず、validatorの指摘に任せる。
151
+ * plan_create_input.v1〜v5: 並びに作成者の意味が無い集合を、入力順に依らず正準形へ寄せる(u03p A81s)。
152
+ * 形が壊れていれば触らず、validatorの指摘に任せる。
114
153
  */
115
- function normalizeCreateInputV5(value) {
154
+ function normalizeCreateInput(value) {
116
155
  const normalizers = {
156
+ tasks: (list) => sortUnique(list, (task) => task?.task_id),
117
157
  hard_dependencies: (list) => sortUnique(list, (edge) => `${refKey(edge?.from)}\0${refKey(edge?.to)}`),
118
158
  phase_accept_dependencies: (list) => sortUnique(list,
119
159
  (edge) => `${phaseRefKey(edge?.from)}\0${refKey(edge?.to)}`),
@@ -142,12 +182,115 @@ export function repairAuthoringArtifact(value) {
142
182
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
143
183
  const field = AUTHORING_DIGEST_FIELDS[value.schema];
144
184
  if (field === undefined) return value;
145
- const base = value.schema === 'lattice.plan_create_input.v5' ? normalizeCreateInputV5(value) : value;
185
+ const base = CREATE_INPUT_SCHEMA.test(value.schema) ? normalizeCreateInput(value) : value;
146
186
  const next = { ...base, [field]: typeof base[field] === 'string' ? base[field] : '' };
147
187
  next[field] = todoSelfDigest(next, field);
148
188
  return next;
149
189
  }
150
190
 
191
+ /**
192
+ * 機械が出せる事実を作成入力へ補う(u03p A81/A80)。AIは意図(tasks・依存)だけを書く:
193
+ * actorは席の解決値、recorded_atは現在時刻、v4/v5の空の設計メモはNO_PLAN、配列は正準順、
194
+ * input_digestは再計算。作成入力でない値と、レコードでない値はそのまま返す。
195
+ */
196
+ export const DEFAULT_EVIDENCE_SLOT = 'acceptance';
197
+ export const DEFAULT_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v5';
198
+ const DEFAULT_LANE = 'main';
199
+ const DEFAULT_GATE_POLICY = 'heavy';
200
+ // 時差を明示したISO時刻だけを読む。時差の無い文字列はhostの現地時刻になり、hostごとに値が変わる。
201
+ const ZONED_ISO = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.[0-9]+)?)?(Z|([+-])([0-9]{2}):([0-9]{2}))$/u;
202
+
203
+ /** 書いた暦の欄がそのまま残る時差付きISO時刻ならUTCミリ秒へ。2月30日のような繰り上がりや時差無しはnull。 */
204
+ function normalizeZonedTimestamp(text) {
205
+ const match = ZONED_ISO.exec(text);
206
+ if (match === null) return null;
207
+ const [, year, month, day, hour, minute, second = '00', zone, sign, offsetHour, offsetMinute] = match;
208
+ const parsed = new Date(text);
209
+ if (Number.isNaN(parsed.getTime())) return null;
210
+ const offset = zone === 'Z' ? 0 : (sign === '-' ? -1 : 1) * (Number(offsetHour) * 60 + Number(offsetMinute));
211
+ const local = new Date(parsed.getTime() + offset * 60_000);
212
+ const written = [year, month, day, hour, minute, second].map(Number);
213
+ const read = [local.getUTCFullYear(), local.getUTCMonth() + 1, local.getUTCDate(),
214
+ local.getUTCHours(), local.getUTCMinutes(), local.getUTCSeconds()];
215
+ return written.every((value, index) => value === read[index]) ? parsed.toISOString() : null;
216
+ }
217
+ const absent = (value) => value === undefined || value === null;
218
+
219
+ // a11: 辺の参照が同じplanを指すなら、作成者はtask_id/phase_idだけ書けばよい。レコードでない参照はvalidatorへ。
220
+ function fillRef(ref, projectId, planKey) {
221
+ if (!isRecord(ref)) return ref;
222
+ const filled = { ...ref };
223
+ if (filled.project_id === undefined && projectId !== undefined) filled.project_id = projectId;
224
+ if (filled.plan_key === undefined && planKey !== undefined) filled.plan_key = planKey;
225
+ return filled;
226
+ }
227
+
228
+ // 配列の各レコードだけを補う。配列でない値・レコードでない要素は触らず、validatorの指摘に任せる。
229
+ function fillEach(next, key, fill) {
230
+ if (!Array.isArray(next[key])) return;
231
+ next[key] = next[key].map((entry) => (isRecord(entry) ? fill(entry) : entry));
232
+ }
233
+
234
+ export function completeCreateInput(value, { env, now }) {
235
+ if (!isRecord(value)) return value;
236
+ const next = { ...value };
237
+ // a11: schemaを書かなければ現行のcreate入力(v5)。他のschemaを持つ値は作成入力でないのでそのまま返す。
238
+ if (absent(next.schema)) next.schema = DEFAULT_CREATE_INPUT_SCHEMA;
239
+ if (typeof next.schema !== 'string' || !CREATE_INPUT_SCHEMA.test(next.schema)) return value;
240
+ const fillNode = (ref) => fillRef(ref, next.project_id, next.plan_key);
241
+ const phaseInput = next.schema !== 'lattice.plan_create_input.v1';
242
+ const memoInput = ['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5'].includes(next.schema);
243
+ const decoupled = !['lattice.plan_create_input.v1', 'lattice.plan_create_input.v2'].includes(next.schema);
244
+ if (absent(next.actor)) next.actor = resolveTodoActor(env);
245
+ if (absent(next.recorded_at)) next.recorded_at = now.toISOString();
246
+ else if (typeof next.recorded_at === 'string') {
247
+ // 厳密形でなくても読める時刻はUTCミリ秒へ寄せる。読めない文字列はそのまま残し、validatorが拒否する。
248
+ next.recorded_at = normalizeZonedTimestamp(next.recorded_at) ?? next.recorded_at;
249
+ }
250
+ if (absent(next.hard_dependencies)) next.hard_dependencies = [];
251
+ if (absent(next.joins)) next.joins = [];
252
+ if (decoupled && absent(next.phase_accept_dependencies)) next.phase_accept_dependencies = [];
253
+ fillEach(next, 'hard_dependencies', (edge) => ({ ...edge, from: fillNode(edge.from), to: fillNode(edge.to) }));
254
+ fillEach(next, 'joins', (join) => ({
255
+ ...join,
256
+ ...(Array.isArray(join.after) ? { after: join.after.map(fillNode) } : {}),
257
+ ...('before' in join ? { before: fillNode(join.before) } : {}),
258
+ }));
259
+ if (decoupled) {
260
+ fillEach(next, 'phase_accept_dependencies',
261
+ (edge) => ({ ...edge, from: fillNode(edge.from), to: fillNode(edge.to) }));
262
+ }
263
+ fillEach(next, 'tasks', (task) => {
264
+ const filled = { ...task };
265
+ for (const key of ['narrative_anchor', 'compile_binding', 'parent_task_id', 'narrative_ref']) {
266
+ if (filled[key] === undefined) filled[key] = null;
267
+ }
268
+ if (absent(filled.lane)) filled.lane = DEFAULT_LANE;
269
+ if (next.schema === DEFAULT_CREATE_INPUT_SCHEMA && filled.done_condition === undefined) {
270
+ filled.done_condition = null;
271
+ }
272
+ if (memoInput && (absent(filled.design_memo)
273
+ || (typeof filled.design_memo === 'string' && filled.design_memo.trim() === ''))) {
274
+ filled.design_memo = 'NO_PLAN';
275
+ }
276
+ return filled;
277
+ });
278
+ if (phaseInput) {
279
+ fillEach(next, 'phases', (phase) => {
280
+ const filled = { ...phase };
281
+ if (absent(filled.gate_policy)) filled.gate_policy = DEFAULT_GATE_POLICY;
282
+ if (absent(filled.predecessor_phase_ids)) filled.predecessor_phase_ids = [];
283
+ // 段が要求する証拠の種類を書かなければ、受入の証拠1つ(acceptance)を求める。
284
+ if (absent(filled.required_evidence_slots)
285
+ || (Array.isArray(filled.required_evidence_slots) && filled.required_evidence_slots.length === 0)) {
286
+ filled.required_evidence_slots = [DEFAULT_EVIDENCE_SLOT];
287
+ }
288
+ return filled;
289
+ });
290
+ }
291
+ return repairAuthoringArtifact(next);
292
+ }
293
+
151
294
  /**
152
295
  * 渡された値がpathでなく本文そのものに見えるか。
153
296
  * `--input`/`--evidence`はfileを取るが、AIも人もインラインの文章を渡して詰まる。
@@ -268,3 +411,22 @@ export function matchFlagCommand(argv, head, { known, required = [], booleans =
268
411
  }
269
412
  return flags;
270
413
  }
414
+
415
+ /**
416
+ * matchFlagCommand が null を返す理由を、最初に落ちた flag と規則で返す。通るなら null。
417
+ * 規則は matchFlagCommand と同じ順で判定する(未知flag・位置引数、必須flag、boolean)。
418
+ */
419
+ export function explainFlagCommand(argv, head, { known, required = [], booleans = [] } = {}) {
420
+ if (!Array.isArray(argv) || !Array.isArray(head) || head.some((token, index) => argv[index] !== token)) {
421
+ return null;
422
+ }
423
+ const { flags, rest } = parseFlagMap(argv.slice(head.length));
424
+ if (rest.length > 0) return { pointer: String(rest[0]), rule: 'flag_unknown' };
425
+ const unknown = Object.keys(flags).find((key) => !known.includes(key));
426
+ if (unknown !== undefined) return { pointer: `--${unknown}`, rule: 'flag_unknown' };
427
+ const missing = required.find((key) => typeof flags[key] !== 'string' || flags[key].length === 0);
428
+ if (missing !== undefined) return { pointer: `--${missing}`, rule: 'flag_missing' };
429
+ const valued = booleans.find((key) => flags[key] !== undefined && flags[key] !== true);
430
+ if (valued !== undefined) return { pointer: `--${valued}`, rule: 'flag_takes_no_value' };
431
+ return null;
432
+ }