@quolu/lattice 0.85.2 → 0.85.3

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,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.plan_revise_input.v1.schema.json",
4
4
  "title": "lattice.plan_revise_input.v1",
5
- "description": "工程全体のdesired stateと、必要なら状態移行の指定。継続方針は機械が全ての旧taskについて算出する(desiredに在れば既定carry、無ければretire)。predecessor/CAS/digest/後継versionも機械が算出する。旧版は保持する。",
5
+ "description": "工程全体のdesired stateと、必要なら状態移行の指定。継続方針は機械が全ての旧taskについて算出する(desiredに在れば既定carry、無ければretire)。predecessor/CAS/digest/後継versionも機械が算出する。旧版は保持する。この包みを使わず、desiredの中身(plan createと同じ形の計画の全体)だけを--inputへ渡してもよい(a31)。そのとき継続方針はすべて機械が算出する。現行planが無いplan_keyはplan createで作る。",
6
6
  "type": "object",
7
7
  "additionalProperties": false,
8
8
  "required": [
@@ -2,12 +2,12 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.plan_scope_review.v1.schema.json",
4
4
  "title": "lattice.plan_scope_review.v1",
5
- "description": "AI-authored review performed after the complete plan is written and before it is registered. Every planned task is judged against the owner-supplied work specifications; task splitting and parallelization are allowed, but a new product purpose is not.",
6
- "$comment": "Lattice validates complete task coverage, known work-spec references, verdict consistency, and digest binding. The operating AI owns the semantic judgment.",
5
+ "description": "AI-authored review performed after the complete plan is written and before it is registered. Every planned task is judged against the owner-supplied work specifications; task splitting and parallelization are allowed, but a new product purpose is not. The plan input may be a plan create input v4 or v5 (the template default; a missing schema reads as v5) or a todo extraction v3/v4.",
6
+ "$comment": "Lattice validates complete task coverage, known work-spec references, verdict consistency, and digest binding. The operating AI owns the semantic judgment. authoring_digest and review_digest may be omitted: the machine computes both (authoring_digest is the plan input's input_digest, or extraction_digest, computed from its content); a written value must match.",
7
7
  "type": "object",
8
8
  "additionalProperties": false,
9
9
  "required": [
10
- "schema", "authoring_digest", "work_specs", "task_assessments", "verdict", "review_digest"
10
+ "schema", "work_specs", "task_assessments", "verdict"
11
11
  ],
12
12
  "properties": {
13
13
  "schema": { "const": "lattice.plan_scope_review.v1" },
@@ -0,0 +1,86 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.todo_witness_draft.v2.schema.json",
4
+ "title": "lattice.todo_witness_draft.v2",
5
+ "description": "What a seat writes to declare, per ToDo, which repo files it owns, reads and writes. `lattice todo independence witness scaffold --plan <key> --input <draft>` turns it into the witness set (lattice.todo_witness_set.v5) that `independence compile` reads, adding what a seat cannot write by hand: fresh affected-test observations, the sensor query wiring and the self-digest. Start from `lattice todo independence witness scaffold --template --plan <key>`.",
6
+ "$comment": "v1 is still accepted; it allows only string `owns`. Include every task that is not done yet (ready, blocked and later ones), not only the current ready ones.",
7
+ "type": "object",
8
+ "required": ["schema", "project_id", "plan_key", "capacity", "tasks"],
9
+ "properties": {
10
+ "schema": { "enum": ["lattice.todo_witness_draft.v2", "lattice.todo_witness_draft.v1"] },
11
+ "project_id": { "$ref": "#/$defs/identifier" },
12
+ "plan_key": { "$ref": "#/$defs/identifier" },
13
+ "capacity": {
14
+ "type": "object",
15
+ "required": ["executors"],
16
+ "properties": {
17
+ "executors": { "type": "integer", "minimum": 1, "description": "How many tasks may run at once." }
18
+ }
19
+ },
20
+ "tasks": {
21
+ "type": "object",
22
+ "minProperties": 1,
23
+ "propertyNames": { "$ref": "#/$defs/identifier" },
24
+ "additionalProperties": { "$ref": "#/$defs/task" },
25
+ "description": "Keyed by task_id."
26
+ }
27
+ },
28
+ "$defs": {
29
+ "identifier": { "type": "string", "pattern": "^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$" },
30
+ "repoRelativePath": {
31
+ "type": "string",
32
+ "minLength": 1,
33
+ "maxLength": 1024,
34
+ "description": "Repo-relative path. Absolute paths, backslashes and '..' traversal are rejected."
35
+ },
36
+ "task": {
37
+ "type": "object",
38
+ "required": ["owns"],
39
+ "properties": {
40
+ "owns": {
41
+ "type": "array",
42
+ "description": "Files this task owns. A file that does not exist yet is written as {\"path\": <file>, \"creates\": true} (v2 only).",
43
+ "items": {
44
+ "anyOf": [
45
+ { "$ref": "#/$defs/repoRelativePath" },
46
+ {
47
+ "type": "object",
48
+ "additionalProperties": false,
49
+ "required": ["path", "creates"],
50
+ "properties": {
51
+ "path": { "$ref": "#/$defs/repoRelativePath" },
52
+ "creates": { "const": true }
53
+ }
54
+ }
55
+ ]
56
+ }
57
+ },
58
+ "reads": { "type": "array", "items": { "$ref": "#/$defs/repoRelativePath" } },
59
+ "writes": { "type": "array", "items": { "$ref": "#/$defs/repoRelativePath" } },
60
+ "unknowns": {
61
+ "type": "array",
62
+ "items": {
63
+ "type": "object",
64
+ "required": ["kind", "ref"],
65
+ "properties": {
66
+ "kind": { "$ref": "#/$defs/identifier" },
67
+ "ref": { "type": "string", "minLength": 1 }
68
+ }
69
+ }
70
+ },
71
+ "concern_anchors": {
72
+ "type": "array",
73
+ "description": "Symbols this task touches inside a contested file it owns or writes; used only to bind seam proposals.",
74
+ "items": {
75
+ "type": "object",
76
+ "required": ["within", "symbols"],
77
+ "properties": {
78
+ "within": { "$ref": "#/$defs/repoRelativePath" },
79
+ "symbols": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/identifier" } }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+ }
@@ -0,0 +1,400 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.todo_witness_set.v5.schema.json",
4
+ "title": "lattice.todo_witness_set.v5",
5
+ "description": "Per-ToDo boundary declaration compiled into a recorded independence judgement (ADR 0127). v5 adds optional semantic line declarations so protocol, stream and schema dependencies can be declared even when file paths do not overlap.",
6
+ "$comment": "Runtime validation additionally enforces canonical JSON+LF bytes, the self-digest rule, unique line_id values per ToDo, and closed line anchor shapes. concern_anchors is stripped before run-request synthesis; lines is preserved because it participates in scheduling. v1-v4 declarations remain valid input without lines, and adding lines to an old schema is rejected rather than reinterpreted.",
7
+ "type": "object",
8
+ "additionalProperties": false,
9
+ "required": [
10
+ "schema",
11
+ "project_id",
12
+ "plan_key",
13
+ "capacity",
14
+ "sensor_query_set",
15
+ "manual_witness",
16
+ "witness_set_digest"
17
+ ],
18
+ "properties": {
19
+ "schema": {
20
+ "const": "lattice.todo_witness_set.v5"
21
+ },
22
+ "project_id": {
23
+ "$ref": "#/$defs/identifier"
24
+ },
25
+ "plan_key": {
26
+ "$ref": "#/$defs/identifier"
27
+ },
28
+ "capacity": {
29
+ "type": "object",
30
+ "additionalProperties": false,
31
+ "required": [
32
+ "executors"
33
+ ],
34
+ "properties": {
35
+ "executors": {
36
+ "type": "integer",
37
+ "minimum": 1
38
+ }
39
+ }
40
+ },
41
+ "sensor_query_set": {
42
+ "type": "object",
43
+ "additionalProperties": false,
44
+ "required": [
45
+ "queries"
46
+ ],
47
+ "description": "Sensor queries backing the declarations. Exactly one query must have operation 'status'.",
48
+ "properties": {
49
+ "queries": {
50
+ "type": "array",
51
+ "maxItems": 256,
52
+ "items": {
53
+ "type": "object",
54
+ "additionalProperties": false,
55
+ "required": [
56
+ "id",
57
+ "operation"
58
+ ],
59
+ "properties": {
60
+ "id": {
61
+ "$ref": "#/$defs/identifier"
62
+ },
63
+ "operation": {
64
+ "enum": [
65
+ "status",
66
+ "query",
67
+ "callers",
68
+ "callees",
69
+ "impact",
70
+ "affected"
71
+ ]
72
+ },
73
+ "target": {
74
+ "type": "string",
75
+ "minLength": 1
76
+ }
77
+ }
78
+ }
79
+ }
80
+ }
81
+ },
82
+ "manual_witness": {
83
+ "type": "object",
84
+ "minProperties": 1,
85
+ "maxProperties": 256,
86
+ "description": "Keyed by task_id of the plan. Keys must be a subset of the plan's tasks.",
87
+ "propertyNames": {
88
+ "$ref": "#/$defs/identifier"
89
+ },
90
+ "additionalProperties": {
91
+ "$ref": "#/$defs/witness"
92
+ }
93
+ },
94
+ "witness_set_digest": {
95
+ "$ref": "#/$defs/digest"
96
+ }
97
+ },
98
+ "$defs": {
99
+ "identifier": {
100
+ "type": "string",
101
+ "pattern": "^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$"
102
+ },
103
+ "digest": {
104
+ "type": "string",
105
+ "pattern": "^[0-9a-f]{64}$"
106
+ },
107
+ "repoRelativePath": {
108
+ "type": "string",
109
+ "minLength": 1,
110
+ "maxLength": 1024,
111
+ "description": "Repo-relative path. Absolute paths, backslashes and '..' traversal are rejected. A trailing '/' declares a directory prefix and is accepted only under 'writes'."
112
+ },
113
+ "lineAnchor": {
114
+ "oneOf": [
115
+ {
116
+ "type": "object",
117
+ "additionalProperties": false,
118
+ "required": ["kind", "path"],
119
+ "properties": {
120
+ "kind": { "const": "path" },
121
+ "path": { "$ref": "#/$defs/repoRelativePath" }
122
+ }
123
+ },
124
+ {
125
+ "type": "object",
126
+ "additionalProperties": false,
127
+ "required": ["kind", "name", "path"],
128
+ "properties": {
129
+ "kind": { "const": "symbol" },
130
+ "name": { "type": "string", "minLength": 1, "maxLength": 1024 },
131
+ "path": { "$ref": "#/$defs/repoRelativePath" }
132
+ }
133
+ }
134
+ ]
135
+ },
136
+ "line": {
137
+ "type": "object",
138
+ "additionalProperties": false,
139
+ "required": ["line_id", "role", "anchors"],
140
+ "properties": {
141
+ "line_id": { "$ref": "#/$defs/identifier" },
142
+ "role": { "enum": ["reads", "writes"] },
143
+ "anchors": {
144
+ "type": "array",
145
+ "minItems": 1,
146
+ "maxItems": 256,
147
+ "items": { "$ref": "#/$defs/lineAnchor" }
148
+ }
149
+ }
150
+ },
151
+ "witness": {
152
+ "type": "object",
153
+ "additionalProperties": false,
154
+ "required": [
155
+ "owns",
156
+ "reads",
157
+ "writes",
158
+ "resources",
159
+ "state_effects",
160
+ "sensor_provenance",
161
+ "affected_tests",
162
+ "unknowns"
163
+ ],
164
+ "properties": {
165
+ "owns": {
166
+ "type": "array",
167
+ "maxItems": 256,
168
+ "description": "Symbols and paths this ToDo claims ownership of. Every entry needs a covering sensor query or it compiles to a sensor_unbound unknown. An entry may additionally declare creates: true for a path this ToDo will bring into existence.",
169
+ "items": {
170
+ "type": "object",
171
+ "additionalProperties": false,
172
+ "required": [
173
+ "kind",
174
+ "target"
175
+ ],
176
+ "properties": {
177
+ "kind": {
178
+ "enum": [
179
+ "symbol",
180
+ "path"
181
+ ]
182
+ },
183
+ "target": {
184
+ "type": "string",
185
+ "minLength": 1,
186
+ "maxLength": 1024
187
+ },
188
+ "creates": {
189
+ "const": true,
190
+ "description": "Optional. Declares that this path does not exist yet and that this ToDo creates it. Only valid when kind is path — existence is a filesystem fact and a symbol has none of its own. Only the value true is accepted: false would be a second spelling of an existing path. Omitted is the default."
191
+ }
192
+ }
193
+ }
194
+ },
195
+ "reads": {
196
+ "type": "array",
197
+ "maxItems": 256,
198
+ "items": {
199
+ "$ref": "#/$defs/repoRelativePath"
200
+ }
201
+ },
202
+ "writes": {
203
+ "type": "array",
204
+ "maxItems": 256,
205
+ "items": {
206
+ "$ref": "#/$defs/repoRelativePath"
207
+ }
208
+ },
209
+ "resources": {
210
+ "type": "array",
211
+ "maxItems": 256,
212
+ "description": "Shared resource ids. A resource with no matching state_effect entry is treated as a shared resource of unknown direction and becomes a conflict.",
213
+ "items": {
214
+ "$ref": "#/$defs/identifier"
215
+ }
216
+ },
217
+ "state_effects": {
218
+ "type": "array",
219
+ "maxItems": 256,
220
+ "items": {
221
+ "type": "object",
222
+ "additionalProperties": false,
223
+ "required": [
224
+ "resource_id",
225
+ "kind"
226
+ ],
227
+ "properties": {
228
+ "resource_id": {
229
+ "$ref": "#/$defs/identifier"
230
+ },
231
+ "kind": {
232
+ "enum": [
233
+ "state",
234
+ "schema",
235
+ "invariant",
236
+ "effect",
237
+ "external_effect"
238
+ ]
239
+ }
240
+ }
241
+ }
242
+ },
243
+ "sensor_provenance": {
244
+ "type": "object",
245
+ "additionalProperties": false,
246
+ "required": [
247
+ "queries"
248
+ ],
249
+ "properties": {
250
+ "queries": {
251
+ "type": "array",
252
+ "maxItems": 256,
253
+ "items": {
254
+ "type": "object",
255
+ "additionalProperties": false,
256
+ "required": [
257
+ "query_id",
258
+ "expect"
259
+ ],
260
+ "properties": {
261
+ "query_id": {
262
+ "$ref": "#/$defs/identifier"
263
+ },
264
+ "expect": {
265
+ "oneOf": [
266
+ {
267
+ "type": "object",
268
+ "additionalProperties": false,
269
+ "required": [
270
+ "kind",
271
+ "name",
272
+ "path"
273
+ ],
274
+ "properties": {
275
+ "kind": {
276
+ "const": "symbol"
277
+ },
278
+ "name": {
279
+ "type": "string",
280
+ "minLength": 1
281
+ },
282
+ "path": {
283
+ "$ref": "#/$defs/repoRelativePath"
284
+ }
285
+ }
286
+ },
287
+ {
288
+ "type": "object",
289
+ "additionalProperties": false,
290
+ "required": [
291
+ "kind",
292
+ "path"
293
+ ],
294
+ "properties": {
295
+ "kind": {
296
+ "enum": [
297
+ "path",
298
+ "affected"
299
+ ]
300
+ },
301
+ "path": {
302
+ "$ref": "#/$defs/repoRelativePath"
303
+ }
304
+ }
305
+ }
306
+ ]
307
+ }
308
+ }
309
+ }
310
+ }
311
+ }
312
+ },
313
+ "affected_tests": {
314
+ "type": "array",
315
+ "maxItems": 256,
316
+ "description": "Declared affected tests. Compared exactly against fresh sensor observation; any drift fails the compile rather than being narrowed.",
317
+ "items": {
318
+ "$ref": "#/$defs/repoRelativePath"
319
+ }
320
+ },
321
+ "unknowns": {
322
+ "type": "array",
323
+ "maxItems": 256,
324
+ "description": "Explicitly declared residual unknowns. Recorded, never rounded away.",
325
+ "items": {
326
+ "type": "object",
327
+ "additionalProperties": false,
328
+ "required": [
329
+ "kind",
330
+ "ref"
331
+ ],
332
+ "properties": {
333
+ "kind": {
334
+ "$ref": "#/$defs/identifier"
335
+ },
336
+ "ref": {
337
+ "type": "string",
338
+ "minLength": 1
339
+ }
340
+ }
341
+ }
342
+ },
343
+ "lines": {
344
+ "type": "array",
345
+ "maxItems": 256,
346
+ "description": "Optional semantic lines read or written by this ToDo. line_id values must be unique within the ToDo.",
347
+ "items": { "$ref": "#/$defs/line" }
348
+ },
349
+ "concern_anchors": {
350
+ "type": "array",
351
+ "maxItems": 256,
352
+ "description": "Optional. Which named symbols inside an owned-but-contested resource are this ToDo's concern. Consumed only when binding seam candidates; it can never create, remove or alter a conflict, so a dishonest declaration degrades the proposal without touching the judgement. Declared symbols must resolve through the sensor with an exact name and path match, must live inside the declared resource, and must not overlap another ToDo's declaration for the same resource; any breach yields a typed unknown instead of a proposal.",
353
+ "items": {
354
+ "type": "object",
355
+ "additionalProperties": false,
356
+ "required": [
357
+ "within",
358
+ "symbols"
359
+ ],
360
+ "properties": {
361
+ "within": {
362
+ "type": "object",
363
+ "additionalProperties": false,
364
+ "required": [
365
+ "kind",
366
+ "target"
367
+ ],
368
+ "description": "The contested resource. Must be a resource this same ToDo claims under 'owns'.",
369
+ "properties": {
370
+ "kind": {
371
+ "enum": [
372
+ "symbol",
373
+ "path"
374
+ ]
375
+ },
376
+ "target": {
377
+ "type": "string",
378
+ "minLength": 1,
379
+ "maxLength": 1024
380
+ }
381
+ }
382
+ },
383
+ "symbols": {
384
+ "type": "array",
385
+ "minItems": 1,
386
+ "maxItems": 256,
387
+ "description": "Symbol names owned by this ToDo inside the resource. Strictly sorted and unique.",
388
+ "items": {
389
+ "type": "string",
390
+ "minLength": 1,
391
+ "maxLength": 1024
392
+ }
393
+ }
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }
399
+ }
400
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.85.2",
3
+ "version": "0.85.3",
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",
@@ -40,6 +40,8 @@
40
40
  "docs/schemas/lattice.todo_extraction.v3.schema.json",
41
41
  "docs/schemas/lattice.todo_extraction.v4.schema.json",
42
42
  "docs/schemas/lattice.todo_structure_set.v1.schema.json",
43
+ "docs/schemas/lattice.todo_witness_draft.v2.schema.json",
44
+ "docs/schemas/lattice.todo_witness_set.v5.schema.json",
43
45
  "docs/schemas/lattice.todo_structure_realization.v1.schema.json",
44
46
  "docs/schemas/lattice.todo_structure_binding.v1.schema.json",
45
47
  "docs/schemas/lattice.run_request.v1.schema.json",
package/src/cli-help.mjs CHANGED
@@ -31,7 +31,9 @@ Commands:
31
31
  create --schema-version <1|2|3|4|5> --json
32
32
  create --template --json # 作者が書くkeyだけの最小のv5入力(そのままplan createが受理する)
33
33
  backchain --schema --json # 最終成果から必要な機能を逆算する入力契約
34
- revise --input <file> [--dry-run] [--json] # 工程の全体と明示した状態移行から改訂する
34
+ revise --input <file> [--dry-run] [--json]
35
+ # 改訂後の計画の全体を、plan createと同じ形で渡す(plan create --template --jsonから始められる)。
36
+ # 継続方針を自分で書くなら {"schema":"lattice.plan_revise_input.v1","desired":<計画>,"continuity":[...]}
35
37
  revise --schema --json
36
38
  backchain --input <file> [--dry-run] [--json]
37
39
  # 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
@@ -128,7 +130,10 @@ Write commands:
128
130
  independence mode --plan <key> --set <witness|conversation> --reason <text>
129
131
  # このplanの調整方式(witness検証で並列するか、会話で調整するか)を記録する
130
132
  independence compile --plan <key> --input <file> # witness setとsensorから並列可否を記録する
133
+ independence compile --schema --json # compileが読むwitness set(lattice.todo_witness_set.v5)のJSON Schema
131
134
  independence witness migrate --plan <key> # revision後の宣言をtask migrationで写す
135
+ independence witness scaffold --template --plan <key> [--json] # 未完の工程を並べた下書きのひな形を出す
136
+ independence witness scaffold --schema --json # 下書き(lattice.todo_witness_draft.v2)のJSON Schema
132
137
  independence witness scaffold --plan <key> --input <draft> # 下書きとfresh観測から宣言を書き出す
133
138
  structure input --plan <key> --input <file> --dry-run --json
134
139
  # plan identity・topology・unfinished task coverage・baseline祖先を無変更で検査する
@@ -243,7 +248,10 @@ const SUBCOMMAND_USAGE = Object.freeze({
243
248
  'plan show': 'plan show <plan_key> --json',
244
249
  'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
245
250
  'plan backchain': 'plan backchain --input <file> [--dry-run] [--json] | --schema --json',
246
- 'plan revise': 'plan revise --input <file> [--dry-run] [--json] | --schema --json',
251
+ 'plan revise': 'plan revise --input <file> [--dry-run] [--json] | --schema --json\n\n'
252
+ + '--input: the whole desired plan in the same shape as `plan create` (start from `plan create --template --json`),\n'
253
+ + 'or {"schema":"lattice.plan_revise_input.v1","desired":<that plan>,"continuity":[{task_id, policy: carry|reset|retire, reason}]}.\n'
254
+ + 'Without continuity the machine computes carry/reset/retire. A plan_key with no active plan is made with `plan create`.',
247
255
  'plan compile': 'plan compile --request <request.json> | --schema --json',
248
256
  'plan verify': 'plan verify --request <request.json> --plan <plan.json>',
249
257
  'run start': 'run start --request <request.json> --executor <adapter>'
@@ -277,10 +285,11 @@ const SUBCOMMAND_USAGE = Object.freeze({
277
285
  'todo status': 'todo status [--json]',
278
286
  'todo show': 'todo show --plan <key> --task <id> --json',
279
287
  'todo note': 'todo note --plan <key> [--task <id>] (--message <text>|--input <file>) | list --plan <key> [--task <id>] --json',
280
- 'todo note list': 'todo note list --plan <key> [--task <id>] --json',
288
+ 'todo note list': 'todo note list --plan <key> [--task <id>] [--json]',
281
289
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
282
290
  'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation> --reason <text>'
283
- + ' | compile --plan <key> --input <file> | witness migrate --plan <key> | witness scaffold --plan <key> --input <draft>',
291
+ + ' | compile --plan <key> --input <file> | compile --schema --json | witness migrate --plan <key>'
292
+ + ' | witness scaffold --template --plan <key> [--json] | witness scaffold --schema --json | witness scaffold --plan <key> --input <draft>',
284
293
  'todo independence mode': 'todo independence mode --plan <key> --set <witness|conversation> --reason <text>',
285
294
  'todo structure': 'todo structure --schema --json | [--plan <key>] --json | input --plan <key> --input <file> [--dry-run --json] | compile --plan <key> --input <file> | realize --plan <key> --task <id> (--planned|--realized <actual-structure.json>) [--commit <HEAD|sha>]... | realize --plan <key> --task <id> --input <full-realization.json> | finalize --plan <key> --json',
286
295
  'todo seam-profile': 'todo seam-profile --plan <key> --file <path> [--json]',
@@ -93,7 +93,12 @@ function keyDifference(detail, ctx, pointer) {
93
93
  const parts = [];
94
94
  if (missing.length > 0) parts.push(`add keys ${names(missing)}`);
95
95
  if (extra.length > 0) parts.push(`remove keys ${names(extra)}`);
96
- return `At ${pointer} ${parts.join(' and ') || `use exactly the keys ${names(expected)}`}.`;
96
+ // a31: 計画の目的・最終成果・受入はplan createでなくbackchainのgoalが持つ(seat contract)。
97
+ const goalHint = ctx.family === 'plan' && ctx.command === 'create' && pointer === '/'
98
+ && extra.some((key) => key === 'goal' || key === 'title')
99
+ ? ' 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`).'
100
+ : '';
101
+ return `At ${pointer} ${parts.join(' and ') || `use exactly the keys ${names(expected)}`}.${goalHint}`;
97
102
  }
98
103
 
99
104
  function acceptedValues(detail) {
@@ -184,6 +189,18 @@ const REGISTRY = {
184
189
  invalid_unblock_transition: {
185
190
  repair: (detail, ctx) => `Only a blocked task can be unblocked; check its status with \`${showTask(detail, ctx)}\`.`,
186
191
  },
192
+ invalid_reopen_transition: {
193
+ // a32: only a done task can be reopened; say the state and the step that fits it.
194
+ repair: (detail, ctx) => {
195
+ const on = `--plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
196
+ return `Only a done task can be reopened; ${planOf(detail, ctx)}/${taskOf(detail, ctx)} is ${detail.status ?? 'not done'}. ` + ({
197
+ 'in-progress': `It is still open: finish it with \`lattice todo done ${on}\`, or undo the start with \`lattice todo retract ${on} --reason <text>\`.`,
198
+ pending: `It has not started: run \`lattice todo start ${on}\`.`,
199
+ blocked: `It is blocked: resume it with \`lattice todo unblock ${on}\`.`,
200
+ retired: `Retire is permanent, so it stays closed; see \`${showTask(detail, ctx)}\`.`,
201
+ }[detail.status] ?? `Check its state with \`${showTask(detail, ctx)}\`.`);
202
+ },
203
+ },
187
204
  reopen_has_started_successor: {
188
205
  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
206
  },
@@ -330,7 +347,8 @@ const REGISTRY = {
330
347
 
331
348
  plan_revise_schema_invalid: {
332
349
  pointer: '--input',
333
- repair: (detail, ctx) => `Use schema ${q(detail.expected)}; see \`${schemaCommand(ctx)}\`.`,
350
+ // a31: 包みの形を名指す。素のplan create入力も受けるので、まずそれを勧める。
351
+ 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
352
  },
335
353
  plan_revise_requires_source_revision: {
336
354
  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,
@@ -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
  }
package/src/todo-cli.mjs CHANGED
@@ -168,8 +168,8 @@ import { collectTodoIndependenceAuthoritativeObservation } from './todo-independ
168
168
  import { applySeamProposal } from './seam-apply.mjs';
169
169
  import { todoPlanPrecedences } from './seam-verification.mjs';
170
170
  import {
171
- WITNESS_DRAFT_SCHEMA, buildWitnessObservationQuerySet, buildWitnessSet, serializeWitnessSet,
172
- validateWitnessDraft,
171
+ WITNESS_DRAFT_SCHEMA, buildWitnessObservationQuerySet, buildWitnessSet, explainWitnessDraft, serializeWitnessSet,
172
+ witnessDraftTemplate,
173
173
  } from './witness-scaffold.mjs';
174
174
  import {
175
175
  completePhaseTodoRevision, explainPhaseTodoRevision, explainTodoRevision, explainTodoRevisionSet,
@@ -215,7 +215,18 @@ const TODO_SCHEMA_COMMANDS = Object.freeze({
215
215
  structure: {
216
216
  title: 'lattice.todo_structure_set.v1', file: 'lattice.todo_structure_set.v1.schema.json',
217
217
  },
218
+ // a32: the witness route's two inputs, so a seat that chose `--set witness` can find their shape.
219
+ 'independence witness scaffold': {
220
+ title: 'lattice.todo_witness_draft.v2', file: 'lattice.todo_witness_draft.v2.schema.json',
221
+ },
222
+ 'independence compile': { title: 'lattice.todo_witness_set.v5', file: 'lattice.todo_witness_set.v5.schema.json' },
218
223
  });
224
+ const witnessTemplateCommand = (planKey) => `lattice todo independence witness scaffold --template --plan ${planKey}`;
225
+ const WITNESS_DRAFT_SCHEMA_COMMAND = 'lattice todo independence witness scaffold --schema --json';
226
+ /** a32: where a witness set comes from: the template, filled, through scaffold (which adds digest and observations). */
227
+ const witnessRoute = (planKey) => `Start from \`${witnessTemplateCommand(planKey)}\` (draft shape: \`${WITNESS_DRAFT_SCHEMA_COMMAND}\`),`
228
+ + ` fill each task's owns/reads/writes, then run \`lattice todo independence witness scaffold --plan ${planKey} --input <draft>\`;`
229
+ + ' it writes the witness set that `independence compile` reads (shape: `lattice todo independence compile --schema --json`).';
219
230
 
220
231
  async function runTodoSchemaCommand(command, stdout) {
221
232
  const spec = TODO_SCHEMA_COMMANDS[command];
@@ -325,11 +336,15 @@ const TODO_FLAG_SPECS = Object.freeze({
325
336
  'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
326
337
  'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
327
338
  'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
339
+ 'independence mode': Object.freeze({ known: ['plan', 'set', 'reason'], required: ['plan', 'set', 'reason'] }),
340
+ 'independence witness scaffold': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
328
341
  show: Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan', 'task'], booleans: ['json'] }),
329
342
  'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
330
343
  structure: Object.freeze({ known: ['plan', 'json'], required: [], booleans: ['json'] }),
331
344
  status: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
332
345
  });
346
+ const WITNESS_TEMPLATE_FLAG_SPEC = Object.freeze({
347
+ known: ['template', 'plan', 'json'], required: ['plan'], booleans: ['template', 'json'] });
333
348
  // a28: command groups, their subcommands and the one a refusal shows as the example.
334
349
  const TODO_SUBCOMMANDS = Object.freeze({
335
350
  dependency: { names: ['connect', 'disconnect'], example: 'connect' },
@@ -402,9 +417,12 @@ function explainMissingSubcommand(argv) {
402
417
  function explainArgumentRefusal(argv) {
403
418
  const missingSubcommand = explainMissingSubcommand(argv);
404
419
  if (missingSubcommand !== null) return missingSubcommand;
405
- const head = GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
406
- ? argv.slice(0, 2) : argv.slice(0, 1);
407
- const spec = TODO_FLAG_SPECS[head.join(' ')];
420
+ const head = argv[0] === 'independence' && argv[1] === 'witness' ? argv.slice(0, 3)
421
+ : GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
422
+ ? argv.slice(0, 2) : argv.slice(0, 1);
423
+ // a32: `scaffold --template` is a read with its own flags.
424
+ const spec = head.join(' ') === 'independence witness scaffold' && argv.includes('--template')
425
+ ? WITNESS_TEMPLATE_FLAG_SPEC : TODO_FLAG_SPECS[head.join(' ')];
408
426
  if (spec === undefined) return {};
409
427
  const { flags } = parseFlagMap(argv.slice(head.length));
410
428
  const flagFailure = explainFlagCommand(argv, head, spec);
@@ -493,7 +511,7 @@ function supportsAtomicStoreCommit(argv) {
493
511
  if (command === 'note') return argv[1] !== 'list';
494
512
  if (command === 'independence') {
495
513
  return argv[1] === 'mode'
496
- || (argv[1] === 'witness' && ['migrate', 'scaffold'].includes(argv[2]));
514
+ || (argv[1] === 'witness' && ['migrate', 'scaffold'].includes(argv[2]) && !argv.includes('--template'));
497
515
  }
498
516
  if (command === 'snapshot') return argv[1] === '--rebuild';
499
517
  if (command === 'migrate') return !argv.includes('--dry-run') && !argv.includes('--schema');
@@ -782,11 +800,23 @@ async function readJsonInput(repoRoot, inputRef, { validate, invalidCode, expect
782
800
  return descriptor;
783
801
  }
784
802
 
803
+ const WITNESS_SET_TOP_LEVEL_KEYS = ['schema', 'project_id', 'plan_key', 'capacity', 'sensor_query_set',
804
+ 'manual_witness', 'witness_set_digest'];
805
+ /** a32: the top-level keys a witness set lacks or should not have. */
806
+ function witnessSetKeyDiff(value) {
807
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return {};
808
+ const keys = Object.keys(value);
809
+ return { missing_keys: WITNESS_SET_TOP_LEVEL_KEYS.filter((key) => !keys.includes(key)),
810
+ unexpected_keys: keys.filter((key) => !WITNESS_SET_TOP_LEVEL_KEYS.includes(key)).sort() };
811
+ }
812
+
785
813
  /** 安全読み取りとcanonical JSON規律を共有したまま、witness set契約で検証する。 */
786
- async function readWitnessSetInput(repoRoot, inputRef) {
814
+ async function readWitnessSetInput(repoRoot, inputRef, planKey = '<key>') {
787
815
  let explained = null;
816
+ let witnessInput;
788
817
  const witnessSet = await readJsonInput(repoRoot, inputRef, {
789
818
  validate: (value) => {
819
+ witnessInput = value;
790
820
  explained = explainTodoWitnessSet(value);
791
821
  return explained.valid;
792
822
  },
@@ -794,7 +824,8 @@ async function readWitnessSetInput(repoRoot, inputRef) {
794
824
  }).catch((error) => {
795
825
  if (error?.code === 'INVALID_TODO_WITNESS_SET' && explained !== null) {
796
826
  throw new TodoStoreError('INVALID_TODO_WITNESS_SET', explained.reason, undefined, {
797
- input_ref: inputRef, path: explained.path,
827
+ input_ref: inputRef, path: explained.path, pointer: explained.path || '/',
828
+ ...witnessSetKeyDiff(witnessInput), next_action: witnessRoute(planKey),
798
829
  });
799
830
  }
800
831
  throw error;
@@ -2269,8 +2300,7 @@ async function splitTodo({ repoRoot, env, planKey, inputRef }) {
2269
2300
  const witnessSet = await readTodoWitnessSet({ repoRoot, planKey });
2270
2301
  if (witnessSet === null) {
2271
2302
  throw new TodoStoreError('WITNESS_MIGRATION_UNAVAILABLE', 'witness_set_absent', undefined, {
2272
- witness_ref: todoWitnessRef(planKey),
2273
- next_action: `lattice todo independence witness scaffold --plan ${planKey} --input <draft>`,
2303
+ witness_ref: todoWitnessRef(planKey), next_action: witnessRoute(planKey),
2274
2304
  });
2275
2305
  }
2276
2306
  const compiled = await compileTodoSplit({ repoRoot, member, proposal });
@@ -3143,7 +3173,7 @@ async function structure({ repoRoot, requestedPlanKey }) {
3143
3173
  }
3144
3174
 
3145
3175
  async function independenceCompile({ repoRoot, planKey, inputRef }) {
3146
- const witnessSet = await readWitnessSetInput(repoRoot, inputRef);
3176
+ const witnessSet = await readWitnessSetInput(repoRoot, inputRef, planKey);
3147
3177
  const storeForReady = await readTodoStore({ repoRoot });
3148
3178
  const memberForReady = storeForReady.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3149
3179
  if (!memberForReady) {
@@ -3233,7 +3263,7 @@ async function independenceWitnessMigrate({ repoRoot, planKey }) {
3233
3263
  const witnessSet = await readTodoWitnessSet({ repoRoot, planKey });
3234
3264
  if (witnessSet === null) {
3235
3265
  throw new TodoStoreError('WITNESS_MIGRATION_UNAVAILABLE', 'witness_set_absent', undefined, {
3236
- witness_ref: todoWitnessRef(planKey),
3266
+ witness_ref: todoWitnessRef(planKey), next_action: witnessRoute(planKey),
3237
3267
  });
3238
3268
  }
3239
3269
  const revision = member.revision;
@@ -3497,10 +3527,29 @@ async function seamProposalCompile({ repoRoot, planKey }) {
3497
3527
  * 推定はしない。何を所有し何を触るかは下書きが述べ、ここが供給するのはAIには作れないもの——
3498
3528
  * affected testのfresh観測、query setとprovenanceの配線、canonical bytesと自己digest——だけである。
3499
3529
  */
3530
+ /** a32: the starting draft for `planKey`: its tasks that are not done or retired, nothing declared yet. */
3531
+ async function witnessDraftTemplateFor({ repoRoot, planKey }) {
3532
+ const store = await readTodoStore({ repoRoot });
3533
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
3534
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
3535
+ return witnessDraftTemplate({ projectId: member.plan.project_id, planKey,
3536
+ taskIds: member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id) });
3537
+ }
3538
+
3500
3539
  async function witnessScaffold({ repoRoot, planKey, inputRef }) {
3540
+ let explained = null;
3501
3541
  const draft = await readJsonInput(repoRoot, inputRef, {
3502
- validate: validateWitnessDraft,
3542
+ validate: (value) => (explained = explainWitnessDraft(value)).valid,
3503
3543
  invalidCode: 'WITNESS_DRAFT_INVALID',
3544
+ }).catch((error) => {
3545
+ // a32: name the failing field and where the draft shape is, not a schema command that does not exist.
3546
+ if (error?.code === 'WITNESS_DRAFT_INVALID' && explained !== null && !explained.valid) {
3547
+ const { valid: _valid, reason, path: at, ...keys } = explained;
3548
+ throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
3549
+ input_ref: inputRef, pointer: at, ...keys, next_action: witnessRoute(planKey),
3550
+ });
3551
+ }
3552
+ throw error;
3504
3553
  });
3505
3554
  if (draft.plan_key !== planKey) {
3506
3555
  throw new TodoStoreError('INPUT_INVALID', 'witness_draft_plan_mismatch', undefined, {
@@ -4244,7 +4293,7 @@ function writesTodoStore(argv) {
4244
4293
  case 'migrate': return !argv.includes('--dry-run');
4245
4294
  case 'snapshot': return argv.includes('--rebuild');
4246
4295
  case 'independence': return second === 'compile'
4247
- || (second === 'witness' && ['migrate', 'scaffold'].includes(third));
4296
+ || (second === 'witness' && ['migrate', 'scaffold'].includes(third) && !argv.includes('--template'));
4248
4297
  case 'structure': return ['compile', 'realize', 'finalize'].includes(second)
4249
4298
  || (second === 'input' && !argv.includes('--dry-run'));
4250
4299
  case 'seam-proposal': return ['compile', 'apply', 'land'].includes(second);
@@ -4478,10 +4527,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4478
4527
 
4479
4528
  // `--schema --json`はstoreを読まない決定的な出力(`plan create --schema`と同じ規律)。
4480
4529
  // 通常dispatchより前に処理し、repoRoot解決やdashboard daemon起動を経由させない。
4481
- if (argv.length === 3 && argv[1] === '--schema' && argv[2] === '--json'
4482
- && Object.hasOwn(TODO_SCHEMA_COMMANDS, argv[0])) {
4530
+ if (argv.length >= 3 && argv.at(-2) === '--schema' && argv.at(-1) === '--json'
4531
+ && Object.hasOwn(TODO_SCHEMA_COMMANDS, argv.slice(0, -2).join(' '))) {
4483
4532
  try {
4484
- await runTodoSchemaCommand(argv[0], stdout);
4533
+ await runTodoSchemaCommand(argv.slice(0, -2).join(' '), stdout);
4485
4534
  return 0;
4486
4535
  } catch (error) {
4487
4536
  return failInternally(error);
@@ -4565,12 +4614,14 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4565
4614
  } else if (argv.length === 5 && argv[0] === 'independence' && argv[1] === 'witness'
4566
4615
  && argv[2] === 'migrate' && argv[3] === '--plan' && isTodoIdentifier(argv[4])) {
4567
4616
  action = (repoRoot) => independenceWitnessMigrate({ repoRoot, planKey: argv[4] });
4568
- } else if (argv.length === 8 && argv[0] === 'independence' && argv[1] === 'mode'
4569
- && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--set'
4570
- && TODO_COORDINATION_MODES.includes(argv[5]) && argv[6] === '--reason' && argv[7].length > 0) {
4571
- action = (repoRoot) => independenceMode({
4572
- repoRoot, env, planKey: argv[3], mode: argv[5], reason: argv[7],
4573
- });
4617
+ } else if (argv[0] === 'independence' && argv[1] === 'mode'
4618
+ && matchFlagCommand(argv, ['independence', 'mode'], TODO_FLAG_SPECS['independence mode']) !== null) {
4619
+ const flags = matchFlagCommand(argv, ['independence', 'mode'], TODO_FLAG_SPECS['independence mode']);
4620
+ if (isTodoIdentifier(flags.plan) && TODO_COORDINATION_MODES.includes(flags.set)) {
4621
+ action = (repoRoot) => independenceMode({
4622
+ repoRoot, env, planKey: flags.plan, mode: flags.set, reason: flags.reason,
4623
+ });
4624
+ }
4574
4625
  } else if (argv[0] === 'dependency' && argv[1] === 'connect'
4575
4626
  && dependencyFlags(argv) !== null) {
4576
4627
  const flags = dependencyFlags(argv);
@@ -4643,10 +4694,18 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
4643
4694
  } else if (argv.length === 4 && argv[0] === 'seam-proposal' && argv[1] === 'apply'
4644
4695
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])) {
4645
4696
  action = (repoRoot) => seamProposalApply({ repoRoot, planKey: argv[3] });
4646
- } else if (argv.length === 7 && argv[0] === 'independence' && argv[1] === 'witness'
4647
- && argv[2] === 'scaffold' && argv[3] === '--plan' && isTodoIdentifier(argv[4])
4648
- && argv[5] === '--input' && isAuthoringPathToken(argv[6])) {
4649
- action = (repoRoot) => witnessScaffold({ repoRoot, planKey: argv[4], inputRef: argv[6] });
4697
+ } else if (argv[0] === 'independence' && argv[1] === 'witness' && argv[2] === 'scaffold'
4698
+ && argv.includes('--template')) {
4699
+ const flags = matchFlagCommand(argv, ['independence', 'witness', 'scaffold'], WITNESS_TEMPLATE_FLAG_SPEC);
4700
+ if (flags !== null && isTodoIdentifier(flags.plan)) {
4701
+ action = (repoRoot) => witnessDraftTemplateFor({ repoRoot, planKey: flags.plan });
4702
+ }
4703
+ } else if (argv[0] === 'independence' && argv[1] === 'witness' && argv[2] === 'scaffold') {
4704
+ const flags = matchFlagCommand(argv, ['independence', 'witness', 'scaffold'],
4705
+ TODO_FLAG_SPECS['independence witness scaffold']);
4706
+ if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
4707
+ action = (repoRoot) => witnessScaffold({ repoRoot, planKey: flags.plan, inputRef: flags.input });
4708
+ }
4650
4709
  } else if (argv.length === 6 && argv[0] === 'seam-proposal' && argv[1] === 'land'
4651
4710
  && argv[2] === '--plan' && isTodoIdentifier(argv[3])
4652
4711
  && argv[4] === '--names' && isAuthoringPathToken(argv[5])) {
@@ -80,7 +80,8 @@ const CATALOG = Object.freeze({
80
80
  }),
81
81
  independence_unrecorded: Object.freeze({
82
82
  message: 'このplanの並列可否はまだ判定していない。競合が無いのではなく、記録が存在しない。',
83
- next_action: 'lattice todo independence compile --plan <key> --input <file>',
83
+ // a32: the first step of the witness route is the draft template, not a file the seat cannot shape.
84
+ next_action: 'lattice todo independence witness scaffold --template --plan <key>',
84
85
  }),
85
86
  independence_task_undeclared: Object.freeze({
86
87
  message: 'この工程はwitness setで宣言されていないため、記録には含まれていない。',
@@ -309,7 +310,7 @@ export function selectSeamProposalGuidance({ coverage, unknownKinds = [], planKe
309
310
  * 足さないと、能力はあるのに機械が黙る面が残る(ADR 0130)。
310
311
  */
311
312
  export const TODO_INDEPENDENCE_WORKFLOW = Object.freeze([
312
- '1. 宣言する: .lattice/todo/witness/<plan_key>.json へ、ToDoごとのowns/reads/writes/affected_testsを書く',
313
+ '1. 宣言する: lattice todo independence witness scaffold --template --plan <key> が出す下書き(形は lattice todo independence witness scaffold --schema --json)へToDoごとのowns/reads/writesを書き、lattice todo independence witness scaffold --plan <key> --input <draft> が .lattice/todo/witness/<plan_key>.json を書く(affected_testsと自己digestは機械が埋める。形は lattice todo independence compile --schema --json)',
313
314
  ' 係争資源しか所有していないToDoは、ownsまたはwritesの内側で自分が触るsymbolをconcern_anchorsへ宣言できる(witness set v2)。並列可否の判定には写らず、切断候補の束縛だけに効く',
314
315
  ' remaining の A 工程(まだ done でない ready / blocked)も同じ witness に含める。現在の ready だけを compile すると、次の frontier の start の助言が未検証(independence_task_undeclared)になる',
315
316
  '2. 判定する: lattice todo independence compile --plan <key> --input <ref>(実sensorを引く。pretty-printやdigest未計算の下書きは機械が直す)。next_ready が witness に無い compile は拒否する',
@@ -2165,6 +2165,12 @@ function resolveTargetedEvent(input, storeMember) {
2165
2165
  if (input.kind === 'reopen' && exactRecord(input.payload, [
2166
2166
  'reason', 'override_reason',
2167
2167
  ])) {
2168
+ // a32: only a done task reopens; any other state is the seat's order, not a damaged store.
2169
+ const status = storeMember.tasks?.find(({ task_id: id }) => id === input.task_id)?.status;
2170
+ if (status !== undefined && status !== 'done') {
2171
+ fail('TODO_TRANSITION_REFUSED', 'invalid_reopen_transition', {
2172
+ cause: 'task_state', status, plan_key: storeMember.plan.plan_key, task_id: input.task_id });
2173
+ }
2168
2174
  const targetDigest = resolveDoneBindingDigest(storeMember, input.task_id);
2169
2175
  if (targetDigest === null) fail('STORE_INCONSISTENT', 'invalid_reopen_binding');
2170
2176
  return {
@@ -51,28 +51,65 @@ function reject(reasons) {
51
51
  return { witnessSet: null, queries: [], reasons: sortedUnique(reasons) };
52
52
  }
53
53
 
54
- /** 下書きの形。AIが書く欄だけを持ち、観測で埋まる欄は持たない。 */
55
- export function validateWitnessDraft(value) {
56
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
57
- if (!DRAFT_SCHEMAS.includes(value.schema)) return false;
58
- if (!isTodoIdentifier(value.project_id) || !isTodoIdentifier(value.plan_key)) return false;
59
- if (value.capacity === null || typeof value.capacity !== 'object'
60
- || !Number.isSafeInteger(value.capacity.executors) || value.capacity.executors < 1) return false;
61
- if (value.tasks === null || typeof value.tasks !== 'object' || Array.isArray(value.tasks)) return false;
54
+ const DRAFT_TOP_LEVEL_KEYS = Object.freeze(['schema', 'project_id', 'plan_key', 'capacity', 'tasks']);
55
+ const plainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
56
+ const refList = (value) => value === undefined || (Array.isArray(value) && value.every(isTodoRef));
57
+
58
+ /** 1 taskの下書きの最初の違反(相対path)、無ければnull。validateWitnessDraftと同じ規則。 */
59
+ function explainDraftTask(task, schema) {
60
+ if (!plainObject(task)) return { reason: 'not_an_object', path: '' };
61
+ if (draftOwnEntries(task, schema) === null) return { reason: 'invalid_owns', path: '/owns' };
62
+ for (const key of ['reads', 'writes']) {
63
+ if (!refList(task[key])) return { reason: 'invalid_repo_relative_paths', path: `/${key}` };
64
+ }
65
+ if (task.unknowns !== undefined && !(Array.isArray(task.unknowns) && task.unknowns.every((entry) => plainObject(entry)
66
+ && isTodoIdentifier(entry.kind) && typeof entry.ref === 'string' && entry.ref.length > 0))) {
67
+ return { reason: 'invalid_unknowns', path: '/unknowns' };
68
+ }
69
+ if (task.concern_anchors !== undefined && !(Array.isArray(task.concern_anchors)
70
+ && task.concern_anchors.every((anchor) => plainObject(anchor) && isTodoRef(anchor.within)
71
+ && Array.isArray(anchor.symbols) && anchor.symbols.length > 0 && anchor.symbols.every(isTodoIdentifier)))) {
72
+ return { reason: 'invalid_concern_anchors', path: '/concern_anchors' };
73
+ }
74
+ return null;
75
+ }
76
+
77
+ /**
78
+ * 下書きの形。AIが書く欄だけを持ち、観測で埋まる欄は持たない。
79
+ * a32: 拒否は最初に落ちた欄(JSON pointer)と理由、topの欠けたkeyを名指す。
80
+ */
81
+ export function explainWitnessDraft(value) {
82
+ const reject = (reason, at, extra = {}) => ({ valid: false, reason, path: at, ...extra });
83
+ if (!plainObject(value)) return reject('not_an_object', '/');
84
+ const missing = DRAFT_TOP_LEVEL_KEYS.filter((key) => !Object.hasOwn(value, key));
85
+ if (missing.length > 0) return reject('missing_top_level_keys', '/', { missing_keys: missing });
86
+ if (!DRAFT_SCHEMAS.includes(value.schema)) return reject('schema_mismatch', '/schema', { expected: DRAFT_SCHEMAS });
87
+ if (!isTodoIdentifier(value.project_id)) return reject('invalid_identifier', '/project_id');
88
+ if (!isTodoIdentifier(value.plan_key)) return reject('invalid_identifier', '/plan_key');
89
+ if (!plainObject(value.capacity) || !Number.isSafeInteger(value.capacity.executors) || value.capacity.executors < 1) {
90
+ return reject('invalid_capacity', '/capacity/executors');
91
+ }
92
+ if (!plainObject(value.tasks)) return reject('not_an_object', '/tasks');
62
93
  const entries = Object.entries(value.tasks);
63
- if (entries.length === 0) return false;
64
- return entries.every(([taskId, task]) => isTodoIdentifier(taskId)
65
- && task !== null && typeof task === 'object' && !Array.isArray(task)
66
- && draftOwnEntries(task, value.schema) !== null
67
- && (task.reads === undefined || (Array.isArray(task.reads) && task.reads.every(isTodoRef)))
68
- && (task.writes === undefined || (Array.isArray(task.writes) && task.writes.every(isTodoRef)))
69
- && (task.unknowns === undefined || (Array.isArray(task.unknowns)
70
- && task.unknowns.every((entry) => entry !== null && typeof entry === 'object'
71
- && isTodoIdentifier(entry.kind) && typeof entry.ref === 'string' && entry.ref.length > 0)))
72
- && (task.concern_anchors === undefined || (Array.isArray(task.concern_anchors)
73
- && task.concern_anchors.every((anchor) => anchor !== null && typeof anchor === 'object'
74
- && isTodoRef(anchor.within) && Array.isArray(anchor.symbols)
75
- && anchor.symbols.length > 0 && anchor.symbols.every(isTodoIdentifier)))));
94
+ if (entries.length === 0) return reject('empty_tasks', '/tasks');
95
+ for (const [taskId, task] of entries) {
96
+ if (!isTodoIdentifier(taskId)) return reject('invalid_identifier', `/tasks/${taskId}`);
97
+ const failure = explainDraftTask(task, value.schema);
98
+ if (failure !== null) return reject(failure.reason, `/tasks/${taskId}${failure.path}`);
99
+ }
100
+ return { valid: true };
101
+ }
102
+
103
+ export function validateWitnessDraft(value) {
104
+ return explainWitnessDraft(value).valid;
105
+ }
106
+
107
+ /** a32: the starting draft for a plan: every task still to do, with nothing declared yet. */
108
+ export function witnessDraftTemplate({ projectId, planKey, taskIds }) {
109
+ return {
110
+ schema: WITNESS_DRAFT_SCHEMA_V2, project_id: projectId, plan_key: planKey, capacity: { executors: 1 },
111
+ tasks: Object.fromEntries([...taskIds].sort(compareText).map((taskId) => [taskId, { owns: [], reads: [], writes: [] }])),
112
+ };
76
113
  }
77
114
 
78
115
  function queryIdFor(index) {