@quolu/lattice 0.115.0 → 0.117.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/lattice.mjs +37 -9
- package/docs/schemas/lattice.plan_backchain.v1.schema.json +2 -2
- package/package.json +1 -1
- package/src/cli-help.mjs +9 -4
- package/src/plan-backchain.mjs +99 -46
- package/src/plan-draft.mjs +448 -0
- package/src/project-cli.mjs +3 -1
- package/src/runtime-error-reporting.mjs +119 -105
- package/src/runtime-errors.mjs +37 -9
- package/src/todo-cli.mjs +12 -7
- package/src/todo-note-store.mjs +195 -113
- package/src/todo-store.mjs +29 -14
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
isTodoIdentifier, isTodoRef, todoSelfDigest,
|
|
5
|
+
} from './todo-contracts.mjs';
|
|
6
|
+
import { TodoStoreError } from './todo-store.mjs';
|
|
7
|
+
import { completeCreateInput } from './todo-authoring-input.mjs';
|
|
8
|
+
import {
|
|
9
|
+
BACKCHAIN_SCHEMA, existingReferenceProblem, readPlanBackchainBinding, sortFindings, taskSignature,
|
|
10
|
+
} from './plan-backchain.mjs';
|
|
11
|
+
|
|
12
|
+
// Goal-side authoring draft (docs/architecture/dfd-plan-draft.md). The AI writes steps downstream-first;
|
|
13
|
+
// this module only normalizes them into the existing backchain chain + create-shaped authoring. It reads
|
|
14
|
+
// the Store through the caller's member and writes nothing; publication stays in runPlanBackchain.
|
|
15
|
+
export const DRAFT_SCHEMA = 'lattice.plan_draft.v1';
|
|
16
|
+
const CREATE_SCHEMA = 'lattice.plan_create_input.v4';
|
|
17
|
+
const KEYS = ['schema', 'project_id', 'plan_key', 'plan_version', 'base_plan_version', 'actor', 'recorded_at',
|
|
18
|
+
'goal', 'phases', 'final', 'steps', 'observations', 'retire', 'continuity', 'context'];
|
|
19
|
+
const MAX_TEXT_BYTES = 16_384;
|
|
20
|
+
const DONE_PLANS = ['lattice.todo_plan.v8', 'lattice.todo_plan.v9'];
|
|
21
|
+
|
|
22
|
+
function fail(reason, pointer, detail = {}) {
|
|
23
|
+
throw new TodoStoreError('PLAN_BACKCHAIN_INVALID', reason, undefined, { pointer, ...detail });
|
|
24
|
+
}
|
|
25
|
+
const rec = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
26
|
+
const text = (value) => typeof value === 'string' && value.trim().length > 0
|
|
27
|
+
&& Buffer.byteLength(value, 'utf8') <= MAX_TEXT_BYTES;
|
|
28
|
+
const push = (list, value) => { if (!list.includes(value)) list.push(value); };
|
|
29
|
+
|
|
30
|
+
function only(value, allowed, pointer, required = []) {
|
|
31
|
+
if (!rec(value)) fail('draft_shape_invalid', pointer, { expected: { type: 'object' } });
|
|
32
|
+
const unexpected = Object.keys(value).filter((key) => !allowed.includes(key));
|
|
33
|
+
const missing = required.filter((key) => value[key] === undefined);
|
|
34
|
+
if (unexpected.length > 0 || missing.length > 0) {
|
|
35
|
+
fail('draft_keys_invalid', pointer, { unexpected_keys: unexpected, missing_keys: missing, allowed_keys: allowed });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function result(value, pointer, withId) {
|
|
40
|
+
only(value, ['capability', 'acceptance', 'feature_id'], pointer, ['capability', 'acceptance']);
|
|
41
|
+
if (!text(value.capability) || !text(value.acceptance)) fail('draft_result_invalid', pointer);
|
|
42
|
+
if (value.feature_id !== undefined && !isTodoIdentifier(value.feature_id)) fail('draft_result_invalid', `${pointer}/feature_id`);
|
|
43
|
+
if (withId && value.feature_id === undefined) {
|
|
44
|
+
fail('draft_result_feature_id_required', `${pointer}/feature_id`, { cause: 'step has no task to name the result' });
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function newTask(task, pointer) {
|
|
50
|
+
only(task, ['task_id', 'title', 'lane', 'design_memo', 'phase_id', 'done'], pointer, ['task_id', 'title', 'design_memo']);
|
|
51
|
+
if (!isTodoIdentifier(task.task_id) || !text(task.title) || !text(task.design_memo)
|
|
52
|
+
|| (task.done !== undefined && !text(task.done))) fail('draft_task_invalid', pointer);
|
|
53
|
+
return task;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Normalizes the draft into { chain, authoring, report }. member is the active plan member or null. */
|
|
57
|
+
export async function compilePlanDraft({ repoRoot, draft, draftRef, member, store, env, now = new Date() }) {
|
|
58
|
+
only(draft, KEYS, '/', ['schema', 'plan_key']);
|
|
59
|
+
if (draft.schema !== DRAFT_SCHEMA) fail('schema_invalid', '/schema', { expected: DRAFT_SCHEMA, actual: draft.schema });
|
|
60
|
+
if (!isTodoIdentifier(draft.plan_key)) fail('identifier_invalid', '/plan_key');
|
|
61
|
+
const plan = member?.plan ?? null;
|
|
62
|
+
const planKey = draft.plan_key;
|
|
63
|
+
const projectId = draft.project_id ?? store?.project_id
|
|
64
|
+
?? (await import('./project-cli.mjs')).identifierFromRepoRoot(repoRoot, 'project');
|
|
65
|
+
if (!isTodoIdentifier(projectId)) fail('identifier_invalid', '/project_id');
|
|
66
|
+
const steps = draft.steps ?? [];
|
|
67
|
+
if (!Array.isArray(steps)) fail('draft_shape_invalid', '/steps', { expected: { type: 'array' } });
|
|
68
|
+
if (plan !== null) {
|
|
69
|
+
if (draft.final !== undefined) {
|
|
70
|
+
fail('final_on_existing_plan', '/final', { next_action: 'Name the goal-side task in steps[].before instead.' });
|
|
71
|
+
}
|
|
72
|
+
if (draft.base_plan_version !== undefined && draft.base_plan_version !== plan.plan_version) {
|
|
73
|
+
fail('draft_base_stale', '/base_plan_version', {
|
|
74
|
+
current_plan_version: plan.plan_version,
|
|
75
|
+
next_action: 'Run lattice plan backchain --template --plan ' + planKey + ' --json, keep your steps, set base_plan_version to the current value, then rerun.',
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
only(draft.final, ['task', 'result'], '/final', ['task', 'result']);
|
|
80
|
+
if (!rec(draft.goal)) fail('goal_missing', '/goal', { expected: ['purpose', 'outcome', 'acceptance'] });
|
|
81
|
+
}
|
|
82
|
+
if (draft.goal !== undefined) {
|
|
83
|
+
only(draft.goal, ['purpose', 'outcome', 'acceptance'], '/goal', ['purpose', 'outcome', 'acceptance']);
|
|
84
|
+
if (!Object.values(draft.goal).every(text)) fail('goal_invalid', '/goal');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const ref = (id) => ({ project_id: projectId, plan_key: planKey, task_id: id });
|
|
88
|
+
const edgeKey = ({ from, to }) => `${from.plan_key}/${from.task_id}->${to.plan_key}/${to.task_id}`;
|
|
89
|
+
const tasks = new Map((plan?.tasks ?? []).map((task) => [task.task_id, { ...task }]));
|
|
90
|
+
const baseIds = new Set(tasks.keys());
|
|
91
|
+
const edges = [...(plan?.hard_dependencies ?? [])];
|
|
92
|
+
const initialEdges = new Set(edges.map(edgeKey));
|
|
93
|
+
const oldChain = plan === null ? null : (await readPlanBackchainBinding({ repoRoot, plan }))?.chain ?? null;
|
|
94
|
+
const features = new Map((oldChain?.features ?? []).map((f) =>
|
|
95
|
+
[f.feature_id, { ...f, requires_feature_ids: [...f.requires_feature_ids] }]));
|
|
96
|
+
const ctasks = new Map((oldChain?.tasks ?? []).map((t) => [t.task_id, {
|
|
97
|
+
task_id: t.task_id, requires_feature_ids: [...t.requires_feature_ids],
|
|
98
|
+
provides_feature_ids: [...t.provides_feature_ids] }]));
|
|
99
|
+
const placeFindings = [];
|
|
100
|
+
const canonicalRoot = await realpath(repoRoot);
|
|
101
|
+
const doneField = plan !== null && DONE_PLANS.includes(plan.schema);
|
|
102
|
+
const defaultPhase = draft.phases?.[0]?.phase_id ?? 'main';
|
|
103
|
+
|
|
104
|
+
// A join (task waits for several) is a consumption too: its `after` tasks serve the task that waits.
|
|
105
|
+
const joinAfter = new Map();
|
|
106
|
+
for (const join of plan?.joins ?? []) {
|
|
107
|
+
if (join.before.plan_key !== planKey) continue;
|
|
108
|
+
joinAfter.set(join.before.task_id, [...(joinAfter.get(join.before.task_id) ?? []),
|
|
109
|
+
...join.after.filter((r) => r.plan_key === planKey).map((r) => r.task_id)]);
|
|
110
|
+
}
|
|
111
|
+
const joinNeeded = new Set();
|
|
112
|
+
const introduced = new Map();
|
|
113
|
+
steps.forEach((step, index) => { if (rec(step?.task)) introduced.set(step.task.task_id, index); });
|
|
114
|
+
|
|
115
|
+
// A task in the plan that the feature chain does not describe yet is described by its own title, so a legacy
|
|
116
|
+
// plan can be edited from the task the author names (the draft declares only the branch it touches).
|
|
117
|
+
const ensure = (id, pointer) => {
|
|
118
|
+
if (!tasks.has(id)) fail('task_unknown', pointer, { task_id: id, available_task_ids: [...tasks.keys()].sort() });
|
|
119
|
+
if (!ctasks.has(id)) {
|
|
120
|
+
const task = tasks.get(id);
|
|
121
|
+
let featureId = id;
|
|
122
|
+
if (features.has(featureId)) featureId = `${id}-result`;
|
|
123
|
+
if (features.has(featureId)) fail('feature_id_taken', pointer, { feature_id: featureId });
|
|
124
|
+
features.set(featureId, { feature_id: featureId, capability: task.title,
|
|
125
|
+
acceptance: task.done_condition ?? task.title, requires_feature_ids: [],
|
|
126
|
+
provider: { kind: 'task', task_id: id } });
|
|
127
|
+
ctasks.set(id, { task_id: id, requires_feature_ids: [], provides_feature_ids: [featureId] });
|
|
128
|
+
}
|
|
129
|
+
return ctasks.get(id);
|
|
130
|
+
};
|
|
131
|
+
const soleFeature = (ctask, wanted, pointer) => {
|
|
132
|
+
if (wanted !== undefined) {
|
|
133
|
+
if (!ctask.provides_feature_ids.includes(wanted)) {
|
|
134
|
+
fail('feature_not_provided', pointer, { task_id: ctask.task_id, provides_feature_ids: ctask.provides_feature_ids });
|
|
135
|
+
}
|
|
136
|
+
return wanted;
|
|
137
|
+
}
|
|
138
|
+
if (ctask.provides_feature_ids.length !== 1) {
|
|
139
|
+
fail('feature_ambiguous', pointer, { task_id: ctask.task_id, provides_feature_ids: ctask.provides_feature_ids });
|
|
140
|
+
}
|
|
141
|
+
return ctask.provides_feature_ids[0];
|
|
142
|
+
};
|
|
143
|
+
// A plan with no chain is described whole (the Store revision needs every task covered): each task by its own
|
|
144
|
+
// title, wired by its existing edges. Only the branch the draft touches is assessed afterwards.
|
|
145
|
+
const touched = new Set();
|
|
146
|
+
if (plan !== null && oldChain === null) {
|
|
147
|
+
for (const id of tasks.keys()) ensure(id, '/');
|
|
148
|
+
for (const { from, to } of edges) {
|
|
149
|
+
if (from.plan_key !== planKey || to.plan_key !== planKey) continue;
|
|
150
|
+
const feature = ctasks.get(from.task_id).provides_feature_ids[0];
|
|
151
|
+
push(ctasks.get(to.task_id).requires_feature_ids, feature);
|
|
152
|
+
push(features.get(ctasks.get(to.task_id).provides_feature_ids[0]).requires_feature_ids, feature);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const addEdge = (from, to) => {
|
|
156
|
+
const edge = { from: ref(from), to: ref(to) };
|
|
157
|
+
if (!edges.some((e) => edgeKey(e) === edgeKey(edge))) edges.push(edge);
|
|
158
|
+
};
|
|
159
|
+
const place = async (step, pointer, phase) => {
|
|
160
|
+
const result0 = result(step.result, `${pointer}/result`, step.task === undefined);
|
|
161
|
+
const provided = [step.task, step.existing, step.unknown].filter((x) => x !== undefined).length;
|
|
162
|
+
if (provided !== 1) fail('draft_provider_invalid', pointer, { expected: 'exactly one of task, existing, unknown' });
|
|
163
|
+
let provider;
|
|
164
|
+
let featureId = result0.feature_id;
|
|
165
|
+
if (step.task !== undefined) {
|
|
166
|
+
const task = newTask(step.task, `${pointer}/task`);
|
|
167
|
+
featureId ??= task.task_id;
|
|
168
|
+
if (tasks.has(task.task_id)) {
|
|
169
|
+
fail('step_task_exists', `${pointer}/task/task_id`, { task_id: task.task_id,
|
|
170
|
+
next_action: 'The plan already has this task: re-read it with lattice plan show and rebase the draft.' });
|
|
171
|
+
}
|
|
172
|
+
provider = { kind: 'task', task_id: task.task_id };
|
|
173
|
+
const phaseId = task.phase_id ?? phase;
|
|
174
|
+
const memo = doneField || task.done === undefined ? task.design_memo : `${task.design_memo}\n完了条件: ${task.done}`;
|
|
175
|
+
tasks.set(task.task_id, { task_id: task.task_id, title: task.title, lane: task.lane ?? 'main',
|
|
176
|
+
design_memo: memo, narrative_ref: null, narrative_anchor: null, compile_binding: null,
|
|
177
|
+
parent_task_id: null, phase_id: phaseId,
|
|
178
|
+
...(doneField ? { done_condition: task.done ?? null } : {}) });
|
|
179
|
+
} else if (step.existing !== undefined) {
|
|
180
|
+
only(step.existing, ['evidence_ref'], `${pointer}/existing`, ['evidence_ref']);
|
|
181
|
+
const given = step.existing.evidence_ref;
|
|
182
|
+
// An observation that cannot be read is a finding, not a refusal: the result stays unresolved and the plan usable.
|
|
183
|
+
const cause = typeof given === 'string' && isTodoRef(given)
|
|
184
|
+
? await existingReferenceProblem(canonicalRoot, given) : 'not_a_repo_file';
|
|
185
|
+
if (cause === null) provider = { kind: 'existing', evidence_ref: given };
|
|
186
|
+
else {
|
|
187
|
+
provider = { kind: 'unknown', reason: `observation ${typeof given === 'string' ? given : '(invalid)'} is not readable (${cause})`,
|
|
188
|
+
question: 'Which readable repo file records this result, or is it still unobserved?' };
|
|
189
|
+
placeFindings.push({ reason: 'observation_unresolved', pointer: `${pointer}/existing`, evidence_ref: given, cause });
|
|
190
|
+
}
|
|
191
|
+
} else {
|
|
192
|
+
only(step.unknown, ['reason', 'question'], `${pointer}/unknown`, ['reason', 'question']);
|
|
193
|
+
if (!text(step.unknown.reason) || !text(step.unknown.question)) fail('draft_provider_invalid', `${pointer}/unknown`);
|
|
194
|
+
provider = { kind: 'unknown', reason: step.unknown.reason, question: step.unknown.question };
|
|
195
|
+
}
|
|
196
|
+
if (features.has(featureId)) fail('feature_id_taken', `${pointer}/result/feature_id`, { feature_id: featureId });
|
|
197
|
+
features.set(featureId, { feature_id: featureId, capability: result0.capability,
|
|
198
|
+
acceptance: result0.acceptance, requires_feature_ids: [], provider });
|
|
199
|
+
if (provider.kind === 'task') {
|
|
200
|
+
ctasks.set(provider.task_id, { task_id: provider.task_id, requires_feature_ids: [], provides_feature_ids: [featureId] });
|
|
201
|
+
}
|
|
202
|
+
return { featureId, provider };
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
for (const afters of joinAfter.values()) for (const id of afters) for (const f of ctasks.get(id)?.provides_feature_ids ?? []) joinNeeded.add(f);
|
|
206
|
+
// Goals of a plan with no chain are its own sinks as they stand before the draft: an edit that cuts a branch off a goal
|
|
207
|
+
// must not turn that branch into a new goal (it is reported as unused instead), and unrelated goals are not rewritten.
|
|
208
|
+
let goalIds = oldChain?.goal.required_feature_ids ?? (plan === null ? null
|
|
209
|
+
: [...features.keys()].filter((id) => ![...features.values()].some((f) => f.requires_feature_ids.includes(id))
|
|
210
|
+
&& !joinNeeded.has(id)));
|
|
211
|
+
if (plan === null) {
|
|
212
|
+
const { featureId } = await place(draft.final, '/final', defaultPhase);
|
|
213
|
+
goalIds = [featureId];
|
|
214
|
+
}
|
|
215
|
+
for (const [index, step] of steps.entries()) {
|
|
216
|
+
const pointer = `/steps/${index}`;
|
|
217
|
+
only(step, ['before', 'task', 'existing', 'unknown', 'result', 'for', 'after', 'unlink'], pointer, ['before', 'result']);
|
|
218
|
+
const before = step.before;
|
|
219
|
+
if (!tasks.has(before)) {
|
|
220
|
+
if (introduced.has(before) && introduced.get(before) > index) {
|
|
221
|
+
fail('step_out_of_order', `${pointer}/before`, { task_id: before, introduced_at_step: introduced.get(before),
|
|
222
|
+
next_action: 'Write the step that adds this task first, or name a task already in the plan.' });
|
|
223
|
+
}
|
|
224
|
+
fail('before_unknown', `${pointer}/before`, { task_id: before, available_task_ids: [...tasks.keys()].sort() });
|
|
225
|
+
}
|
|
226
|
+
touched.add(before);
|
|
227
|
+
const consumer = ensure(before, `${pointer}/before`);
|
|
228
|
+
const consumerFeature = soleFeature(consumer, step.for, `${pointer}/for`);
|
|
229
|
+
const { featureId, provider } = await place(step, pointer, tasks.get(before).phase_id);
|
|
230
|
+
if (provider.kind === 'task') touched.add(provider.task_id);
|
|
231
|
+
push(consumer.requires_feature_ids, featureId);
|
|
232
|
+
push(features.get(consumerFeature).requires_feature_ids, featureId);
|
|
233
|
+
if (provider.kind === 'task') addEdge(provider.task_id, before);
|
|
234
|
+
const after = step.after ?? [];
|
|
235
|
+
if (!Array.isArray(after) || (after.length > 0 && provider.kind !== 'task')) {
|
|
236
|
+
fail('draft_after_invalid', `${pointer}/after`, { expected: 'a list of task ids, only on a step that adds a task' });
|
|
237
|
+
}
|
|
238
|
+
after.forEach((upstream, i) => {
|
|
239
|
+
const at = `${pointer}/after/${i}`;
|
|
240
|
+
const id = typeof upstream === 'string' ? upstream : upstream?.task_id;
|
|
241
|
+
touched.add(id);
|
|
242
|
+
if (!tasks.has(id) || id === provider.task_id) fail('task_unknown', at, { task_id: id, available_task_ids: [...tasks.keys()].sort() });
|
|
243
|
+
const feature = soleFeature(ensure(id, at), typeof upstream === 'string' ? undefined : upstream.feature_id, at);
|
|
244
|
+
push(ctasks.get(provider.task_id).requires_feature_ids, feature);
|
|
245
|
+
push(features.get(featureId).requires_feature_ids, feature);
|
|
246
|
+
addEdge(id, provider.task_id);
|
|
247
|
+
});
|
|
248
|
+
(step.unlink ?? []).forEach((edge, i) => {
|
|
249
|
+
const at = `${pointer}/unlink/${i}`;
|
|
250
|
+
only(edge, ['from', 'to'], at, ['from', 'to']);
|
|
251
|
+
const index2 = edges.findIndex((e) => e.from.plan_key === planKey && e.to.plan_key === planKey
|
|
252
|
+
&& e.from.task_id === edge.from && e.to.task_id === edge.to);
|
|
253
|
+
if (index2 < 0) fail('unlink_edge_missing', at, { from: edge.from, to: edge.to });
|
|
254
|
+
edges.splice(index2, 1);
|
|
255
|
+
touched.add(edge.from); touched.add(edge.to);
|
|
256
|
+
const gone = ctasks.get(edge.from)?.provides_feature_ids ?? [];
|
|
257
|
+
const to = ctasks.get(edge.to);
|
|
258
|
+
if (to !== undefined) {
|
|
259
|
+
to.requires_feature_ids = to.requires_feature_ids.filter((id) => !gone.includes(id));
|
|
260
|
+
for (const id of to.provides_feature_ids) {
|
|
261
|
+
const f = features.get(id);
|
|
262
|
+
f.requires_feature_ids = f.requires_feature_ids.filter((r) => !gone.includes(r));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const continuity = [];
|
|
269
|
+
const retired = new Set();
|
|
270
|
+
(draft.retire ?? []).forEach((entry, i) => {
|
|
271
|
+
const at = `/retire/${i}`;
|
|
272
|
+
only(entry, ['task_id', 'reason'], at, ['task_id', 'reason']);
|
|
273
|
+
if (!baseIds.has(entry.task_id) || retired.has(entry.task_id) || !text(entry.reason)) {
|
|
274
|
+
fail('retire_invalid', at, { task_id: entry.task_id, cause: 'must name a task of the active plan once, with a reason' });
|
|
275
|
+
}
|
|
276
|
+
const dependent = [...(plan.joins ?? []), ...(plan.phase_accept_dependencies ?? [])].some((e) =>
|
|
277
|
+
JSON.stringify(e).includes(`"task_id":"${entry.task_id}"`));
|
|
278
|
+
if (dependent) fail('retire_task_referenced', at, { task_id: entry.task_id, cause: 'a join or phase accept names it' });
|
|
279
|
+
retired.add(entry.task_id);
|
|
280
|
+
for (const e of edges) { if (e.from.task_id === entry.task_id) touched.add(e.to.task_id); }
|
|
281
|
+
tasks.delete(entry.task_id);
|
|
282
|
+
for (let k = edges.length - 1; k >= 0; k -= 1) {
|
|
283
|
+
if (edges[k].from.task_id === entry.task_id || edges[k].to.task_id === entry.task_id) {
|
|
284
|
+
if (edges[k].from.plan_key === planKey && edges[k].to.plan_key === planKey) edges.splice(k, 1);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
for (const id of ctasks.get(entry.task_id)?.provides_feature_ids ?? []) {
|
|
288
|
+
if (goalIds?.includes(id)) fail('retire_goal_feature', at, { task_id: entry.task_id, feature_id: id });
|
|
289
|
+
features.delete(id);
|
|
290
|
+
for (const f of features.values()) f.requires_feature_ids = f.requires_feature_ids.filter((r) => r !== id);
|
|
291
|
+
for (const t of ctasks.values()) t.requires_feature_ids = t.requires_feature_ids.filter((r) => r !== id);
|
|
292
|
+
}
|
|
293
|
+
ctasks.delete(entry.task_id);
|
|
294
|
+
continuity.push({ task_id: entry.task_id, policy: 'retire', reason: entry.reason });
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
goalIds = goalIds.filter((id) => features.has(id));
|
|
298
|
+
const goal = {
|
|
299
|
+
purpose: draft.goal?.purpose ?? oldChain?.goal.purpose ?? `${planKey}`,
|
|
300
|
+
outcome: draft.goal?.outcome ?? oldChain?.goal.outcome ?? '(plan goal not recorded)',
|
|
301
|
+
acceptance: draft.goal?.acceptance ?? oldChain?.goal.acceptance ?? '(plan goal not recorded)',
|
|
302
|
+
required_feature_ids: goalIds,
|
|
303
|
+
};
|
|
304
|
+
const chain = {
|
|
305
|
+
schema: BACKCHAIN_SCHEMA, authoring_ref: isTodoRef(draftRef) ? draftRef : 'plan-draft.json',
|
|
306
|
+
project_id: projectId, plan_key: planKey, plan_version: plan?.plan_version ?? draft.plan_version ?? 'v1',
|
|
307
|
+
goal, features: [...features.values()], tasks: [...ctasks.values()], chain_digest: '',
|
|
308
|
+
};
|
|
309
|
+
// Existing work keeps its state unless the author says otherwise; a first draft over a plan with no chain
|
|
310
|
+
// must not read "no record" as "everything changed" (it would reset the history).
|
|
311
|
+
const explicit = new Map((draft.continuity ?? []).map((entry, i) => {
|
|
312
|
+
only(entry, ['task_id', 'policy', 'reason'], `/continuity/${i}`, ['task_id', 'policy', 'reason']);
|
|
313
|
+
if (!baseIds.has(entry.task_id) || retired.has(entry.task_id) || !['carry', 'reset'].includes(entry.policy) || !text(entry.reason)) {
|
|
314
|
+
fail('continuity_invalid', `/continuity/${i}`, { task_id: entry.task_id });
|
|
315
|
+
}
|
|
316
|
+
return [entry.task_id, entry];
|
|
317
|
+
}));
|
|
318
|
+
continuity.push(...explicit.values());
|
|
319
|
+
for (const id of baseIds) {
|
|
320
|
+
if (retired.has(id) || explicit.has(id) || !ctasks.has(id)) continue;
|
|
321
|
+
const incomingOf = (list) => list.filter((e) => e.to.task_id === id).map(edgeKey).sort().join();
|
|
322
|
+
if ((oldChain !== null && taskSignature(oldChain, id) !== taskSignature(chain, id))
|
|
323
|
+
|| incomingOf(plan.hard_dependencies) !== incomingOf(edges)) {
|
|
324
|
+
continuity.push({ task_id: id, policy: 'carry', reason: 'draft changed its inputs or outputs; recorded state is kept' });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (continuity.length > 0) chain.continuity = continuity.sort((a, b) => a.task_id.localeCompare(b.task_id));
|
|
328
|
+
chain.chain_digest = todoSelfDigest(chain, 'chain_digest');
|
|
329
|
+
|
|
330
|
+
const authoring = completeCreateInput({
|
|
331
|
+
schema: CREATE_SCHEMA, project_id: projectId, plan_key: planKey, plan_version: chain.plan_version,
|
|
332
|
+
...(draft.actor !== undefined ? { actor: draft.actor } : {}),
|
|
333
|
+
...(draft.recorded_at !== undefined ? { recorded_at: draft.recorded_at } : {}),
|
|
334
|
+
tasks: [...tasks.values()],
|
|
335
|
+
phases: plan?.phases ?? draft.phases ?? [{ phase_id: defaultPhase, title: planKey }],
|
|
336
|
+
hard_dependencies: edges, joins: plan?.joins ?? [],
|
|
337
|
+
phase_accept_dependencies: plan?.phase_accept_dependencies ?? [],
|
|
338
|
+
}, { env, now });
|
|
339
|
+
|
|
340
|
+
const { findings, unreachedTaskIds } = await draftFindings({ repoRoot, draft, chain, member, baseIds, extra: placeFindings,
|
|
341
|
+
scope: oldChain === null && plan !== null ? touched : null, joinAfter });
|
|
342
|
+
const finalEdges = new Set(edges.map(edgeKey));
|
|
343
|
+
const pairs = (keys) => keys.map((key) => { const [from, to] = key.split('->'); return { from: from.split('/')[1], to: to.split('/')[1] }; });
|
|
344
|
+
return { chain, authoring, report: {
|
|
345
|
+
summary: {
|
|
346
|
+
mode: plan === null ? (store === null ? 'create' : 'add') : 'revise',
|
|
347
|
+
added_task_ids: [...tasks.keys()].filter((id) => !baseIds.has(id)),
|
|
348
|
+
retired_task_ids: [...retired].sort(),
|
|
349
|
+
edge_changes: {
|
|
350
|
+
added: pairs([...finalEdges].filter((k) => !initialEdges.has(k))),
|
|
351
|
+
removed: pairs([...initialEdges].filter((k) => !finalEdges.has(k))),
|
|
352
|
+
},
|
|
353
|
+
unassessed_task_count: oldChain === null && plan !== null ? [...tasks.keys()].filter((id) => !touched.has(id) && baseIds.has(id) && !unreachedTaskIds.includes(id)).length : 0,
|
|
354
|
+
},
|
|
355
|
+
findings,
|
|
356
|
+
} };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Advisory only (never blocks publish or readiness). Mechanical facts over the declared scope:
|
|
361
|
+
* an output nobody consumes, one capability string claimed by two providers, and a planned provider whose result
|
|
362
|
+
* the author matched to an observation file. A matched file is a candidate for comparison, not equivalence.
|
|
363
|
+
*/
|
|
364
|
+
async function draftFindings({ repoRoot, draft, chain, member, baseIds, scope, extra, joinAfter }) {
|
|
365
|
+
const found = [];
|
|
366
|
+
const state = new Map((member?.tasks ?? []).map((task) => [task.task_id, task.status]));
|
|
367
|
+
const features = new Map(chain.features.map((f) => [f.feature_id, f]));
|
|
368
|
+
// Reachable from a goal result through requirements. A task result outside it serves no goal: the branch an edit cut off
|
|
369
|
+
// (with everything only it needed) is the retirement candidate, found from the edit and not from the whole plan.
|
|
370
|
+
const reached = new Set();
|
|
371
|
+
const byTask = new Map(chain.tasks.map((t) => [t.task_id, t]));
|
|
372
|
+
const walk = (id) => {
|
|
373
|
+
if (reached.has(id) || !features.has(id)) return;
|
|
374
|
+
reached.add(id);
|
|
375
|
+
const feature = features.get(id);
|
|
376
|
+
feature.requires_feature_ids.forEach(walk);
|
|
377
|
+
if (feature.provider.kind === 'task') {
|
|
378
|
+
(byTask.get(feature.provider.task_id)?.requires_feature_ids ?? []).forEach(walk);
|
|
379
|
+
for (const after of joinAfter.get(feature.provider.task_id) ?? []) (byTask.get(after)?.provides_feature_ids ?? []).forEach(walk);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
chain.goal.required_feature_ids.forEach(walk);
|
|
383
|
+
const stateOf = (id) => (baseIds.has(id) ? state.get(id) ?? null : 'new');
|
|
384
|
+
const inScope = (feature) => scope === null || (feature.provider.kind === 'task' && scope.has(feature.provider.task_id));
|
|
385
|
+
for (const [index, feature] of chain.features.entries()) {
|
|
386
|
+
if (feature.provider.kind === 'task' && !reached.has(feature.feature_id)) {
|
|
387
|
+
found.push({ reason: 'unused_output', pointer: `/features/${index}`, feature_id: feature.feature_id,
|
|
388
|
+
task_id: feature.provider.task_id, task_state: stateOf(feature.provider.task_id),
|
|
389
|
+
candidate: 'retirement' });
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const byCapability = new Map();
|
|
393
|
+
for (const feature of chain.features.filter(inScope)) {
|
|
394
|
+
const key = `${feature.capability.trim()}\u0000${feature.acceptance.trim()}`; // same capability with another acceptance/scope is a different result
|
|
395
|
+
byCapability.set(key, [...(byCapability.get(key) ?? []), feature.feature_id]);
|
|
396
|
+
}
|
|
397
|
+
for (const [capability, ids] of byCapability) {
|
|
398
|
+
if (ids.length > 1) found.push({ reason: 'duplicate_result', pointer: '/features', capability: capability.split('\u0000')[0], feature_ids: ids.sort() });
|
|
399
|
+
}
|
|
400
|
+
const canonicalRoot = await realpath(repoRoot);
|
|
401
|
+
for (const [index, entry] of (draft.observations ?? []).entries()) {
|
|
402
|
+
const at = `/observations/${index}`;
|
|
403
|
+
only(entry, ['feature_id', 'evidence_ref'], at, ['feature_id', 'evidence_ref']);
|
|
404
|
+
const feature = features.get(entry.feature_id);
|
|
405
|
+
const cause = typeof entry.evidence_ref === 'string' && isTodoRef(entry.evidence_ref)
|
|
406
|
+
? await existingReferenceProblem(canonicalRoot, entry.evidence_ref) : 'not_a_repo_file';
|
|
407
|
+
if (feature === undefined) {
|
|
408
|
+
found.push({ reason: 'observation_unresolved', pointer: at, feature_id: entry.feature_id, evidence_ref: entry.evidence_ref,
|
|
409
|
+
cause: 'feature_unknown' });
|
|
410
|
+
} else if (cause !== null) {
|
|
411
|
+
found.push({ reason: 'observation_unresolved', pointer: at, feature_id: feature.feature_id, evidence_ref: entry.evidence_ref, cause });
|
|
412
|
+
} else if (feature.provider.kind === 'task') {
|
|
413
|
+
found.push({ reason: 'planned_provider_has_observation', pointer: at, feature_id: feature.feature_id,
|
|
414
|
+
task_id: feature.provider.task_id, task_state: stateOf(feature.provider.task_id), evidence_ref: entry.evidence_ref });
|
|
415
|
+
} else {
|
|
416
|
+
// A result that has no planned task (an existing observation or an open question): the file is noted, never a refusal.
|
|
417
|
+
found.push({ reason: 'observation_noted', pointer: at, feature_id: feature.feature_id, provider_kind: feature.provider.kind,
|
|
418
|
+
evidence_ref: entry.evidence_ref });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return { findings: sortFindings([...found, ...extra]),
|
|
422
|
+
unreachedTaskIds: chain.features.filter((f) => f.provider.kind === 'task' && !reached.has(f.feature_id)).map((f) => f.provider.task_id) };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** The authoring entry: a skeleton to fill in, seeded from the active plan on revision. */
|
|
426
|
+
export async function draftTemplate({ repoRoot, member, store }) {
|
|
427
|
+
const projectId = store?.project_id ?? (await import('./project-cli.mjs')).identifierFromRepoRoot(repoRoot, 'project');
|
|
428
|
+
const step = { before: '<downstream task id already in the plan or an earlier step>',
|
|
429
|
+
task: { task_id: '<new task id>', title: '<title>', design_memo: '<what to do>', done: '<completion condition>' },
|
|
430
|
+
result: { capability: '<what the downstream task needs from this one>', acceptance: '<how to tell it is there>' },
|
|
431
|
+
after: ['<existing upstream task id to link, optional>'], unlink: [] };
|
|
432
|
+
if (member === null || member === undefined) {
|
|
433
|
+
return { schema: DRAFT_SCHEMA, project_id: projectId, plan_key: '<plan key>',
|
|
434
|
+
goal: { purpose: '<why>', outcome: '<final result>', acceptance: '<how the goal is judged>' },
|
|
435
|
+
final: { task: { task_id: '<goal task id>', title: '<title>', design_memo: '<what to do>', done: '<completion condition>' },
|
|
436
|
+
result: { capability: '<the observable result>', acceptance: '<how to tell it is there>' } },
|
|
437
|
+
steps: [step], observations: [] };
|
|
438
|
+
}
|
|
439
|
+
const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
|
|
440
|
+
const states = new Map(member.tasks.map((task) => [task.task_id, task.status]));
|
|
441
|
+
return { schema: DRAFT_SCHEMA, project_id: projectId, plan_key: member.plan.plan_key,
|
|
442
|
+
base_plan_version: member.plan.plan_version,
|
|
443
|
+
...(binding === null ? {} : { goal: {
|
|
444
|
+
purpose: binding.chain.goal.purpose, outcome: binding.chain.goal.outcome,
|
|
445
|
+
acceptance: binding.chain.goal.acceptance } }),
|
|
446
|
+
steps: [step], observations: [],
|
|
447
|
+
context: { tasks: member.plan.tasks.map(({ task_id: id, title }) => ({ task_id: id, title, state: states.get(id) })) } };
|
|
448
|
+
}
|
package/src/project-cli.mjs
CHANGED
|
@@ -817,7 +817,7 @@ export function validatePlanCreateInput(input) {
|
|
|
817
817
|
}
|
|
818
818
|
|
|
819
819
|
/** a17: repo root名をtodo identifierへ寄せる。小文字化し、使えない文字は'-'へ、前後の記号は落とす。 */
|
|
820
|
-
function identifierFromRepoRoot(repoRoot, fallback) {
|
|
820
|
+
export function identifierFromRepoRoot(repoRoot, fallback) {
|
|
821
821
|
const name = path.basename(repoRoot).toLowerCase().replace(/[^0-9a-z._-]+/gu, '-')
|
|
822
822
|
.replace(/^[^0-9a-z]+|[^0-9a-z]+$/gu, '').slice(0, 128);
|
|
823
823
|
return isTodoIdentifier(name) ? name : fallback;
|
|
@@ -1070,6 +1070,8 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
|
|
|
1070
1070
|
max_frontier_width: dispatchShape.max_frontier_width,
|
|
1071
1071
|
serialization_ratio: dispatchShape.serialization_ratio,
|
|
1072
1072
|
},
|
|
1073
|
+
// The goal bound by `plan backchain` (null when the plan has none or its binding is unreadable), so the next author starts from it.
|
|
1074
|
+
goal: (await (await import('./plan-backchain.mjs')).readPlanBackchainBinding({ repoRoot, plan }).catch(() => null))?.chain.goal ?? null,
|
|
1073
1075
|
result_digest: '',
|
|
1074
1076
|
};
|
|
1075
1077
|
result.result_digest = resultDigest(result);
|