@quolu/lattice 0.85.2 → 0.85.4

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.
@@ -2,6 +2,8 @@
2
2
  // (next_action) in one detail. Pure: reads only the error and the CLI context, no I/O.
3
3
  // Refusal sites keep their own keys; this fills the three keys the seat contract requires.
4
4
 
5
+ import { auditPendingNextCommands, isAuditPendingPhaseStatus } from './todo-audit-pending.mjs';
6
+
5
7
  const PLACEHOLDER = /^[a-z_]+$/u;
6
8
  // a27: one placeholder per flag for every missing-flag text (plan and todo alike).
7
9
  export const FLAG_PLACEHOLDER = Object.freeze({
@@ -35,15 +37,38 @@ const unfinishedFirst = (detail, ctx) => {
35
37
  blocked: `Unblock ${name} with \`lattice todo unblock ${on}\`, then record done on it`,
36
38
  })[first.status] ?? `Record done on ${name} first with \`lattice todo done ${on} --message <text>\` (see \`lattice todo show ${on} --json\`)`;
37
39
  };
40
+ // a36: a start without LATTICE_SEAT_ID is recorded under the OS user; after the seat sets its id that
41
+ // start looks like another seat's. Say so and give the seat contract's one-time fix.
42
+ const inProgressHolder = (detail, ctx, on) => {
43
+ const holder = typeof detail.started_by === 'string' ? detail.started_by : null;
44
+ const actors = record(ctx.actors) ? ctx.actors : {};
45
+ if (holder !== null && holder === actors.anonymous && holder !== actors.agent) {
46
+ return `It is in-progress under '${holder}', the name a start gets without LATTICE_SEAT_ID: most likely this seat's own`
47
+ + ` start from before it set LATTICE_SEAT_ID. One-time fix (seat contract): with LATTICE_SEAT_ID unset, undo that start`
48
+ + ` with \`lattice todo retract ${on} --reason <text>\` and start it again here, or finish it there first with`
49
+ + ` \`lattice todo done ${on} --message <text>\`.`;
50
+ }
51
+ return `It is already in-progress under ${holder === null ? 'another seat' : `seat '${holder}'`}; see \`${showTask(detail, ctx)}\`.`
52
+ + ` To move it to this seat run \`lattice todo start ${on} --rebind --reason <text>\`.`;
53
+ };
38
54
  const startState = (detail, ctx) => {
39
55
  const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
40
56
  return ({
41
57
  blocked: `It is blocked: run \`lattice todo unblock ${on}\`; that resumes it (no start needed).`,
42
58
  done: `It is done: to work on it again run \`lattice todo reopen ${on} --reason <text>\`.`,
43
- 'in-progress': `It is already in-progress under another seat; see \`${showTask(detail, ctx)}\`.`,
59
+ 'in-progress': inProgressHolder(detail, ctx, on),
44
60
  retired: `It is retired, which is permanent; see \`${showTask(detail, ctx)}\`.`,
45
61
  })[detail.status] ?? `Only a pending task can start; check its status with \`${showTask(detail, ctx)}\`.`;
46
62
  };
63
+ // a35: done needs in-progress; the way there depends on where the task is now (start cannot leave retired).
64
+ const doneState = (detail, ctx) => {
65
+ const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
66
+ return ({
67
+ blocked: `It is blocked: run \`lattice todo unblock ${on}\` (it resumes in-progress), then done.`,
68
+ retired: `${planOf(detail, ctx)}/${taskOf(detail, ctx)} is retired, which is permanent: it cannot be started or finished. `
69
+ + 'If the work is still needed, add it as a new task with `lattice plan revise --input <file>`.',
70
+ })[detail.status] ?? `It must be in-progress: run \`${startTask(detail, ctx)}\` first.`;
71
+ };
47
72
  const cyclePath = (detail) => (Array.isArray(detail.cycle)
48
73
  ? detail.cycle.filter(record).map((node) => `${node.plan_key}/${node.task_id ?? `phase:${node.phase_id}`}`).join(' -> ')
49
74
  : null);
@@ -67,6 +92,16 @@ const dependencyExists = {
67
92
  };
68
93
 
69
94
  /** The flag that carried the unreadable input: the one whose value is the refused path. */
95
+ const OPENED_BY_TEXT = Object.freeze({
96
+ reopen: ' because it was reopened', historical_import: ' from a historical import',
97
+ start: ' from a start',
98
+ });
99
+ /** a35: why an in-progress task is open, as a clause ('' when the store did not say). */
100
+ function openedByText(detail) {
101
+ return Object.hasOwn(OPENED_BY_TEXT, detail.opened_by ?? '') ? OPENED_BY_TEXT[detail.opened_by]
102
+ : detail.opened_by === null ? ' with no start recorded in this plan version' : '';
103
+ }
104
+
70
105
  function inputFlag(detail, ctx) {
71
106
  const flags = record(ctx.flags) ? ctx.flags : {};
72
107
  const byValue = Object.keys(flags).find((name) => flags[name] === detail.input_ref);
@@ -93,7 +128,12 @@ function keyDifference(detail, ctx, pointer) {
93
128
  const parts = [];
94
129
  if (missing.length > 0) parts.push(`add keys ${names(missing)}`);
95
130
  if (extra.length > 0) parts.push(`remove keys ${names(extra)}`);
96
- return `At ${pointer} ${parts.join(' and ') || `use exactly the keys ${names(expected)}`}.`;
131
+ // a31: 計画の目的・最終成果・受入はplan createでなくbackchainのgoalが持つ(seat contract)。
132
+ const goalHint = ctx.family === 'plan' && ctx.command === 'create' && pointer === '/'
133
+ && extra.some((key) => key === 'goal' || key === 'title')
134
+ ? ' A plan is named by plan_key; its purpose, final outcome and acceptance go in `goal` of `lattice plan backchain` (see `lattice plan backchain --schema --json`).'
135
+ : '';
136
+ return `At ${pointer} ${parts.join(' and ') || `use exactly the keys ${names(expected)}`}.${goalHint}`;
97
137
  }
98
138
 
99
139
  function acceptedValues(detail) {
@@ -167,7 +207,7 @@ const REGISTRY = {
167
207
  repair: (detail, ctx) => ({
168
208
  predecessor_unfinished: `${unfinishedFirst(detail, ctx)}.`,
169
209
  acceptance_edge: phaseAcceptFirst(detail, ctx),
170
- task_state: `It must be in-progress: run \`${startTask(detail, ctx)}\` first.`,
210
+ task_state: doneState(detail, ctx),
171
211
  })[detail.cause] ?? `Check the task state with \`${showTask(detail, ctx)}\`, then rerun.`,
172
212
  },
173
213
  invalid_start_transition: {
@@ -184,6 +224,49 @@ const REGISTRY = {
184
224
  invalid_unblock_transition: {
185
225
  repair: (detail, ctx) => `Only a blocked task can be unblocked; check its status with \`${showTask(detail, ctx)}\`.`,
186
226
  },
227
+ invalid_reopen_transition: {
228
+ // a32: only a done task can be reopened; say the state and the step that fits it.
229
+ repair: (detail, ctx) => {
230
+ const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
231
+ return `Only a done task can be reopened; ${planOf(detail, ctx)}/${taskOf(detail, ctx)} is ${detail.status ?? 'not done'}. ` + ({
232
+ // a35: retract undoes only an authored start; a reopened task has none.
233
+ 'in-progress': detail.opened_by === 'start'
234
+ ? `It is still open: finish it with \`lattice todo done ${on}\`, or undo the start with \`lattice todo retract ${on} --reason <text>\`.`
235
+ : `It is still open${openedByText(detail)}: finish it with \`lattice todo done ${on}\`.`,
236
+ pending: `It has not started: run \`lattice todo start ${on}\`.`,
237
+ blocked: `It is blocked: resume it with \`lattice todo unblock ${on}\`.`,
238
+ retired: `Retire is permanent, so it stays closed; see \`${showTask(detail, ctx)}\`.`,
239
+ }[detail.status] ?? `Check its state with \`${showTask(detail, ctx)}\`.`);
240
+ },
241
+ },
242
+ phase_gate_not_ready: {
243
+ // a36: review and close-unaudited need gate_ready; name the phase state and the step that fits it.
244
+ repair: (detail, ctx) => {
245
+ const phase = detail.phase_id ?? ctx.flags?.phase ?? '<phase>';
246
+ const plan = planOf(detail, ctx);
247
+ const on = `--plan ${plan} --phase ${phase}`;
248
+ const status = detail.phase_status;
249
+ const head = `Phase ${plan}/${phase} is ${status ?? 'not gate_ready'}; review and close-unaudited need gate_ready. `;
250
+ if (isAuditPendingPhaseStatus(status) && status !== 'gate_ready') {
251
+ const [first, second] = auditPendingNextCommands(plan, phase, status, strings(detail.required_evidence_slots).length || 1);
252
+ return head + (status === 'reviewing'
253
+ ? `It is already in review: decide it with \`${first}\`, or \`${second}\`.`
254
+ : `Its review was rejected: run \`${first}\`, then review it again.`);
255
+ }
256
+ return head + ({
257
+ active: `Not all of its tasks are done: record done on them (\`lattice todo status --json\` lists them), then rerun.`,
258
+ locked: `Its predecessor phases are not accepted yet; see \`lattice todo phase status --plan ${plan}\`.`,
259
+ accepted: `It is already decided; to audit it again run \`lattice todo phase reopen ${on} --reason <text>\` first.`,
260
+ closed_unaudited: `It is already closed; to audit it run \`lattice todo phase reopen ${on} --reason <text>\` first.`,
261
+ }[status] ?? `See \`lattice todo phase status --plan ${plan}\`.`);
262
+ },
263
+ },
264
+ authored_start_binding_missing: {
265
+ // a35: say why there is nothing to retract and the step that closes the task instead.
266
+ repair: (detail, ctx) => `retract undoes only a start recorded by \`lattice todo start\`; `
267
+ + `${planOf(detail, ctx)}/${taskOf(detail, ctx)} is in progress${openedByText(detail)}, so there is no start to undo. `
268
+ + `Finish it with \`lattice todo done --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}\`.`,
269
+ },
187
270
  reopen_has_started_successor: {
188
271
  repair: (detail, ctx) => `A successor of ${taskOf(detail, ctx)} has already started: to reopen it anyway run \`lattice todo reopen --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)} --reason <text> --override-reason <text>\`.`,
189
272
  },
@@ -330,7 +413,8 @@ const REGISTRY = {
330
413
 
331
414
  plan_revise_schema_invalid: {
332
415
  pointer: '--input',
333
- repair: (detail, ctx) => `Use schema ${q(detail.expected)}; see \`${schemaCommand(ctx)}\`.`,
416
+ // a31: 包みの形を名指す。素のplan create入力も受けるので、まずそれを勧める。
417
+ repair: (detail, ctx) => `Pass the whole desired plan in the same shape as \`lattice plan create\` (start from \`lattice plan create --template --json\`), or wrap it as {"schema":${JSON.stringify(detail.expected)},"desired":<that plan>,"continuity":[...]} to state carry/reset/retire yourself; see \`${schemaCommand(ctx)}\`.`,
334
418
  },
335
419
  plan_revise_requires_source_revision: {
336
420
  repair: (detail) => `This plan carries source revisions: use ${detail.next_action ?? '`lattice todo revise-phase --plan <plan> --input <file>`'}.`,
@@ -174,6 +174,14 @@ export function resolvePlanRevision({ member, input, env = process.env, now = ne
174
174
  fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
175
175
  }
176
176
  if (input.schema !== INPUT_SCHEMA) fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
177
+ // a31: 無いplanは補完の前に断る。補完は現行planの値を使うので、無いplanでは「欄を足せ」に化ける。
178
+ if (member === undefined) {
179
+ const planKey = typeof input.desired?.plan_key === 'string' ? input.desired.plan_key : null;
180
+ fail('plan_not_active', '/desired/plan_key', {
181
+ plan_key: planKey,
182
+ next_action: `No active plan ${planKey === null ? 'with that plan_key' : `'${planKey}'`}: make it as a new plan with \`lattice plan create --input <file>\` (the plan itself, without the revise wrapper); to revise an existing one, set plan_key to one listed by \`lattice todo status --json\`.`,
183
+ });
184
+ }
177
185
  // a17: 改訂は既存planの上で行うので、project_id・plan_versionは書かなければ現行planの値で埋まる。
178
186
  const desired = completeCreateInput(input.desired, {
179
187
  env, now, projectId: member?.plan.project_id, planVersion: member?.plan.plan_version,
@@ -192,7 +200,6 @@ export function resolvePlanRevision({ member, input, env = process.env, now = ne
192
200
  actual: desired.schema, next_action: 'lattice plan create --schema-version 5 --json',
193
201
  });
194
202
  }
195
- if (member === undefined) fail('plan_not_active', '/desired/plan_key');
196
203
  if (member.plan.schema === 'lattice.todo_plan.v6'
197
204
  || member.journal.events[0].schema === 'lattice.todo_event.v2'
198
205
  || [...member.plan.tasks, ...desired.tasks].some((task) => task.narrative_anchor !== null)) {
@@ -310,12 +317,45 @@ export function desiredFromPlan(plan, { env = process.env, now = new Date() } =
310
317
  * 公開→履歴note→作業中taskの結び直しまで行って、結果artifactを返す(印字はしない)。
311
318
  * notes: 履歴noteへ足す plan scope の追加note([{task_id, body}])。公開後に改訂noteと同じ経路で追記する。
312
319
  */
320
+ /**
321
+ * a31: 作成・追加・改訂は同じ入力の形を持つ(seat contract)。`desired`で包まないplan create入力は
322
+ * そのまま望む全体として読み、継続方針は機械が算出する。包んだ形(continuity付き)もそのまま受ける。
323
+ */
324
+ export function isBareCreateInput(input) {
325
+ return input !== null && typeof input === 'object' && !Array.isArray(input)
326
+ && !('desired' in input) && Array.isArray(input.tasks)
327
+ && (input.schema === undefined || /^lattice\.plan_create_input\.v[0-9]+$/u.test(input.schema));
328
+ }
329
+
330
+ /** 包まない入力の拒否は、包みの`/desired`を名指さない。 */
331
+ function unwrapPointers(error) {
332
+ const detail = error?.detail;
333
+ if (detail === null || typeof detail !== 'object') return error;
334
+ if (typeof detail.pointer === 'string' && detail.pointer.startsWith('/desired')) {
335
+ detail.pointer = detail.pointer.slice('/desired'.length) || '/';
336
+ }
337
+ if (typeof detail.next_action === 'string') {
338
+ detail.next_action = detail.next_action.replaceAll('/desired/', '/');
339
+ }
340
+ for (const problem of Array.isArray(detail.problems) ? detail.problems : []) {
341
+ if (typeof problem?.pointer === 'string' && problem.pointer.startsWith('/desired')) {
342
+ problem.pointer = problem.pointer.slice('/desired'.length) || '/';
343
+ }
344
+ }
345
+ return error;
346
+ }
347
+
313
348
  export async function applyPlanRevision({
314
- repoRoot, input, env = process.env, dryRun = false, notes: extraNotes = [],
349
+ repoRoot, input: authored, env = process.env, dryRun = false, notes: extraNotes = [],
315
350
  }) {
351
+ const bare = isBareCreateInput(authored);
352
+ const input = bare ? { schema: INPUT_SCHEMA, desired: authored } : authored;
316
353
  const store = await readTodoStore({ repoRoot });
317
354
  const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
318
- const { desired, continuity } = resolvePlanRevision({ member, input, env, now: new Date() });
355
+ let resolved;
356
+ try { resolved = resolvePlanRevision({ member, input, env, now: new Date() }); }
357
+ catch (error) { throw bare ? unwrapPointers(error) : error; }
358
+ const { desired, continuity } = resolved;
319
359
  // 集合の並びは正準化済みなので、同じ内容の別の並びは「変更なし」になる。
320
360
  const unchanged = continuity.every(({ policy }) => policy === 'carry')
321
361
  && canonicalizeTodoArtifact(planSeed(desired, null, member.plan))
@@ -14,7 +14,9 @@ import { TodoStoreError } from './todo-store.mjs';
14
14
 
15
15
  const REVIEW_SCHEMA = 'lattice.plan_scope_review.v1';
16
16
  const RESULT_SCHEMA = 'lattice.plan_scope_review_result.v1';
17
- const PLAN_CREATE_SCHEMA = 'lattice.plan_create_input.v4';
17
+ // a31: 席が書く既定(v5、template)も審査できる。schemaを省いた入力はv5として読む(plan createと同じ)。
18
+ const PLAN_CREATE_SCHEMAS = new Set(['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5']);
19
+ const DEFAULT_PLAN_CREATE_SCHEMA = 'lattice.plan_create_input.v5';
18
20
  const TODO_EXTRACTION_SCHEMAS = new Set([
19
21
  'lattice.todo_extraction.v3',
20
22
  'lattice.todo_extraction.v4',
@@ -76,18 +78,22 @@ async function readJsonWithinRepo(repoRoot, inputRef) {
76
78
  }
77
79
 
78
80
  function authoredPlan(value) {
79
- const digestField = value?.schema === PLAN_CREATE_SCHEMA ? 'input_digest'
81
+ const createInput = value !== null && typeof value === 'object' && !Array.isArray(value)
82
+ && (PLAN_CREATE_SCHEMAS.has(value.schema) || value.schema === undefined);
83
+ const digestField = createInput ? 'input_digest'
80
84
  : TODO_EXTRACTION_SCHEMAS.has(value?.schema) ? 'extraction_digest' : null;
81
85
  if (digestField === null) {
82
86
  throw new TodoStoreError('PLAN_SCOPE_REVIEW_INVALID', 'authoring_schema_unsupported', undefined, {
83
- pointer: '/schema', expected: [PLAN_CREATE_SCHEMA, ...TODO_EXTRACTION_SCHEMAS],
87
+ pointer: '/schema', expected: [...PLAN_CREATE_SCHEMAS, ...TODO_EXTRACTION_SCHEMAS],
84
88
  actual: typeof value?.schema === 'string' ? value.schema : null,
85
89
  });
86
90
  }
87
- if (!isTodoDigest(value[digestField])
88
- || value[digestField] !== todoSelfDigest(value, digestField)) {
91
+ // a31: digestは機械が計算する。書かれていなければ本文から求め、書かれていて違えば期待値を返す。
92
+ const digest = todoSelfDigest(value, digestField);
93
+ if (value[digestField] !== undefined && value[digestField] !== '' && value[digestField] !== digest) {
89
94
  throw new TodoStoreError('PLAN_SCOPE_REVIEW_INVALID', 'authoring_digest_mismatch', undefined, {
90
- pointer: `/${digestField}`,
95
+ pointer: `/${digestField}`, expected: digest, actual: value[digestField],
96
+ next_action: `Omit ${digestField} (the machine computes it) or set it to "${digest}".`,
91
97
  });
92
98
  }
93
99
  const selected = TODO_EXTRACTION_SCHEMAS.has(value.schema)
@@ -106,17 +112,33 @@ function authoredPlan(value) {
106
112
  pointer: '/tasks',
107
113
  });
108
114
  }
109
- return { schema: value.schema, digest: value[digestField], taskIds };
115
+ return { schema: value.schema ?? DEFAULT_PLAN_CREATE_SCHEMA, digest, taskIds };
110
116
  }
111
117
 
112
118
  function invalid(reason, pointer, detail = {}) {
113
119
  throw new TodoStoreError('PLAN_SCOPE_REVIEW_INVALID', reason, undefined, { pointer, ...detail });
114
120
  }
115
121
 
122
+ const REVIEW_KEYS = ['schema', 'authoring_digest', 'work_specs', 'task_assessments', 'verdict', 'review_digest'];
123
+
124
+ /** a31: 席は判断だけを書く。authoring_digestとreview_digestは省けば機械が埋める(書けば照合する)。 */
125
+ function completeReview(review, authored) {
126
+ if (review === null || typeof review !== 'object' || Array.isArray(review)) return review;
127
+ const filled = { ...review };
128
+ if (filled.authoring_digest === undefined || filled.authoring_digest === '') filled.authoring_digest = authored.digest;
129
+ if (filled.review_digest === undefined || filled.review_digest === '') {
130
+ filled.review_digest = todoSelfDigest(filled, 'review_digest');
131
+ }
132
+ return filled;
133
+ }
134
+
116
135
  function validateReview(review, authored) {
117
- if (!exactRecord(review, [
118
- 'schema', 'authoring_digest', 'work_specs', 'task_assessments', 'verdict', 'review_digest',
119
- ]) || review.schema !== REVIEW_SCHEMA) invalid('review_schema_invalid', '/schema');
136
+ if (!exactRecord(review, REVIEW_KEYS) || review.schema !== REVIEW_SCHEMA) {
137
+ invalid('review_schema_invalid', exactRecord(review, REVIEW_KEYS) ? '/schema' : '/', {
138
+ expected: { schema: REVIEW_SCHEMA, keys: [...REVIEW_KEYS].sort() },
139
+ actual: review !== null && typeof review === 'object' ? { keys: Object.keys(review).sort() } : null,
140
+ });
141
+ }
120
142
  if (!isTodoDigest(review.authoring_digest) || review.authoring_digest !== authored.digest) {
121
143
  invalid('review_authoring_digest_mismatch', '/authoring_digest', {
122
144
  expected: authored.digest, actual: review.authoring_digest ?? null,
@@ -124,7 +146,9 @@ function validateReview(review, authored) {
124
146
  }
125
147
  if (!isTodoDigest(review.review_digest)
126
148
  || review.review_digest !== todoSelfDigest(review, 'review_digest')) {
127
- invalid('review_digest_mismatch', '/review_digest');
149
+ invalid('review_digest_mismatch', '/review_digest', {
150
+ expected: todoSelfDigest(review, 'review_digest'), actual: review.review_digest ?? null,
151
+ });
128
152
  }
129
153
  if (!Array.isArray(review.work_specs) || review.work_specs.length === 0
130
154
  || !review.work_specs.every((spec) => exactRecord(spec, [
@@ -170,8 +194,9 @@ function validateReview(review, authored) {
170
194
  return { outOfScopeTaskIds, uncoveredWorkSpecIds };
171
195
  }
172
196
 
173
- export function evaluatePlanScopeReview(planInput, review) {
197
+ export function evaluatePlanScopeReview(planInput, authoredReview) {
174
198
  const authored = authoredPlan(planInput);
199
+ const review = completeReview(authoredReview, authored);
175
200
  const findings = validateReview(review, authored);
176
201
  const result = {
177
202
  schema: RESULT_SCHEMA,
@@ -581,6 +581,47 @@ export function compileRuntimePlanV1(options = {}) {
581
581
  }
582
582
  if (ambiguous.length > 0) return nonDispatchable('QUERY_DRIFT', { ambiguous_targets: ambiguous });
583
583
 
584
+ // observation set resources。
585
+ const resources = [];
586
+ for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
587
+ const coveringQueryId = coveringByTarget.get(key);
588
+ if (coveringQueryId === undefined) continue; // 未束縛ownsは既にunknownへ落ちている
589
+ const outcome = outcomeByQueryId.get(coveringQueryId);
590
+ // covering bindingのexpectを、実際にこのtargetを束縛したwitnessから再取得する。
591
+ let representative;
592
+ for (const todoId of group.todoIds) {
593
+ representative = bindingsByTodo.get(todoId).find((entry) => (
594
+ entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
595
+ ));
596
+ if (representative !== undefined) break;
597
+ }
598
+ if (representative === undefined) fail(`covering binding不整合: ${group.own.target}`);
599
+ if (predictionsOnly && resolveBindingStatus(representative, outcome) !== 'ready') continue;
600
+ const status = statusOutcome.status !== 'ready'
601
+ ? statusOutcome.status
602
+ : resolveBindingStatus(representative, outcome);
603
+ resources.push({
604
+ resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
605
+ kind: group.own.kind,
606
+ target: group.own.target,
607
+ todo_ids: [...group.todoIds].sort(compareText),
608
+ provenance: [
609
+ {
610
+ source: 'sensor',
611
+ evidence_ref: coveringQueryId,
612
+ evidence_digest: outcome.portable_digest,
613
+ status,
614
+ },
615
+ candidateProvenance(request),
616
+ ],
617
+ });
618
+ }
619
+
620
+ const ownResourceCovers = (target, leftId, rightId) => resources.some((resource) => (
621
+ resource.kind === 'path' && resource.target === target
622
+ && resource.todo_ids.includes(leftId) && resource.todo_ids.includes(rightId)
623
+ ));
624
+
584
625
  // 最新契約ではwrite scopeは予測である。既知の交差はserial conflictへ使うが、
585
626
  // 予測が足りないこと自体はunknownへ落とさない。
586
627
  const predictedWriteGroups = [];
@@ -588,15 +629,13 @@ export function compileRuntimePlanV1(options = {}) {
588
629
  for (let right = left + 1; right < todoIds.length; right += 1) {
589
630
  const leftWitness = request.manual_witness[todoIds[left]];
590
631
  const rightWitness = request.manual_witness[todoIds[right]];
591
- const leftOwnPaths = new Set(leftWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
592
- const rightOwnPaths = new Set(rightWitness.owns.filter((own) => own.kind === 'path').map((own) => own.target));
593
632
  for (const leftPath of leftWitness.writes) {
594
633
  for (const rightPath of rightWitness.writes) {
595
634
  if (!pathPrefixOverlap(leftPath, rightPath)) continue;
596
- // 同一targetを両者がownsで所有主張している場合はwrite conflictとして
597
- // resource経由で扱われる。owns解決のない交差だけをunknownにする。
598
- if (leftOwnPaths.has(leftPath) && rightOwnPaths.has(rightPath)
599
- && leftPath === rightPath) continue;
635
+ // 同一targetを両者がownsで所有主張し、そのowns resourceが実際に両者を含む時だけ
636
+ // write conflictはresource経由で扱われる。予測契約では裏付けの無いownsはresourceに
637
+ // ならないので、ここで飛ばすと衝突が消える(a35、主張4)。
638
+ if (leftPath === rightPath && ownResourceCovers(leftPath, todoIds[left], todoIds[right])) continue;
600
639
  if (predictionsOnly) {
601
640
  predictedWriteGroups.push({
602
641
  target: [leftPath, rightPath].sort(compareText).join(' ↔ '),
@@ -683,42 +722,6 @@ export function compileRuntimePlanV1(options = {}) {
683
722
  }
684
723
  }
685
724
 
686
- // observation set resources。
687
- const resources = [];
688
- for (const [key, group] of [...ownGroups.entries()].sort((left, right) => compareText(left[0], right[0]))) {
689
- const coveringQueryId = coveringByTarget.get(key);
690
- if (coveringQueryId === undefined) continue; // 未束縛ownsは既にunknownへ落ちている
691
- const outcome = outcomeByQueryId.get(coveringQueryId);
692
- // covering bindingのexpectを、実際にこのtargetを束縛したwitnessから再取得する。
693
- let representative;
694
- for (const todoId of group.todoIds) {
695
- representative = bindingsByTodo.get(todoId).find((entry) => (
696
- entry.query_id === coveringQueryId && bindingCoversOwn(entry, group.own)
697
- ));
698
- if (representative !== undefined) break;
699
- }
700
- if (representative === undefined) fail(`covering binding不整合: ${group.own.target}`);
701
- if (predictionsOnly && resolveBindingStatus(representative, outcome) !== 'ready') continue;
702
- const status = statusOutcome.status !== 'ready'
703
- ? statusOutcome.status
704
- : resolveBindingStatus(representative, outcome);
705
- resources.push({
706
- resource_id: `own-${group.own.kind}-${sha16(group.own.target)}`,
707
- kind: group.own.kind,
708
- target: group.own.target,
709
- todo_ids: [...group.todoIds].sort(compareText),
710
- provenance: [
711
- {
712
- source: 'sensor',
713
- evidence_ref: coveringQueryId,
714
- evidence_digest: outcome.portable_digest,
715
- status,
716
- },
717
- candidateProvenance(request),
718
- ],
719
- });
720
- }
721
-
722
725
  const stateGroups = new Map();
723
726
  for (const todoId of todoIds) {
724
727
  for (const entry of request.manual_witness[todoId].state_effects) {
@@ -16,8 +16,16 @@ export function resolveSeatIdentity(env = process.env) {
16
16
  return Object.freeze({ seat_id, state_dir });
17
17
  }
18
18
 
19
- /** status / session-context の top-level へ混ぜる欄。未設定なら空(欄を出さない)。 */
19
+ /**
20
+ * session-context の top-level へ混ぜる欄。未設定なら空(欄を出さない)。
21
+ * 設定したのに不正な値は、断らずに無名へ落とし、捨てた値と規則を名指す(打ち間違いに気づかせる、a33)。
22
+ */
20
23
  export function seatIdentityFields(env = process.env) {
21
24
  const { seat_id } = resolveSeatIdentity(env);
22
- return seat_id === null ? {} : { seat_id };
25
+ if (seat_id !== null) return { seat_id };
26
+ const raw = env.LATTICE_SEAT_ID;
27
+ // An empty value is the usual way to clear the variable, so it stays silent.
28
+ if (typeof raw !== 'string' || raw === '') return {};
29
+ return { seat_id_ignored: { value: raw.slice(0, 80),
30
+ rule: 'LATTICE_SEAT_ID must be 1-64 of letters, digits, ".", "_", "-", starting with a letter or digit; this seat runs anonymous' } };
23
31
  }
@@ -38,9 +38,11 @@ export function isAuditPendingPhaseStatus(status) {
38
38
  * 監査待ちでない状態を渡すのは呼び出し側の誤りなので、空配列へ丸めずに投げる。
39
39
  * 呼ぶ前に`isAuditPendingPhaseStatus`で絞ること。
40
40
  *
41
+ * `slotCount`は必須evidence slotの数。1つなら`--evidence`で足り、複数なら`--input`が要る。
42
+ *
41
43
  * @returns {string[]} 実行可能なコマンド行(1つ以上)
42
44
  */
43
- export function auditPendingNextCommands(planKey, phaseId, status) {
45
+ export function auditPendingNextCommands(planKey, phaseId, status, slotCount = 1) {
44
46
  const target = `--plan ${planKey} --phase ${phaseId}`;
45
47
  if (status === 'gate_ready') {
46
48
  return [
@@ -50,8 +52,9 @@ export function auditPendingNextCommands(planKey, phaseId, status) {
50
52
  }
51
53
  if (status === 'reviewing') {
52
54
  return [
53
- `lattice todo phase accept ${target} --input <file>`,
54
- `lattice todo phase reject ${target} --input <file>`,
55
+ // a36: --evidence fills the decision from one committed file; several slots need --input.
56
+ `lattice todo phase accept ${target} ${slotCount === 1 ? '--evidence <file>' : '--input <file>'}`,
57
+ `lattice todo phase reject ${target} --reason <text> --evidence <file>`,
55
58
  ];
56
59
  }
57
60
  if (status === 'rejected') {
@@ -36,6 +36,15 @@ function seatAgent(env) {
36
36
  return isTodoIdentifier(seat_id) ? seat_id : null;
37
37
  }
38
38
 
39
+ const anonymousAgent = (env) => (isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
40
+ ? env.LATTICE_TODO_ACTOR_AGENT : sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'));
41
+
42
+ /** a36: the agent this env writes now, and the one it wrote before setting LATTICE_SEAT_ID. No I/O. */
43
+ export function todoActorAgents(env) {
44
+ const anonymous = anonymousAgent(env);
45
+ return { agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT) ? anonymous : seatAgent(env) ?? anonymous, anonymous };
46
+ }
47
+
39
48
  // u03s A57: a set but non-identifier value is treated like an unset one (no refusal).
40
49
  export function resolveTodoActor(env) {
41
50
  return {
@@ -46,9 +55,7 @@ export function resolveTodoActor(env) {
46
55
  ? env.LATTICE_TODO_ACTOR_SESSION
47
56
  : 'session',
48
57
  // 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'),
58
+ agent: todoActorAgents(env).agent,
52
59
  };
53
60
  }
54
61