okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
18.7 KiB290 linesraw
1/**
2 * One Time-skip run.
3 *
4 * A run is either a **developer preview** (the scripted timeline, kept for design review) or a
5 * **real job** driven by Strata Control through `/api/timeskip`. When `job` is present the panel
6 * renders the job's own phases, decisions and check outcomes; the scripted moments still supply the
7 * motion and layout, but they no longer decide anything.
8 *
9 * `job` being absent is what makes a run a preview. There is no flag to forget to clear.
10 */
11export interface TimeSkipRun {
12  id: string;
13  prompt: string;
14  startedAt: number;
15  completedAt?: number;
16  /** The selected result. */
17  retainedVersion?: TimeSkipVersion;
18  /** Present only for a real job. */
19  job?: TimeSkipJob;
20}
21
22/** What the App Host reports about a real run. Field names mirror the job's durable record. */
23export interface TimeSkipJob {
24  id: string;
25  phase: 'planning' | 'choosing' | 'running' | 'comparing' | 'queued' | 'checkpointing' | 'generating' | 'checking' | 'decision' | 'completed'
26       | 'cancelled' | 'failed' | 'interrupted' | 'needs_user_review';
27  attempts: { index: number; decision: string | null; reason: string;
28              checks: { id: string; outcome: string; kind: string }[] }[];
29  checkpoints: { id: string; label: string; digest: string;
30                 checks: { id: string; outcome: string; kind: string }[] }[];
31  selectedCheckpoint: string | null;
32  decision: { outcome?: string; reason?: string; improvements?: string[];
33              regressions?: string[]; retained?: string } | null;
34  needsUserReview: boolean;
35  /** What the host says it is doing now (notes-split-agent3.md): a code, English words with {0} slots, and arguments. */
36  activity?: { code: string; text: string; args?: Record<string, unknown> } | null;
37  error: string | null;
38  finishedAt?: number | null;
39  /** The fork design (notes-split-agent8.md, item 11): the plan, the one step where checking matters most, and the two agents' progress. */
40  plan?: { steps: { id: string; text: string }[] } | null;
41  lever?: ForkLever | null;
42  a?: ForkLane | null;
43  b?: ForkLane | null;
44  /** The files the run changed (saved original against the revision), read from the job's own folders. */
45  files?: TimeSkipFile[];
46  /** More changed files than are listed. */
47  moreFiles?: number;
48  /** The revision attempt "Keep the update" applies when the checks did not keep one themselves. */
49  applyAttempt?: number | null;
50}
51
52export interface ForkLever { step: number; total: number; text: string; why: string; defaulted: boolean }
53export interface ForkLane { state: string; step: number; total: number; text: string; line: string; waiting: boolean }
54
55const lane = (raw: unknown): ForkLane | null => {
56  if (!raw || typeof raw !== 'object') return null;
57  const l = raw as Record<string, unknown>;
58  return { state: typeof l.state === 'string' ? l.state : 'waiting', step: Number(l.step) || 0, total: Number(l.total) || 0, text: typeof l.text === 'string' ? l.text : '', line: typeof l.line === 'string' ? l.line : '', waiting: l.waiting === true };
59};
60
61/**
62 * What an event or a status answer adds to a job under the fork design: the plan, the lever with its why, both lanes, and the activity as one
63 * friendly line (a string there; the older host sends an object, which is left as it is).
64 */
65export function forkFields(data: Record<string, unknown>): Partial<TimeSkipJob> {
66  const out: Partial<TimeSkipJob> = {};
67  const plan = data.plan as { steps?: unknown } | null | undefined;
68  if (plan && Array.isArray(plan.steps)) out.plan = { steps: plan.steps.flatMap((s, i) => (s && typeof s === 'object' && typeof (s as { text?: unknown }).text === 'string' ? [{ id: String((s as { id?: unknown }).id ?? i + 1), text: (s as { text: string }).text }] : [])) };
69  const lv = data.lever as Record<string, unknown> | null | undefined;
70  if (lv && typeof lv === 'object' && Number(lv.step) > 0) out.lever = { step: Number(lv.step), total: Number(lv.total) || 0, text: typeof lv.text === 'string' ? lv.text : '', why: typeof lv.why === 'string' ? lv.why : '', defaulted: lv.defaulted === true };
71  else if (lv === null) out.lever = null;
72  if ('a' in data) out.a = lane(data.a);
73  if ('b' in data) out.b = lane(data.b);
74  if (typeof data.activity === 'string' && data.activity) out.activity = { code: 'line', text: data.activity };
75  else if (data.activity && typeof data.activity === 'object') out.activity = data.activity as TimeSkipJob['activity'];
76  return out;
77}
78
79/** A job that runs as two agents (A, and B forked at the lever step) rather than one revision. */
80export const isForkJob = (job: Pick<TimeSkipJob, 'plan' | 'lever' | 'a' | 'b'> | undefined | null): boolean => !!job && !!(job.plan || job.lever || job.a || job.b);
81
82export interface TimeSkipFile {
83  path: string;
84  status: 'added' | 'changed' | 'removed';
85  original?: string;
86  updated?: string;
87  /** Too big or not text: listed, but not shown. */
88  unreadable?: boolean;
89}
90
91export type TimeSkipVersion = 'original' | 'updated';
92
93export const TIME_SKIP_DURATION = 28000;
94export const timeSkipTabId = (id: string) => `time-skip:${id}`;
95
96/** null means an ordinary chat message; an empty string means a missing prompt. */
97export function timeSkipPrompt(text: string): string | null {
98  const match = text.trim().match(/^\/time-skip(?:\s+([\s\S]*))?$/i);
99  return match ? (match[1] ?? '').trim() : null;
100}
101
102const moments = [
103  { at: 0, status: 'Saving', title: 'A good starting point.', body: 'Saving the first draft before exploring a different direction.', reason: 'The original stays available.', chosen: 'a', pass: 1 },
104  { at: 2600, status: 'Exploring', title: 'Two possible directions.', body: 'Keeping the original while a candidate fills its gaps.', reason: 'Building B from the saved draft.', chosen: 'a', pass: 1 },
105  { at: 6000, status: 'Exploring', title: 'Making the next step clearer.', body: 'The candidate is adding detail without losing the original idea.', reason: 'A focused correction, from the same checkpoint.', chosen: 'a', pass: 1 },
106  { at: 9500, status: 'Comparing', title: 'Does the change hold up?', body: 'Comparing the candidate with the original against the same checks.', reason: 'Checking completeness and what was already working.', chosen: 'a', pass: 1 },
107  { at: 12500, status: 'Time-skipping', title: 'Taking the stronger direction.', body: 'B fills the gaps and keeps the useful parts of A.', reason: 'A → B · missing detail added, no check regressed.', chosen: 'b', pass: 1 },
108  { at: 16000, status: 'Refining', title: 'Can we take it further?', body: 'B is saved. Trying one more focused revision in the other stream.', reason: 'A new candidate starts from B’s checkpoint.', chosen: 'b', pass: 2 },
109  { at: 20500, status: 'Comparing', title: 'Shorter isn’t always better.', body: 'The new revision is concise, but loses a useful detail.', reason: 'One previously passing check now fails.', chosen: 'b', pass: 2 },
110  { at: 24000, status: 'Keeping B', title: 'Keep the progress we made.', body: 'Discarding the weaker revision and continuing from B.', reason: 'Revision rejected · the stronger checkpoint is kept.', chosen: 'b', pass: 2 },
111  { at: TIME_SKIP_DURATION, status: 'Ready', title: 'The stronger version stays.', body: 'Two passes. One useful improvement. The original is still here.', reason: 'B selected · all three example checks pass.', chosen: 'b', pass: 2 },
112] as const;
113
114export function timeSkipFrame(run: TimeSkipRun, now: number) {
115  const elapsed = run.completedAt ? TIME_SKIP_DURATION : Math.max(0, now - run.startedAt);
116  let index = 0;
117  for (let i = 1; i < moments.length; i++) if (elapsed >= moments[i].at) index = i;
118  return { ...moments[Math.max(0, index)], index, done: elapsed >= TIME_SKIP_DURATION };
119}
120
121/** Result selection is only available after the automatic comparison finishes. */
122export function withTimeSkipResult(run: TimeSkipRun, version: TimeSkipVersion, now: number): TimeSkipRun {
123  return timeSkipFrame(run, now).done ? { ...run, retainedVersion: version } : run;
124}
125
126export function timeSkipResultState(run: TimeSkipRun, now: number) {
127  if (run.job) return realResultState(run.job, run.retainedVersion);
128  const frame = timeSkipFrame(run, now);
129  const ready = frame.index >= 3;
130  const kept: TimeSkipVersion = frame.done && run.retainedVersion === 'original' ? 'original' : frame.chosen === 'b' ? 'updated' : 'original';
131  const status = frame.done ? kept === 'original' ? 'Original restored' : 'Updated result kept'
132    : frame.index === 0 ? 'Saving original…'
133    : frame.index === 3 || frame.index === 6 ? 'Checking changes…'
134    : frame.index >= 7 ? 'Finishing up…' : 'Revising…';
135  return { frame, ready, kept, status };
136}
137
138/**
139 * Result state for a **real** job.
140 *
141 * The scripted frame index is derived from the job's phase so the existing layout and motion are
142 * unchanged, but every value that carries meaning comes from the job:
143 *
144 *   * `kept` is the job's retained checkpoint, not a scripted 'a'/'b' choice;
145 *   * `status` names the actual phase, and says when the evidence was inconclusive rather than
146 *     dressing it as a success;
147 *   * `unknown` check outcomes are surfaced as unknown. A phase is not a percentage and this
148 *     returns none.
149 */
150function realResultState(job: TimeSkipJob, chosen?: TimeSkipVersion) {
151  const done = ['completed', 'cancelled', 'failed', 'interrupted'].includes(job.phase);
152  const index =
153    job.phase === 'queued' ? 0
154    : job.phase === 'checkpointing' ? 0
155    : job.phase === 'generating' ? 2
156    : job.phase === 'checking' ? 4
157    : job.phase === 'decision' ? 5
158    : 8;
159  // The decision's `improvements` is the job's own answer about what got better; nothing here
160  // re-derives a verdict from the attempt list.
161  const improved = (job.decision?.improvements?.length ?? 0) > 0;
162  const kept: TimeSkipVersion = chosen ?? (improved ? 'updated' : 'original');
163  const outcome = job.decision?.outcome ?? null;
164
165  let status: string;
166  if (job.phase === 'failed') status = 'The revision could not be completed';
167  else if (job.phase === 'cancelled') status = 'Stopped · the saved version was kept';
168  else if (job.phase === 'interrupted') status = 'Interrupted · the saved version was kept';
169  else if (!done) {
170    status = job.phase === 'checkpointing' ? 'Saving the current version…'
171      : job.phase === 'generating' ? 'Revising…'
172      : job.phase === 'checking' ? 'Checking the changes…'
173      : job.phase === 'decision' ? 'Deciding from the checks…'
174      : 'Starting…';
175  } else if (chosen === 'updated') {
176    status = 'Update kept · your files now have it';
177  } else if (chosen === 'original') {
178    status = 'Original kept · your files are unchanged';
179  } else if (job.needsUserReview || outcome === 'inconclusive' || outcome === 'conflict') {
180    status = 'Ready to compare · you choose which to keep';
181  } else if (outcome === 'accepted') {
182    status = 'Update kept · the checks improved';
183  } else {
184    status = 'Saved version kept';
185  }
186
187  const frame = { ...moments[Math.max(0, Math.min(moments.length - 1, index))], index, done,
188                  pass: job.attempts.length > 1 ? 2 : 1 };
189  return { frame, ready: index >= 3, kept, status };
190}
191
192/**
193 * Whether a run still needs a person to choose.
194 *
195 * The panel uses this to offer Compare instead of claiming a result. It is deliberately not the same
196 * question as "is the run finished".
197 */
198export function timeSkipNeedsReview(run: TimeSkipRun): boolean {
199  return Boolean(run.job?.needsUserReview);
200}
201
202/** The job's own check outcomes for a checkpoint, for the details table. */
203export function timeSkipCheckOutcomes(run: TimeSkipRun): { id: string; outcome: string }[] {
204  const job = run.job;
205  if (!job) return [];
206  const checkpoint = job.checkpoints.find(c => c.id === job.selectedCheckpoint) ?? job.checkpoints[0];
207  return (checkpoint?.checks ?? []).map(c => ({ id: c.id, outcome: c.outcome }));
208}
209
210export interface TimeSkipDocument {
211  title: string;
212  steps: readonly string[];
213  successCheck: string;
214  code?: string;
215  image?: { url: string; alt: string };
216  /** A real run has no sample "success check" to show. */
217  hideCheck?: boolean;
218}
219
220/** Immutable paired sample outputs, separate from the later rejected attempt. */
221export function timeSkipDocuments(prompt: string): Record<TimeSkipVersion | 'revision', TimeSkipDocument> & { changes: string[] } {
222  if (/image|photo|poster|illustration/i.test(prompt)) return {
223    original: { title: 'Fieldnotes cover.svg', steps: [], successCheck: 'Not defined', image: { url: '/examples/fieldnotes-cover.svg', alt: 'Original Fieldnotes cover: Room to begin again, with botanical shapes.' } },
224    updated: { title: 'Fieldnotes cover.svg', steps: [], successCheck: 'Keep the botanical style and make the headline easier to scan.', image: { url: '/examples/fieldnotes-cover-timeskip.svg', alt: 'Updated Fieldnotes cover: Make room for ideas, with more open space around the headline.' } },
225    revision: { title: 'Fieldnotes cover.svg', steps: [], successCheck: 'Keep the botanical style and make the headline easier to scan.', image: { url: '/examples/fieldnotes-cover-revision.svg', alt: 'Rejected Fieldnotes cover revision: the shortened layout removes the useful subtitle.' } },
226    changes: ['Shortened the headline', 'Opened up the composition'],
227  } satisfies Record<TimeSkipVersion | 'revision', TimeSkipDocument> & { changes: string[] };
228  if (/website|app\b|code|voxel|html|dashboard/i.test(prompt)) return {
229    original: { title: 'Counter component', steps: [], successCheck: 'Not defined', code: '<section class="counter">\n  <output>0</output>\n  <button onclick="add()">Add one</button>\n  <button>Reset</button>\n</section>\n<style>\n  .counter { width: 600px; }\n</style>\n<script>\n  const value = document.querySelector("output");\n  function add() { value.value = +value.value + 1; }\n</script>' },
230    updated: { title: 'Counter component', steps: [], successCheck: 'Add twice, reset to 0, then check at 320 px.', code: '<section class="counter">\n  <output>0</output>\n  <button onclick="add()">Add one</button>\n  <button onclick="reset()">Reset</button>\n</section>\n<style>\n  .counter { width: min(600px, 100%); }\n</style>\n<script>\n  const value = document.querySelector("output");\n  function add() { value.value = +value.value + 1; }\n  function reset() { value.value = 0; }\n</script>' },
231    revision: { title: 'Counter component', steps: [], successCheck: 'Add twice, reset to 0, then check at 320 px.', code: '<section class="counter">\n  <output>0</output>\n  <button onclick="add()">Add one</button>\n  <button>Reset</button>\n</section>\n<style>\n  .counter { width: min(600px, 100%); }\n</style>\n<script>\n  const value = document.querySelector("output");\n  function add() { value.value = +value.value + 1; }\n</script>' },
232    changes: ['Connected Reset to clear the counter', 'Made the layout fit small screens', 'Added a repeatable success check'],
233  } satisfies Record<TimeSkipVersion | 'revision', TimeSkipDocument> & { changes: string[] };
234  return {
235    original: { title: 'Launch plan', steps: ['Invite a few testers', 'Collect feedback', 'Make improvements'], successCheck: 'Not defined' },
236    updated: { title: 'Launch plan', steps: ['Invite 10 testers', 'Collect feedback by Friday', 'Fix the top 3 issues'], successCheck: '8 of 10 testers complete setup.' },
237    revision: { title: 'Launch plan', steps: ['Invite 10 testers', 'Fix the top 3 issues'], successCheck: '8 of 10 testers complete setup.' },
238    changes: ['Made all 3 steps specific', 'Added a success check'],
239  } satisfies Record<TimeSkipVersion | 'revision', TimeSkipDocument> & { changes: string[] };
240}
241
242export function timeSkipDocumentMarkdown(document: TimeSkipDocument) {
243  if (document.hideCheck) return `# ${document.title}\n\n\`\`\`\n${document.code ?? ''}\n\`\`\``;
244  return `# ${document.title}\n\n${document.image ? `![${document.image.alt}](${document.image.url})` : document.code ? `\`\`\`html\n${document.code}\n\`\`\`` : document.steps.map((step, i) => `${i + 1}. ${step}`).join('\n')}\n\n## Success check\n\n${document.successCheck}\n\n*Time-skip example · sample output, simulated checks.*`;
245}
246
247const FILE_VERB = { added: 'Added', changed: 'Changed', removed: 'Removed' } as const;
248
249/** The two sides of a real run as documents: the changed files, one after another. */
250export function realTimeSkipDocuments(job: TimeSkipJob): Record<TimeSkipVersion | 'revision', TimeSkipDocument> & { changes: string[] } {
251  const files = job.files ?? [];
252  const side = (which: 'original' | 'updated') => files.map(f => {
253    const text = f.unreadable ? '(too big or not text, so it is not shown here)'
254      : which === 'original' ? (f.status === 'added' ? '(this file did not exist)' : f.original ?? '')
255      : (f.status === 'removed' ? '(this file was removed)' : f.updated ?? '');
256    return files.length === 1 ? text : '── ' + f.path + ' ──\n' + text;
257  }).join('\n\n');
258  const title = files.length === 1 ? files[0].path : files.length ? files.length + ' files' : 'Nothing changed';
259  const make = (which: 'original' | 'updated'): TimeSkipDocument => ({ title, steps: [], successCheck: '', hideCheck: true, code: files.length ? side(which) : '(nothing changed)' });
260  const changes = files.map(f => FILE_VERB[f.status] + ' ' + f.path);
261  if (job.moreFiles) changes.push('and ' + job.moreFiles + ' more files');
262  return { original: make('original'), updated: make('updated'), revision: make('updated'), changes };
263}
264
265export function timeSkipExample(prompt: string) {
266  if (/image|photo|poster|illustration/i.test(prompt)) return {
267    labels: ['Visual style', 'Headline', 'Composition'],
268    original: ['Botanical direction', 'Longer phrase', 'Dense text area'],
269    improved: ['Botanical style kept', 'Shorter and clearer', 'More open space'],
270    revision: ['Visual style kept', 'Shortened further', 'Useful subtitle lost'],
271    correction: 'Shorten the headline and open up the composition while keeping the botanical style.',
272    rejection: 'The later revision removes the useful subtitle. Keep the complete cover.',
273  };
274  if (/website|app\b|code|voxel|html|dashboard/i.test(prompt)) return {
275    labels: ['Core layout', 'Controls', 'Small screens'],
276    original: ['Structure in place', 'Reset needs work', 'Content overflows'],
277    improved: ['Structure preserved', 'Reset works', 'Fits the viewport'],
278    revision: ['Layout simplified', 'Reset lost its state', 'Still fits'],
279    correction: 'Fix reset and mobile fit while preserving the layout.',
280    rejection: 'The shorter revision breaks reset. Keep B’s working controls.',
281  };
282  return {
283    labels: ['Main idea', 'Next steps', 'Success check'],
284    original: ['Clear starting point', 'Too general', 'Not defined yet'],
285    improved: ['Original idea kept', 'Specific and ordered', 'Clear way to verify'],
286    revision: ['More concise', 'Key detail removed', 'Check preserved'],
287    correction: 'Make the steps actionable and add a way to check the result.',
288    rejection: 'The shorter revision removes a useful step. Keep B’s complete version.',
289  };
290}