mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-30 20:04:15 +01:00
First versions open with the owner's own words, and the try-it check follows his exact steps (GST-3608) (#4759)
When we hand someone the first version of something, the approval page and the try-it message now open with their own quoted requests, each marked "does it" or a lettered choice. Before they're asked to try it, gstack-first-use has an agent from another model family follow the exact numbered steps on their real setup, and holds the message until no step is broken, wrong or needs a lookup. Nothing to do: this changes /autoplan's first-version gate, gstack-first-use and the guides that point to it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#3 reader=red-team Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p2/outside-voice#1 reader=outside-voice Review-Finding: p3/red-team#1 reader=red-team Review-Finding: gsta825-ship2/p1/outside-voice#2 reader=outside-voice Review-Finding: gsta825-ship2/p1/outside-voice#3 reader=outside-voice Review-Finding: p1/specialist-batched#1 reader=state-machines
This commit is contained in:
1 parent
40986b7c76
commit
e78a1bfe32
38 files changed
+1126
-342
No files matched your search
+60
-13
@@ -9,24 +9,28 @@
|
||||
* Owner's words section keeps today's defaults and gets one item asking the
|
||||
* owner to confirm its direction. The day-one items ask about every assumed
|
||||
* day-one row, a missing day-one page on an app plan, and each cut that drops
|
||||
* a day-one row or a quoted owner line (the other cuts are one grouped item).
|
||||
* a day-one row (the other cuts are one grouped item, or one item each on a
|
||||
* first version). A quote the plan leaves for later (its line says `choice`),
|
||||
* a cut that drops a quote, and a reviewer's `narrows_quote` finding each become
|
||||
* one choice to build what the owner asked for, recommended unless the plan
|
||||
* gives a reason to leave it out (GST-3608).
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { branchKey, captainApprovalsDir } from './approval-record';
|
||||
import { readVersionedSlugCache, sanitizeSlug } from './bin-context';
|
||||
import { cutDrops, parseCuts, parseDayOne, parseOwnerWords, wordKey, type DayOneTable, type OwnerQuote, type OwnerWordsSection } from './autoplan-owner-text';
|
||||
import { cutDrops, cutQuote, isFirstVersion, parseCuts, parseDayOne, parseOwnerWords, quoteGaps, quoteWhen, wordKey, type DayOneTable, type OwnerQuote, type OwnerWordsSection } from './autoplan-owner-text';
|
||||
import { SETTLEABLE_CHANGES } from './autoplan-reconcile';
|
||||
import { readDecisions, readJournal, type RunState } from './autoplan-state';
|
||||
import { resolveStateRoot } from './state-root';
|
||||
import type { GateItem } from './gate-list';
|
||||
import type { FindingRow } from './headless-artifacts';
|
||||
|
||||
export type ChallengeRow = FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string; owner_quote?: number; resolves?: string };
|
||||
export type ChallengeRow = FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string; owner_quote?: number; narrows_quote?: number; resolves?: string };
|
||||
export type NewItem = Omit<GateItem, 'id'> & { idKind: 'd' | 'uc'; key: string };
|
||||
export interface GateOwnerWords { status: OwnerWordsSection['status']; quotes: Array<OwnerQuote & { verified: boolean }>; reason?: string; fix?: string }
|
||||
export interface OwnerContext { words: OwnerWordsSection; verified: Set<number>; dayOne: DayOneTable; cuts: string[]; app: boolean; lean: boolean }
|
||||
export interface OwnerContext { words: OwnerWordsSection; verified: Set<number>; dayOne: DayOneTable; cuts: string[]; app: boolean; lean: boolean; firstVersion: boolean }
|
||||
|
||||
/**
|
||||
* The owner's words in this repository's approvals record for the branch checked out at `cwd` (lib/approval-record.ts
|
||||
@@ -72,7 +76,8 @@ export function ownerContext(state: RunState, recorded: string[] = recordedOwner
|
||||
const words = parseOwnerWords(text);
|
||||
const keys = recorded.map(wordKey);
|
||||
const verified = new Set(words.quotes.filter(q => keys.some(k => k.includes(wordKey(q.text)))).map(q => q.n));
|
||||
return { words, verified, dayOne: parseDayOne(text), cuts: parseCuts(text), app: !!state.scope?.ui, lean: !!state.lean };
|
||||
return { words, verified, dayOne: parseDayOne(text), cuts: parseCuts(text), app: !!state.scope?.ui, lean: !!state.lean,
|
||||
firstVersion: isFirstVersion(text, !!state.scope?.first_version) };
|
||||
}
|
||||
|
||||
export function gateOwnerWords(ctx: OwnerContext): GateOwnerWords {
|
||||
@@ -80,6 +85,10 @@ export function gateOwnerWords(ctx: OwnerContext): GateOwnerWords {
|
||||
...(ctx.words.reason ? { reason: ctx.words.reason, fix: ctx.words.fix } : {}) };
|
||||
}
|
||||
|
||||
/** The quote a reviewer says the plan narrows (a cut or a "does it" line that does less than the owner asked), when the plan quotes it. */
|
||||
export const narrowedQuoteOf = (ctx: OwnerContext, f: ChallengeRow | undefined): OwnerQuote | undefined =>
|
||||
f?.narrows_quote ? ctx.words.quotes.find(q => q.n === f.narrows_quote) : undefined;
|
||||
|
||||
/** The owner line a challenge names, when the plan quotes one there. */
|
||||
export const ownerQuoteOf = (ctx: OwnerContext, f: ChallengeRow | undefined): OwnerQuote | undefined =>
|
||||
f?.owner_quote ? ctx.words.quotes.find(q => q.n === f.owner_quote) : undefined;
|
||||
@@ -135,10 +144,28 @@ export function confirmDirectionItem(challenges: string[]): NewItem {
|
||||
{ key: 'b', text: "no, it is a draft: quote what I said in an Owner's words section and revise, so the challenges are judged against it", changes_plan: true }] };
|
||||
}
|
||||
|
||||
/** The day-one questions: each assumed row, a missing page on an app plan, and the plan's cuts. */
|
||||
export function dayOneItems(ctx: OwnerContext): NewItem[] {
|
||||
/**
|
||||
* The owner-page questions: on a first version, missing quotes or lines; each assumed day-one row; a missing page on an
|
||||
* app plan; one build-it choice per quote the plan leaves out (its `choice` line, a cut that drops it, or a reviewer's
|
||||
* narrows_quote finding); and the cuts, one item each on a first version, else those matching a day-one row alone.
|
||||
*/
|
||||
export function dayOneItems(ctx: OwnerContext, narrowed: ChallengeRow[] = []): NewItem[] {
|
||||
const items: NewItem[] = [];
|
||||
const reopen = ctx.lean ? 'applies without re-review (lean run)' : 'reopens ceo and eng once the plan is revised';
|
||||
if (ctx.firstVersion && ctx.words.status === 'none') {
|
||||
items.push({ idKind: 'uc', key: 'owner-words', kind: 'approval', recommended: 'a', item_class: 'owner_words', changes: 'scope', cost: `a ${reopen}`,
|
||||
title: 'This is a first version, but the plan quotes none of your messages that ask for it',
|
||||
why: 'a first version is checked against your own words for the job, not against the plan: each quoted message, with its time, gets a line saying what this version does with it',
|
||||
options: [{ key: 'a', text: "add it: an ### Owner's words section quoting each message that states the job, with its time and a line each (does it or choice), then revise", changes_plan: true },
|
||||
{ key: 'b', text: 'approve without it', changes_plan: false }] });
|
||||
}
|
||||
const gaps = ctx.firstVersion ? ctx.words.quotes.filter(q => quoteGaps(q).length) : [];
|
||||
if (gaps.length) {
|
||||
items.push({ idKind: 'uc', key: `owner-lines:${gaps.map(q => q.n).join(',')}`, kind: 'approval', recommended: 'a', item_class: 'owner_words', changes: 'scope', cost: `a ${reopen}`,
|
||||
title: `${gaps.length} of your quoted messages ${gaps.length === 1 ? 'has' : 'have'} no time or no line saying what this version does with ${gaps.length === 1 ? 'it' : 'them'}: ${gaps.map(q => `“${q.text}” (missing ${quoteGaps(q).join(' and ')})`).join('; ')}`,
|
||||
why: 'on a first version every quote says when it was said and whether this version does it or leaves it as a lettered choice',
|
||||
options: [{ key: 'a', text: 'add the time and the line to each, then revise', changes_plan: true }, { key: 'b', text: 'approve without them', changes_plan: false }] });
|
||||
}
|
||||
if (ctx.app && ctx.dayOne.status !== 'ok') {
|
||||
items.push({ idKind: 'uc', key: 'day-one-page', kind: 'approval', recommended: 'a', item_class: 'day_one', changes: 'scope', cost: `a ${reopen}`,
|
||||
title: `The plan has no day-one page${ctx.dayOne.reason ? ` (${ctx.dayOne.reason})` : ''}: the first things you will do with it, how often, and which build puts each on your device`,
|
||||
@@ -151,17 +178,37 @@ export function dayOneItems(ctx: OwnerContext): NewItem[] {
|
||||
why: `no owner words or owner evidence back this row; feature: ${row.feature || 'none named'}; first build: ${row.first_build || 'none named'}`,
|
||||
options: [{ key: 'a', text: 'yes, I do that: keep the row', changes_plan: false }, { key: 'b', text: 'no, or not like that: say what you do instead, then revise', changes_plan: true }] });
|
||||
}
|
||||
const targets = [...ctx.dayOne.rows.flatMap(r => [r.action, r.feature]), ...ctx.words.quotes.map(q => q.text)].filter(Boolean);
|
||||
const named = ctx.cuts.filter(c => targets.some(t => cutDrops(c, t)));
|
||||
const left = new Map<number, string[]>();
|
||||
const note = (q: OwnerQuote, why: string) => left.set(q.n, [...(left.get(q.n) ?? []), why]);
|
||||
for (const q of ctx.words.quotes) if (q.line?.kind === 'choice') note(q, "the plan's line for it says this version doesn't do it yet");
|
||||
const quoteCuts = ctx.cuts.filter(c => cutQuote(c, ctx.words.quotes));
|
||||
for (const cut of quoteCuts) note(cutQuote(cut, ctx.words.quotes)!, `the plan cuts it: "${cut}"`);
|
||||
for (const f of narrowed) { const q = ctx.words.quotes.find(x => x.n === f.narrows_quote); if (q) note(q, `a reviewer (${f.voice}) says the plan narrows it: ${f.title}`); }
|
||||
for (const q of ctx.words.quotes.filter(x => left.has(x.n))) {
|
||||
const choice = q.line?.kind === 'choice' ? q.line : undefined;
|
||||
const blocking = narrowed.find(f => f.narrows_quote === q.n && (f.severity === 'Critical' || f.severity === 'High'));
|
||||
const leave = blocking ? undefined : choice?.leave_out;
|
||||
const size = choice?.size ? `about ${choice.size}` : 'size not stated';
|
||||
items.push({ idKind: 'uc', key: `quote:${q.n}`, kind: 'approval', recommended: leave ? 'b' : 'a', item_class: 'owner_choice', changes: 'scope',
|
||||
recommended_basis: blocking ? `your own words asked for it, and a ${blocking.severity} finding says the plan falls short of them` : leave ? `the plan's reason to leave it out: ${leave}` : 'your own words asked for it, and only your words are direction',
|
||||
cost: `a adds ${size} to this version and ${reopen}`,
|
||||
title: `Your words${quoteWhen(q) ? ` (${quoteWhen(q)})` : ''}: “${q.text}”, which this version doesn't fully do`,
|
||||
why: left.get(q.n)!.join('; '),
|
||||
options: [{ key: 'a', text: `build it in this version (${size})`, changes_plan: true }, { key: 'b', text: `leave it out for now${leave ? `: ${leave}` : ''}`, changes_plan: false }] });
|
||||
}
|
||||
const rest = ctx.cuts.filter(c => !quoteCuts.includes(c));
|
||||
const rowTargets = ctx.dayOne.rows.flatMap(r => [r.action, r.feature]).filter(Boolean);
|
||||
const named = ctx.firstVersion ? rest : rest.filter(c => rowTargets.some(t => cutDrops(c, t)));
|
||||
for (const cut of named) {
|
||||
const drops = rowTargets.some(t => cutDrops(cut, t));
|
||||
items.push({ idKind: 'uc', key: `cut:${wordKey(cut).trim()}`, kind: 'approval', recommended: 'a', item_class: 'cut', changes: 'scope', cost: `b ${reopen}`,
|
||||
title: `Cut: ${cut}`, why: 'this cut drops something on the day-one page or in your own words',
|
||||
title: `Cut: ${cut}`, why: drops ? 'this cut drops something on the day-one page' : 'on a first version every cut is your decision, one letter each',
|
||||
options: [{ key: 'a', text: 'keep the cut: not in the first build', changes_plan: false }, { key: 'b', text: 'put it back in the first build', changes_plan: true }] });
|
||||
}
|
||||
const rest = ctx.cuts.filter(c => !named.includes(c));
|
||||
if (rest.length) {
|
||||
const grouped = rest.filter(c => !named.includes(c));
|
||||
if (grouped.length) {
|
||||
items.push({ idKind: 'd', key: 'cuts', kind: 'auto', recommended: 'a', item_class: 'cuts', changes: 'scope', cost: `b ${reopen}`,
|
||||
title: `${rest.length} other cut${rest.length === 1 ? '' : 's'}: ${rest.join('; ')}`, why: 'none of these drops a day-one row or a quoted owner line',
|
||||
title: `${grouped.length} other cut${grouped.length === 1 ? '' : 's'}: ${grouped.join('; ')}`, why: 'none of these drops a day-one row or a quoted owner line',
|
||||
options: [{ key: 'a', text: 'keep these cuts', changes_plan: false }, { key: 'b', text: 'put some back: name them, then revise', changes_plan: true }] });
|
||||
}
|
||||
return items;
|
||||
|
||||
+10
-4
@@ -27,7 +27,7 @@ import { applyCapChoices, pendingDeltas, releaseUndispatched, roundCap, roundOf
|
||||
import { evaluateCarry, gateEvidence, voidPendingCheck } from './autoplan-carry';
|
||||
import { buildEli5, capyRelayLine } from './captain-brief';
|
||||
import { FINDING_ORIGIN, openEarlier, previousReview, reviewRows, settledIds } from './autoplan-confirm';
|
||||
import { blockingProposal, confirmDirectionItem, dayOneItems, directionIsOwners, gateOwnerWords, heaviestChanges, ownerContext, ownerQuoteOf, proposalItem, type ChallengeRow, type NewItem } from './autoplan-gate-items';
|
||||
import { blockingProposal, confirmDirectionItem, dayOneItems, directionIsOwners, gateOwnerWords, heaviestChanges, narrowedQuoteOf, ownerContext, ownerQuoteOf, proposalItem, type ChallengeRow, type NewItem } from './autoplan-gate-items';
|
||||
import { phaseClose } from './autoplan-timing';
|
||||
import { agentWords, ANSWERED_BY_RE, applyReply, autoDefault, decisionId, decisionRows, keepDirection, legacyRecHash, parseReply, pendingHint, recHash, replyShape, validateGateList, type GateChoice, type GateItem, type GateList, type GateOption, type ParsedReply } from './gate-list';
|
||||
import type { DecisionRow, FindingRow } from './headless-artifacts';
|
||||
@@ -201,6 +201,7 @@ export function buildGate(state: RunState, gateRev: number): GateList {
|
||||
const quoted = owner.words.status !== 'none';
|
||||
const kept: string[] = [];
|
||||
const keptIds: string[] = [];
|
||||
const narrowed: ChallengeRow[] = [];
|
||||
const add = ({ idKind, key, ...item }: NewItem, origin: (options: GateOption[]) => string): string => {
|
||||
const id = idKind === 'uc' ? `uc${++uc}` : `d${++d}`;
|
||||
items.push({ id, ...item, origin: origin(item.options) });
|
||||
@@ -251,9 +252,10 @@ export function buildGate(state: RunState, gateRev: number): GateList {
|
||||
const twinOf = (id: string) => twins.get(id) ?? [...twins].find(([, out]) => out === id)?.[0];
|
||||
for (const f of [...native, ...outside, ...carried] as ChallengeRow[]) {
|
||||
if (challenged.has(f.id) || f.settled_by) continue;
|
||||
if (narrowedQuoteOf(owner, f)) { challenged.add(f.id); narrowed.push(f); continue; }
|
||||
if (quoted && (f.changes || f.user_challenge) && !ownerQuoteOf(owner, f)) {
|
||||
const twin = twinOf(f.id) ? byId.get(twinOf(f.id)!) as ChallengeRow | undefined : undefined;
|
||||
propose(twin && !twin.settled_by && !ownerQuoteOf(owner, twin) ? [f, twin] : [f], carried.includes(f));
|
||||
propose(twin && !twin.settled_by && !ownerQuoteOf(owner, twin) && !narrowedQuoteOf(owner, twin) ? [f, twin] : [f], carried.includes(f));
|
||||
continue;
|
||||
}
|
||||
if (!f.user_challenge || !directionIsOwners(owner, [f])) continue;
|
||||
@@ -280,10 +282,14 @@ export function buildGate(state: RunState, gateRev: number): GateList {
|
||||
}
|
||||
items.push(...capItems(state, { d: () => `d${++d}`, uc: () => `uc${++uc}` }));
|
||||
if (!quoted && kept.length) add(confirmDirectionItem(kept), options => ['owner', 'confirm-direction', optionHash(options), keptIds.join('+')].join('|'));
|
||||
for (const item of dayOneItems(owner)) add(item, options => ['owner', item.key, optionHash(options), createHash('sha256').update(item.title).digest('hex').slice(0, 16)].join('|'));
|
||||
const settles = (key: string) => narrowed.filter(f => key === `quote:${narrowedQuoteOf(owner, f)!.n}`);
|
||||
for (const item of dayOneItems(owner, narrowed)) {
|
||||
const found = settles(item.key);
|
||||
add(item, options => ['owner', [item.key, ...found.map(f => f.id)].join('+'), optionHash(options), createHash('sha256').update(item.title).digest('hex').slice(0, 16), ...(blockingProposal(found) ? [FINDING_ORIGIN] : [])].join('|'));
|
||||
}
|
||||
items.push(planApproval(state, items));
|
||||
const list: GateList = { schema_version: 1, run: state.run, gate_rev: gateRev, items, title: '/autoplan final approval gate', rec_rev: 0, rec_hash_v: 2,
|
||||
...(quoted ? { owner_words: gateOwnerWords(owner) } : {}),
|
||||
...(quoted ? { owner_words: gateOwnerWords(owner) } : {}), ...(owner.firstVersion ? { first_version: true } : {}),
|
||||
...(fs.existsSync(state.active_plan) ? { eli5: buildEli5(fs.readFileSync(state.active_plan, 'utf8'), state.active_plan) } : {}) };
|
||||
const problems = validateGateList(list);
|
||||
if (problems.length) throw new Error(`gate list invalid: ${problems.join('; ')}`);
|
||||
|
||||
+82
-13
@@ -7,7 +7,10 @@
|
||||
* table of the owner's first actions (action, frequency, source, feature,
|
||||
* route, first build, check); a row whose source is `assumed` becomes an
|
||||
* owner question at the gate. `### What it won't do yet` lists the plan's
|
||||
* cuts. Read by the gate builder and the owner and captain briefs.
|
||||
* cuts. Read by the gate builder and the owner and captain briefs. On a first
|
||||
* version each Owner's words bullet also carries a line after an arrow saying
|
||||
* what this version does with those words: `does it`, `choice` (a lettered
|
||||
* gate choice, optionally `; size: …` and `; leave out: <reason>`) (GST-3608).
|
||||
*/
|
||||
import { findSection } from './markdown-sections';
|
||||
|
||||
@@ -16,7 +19,8 @@ export const DAY_ONE_TITLES = ['Day one', 'Day-one page', 'Day one page'];
|
||||
export const CUTS_TITLES = ["What it won't do yet", 'What it will not do yet', "Won't do yet"];
|
||||
export const DAY_ONE_COLUMNS = ['action', 'frequency', 'source', 'feature', 'route', 'first build', 'check'] as const;
|
||||
|
||||
export interface OwnerQuote { n: number; who: string; text: string }
|
||||
export type OwnerLine = { kind: 'does' } | { kind: 'choice'; size?: string; leave_out?: string };
|
||||
export interface OwnerQuote { n: number; who: string; text: string; line?: OwnerLine }
|
||||
export interface OwnerWordsSection { status: 'none' | 'ok' | 'malformed'; quotes: OwnerQuote[]; reason?: string; fix?: string }
|
||||
export interface DayOneRow { action: string; frequency: string; source: string; feature: string; route: string; first_build: string; check: string; assumed: boolean }
|
||||
export interface DayOneTable { status: 'none' | 'ok' | 'malformed'; rows: DayOneRow[]; reason?: string }
|
||||
@@ -24,7 +28,47 @@ export interface DayOneTable { status: 'none' | 'ok' | 'malformed'; rows: DayOne
|
||||
const BULLET = /^\s*[-*+]\s+(.*)$/;
|
||||
const QUOTED = /[“"](.+)[”"]/;
|
||||
|
||||
/** The quotes under `### Owner's words`; a bullet with no quoted words makes the section malformed (its other quotes still count). */
|
||||
const count = (s: string, c: string) => s.split(c).length - 1;
|
||||
const paired = (s: string) => count(s, '"') % 2 === 0 && count(s, '“') === count(s, '”');
|
||||
|
||||
/**
|
||||
* The bullet split into its quote (left) and its line (right). It splits at the first `→` or `->` that follows quoted
|
||||
* words and is followed by a line parseLine reads, with its quote marks paired, so an arrow in the attribution or inside
|
||||
* the quote never splits it. Otherwise the bullet reads as it did before lines existed, with no line, except that an arrow
|
||||
* after its last closing quote mark still returns what follows as a line, for parseOwnerWords to name as malformed.
|
||||
*/
|
||||
export function splitLine(bullet: string): { left: string; line?: string } {
|
||||
for (const a of bullet.matchAll(/→|->/g)) {
|
||||
const left = bullet.slice(0, a.index).trimEnd(), line = bullet.slice(a.index + a[0].length).trim();
|
||||
if (QUOTED.exec(left)?.[1]?.trim() && paired(line) && parseLine(line)) return { left, line };
|
||||
}
|
||||
const quote = QUOTED.exec(bullet);
|
||||
const close = quote ? quote.index + quote[0].length : 0;
|
||||
const arrow = quote ? [...bullet.slice(close).matchAll(/→|->/g)].pop() : undefined;
|
||||
return arrow ? { left: bullet.slice(0, close + arrow.index).trimEnd(), line: bullet.slice(close + arrow.index + arrow[0].length).trim() } : { left: bullet };
|
||||
}
|
||||
|
||||
/** A bullet's line: `does it` or `choice[; size: …][; leave out: …]`; undefined when it reads as neither. */
|
||||
export function parseLine(line: string): OwnerLine | undefined {
|
||||
if (/^does it\W*$/i.test(line)) return { kind: 'does' };
|
||||
if (!/^choice\b/i.test(line)) return undefined;
|
||||
const out: { kind: 'choice'; size?: string; leave_out?: string } = { kind: 'choice' };
|
||||
for (const part of line.replace(/^choice\b[^;]*/i, '').split(';').map(p => p.trim()).filter(Boolean)) {
|
||||
const m = /^(size|(?:recommend )?leave out)\s*:\s*(.+)$/i.exec(part);
|
||||
if (!m) return undefined;
|
||||
if (/^size$/i.test(m[1]!)) out.size = m[2]!.trim(); else out.leave_out = m[2]!.trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The time a quote names: the part of its attribution after the first comma (`The owner, 2026-11-23 10:04Z`), or ''. */
|
||||
export const quoteWhen = (q: Pick<OwnerQuote, 'who'>): string => (q.who.includes(',') ? q.who.slice(q.who.indexOf(',') + 1).trim() : '');
|
||||
|
||||
/**
|
||||
* The quotes under `### Owner's words`; a bullet with no quoted words, or a line that reads as none of the three, makes
|
||||
* the section malformed (its other quotes still count). A bullet with no line still parses: only a first version's gate
|
||||
* item and gstack-first-use ask for one.
|
||||
*/
|
||||
export function parseOwnerWords(planText: string): OwnerWordsSection {
|
||||
const section = findSection(planText, OWNER_WORDS_TITLES);
|
||||
if (!section) return { status: 'none', quotes: [] };
|
||||
@@ -32,13 +76,31 @@ export function parseOwnerWords(planText: string): OwnerWordsSection {
|
||||
const fix = 'one bullet per quote: - <who>, <when>: "<their exact words>"';
|
||||
if (!bullets.length) return { status: 'malformed', quotes: [], reason: 'the section has no bullet list', fix };
|
||||
const quotes: OwnerQuote[] = [];
|
||||
const bad: number[] = [];
|
||||
const bad: number[] = [], badLine: number[] = [];
|
||||
bullets.forEach((b, i) => {
|
||||
const m = QUOTED.exec(b);
|
||||
const { left, line } = splitLine(b);
|
||||
const m = QUOTED.exec(left);
|
||||
if (!m || !m[1]!.trim()) { bad.push(i + 1); return; }
|
||||
quotes.push({ n: i + 1, who: b.slice(0, m.index).replace(/[\s:,-]+$/, '').trim() || 'unattributed', text: m[1]!.trim() });
|
||||
const parsed = line ? parseLine(line) : undefined;
|
||||
if (line && !parsed) badLine.push(i + 1);
|
||||
quotes.push({ n: i + 1, who: left.slice(0, m.index).replace(/[\s:,-]+$/, '').trim() || 'unattributed', text: m[1]!.trim(), ...(parsed ? { line: parsed } : {}) });
|
||||
});
|
||||
return bad.length ? { status: 'malformed', quotes, reason: `bullet ${bad.join(', ')} quotes no words`, fix } : { status: 'ok', quotes };
|
||||
const reasons = [...(bad.length ? [`bullet ${bad.join(', ')} quotes no words`] : []),
|
||||
...(badLine.length ? [`bullet ${badLine.join(', ')} has a line that is not does it or choice`] : [])];
|
||||
return reasons.length ? { status: 'malformed', quotes, reason: reasons.join('; '), fix: badLine.length ? fix + ' → does it | choice' : fix } : { status: 'ok', quotes };
|
||||
}
|
||||
|
||||
/** What a first version still owes on a quote: when it was said, and a line. Empty when both are there. */
|
||||
export const quoteGaps = (q: OwnerQuote): string[] => [...(quoteWhen(q) ? [] : ['when it was said']), ...(q.line ? [] : ['a line (does it or choice)'])];
|
||||
|
||||
/** The quote a cut drops, by its words (cutDrops), or undefined. */
|
||||
export const cutQuote = (cut: string, quotes: OwnerQuote[]): OwnerQuote | undefined => quotes.find(q => cutDrops(cut, q.text));
|
||||
|
||||
/** A quote's line in the owner's words. */
|
||||
export function lineText(q: OwnerQuote): string {
|
||||
if (!q.line) return 'no line yet: asked below';
|
||||
if (q.line.kind === 'does') return 'does it';
|
||||
return 'not in this version yet: a lettered choice below';
|
||||
}
|
||||
|
||||
/** The OWNER_WORDS line `next` and the gate print. */
|
||||
@@ -73,21 +135,28 @@ export function parseDayOne(planText: string): DayOneTable {
|
||||
return rows.length ? { status: 'ok', rows } : { status: 'malformed', rows: [], reason: 'the table has no rows' };
|
||||
}
|
||||
|
||||
/** A first version: the plan has a Day one section, or the run's `--first-version` scope flag says so. */
|
||||
export const isFirstVersion = (planText: string, flag = false): boolean => flag || parseDayOne(planText).status !== 'none';
|
||||
|
||||
export const FIRST_USE_LINE = "Before you're asked to try it, an agent from another model family follows the exact try-it steps on your setup and records a verdict for each; a step that is broken, wrong or would make you look something up is fixed before you get it (gstack-first-use).";
|
||||
|
||||
/**
|
||||
* What the owner reads first at the gate (lib/captain-brief.ts, lib/owner-brief.ts): the day-one table, what the first
|
||||
* build won't do yet, and the quoted owner words a reviewer needs the owner's answer to change. Empty when the plan has none.
|
||||
* What the owner reads first at the gate (lib/captain-brief.ts, lib/owner-brief.ts): the quoted owner words, each with what
|
||||
* this version does with them, then the day-one table, then what it won't do yet. A cut that drops a quoted line is asked
|
||||
* beside that quote as a lettered choice, never listed under "What it won't do yet". Empty when the plan has none of them.
|
||||
*/
|
||||
export function renderDayOne(planText: string, quotes: Array<OwnerQuote & { verified?: boolean }> = []): string[] {
|
||||
export function renderOwnerPage(planText: string, quotes: Array<OwnerQuote & { verified?: boolean }> = [], o: { firstVersion?: boolean } = {}): string[] {
|
||||
const day = parseDayOne(planText);
|
||||
const cuts = parseCuts(planText);
|
||||
const cuts = parseCuts(planText).filter(c => !cutQuote(c, quotes));
|
||||
const out: string[] = [];
|
||||
if (quotes.length) out.push('### Your words this plan follows', '', ...quotes.map(q => `- ${q.who}: “${q.text}”${q.verified === false ? ' (not found in your recorded replies)' : ''} → ${lineText(q)}`), '',
|
||||
'A reviewer who wants to change one of these needs your answer. Anything else in the plan was written by the planning agent, so a reviewer\'s change to it is recommended below.', '');
|
||||
if (day.status === 'ok') {
|
||||
out.push('### Day one', '', 'What you can do with it on day one:', '', '| What you do | How often | Feature | How you get there | First build with it | How we check it works |', '|---|---|---|---|---|---|',
|
||||
...day.rows.map(r => `| ${r.action}${r.assumed ? ' (our guess: asked below)' : ''} | ${r.frequency} | ${r.feature} | ${r.route} | ${r.first_build} | ${r.check} |`), '');
|
||||
}
|
||||
if (cuts.length) out.push("### What it won't do yet", '', ...cuts.map(c => `- ${c}`), '');
|
||||
if (quotes.length) out.push('### Your words this plan follows', '', ...quotes.map(q => `- ${q.who}: “${q.text}”${q.verified === false ? ' (not found in your recorded replies)' : ''}`), '',
|
||||
'A reviewer who wants to change one of these needs your answer. Anything else in the plan was written by the planning agent, so a reviewer\'s change to it is recommended below.', '');
|
||||
if (o.firstVersion) out.push(FIRST_USE_LINE, '');
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -133,11 +133,15 @@ const SUFFIXES: Array<[string, string]> = [["n't", 'not'], ["'re", 'are'], ["'ve
|
||||
const IS_BASES = new Set(['it', 'that', 'there', 'here', 'what', 'who', 'where', 'he', 'she']);
|
||||
|
||||
interface Token { key: string; start: number; end: number }
|
||||
/** A word: one character of a script written without spaces (Han, kana, Thai), or a run of other letters and digits. */
|
||||
const UNSPACED = String.raw`\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}`;
|
||||
const LETTER = String.raw`(?:(?![${UNSPACED}])[\p{L}\p{M}\p{N}])`;
|
||||
const WORD = new RegExp(String.raw`[${UNSPACED}]|${LETTER}+(?:['\u2019\u02bc]${LETTER}+)*`, 'gu');
|
||||
/** Words of `text` in the rendered (default) or raw view, with their original [start, end) offsets. */
|
||||
export function tokens(text: string, rendered = true): Token[] {
|
||||
const m = normalize(text, rendered);
|
||||
const out: Token[] = [];
|
||||
for (const w of m.s.matchAll(/[\p{L}\p{M}\p{N}]+(?:['\u2019\u02bc][\p{L}\p{M}\p{N}]+)*/gu)) {
|
||||
for (const w of m.s.matchAll(WORD)) {
|
||||
const start = m.from[w.index!]!, end = m.to[w.index! + w[0].length - 1]!;
|
||||
const key = w[0].normalize('NFKC').replace(/[\u2019\u02bc]/g, "'").toLowerCase();
|
||||
const suffix = SUFFIXES.find(([s]) => key.endsWith(s) && key.length > s.length);
|
||||
|
||||
@@ -42,6 +42,8 @@ export interface Scope {
|
||||
source?: 'detected' | 'flags';
|
||||
/** A docs-only plan runs CEO (native voice only) and Eng; `--docs-only`, the marker, or every Implementation-plan path docs-class. */
|
||||
docs_only?: boolean; docs_only_source?: ScopeSource;
|
||||
/** `--first-version` (flag or marker): the plan is a first version even without a Day one section (lib/autoplan-owner-text.ts isFirstVersion). */
|
||||
first_version?: boolean;
|
||||
}
|
||||
|
||||
export function snapshotTool(args: string[], cwd: string): any {
|
||||
@@ -64,7 +66,7 @@ export function detectScope(activePlan: string, cwd: string, flags: ScopeFlags,
|
||||
const dxSource: ScopeSource = flags.dx !== undefined ? 'flag' : m.dx !== undefined ? 'marker'
|
||||
: flags.developerTool || flags.agentPrimary ? 'flag' : m.developerTool || m.agentPrimary ? 'marker' : 'detected';
|
||||
const cli = scopeTokens(flags);
|
||||
const merged = scopeTokens({ ui: flags.ui ?? m.ui, dx: flags.dx ?? m.dx, developerTool, agentPrimary, docsOnly: !!(flags.docsOnly || m.docsOnly) });
|
||||
const merged = scopeTokens({ ui: flags.ui ?? m.ui, dx: flags.dx ?? m.dx, developerTool, agentPrimary, docsOnly: !!(flags.docsOnly || m.docsOnly), firstVersion: !!(flags.firstVersion || m.firstVersion) });
|
||||
const pinned = !cli.length || (marker !== null && [...merged].sort().join(' ') === [...marker.tokens].sort().join(' '));
|
||||
// A flag or marker that turns a phase on outranks docs-only detection; --docs-only itself outranks everything.
|
||||
const enables = flags.ui === true || m.ui === true || developerTool || agentPrimary;
|
||||
@@ -77,6 +79,7 @@ export function detectScope(activePlan: string, cwd: string, flags: ScopeFlags,
|
||||
sources: { ui: flags.ui !== undefined ? 'flag' : m.ui !== undefined ? 'marker' : 'detected', dx: dxSource }, ui_evidence: detected.uiEvidence, dx_terms: detected.matches,
|
||||
cli_flags: cli, marker: marker?.tokens ?? null, pin: pinned ? null : { marker: scopeMarker(merged), file: sourcePlan },
|
||||
docs_only: docsOnly, docs_only_source: docsOnlySource,
|
||||
...(flags.firstVersion || m.firstVersion ? { first_version: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -124,7 +127,7 @@ ${RESULT_FORMAT_HEADER}
|
||||
\`\`\`gstack-findings
|
||||
{"id":"F1","severity":"High","title":"<one line>","file":"<path or omit>","line":12,"fix":"<the fix>"}
|
||||
\`\`\`
|
||||
severity is Critical | High | Medium | Low | Informational. Any finding that recommends changing the plan's scope, cost or direction adds "changes": "scope" | "cost" | "direction", or "packaging" | "ordering" when only its delivery packaging or build order changes, with no Implementation-plan edit; that holds at any severity. Only the owner's own words are the plan's direction: add "user_challenge": true and "owner_quote": <n> only when the change goes against bullet n (from 1) of the plan's "Owner's words" section. Scope, order or features the planning agent wrote are proposals, so a change to them is an ordinary finding with "changes" and no user_challenge. A plan with no "Owner's words" section: add "user_challenge": true (no owner_quote) when you recommend changing its stated direction. Naming and other reversible choices are ordinary findings with no "changes". Add "urgent": true and "suggested_owner": "<who>" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused.
|
||||
severity is Critical | High | Medium | Low | Informational. Any finding that recommends changing the plan's scope, cost or direction adds "changes": "scope" | "cost" | "direction", or "packaging" | "ordering" when only its delivery packaging or build order changes, with no Implementation-plan edit; that holds at any severity. Only the owner's own words are the plan's direction: add "user_challenge": true and "owner_quote": <n> only when the change goes against bullet n (from 1) of the plan's "Owner's words" section. Scope, order or features the planning agent wrote are proposals, so a change to them is an ordinary finding with "changes" and no user_challenge. Check every "What it won't do yet" cut and every "does it" line against each quoted owner bullet and any owner answer under DECIDED AT THE GATE: a cut or line that does less than bullet n asked is a finding with "narrows_quote": <n> and "changes": "scope" (no user_challenge), even when the two share no words. A plan with no "Owner's words" section: add "user_challenge": true (no owner_quote) when you recommend changing its stated direction. Naming and other reversible choices are ordinary findings with no "changes". Add "urgent": true and "suggested_owner": "<who>" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused.
|
||||
3. Write the whole result to this file: ${resultPath}
|
||||
`;
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ export interface CanonicalFinding {
|
||||
changes?: Changes;
|
||||
/** A challenge to the owner's own words: the 1-based bullet of the plan's `### Owner's words` it would change. */
|
||||
owner_quote?: number;
|
||||
/** A cut or a "does it" line that does less than the plan's `### Owner's words` bullet n asked: the gate asks the owner to build it (lib/autoplan-gate-items.ts). */
|
||||
narrows_quote?: number;
|
||||
/** A confirm round's row naming the earlier challenge id the revised plan now fixes. */
|
||||
resolves?: string;
|
||||
}
|
||||
@@ -98,6 +100,7 @@ function parseFences(text: string, errors: string[]): { findings: CanonicalFindi
|
||||
if (Array.isArray(row.plan_items)) finding.plan_items = row.plan_items.filter((p: unknown): p is string => typeof p === 'string');
|
||||
if (typeof row.dimension === 'string') finding.dimension = row.dimension;
|
||||
if (Number.isInteger(row.owner_quote) && row.owner_quote > 0) finding.owner_quote = row.owner_quote;
|
||||
if (Number.isInteger(row.narrows_quote) && row.narrows_quote > 0) finding.narrows_quote = row.narrows_quote;
|
||||
if (typeof row.resolves === 'string' && row.resolves.trim()) finding.resolves = row.resolves.trim();
|
||||
if (row.changes !== undefined) {
|
||||
if (!(CHANGES as readonly unknown[]).includes(row.changes)) { errors.push(`findings row ${i + 1}: changes ${JSON.stringify(row.changes)} is not one of ${CHANGES.join('|')}`); return; }
|
||||
@@ -195,7 +198,7 @@ export function canonicalRows(findings: CanonicalFinding[], ctx: { run: string;
|
||||
...(f.local_id ? { source: f.local_id } : {}),
|
||||
...(f.user_challenge ? { user_challenge: true } : {}), ...(f.urgent ? { urgent: true } : {}),
|
||||
...(f.suggested_owner ? { suggested_owner: f.suggested_owner } : {}), ...(f.dimension ? { dimension: f.dimension } : {}),
|
||||
...(f.changes ? { changes: f.changes } : {}), ...(f.owner_quote ? { owner_quote: f.owner_quote } : {}), ...(f.resolves ? { resolves: f.resolves } : {}),
|
||||
...(f.changes ? { changes: f.changes } : {}), ...(f.owner_quote ? { owner_quote: f.owner_quote } : {}), ...(f.narrows_quote ? { narrows_quote: f.narrows_quote } : {}), ...(f.resolves ? { resolves: f.resolves } : {}),
|
||||
} as FindingRow));
|
||||
}
|
||||
|
||||
|
||||
@@ -84,13 +84,13 @@ export function detectDocsOnly(implementationPlan: string, root: string): DocsOn
|
||||
return { docsOnly: paths.length > 0 && code.length === 0, paths, code };
|
||||
}
|
||||
|
||||
export interface ScopeFlags { ui?: boolean; developerTool?: boolean; agentPrimary?: boolean; dx?: boolean; docsOnly?: boolean }
|
||||
export const SCOPE_FLAG_TOKENS = ['--ui', '--no-ui', '--no-dx', '--developer-tool', '--agent-primary', '--docs-only'] as const;
|
||||
export interface ScopeFlags { ui?: boolean; developerTool?: boolean; agentPrimary?: boolean; dx?: boolean; docsOnly?: boolean; firstVersion?: boolean }
|
||||
export const SCOPE_FLAG_TOKENS = ['--ui', '--no-ui', '--no-dx', '--developer-tool', '--agent-primary', '--docs-only', '--first-version'] as const;
|
||||
export const MARKER_RE = /^<!--\s*gstack-autoplan-scope:(.*?)-->\s*$/;
|
||||
|
||||
export function scopeTokens(f: ScopeFlags): string[] {
|
||||
return [...(f.ui === true ? ['--ui'] : f.ui === false ? ['--no-ui'] : []), ...(f.dx === false ? ['--no-dx'] : []),
|
||||
...(f.developerTool ? ['--developer-tool'] : []), ...(f.agentPrimary ? ['--agent-primary'] : []), ...(f.docsOnly ? ['--docs-only'] : [])];
|
||||
...(f.developerTool ? ['--developer-tool'] : []), ...(f.agentPrimary ? ['--agent-primary'] : []), ...(f.docsOnly ? ['--docs-only'] : []), ...(f.firstVersion ? ['--first-version'] : [])];
|
||||
}
|
||||
|
||||
export function parseScopeTokens(tokens: readonly string[], where: string): ScopeFlags {
|
||||
@@ -103,6 +103,7 @@ export function parseScopeTokens(tokens: readonly string[], where: string): Scop
|
||||
...(tokens.includes('--developer-tool') ? { developerTool: true } : {}),
|
||||
...(tokens.includes('--agent-primary') ? { agentPrimary: true } : {}),
|
||||
...(tokens.includes('--docs-only') ? { docsOnly: true } : {}),
|
||||
...(tokens.includes('--first-version') ? { firstVersion: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import * as path from 'node:path';
|
||||
import { gateCost, gateCostSentence, priorChoices } from './autoplan-gate-cost';
|
||||
import { parseReply, recHash, type GateEli5, type GateItem } from './gate-list';
|
||||
import { renderUrgentBlock } from './headless-artifacts';
|
||||
import { renderDayOne } from './autoplan-owner-text';
|
||||
import { renderOwnerPage } from './autoplan-owner-text';
|
||||
import { findSection, firstTitle } from './markdown-sections';
|
||||
import type { BriefInputs } from './owner-brief';
|
||||
|
||||
@@ -142,7 +142,7 @@ export function renderCaptainBrief(inputs: BriefInputs, o: { outDir: string; cap
|
||||
`\`gstack-autoplan answer --out ${o.outDir} --gate-rev ${list.gate_rev} --reply rec --rec-hash ${hash} --by agent:<id> --owner-reply "<their exact words>"\`, then \`gstack-approvals import --autoplan ${o.outDir} --by <name>\`.`;
|
||||
// The price sits above the trailer: the relaying agent sends everything above that line, so the person approving sees it.
|
||||
const cost = inputs.run ? ['### Cost', '', gateCostSentence(gateCost(o.outDir, list, { phase_order: inputs.run.phase_order ?? [], outside_enabled: inputs.run.outside_enabled !== false, spend_cap_usd: inputs.run.spend_cap_usd ?? null, scope_flags: inputs.run.scope_flags, lean: inputs.run.lean })), ''] : [];
|
||||
const dayOne = renderDayOne(plan.text, list.owner_words?.quotes);
|
||||
const dayOne = renderOwnerPage(plan.text, list.owner_words?.quotes, { firstVersion: list.first_version });
|
||||
const text = [...urgent, ...header, '', ...dayOne, ...body, ...need, ...cost, '---', '', trailer, ''].join('\n');
|
||||
return { text, missing, pending, recHash: hash };
|
||||
}
|
||||
|
||||
+103
-48
@@ -1,25 +1,32 @@
|
||||
/**
|
||||
* first-use-message — the play spec and the two texts the first-use check prints
|
||||
* (docs/first-use-check.md). The play spec holds the ten parts every ask to play
|
||||
* or try a build carries (the factory's R47): the links, the device and setup,
|
||||
* what it is, how to start, the controls, how long, what we want to learn, how
|
||||
* to report back, known quirks and the reply word. renderPlayMessage() is the
|
||||
* only "try this build" text, printed after decide() passes; renderBrief() is
|
||||
* what the cold checker from the other model family is given, and nothing more.
|
||||
* first-use-message — the play spec and the texts the first-use check prints (docs/first-use-check.md).
|
||||
* The play spec holds the ten parts every ask to play or try a build carries (the factory's R47):
|
||||
* the links, the device and setup (with the target the steps run on), what it is, how to start
|
||||
* (with the numbered try-it steps, each declaring what it writes), the controls, how long, what we
|
||||
* want to learn, how to report back, known quirks and the reply word. renderTryText() is the one
|
||||
* try-it text, frozen at start, opened by the owner's own quoted words: the checker follows it and
|
||||
* the owner gets it. renderPlayMessage() adds what the check found, printed after decide() passes;
|
||||
* renderBrief() is what the cold checker from the other model family is given, and nothing more.
|
||||
*/
|
||||
import { buildLabel, type Decision, type FirstUseError, type Manifest } from './first-use';
|
||||
|
||||
export interface PlayLink { url: string; label: string; login_gated?: boolean }
|
||||
/** A numbered try-it step: what the owner does, and what it writes (`none` or what); a write on his real setup names his approval. */
|
||||
export interface PlayStep { text: string; writes: string; approved_write?: string }
|
||||
/** What one of the five day-one actions writes, in table order; on the owner's real setup each is required. */
|
||||
export type ActionWrites = Omit<PlayStep, 'text'>;
|
||||
/** Where the steps run: the owner's real setup, or a copy loaded with realistic data (the default), named exactly. */
|
||||
export interface PlayTarget { kind: 'real' | 'realistic-copy'; name: string; data?: string }
|
||||
export interface PlaySpec {
|
||||
links: PlayLink[]; device: string; setup: string; account: string; what: string; start: string;
|
||||
links: PlayLink[]; device: string; setup: string; account: string; target: PlayTarget; what: string; start: string; steps: PlayStep[]; action_writes?: ActionWrites[];
|
||||
controls: string; minutes: number; learn: string; report: string; quirks: string; reply_word: string;
|
||||
}
|
||||
/** R47's ten parts in order, with the play-spec fields each one reads. */
|
||||
export const PLAY_PARTS: Array<{ part: string; fields: Array<keyof PlaySpec> }> = [
|
||||
{ part: 'The links, each checked live minutes before sending', fields: ['links'] },
|
||||
{ part: 'Device and setup', fields: ['device', 'setup', 'account'] },
|
||||
{ part: 'Device and setup', fields: ['device', 'setup', 'account', 'target', 'action_writes'] },
|
||||
{ part: 'What it is, in a sentence', fields: ['what'] },
|
||||
{ part: 'How to start', fields: ['start'] },
|
||||
{ part: 'How to start', fields: ['start', 'steps'] },
|
||||
{ part: 'Controls', fields: ['controls'] },
|
||||
{ part: 'How long to play', fields: ['minutes'] },
|
||||
{ part: 'What we want to learn', fields: ['learn'] },
|
||||
@@ -28,46 +35,66 @@ export const PLAY_PARTS: Array<{ part: string; fields: Array<keyof PlaySpec> }>
|
||||
{ part: 'Reply word', fields: ['reply_word'] },
|
||||
];
|
||||
const TEXT_FIELDS = ['device', 'setup', 'account', 'what', 'start', 'controls', 'learn', 'report', 'quirks', 'reply_word'] as const;
|
||||
const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '');
|
||||
|
||||
/** A complete play spec, or the R47 parts it is missing. "none" is a fine answer for quirks; an empty field is not. */
|
||||
/**
|
||||
* A complete play spec, or the R47 parts it is missing. "none" is a fine answer for quirks and for a step's writes; an
|
||||
* empty field is not. A step that writes on the owner's real setup needs `approved_write` naming his approval, and on that
|
||||
* setup `action_writes` says what each of the five day-one actions writes, under the same rule.
|
||||
*/
|
||||
export function checkPlaySpec(raw: unknown): { spec: PlaySpec } | { error: FirstUseError } {
|
||||
const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
|
||||
const bad = new Set<keyof PlaySpec>();
|
||||
for (const f of TEXT_FIELDS) if (typeof o[f] !== 'string' || !(o[f] as string).trim()) bad.add(f);
|
||||
for (const f of TEXT_FIELDS) if (!str(o[f])) bad.add(f);
|
||||
if (typeof o.reply_word === 'string' && !/^[A-Za-z][A-Za-z0-9-]{0,23}$/.test(o.reply_word.trim())) bad.add('reply_word');
|
||||
if (!Number.isInteger(o.minutes) || (o.minutes as number) < 1 || (o.minutes as number) > 240) bad.add('minutes');
|
||||
const links = Array.isArray(o.links) ? o.links as Array<Record<string, unknown>> : [];
|
||||
const linkOk = (l: Record<string, unknown>) => typeof l?.label === 'string' && !!l.label.trim() && typeof l.url === 'string' && /^https?:\/\/[^\s]+$/.test(l.url)
|
||||
&& (l.login_gated === undefined || typeof l.login_gated === 'boolean');
|
||||
if (!links.length || !links.every(linkOk)) bad.add('links');
|
||||
const t = (o.target && typeof o.target === 'object' ? o.target : {}) as Record<string, unknown>;
|
||||
const kind = t.kind === undefined ? 'realistic-copy' : t.kind;
|
||||
if ((kind !== 'real' && kind !== 'realistic-copy') || !str(t.name) || (kind === 'realistic-copy' && !str(t.data))) bad.add('target');
|
||||
const steps = Array.isArray(o.steps) ? o.steps as Array<Record<string, unknown>> : [];
|
||||
if (!steps.length || !steps.every(s => !!str(s?.text) && !!str(s?.writes))) bad.add('steps');
|
||||
const acts = o.action_writes === undefined ? undefined : Array.isArray(o.action_writes) ? o.action_writes as Array<Record<string, unknown>> : [];
|
||||
if (acts ? acts.length !== 5 || !acts.every(a => !!str(a?.writes)) : kind === 'real') bad.add('action_writes');
|
||||
if (bad.size) {
|
||||
const parts = PLAY_PARTS.filter(p => p.fields.some(f => bad.has(f))).map(p => `${p.part} (${p.fields.filter(f => bad.has(f)).join(', ')})`);
|
||||
return { error: { code: 'FIRST_USE_PLAY_SPEC_INCOMPLETE', detail: `missing or invalid: ${parts.join('; ')}` } };
|
||||
}
|
||||
const writesUnapproved = (s: Record<string, unknown>) => !/^none$/i.test(str(s.writes)) && !str(s.approved_write);
|
||||
const unapproved = kind === 'real' ? [...steps.map((s, i) => (writesUnapproved(s) ? `step ${i + 1}` : '')), ...(acts ?? []).map((a, i) => (writesUnapproved(a) ? `day-one action ${i + 1}` : ''))].filter(Boolean) : [];
|
||||
if (unapproved.length) return { error: { code: 'FIRST_USE_PLAY_SPEC_INCOMPLETE', detail: `${unapproved.join(', ')} ${unapproved.length === 1 ? 'writes' : 'write'} on the owner's real setup with no approved_write naming his lettered approval; run it on a realistic copy, or get his approval for that write first` } };
|
||||
const writesOf = (s: Record<string, unknown>) => ({ writes: str(s.writes), ...(str(s.approved_write) ? { approved_write: str(s.approved_write) } : {}) });
|
||||
const spec: PlaySpec = {
|
||||
links: links.map(l => ({ url: l.url as string, label: (l.label as string).trim(), ...(l.login_gated ? { login_gated: true } : {}) })),
|
||||
minutes: o.minutes as number,
|
||||
...Object.fromEntries(TEXT_FIELDS.map(f => [f, (o[f] as string).trim()])) as Omit<PlaySpec, 'links' | 'minutes'>,
|
||||
target: { kind: kind as PlayTarget['kind'], name: str(t.name), ...(str(t.data) ? { data: str(t.data) } : {}) },
|
||||
steps: steps.map(s => ({ text: str(s.text), ...writesOf(s) })),
|
||||
...(acts ? { action_writes: acts.map(writesOf) } : {}),
|
||||
...Object.fromEntries(TEXT_FIELDS.map(f => [f, str(o[f])])) as Omit<PlaySpec, 'links' | 'minutes' | 'target' | 'steps' | 'action_writes'>,
|
||||
};
|
||||
return { spec };
|
||||
}
|
||||
|
||||
const hhmm = (iso: string) => iso.slice(11, 16);
|
||||
const platformName = { ios: 'iOS', android: 'Android', web: 'web' } as const;
|
||||
const platformName = { ios: 'iOS', android: 'Android', web: 'web', macos: 'Mac', server: 'server' } as const;
|
||||
export const targetLabel = (t: PlayTarget) => (t.kind === 'real' ? `${t.name} (your real setup)` : `${t.name} (a copy loaded with ${t.data})`);
|
||||
|
||||
/** The "try this build" message: R47's ten parts, then what the cold check covered. Call only after decide() passed. */
|
||||
export function renderPlayMessage(d: Decision, now: Date = new Date()): string {
|
||||
const m = d.manifest!, p = m.play;
|
||||
const checked = d.links.map(l => Date.parse(l.checked_at));
|
||||
const oldest = Math.min(...checked);
|
||||
const ago = Math.max(0, Math.round((now.getTime() - oldest) / 60_000));
|
||||
type TryInput = Pick<Manifest, 'app' | 'build' | 'play' | 'quotes' | 'steps'>;
|
||||
/** The try-it text, frozen at start: the owner's quoted words with what this version does with each, then R47's ten parts with the numbered steps. */
|
||||
export function renderTryText(m: TryInput): string {
|
||||
const p = m.play;
|
||||
return [
|
||||
`**Try ${m.app}: ${buildLabel(m.build)}**`, '',
|
||||
`1. **Links** (each checked live at ${new Date(oldest).toISOString().slice(11, 16)} UTC, ${ago} min before this message):`,
|
||||
'**What you asked for, and what this version does with it:**',
|
||||
...m.quotes.map(q => `- ${q.who}: “${q.text}” → ${q.line}`), '',
|
||||
'1. **Links:**',
|
||||
...p.links.map(l => ` - [${l.label}](${l.url})${l.login_gated ? ' (asks you to sign in)' : ''}`),
|
||||
`2. **Device and setup:** ${p.device}. ${p.setup} Account: ${p.account}.`,
|
||||
`2. **Device and setup:** ${p.device}. ${p.setup} Account: ${p.account}. It runs on ${targetLabel(p.target)}.`,
|
||||
`3. **What it is:** ${p.what}`,
|
||||
`4. **How to start:** ${p.start}`,
|
||||
`4. **How to start:** ${p.start} Then:`,
|
||||
...m.steps.map(s => ` ${s.n}. ${s.kind === 'action' ? `Try: ${s.text}` : s.text}`),
|
||||
`5. **Controls:** ${p.controls}`,
|
||||
`6. **How long:** about ${p.minutes} minutes.`,
|
||||
`7. **What we want to learn:** ${p.learn}`,
|
||||
@@ -75,8 +102,25 @@ export function renderPlayMessage(d: Decision, now: Date = new Date()): string {
|
||||
`9. **Known quirks:** ${p.quirks}`,
|
||||
`10. **Reply word:** ${p.reply_word}, then your score and your line, for example "${p.reply_word} 7, the first screen was slow".`,
|
||||
'',
|
||||
`Checked before it reached you: an agent from another model family (${m.checker.model}) played this exact build cold on a ${platformName[m.build.platform]} cloud device and did the first ${m.actions.length} things you'll do on day one. All ${d.passed} worked, with a screenshot or video of each:`,
|
||||
...m.actions.map(a => `- ${a.action}`),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** The try-it message: the frozen try-it text, then what the check found and the build the owner holds now. Call only after decide() passed. */
|
||||
export function renderPlayMessage(d: Decision, now: Date = new Date()): string {
|
||||
const m = d.manifest!;
|
||||
const oldest = Math.min(...d.links.map(l => Date.parse(l.checked_at)));
|
||||
const ago = Math.max(0, Math.round((now.getTime() - oldest) / 60_000));
|
||||
const notice = [...d.verdicts.filter(v => v.verdict === 'thin').map(v => `- Step ${v.n} is thin: ${v.line}`),
|
||||
...d.verdicts.filter(v => v.notice).map(v => `- At step ${v.n} you'll see: ${v.notice}`)];
|
||||
const held = /^none$/i.test(m.holding.build) ? 'none yet: this is your first build of it.'
|
||||
: `${m.holding.build}. Known defects in it: ${m.holding.defects}.`;
|
||||
return [
|
||||
m.try_text,
|
||||
`Every link was checked live at ${new Date(oldest).toISOString().slice(11, 16)} UTC, ${ago} min before this message.`, '',
|
||||
`**What you'll notice:**`, ...(notice.length ? notice : ['- nothing beyond the known quirks above']), '',
|
||||
`**The build on your device now:** ${held}`, '',
|
||||
`**Checked before it reached you:** an agent from another model family (${m.checker.model}) followed these exact steps on ${targetLabel(m.play.target)}, on a ${platformName[m.build.platform]} ${m.build.platform === 'ios' || m.build.platform === 'android' ? 'device' : 'setup'} like yours. One line per step:`,
|
||||
...d.verdicts.map(v => `- ${v.n} (${v.verdict}): ${v.line}`),
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
@@ -84,32 +128,43 @@ export function renderPlayMessage(d: Decision, now: Date = new Date()): string {
|
||||
/** One POSIX shell word: single quotes, with each embedded single quote closed, escaped and reopened. */
|
||||
export const shellQuote = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
/** What the cold checker is given: the build, the device and account, the play message parts and the frozen actions, with the commands that record each. */
|
||||
const DRIVE: Record<Manifest['build']['platform'], (m: Manifest) => string> = {
|
||||
ios: m => phone(m), android: m => phone(m),
|
||||
web: () => 'open the first link in a browser on that kind of device',
|
||||
macos: m => (m.play.target.kind === 'real'
|
||||
? "drive the owner's own Mac through the Aside CLI, preferably over Tailscale; use computer use only where the browser can't reach, and never while he is using the Mac"
|
||||
: `use the Mac named as the target (${m.play.target.name}); install this exact build (deploy ${m.build.deploy ?? m.build.testflight}) the way the steps say`),
|
||||
server: m => `work on ${m.play.target.name} over its shell or CLI as the steps say, with this exact build (deploy ${m.build.deploy ?? m.build.testflight}); save a terminal capture (.txt or .log) as evidence where a screenshot shows nothing`,
|
||||
};
|
||||
function phone(m: Manifest): string {
|
||||
const b = m.build;
|
||||
return `attach a ${platformName[b.platform]} phone (\`tools.capy.phone\` with action "attach", platform "${b.platform}" and the model closest to the device above), install this exact build on it (action "install"; ${b.testflight ? `TestFlight build ${b.testflight}` : `version ${b.deploy}`}), point it at ${m.play.target.name}, and drive its screen with \`tools.capy.computer.on({ machine_id })\``;
|
||||
}
|
||||
|
||||
/** What the cold checker is given: the exact try-it text, the target and its rules, and the commands that record each step. */
|
||||
export function renderBrief(m: Manifest, dir: string): string {
|
||||
const p = m.play, b = m.build;
|
||||
const install = b.platform === 'web'
|
||||
? 'open the first link in a browser on that device'
|
||||
: `attach a ${platformName[b.platform]} phone (\`tools.capy.phone\` with action "attach", platform "${b.platform}" and the model closest to the device above), install this exact build on it (action "install"; ${b.testflight ? `TestFlight build ${b.testflight}` : `version ${b.deploy}`}), and drive its screen with \`tools.capy.computer.on({ machine_id })\``;
|
||||
const by = `--by ${shellQuote(m.checker.model)}`, run = `--run ${shellQuote(dir)}`;
|
||||
const p = m.play;
|
||||
const by = `--by ${shellQuote(m.checker.model)}`, run = `--run ${shellQuote(dir)}`, fixed = `--account ${shellQuote(p.account)} --target ${shellQuote(p.target.name)} ${by}`;
|
||||
return [
|
||||
`# Cold first-use check: ${m.app}, ${buildLabel(b)}`, '',
|
||||
`You are playing this build for the first time, as its owner will. You run on ${m.checker.model}; the team that built it runs on ${m.builder.family} models, and you have not seen its plan, code, notes or messages. Do not read them: you get only what the owner gets, below.`, '',
|
||||
'## Device and account', '',
|
||||
`Use the same kind of device and account as the owner: ${p.device}. ${p.setup} Account: ${p.account} (play only on this kind of account; \`record\` takes it exactly). On Capy, ${install}.`, '',
|
||||
'## What the owner is told', '',
|
||||
`- What it is: ${p.what}`, `- Links: ${p.links.map(l => `${l.label} ${l.url}`).join('; ')}`, `- How to start: ${p.start}`, `- Controls: ${p.controls}`,
|
||||
`- How long: about ${p.minutes} minutes`, `- Known quirks: ${p.quirks}`, '',
|
||||
`## The ${m.actions.length} things the owner will do on day one (frozen ${m.created_at.slice(0, 10)})`, '',
|
||||
...m.actions.map(a => `${a.n}. ${a.action} (${a.frequency || 'how often unstated'}). Way in: ${a.route || 'not stated'}. It works when: ${a.check}`), '',
|
||||
`# Cold first-use check: ${m.app}, ${buildLabel(m.build)}`, '',
|
||||
`You are trying this build for the first time, as its owner will. You run on ${m.checker.model}; the team that built it runs on ${m.builder.family} models, and you have not seen its plan, code, notes or messages. Do not read them: you get only what the owner gets, below.`, '',
|
||||
'## Where you run it, and the rules', '',
|
||||
`Run every step on ${targetLabel(p.target)}, with the owner's kind of device and account: ${p.device}. Account: ${p.account} (\`record\` takes the account and the target exactly). On Capy, ${DRIVE[m.build.platform](m)}.`, '',
|
||||
"- Never send anything as the owner (no messages, mail or posts), and never write to the owner's real setup: a step that writes runs on the copy, except one whose approved_write below names his approval.",
|
||||
"- Never raise a prompt, a permission dialog or a sign-in on the owner's own machine while he is at it.",
|
||||
`- What you read is sent to your model provider (${m.checker.family}); stay inside the steps.`, '',
|
||||
'## The exact message the owner will get', '',
|
||||
'~~~markdown', m.try_text.trimEnd(), '~~~', '',
|
||||
`## The ${m.steps.length} steps you check (frozen ${m.created_at.slice(0, 10)})`, '',
|
||||
...m.steps.map(s => `${s.n}. ${s.kind === 'action' ? `Day-one action, from the owner's words (quote ${s.quote}): ${s.text}. It works when: ${s.check}` : s.text}. Writes: ${s.writes === 'unknown' ? 'unknown, so treat it as a write' : s.writes}${s.approved_write ? ` (approved: ${s.approved_write})` : ''}`), '',
|
||||
'## What to do', '',
|
||||
'1. Do each action as the owner would, from a cold start, with no help beyond the text above.',
|
||||
'2. Capture a screenshot or a short video that shows the result, then record it. A pass means the owner would see it work on the first try; anything else is a fail, and the note says what happened:',
|
||||
'', '```bash', `gstack-first-use record ${run} --action N --verdict pass --evidence FILE --device 'DEVICE YOU USED' --account ${shellQuote(p.account)} ${by}`,
|
||||
`gstack-first-use record ${run} --action N --verdict fail --evidence FILE --device 'DEVICE YOU USED' --account ${shellQuote(p.account)} ${by} --note 'WHAT HAPPENED'`, '```', '',
|
||||
'1. Follow the message above word for word, from a cold start, with no help beyond it.',
|
||||
"2. For each step, capture a screenshot, a short video or a terminal capture that shows the result, then record a verdict and one line on what the owner would see. useful: it does what he asked, well. thin: it works but does little. wrong: it does something other than what he asked. broken: it fails. Add --needs-lookup when the step asks the owner for something an agent could look up or do, and --notice when a system notice or prompt appears that the message doesn't warn about:",
|
||||
'', '~~~bash', `gstack-first-use record ${run} --step N --verdict useful --line 'WHAT THE OWNER SEES' --evidence FILE --device 'DEVICE YOU USED' ${fixed}`,
|
||||
`gstack-first-use record ${run} --step N --verdict thin --line 'WHAT THE OWNER SEES' --evidence FILE --device 'DEVICE YOU USED' ${fixed} --notice 'THE NOTICE' --needs-lookup 'WHAT IT ASKED FOR'`, '~~~', '',
|
||||
'3. Predict the owner\'s score from 1 to 10 for this build, with one line on why:', '',
|
||||
'```bash', `gstack-first-use predict ${run} --score N --why 'ONE LINE' ${by}`, '```', '',
|
||||
'4. Report back: one line per action (pass or fail and why), your predicted score, and the one thing most likely to disappoint the owner.',
|
||||
'~~~bash', `gstack-first-use predict ${run} --score N --why 'ONE LINE' ${by}`, '~~~', '',
|
||||
'4. Report back: one line per step (its verdict and why), your predicted score, and the one thing most likely to disappoint the owner.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
+126
-69
@@ -1,50 +1,62 @@
|
||||
/**
|
||||
* first-use — the cold first-use check for an app build (docs/first-use-check.md).
|
||||
* Before a build reaches its owner as "ready to try", an agent from another model
|
||||
* family plays that exact build on the same kind of device and account and does
|
||||
* the first five things the plan's day-one table says the owner will do. This
|
||||
* module keeps the record: an immutable start manifest (the frozen day-one rows
|
||||
* with their hash, the play spec, the build fingerprint, the builder's and the
|
||||
* checker's model families), one write-once file per action result with its
|
||||
* evidence copied in and hashed, dated link receipts, the checker's predicted
|
||||
* score and the owner's scores and words. decide() reads it back and refuses the
|
||||
* "try it" message unless every frozen action passed on this build, every link
|
||||
* was live within 15 minutes, the day-one rows are unchanged and a prediction
|
||||
* exists. The record lives in the owner's private user-level Capy Drive folder
|
||||
* on Capy (never the public repository), else under the gstack state root.
|
||||
* first-use — the cold first-use check for a first version or app build (docs/first-use-check.md).
|
||||
* Before a build reaches its owner as "ready to try", an agent from another model family follows
|
||||
* the exact try-it message the owner will get, step by step, on the real target (the owner's own
|
||||
* setup, or a copy loaded with realistic data that the play spec names), and writes a verdict and
|
||||
* one line per step: useful, thin, wrong or broken. The steps are the play spec's numbered steps,
|
||||
* then the first five things the plan's day-one table says the owner will do, each citing the
|
||||
* owner's own quoted words (GST-3608). This module keeps the record: an immutable start manifest
|
||||
* (the owner's quotes, the frozen steps and their hash, the try-it text, the play spec, the build
|
||||
* fingerprint, the build the owner holds now with its known defects, the builder's and the
|
||||
* checker's model families), one write-once file per step result with its evidence copied in and
|
||||
* hashed, dated link receipts, the checker's predicted score and the owner's scores and words.
|
||||
* decide() reads it back and refuses the try-it message unless every step was played on this
|
||||
* build and target, none is wrong, broken or asks the owner for something an agent could look up,
|
||||
* no day-one action is thin, every link was live within 15 minutes, the frozen rows and quotes
|
||||
* are unchanged and a prediction exists. The record lives in the owner's private user-level Capy
|
||||
* Drive folder on Capy (never the public repository), else under the gstack state root.
|
||||
*/
|
||||
import * as crypto from 'node:crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { parseDayOne } from './autoplan-owner-text';
|
||||
import { lineText, parseDayOne, parseOwnerWords, quoteGaps, quoteWhen } from './autoplan-owner-text';
|
||||
import { resolveStateRoot } from './state-root';
|
||||
import { checkPlaySpec, type PlaySpec } from './first-use-message';
|
||||
import { checkPlaySpec, renderTryText, type PlaySpec } from './first-use-message';
|
||||
|
||||
export const FIRST_USE_ACTIONS = 5;
|
||||
export const LINK_FRESH_MS = 15 * 60 * 1000;
|
||||
export const EVIDENCE_MAX_BYTES = 100 * 1024 * 1024;
|
||||
export const EVIDENCE_KINDS: Record<string, 'screenshot' | 'video'> = {
|
||||
export const NOTE_MAX = 240;
|
||||
export const EVIDENCE_KINDS: Record<string, 'screenshot' | 'video' | 'text'> = {
|
||||
'.png': 'screenshot', '.jpg': 'screenshot', '.jpeg': 'screenshot', '.gif': 'screenshot', '.webp': 'screenshot', '.heic': 'screenshot',
|
||||
'.mp4': 'video', '.mov': 'video', '.webm': 'video',
|
||||
'.mp4': 'video', '.mov': 'video', '.webm': 'video', '.txt': 'text', '.log': 'text',
|
||||
};
|
||||
export const VERDICTS = ['useful', 'thin', 'wrong', 'broken'] as const;
|
||||
export type Verdict = typeof VERDICTS[number];
|
||||
export const PLATFORMS = ['ios', 'android', 'web', 'macos', 'server'] as const;
|
||||
export type FirstUseCode = 'FIRST_USE_PLAN_UNREADY' | 'FIRST_USE_PLAY_SPEC_INCOMPLETE' | 'FIRST_USE_SAME_FAMILY' | 'FIRST_USE_NO_PRIVATE_DRIVE' | 'FIRST_USE_RECORD_INVALID' | 'FIRST_USE_REFUSED';
|
||||
export interface FirstUseError { code: FirstUseCode; detail: string }
|
||||
type Result<T> = T | { error: FirstUseError };
|
||||
const fail = (code: FirstUseCode, detail: string) => ({ error: { code, detail } });
|
||||
|
||||
export interface FrozenAction { n: number; action: string; frequency: string; feature: string; route: string; first_build: string; check: string; source: string }
|
||||
export interface BuildId { platform: 'ios' | 'android' | 'web'; commit: string; testflight?: string; deploy?: string }
|
||||
export interface FrozenQuote { n: number; who: string; when: string; text: string; line: string }
|
||||
export interface FrozenAction { n: number; action: string; frequency: string; feature: string; route: string; first_build: string; check: string; source: string; quote: number }
|
||||
/** One step of the try-it message: a play-spec step, or one of the five day-one actions (which cite a quote). */
|
||||
export interface FrozenStep { n: number; kind: 'step' | 'action'; text: string; writes: string; approved_write?: string; check?: string; quote?: number }
|
||||
export interface BuildId { platform: typeof PLATFORMS[number]; commit: string; testflight?: string; deploy?: string }
|
||||
export interface Holding { build: string; defects: string }
|
||||
export interface Manifest {
|
||||
schema_version: 1; kind: 'first-use-manifest'; app: string; created_at: string;
|
||||
source: { path: string; rows_sha256: string }; actions: FrozenAction[];
|
||||
build: BuildId & { fingerprint: string }; play: PlaySpec;
|
||||
schema_version: 2; kind: 'first-use-manifest'; app: string; created_at: string;
|
||||
source: { path: string; rows_sha256: string }; quotes: FrozenQuote[]; actions: FrozenAction[]; steps: FrozenStep[];
|
||||
try_text: string; try_sha256: string; build: BuildId & { fingerprint: string }; play: PlaySpec; holding: Holding;
|
||||
builder: { model: string; family: string }; checker: { model: string; family: string };
|
||||
}
|
||||
export interface ActionResult {
|
||||
schema_version: 1; kind: 'first-use-result'; action: number; action_text: string; build_fingerprint: string; at: string;
|
||||
verdict: 'pass' | 'fail'; evidence: { file: string; sha256: string; bytes: number; kind: 'screenshot' | 'video' };
|
||||
device: string; account: string; by: { model: string; family: string }; note: string;
|
||||
export interface StepResult {
|
||||
schema_version: 2; kind: 'first-use-result'; step: number; step_text: string; step_kind: FrozenStep['kind']; build_fingerprint: string; at: string;
|
||||
verdict: Verdict; line: string; needs_lookup?: string; notice?: string;
|
||||
evidence: { file: string; sha256: string; bytes: number; kind: 'screenshot' | 'video' | 'text' };
|
||||
device: string; account: string; target: string; by: { model: string; family: string };
|
||||
}
|
||||
/** Who a check speaks for: the owner-equivalent account from the play spec and the build's device class. */
|
||||
export interface Audience { account: string; device_class: BuildId['platform'] }
|
||||
@@ -78,28 +90,45 @@ export function modelFamily(model: string): string | undefined {
|
||||
return FAMILY_WORDS.find(([, re]) => re.test(s))?.[0] ?? (slash > 0 ? prefix : undefined);
|
||||
}
|
||||
|
||||
/** The first five rows of the plan's `### Day one` table (lib/autoplan-owner-text.ts parses it; the format is pinned by test/first-use.test.ts). */
|
||||
export function freezeActions(planText: string): Result<{ actions: FrozenAction[]; rows_sha256: string }> {
|
||||
/** Checker free text as one plain line: Markdown links keep their text, HTML tags and line breaks go, at most NOTE_MAX characters. */
|
||||
export const plainLine = (t: string | undefined): string => (t ?? '').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/<[^>]*>/g, '')
|
||||
.replace(/\s+/g, ' ').trim().slice(0, NOTE_MAX);
|
||||
|
||||
/**
|
||||
* What the check freezes from the plan: every quote under `### Owner's words` (each with its time and line) and the first
|
||||
* five rows of the `### Day one` table, each citing `owner words <n>` for a real quote. The hash covers the rows and the
|
||||
* text of every quote, so editing or renumbering a cited quote changes it. The format is pinned by test/first-use.test.ts.
|
||||
*/
|
||||
export function freezeActions(planText: string): Result<{ actions: FrozenAction[]; quotes: FrozenQuote[]; rows_sha256: string }> {
|
||||
const day = parseDayOne(planText);
|
||||
if (day.status === 'none') return fail('FIRST_USE_PLAN_UNREADY', 'the plan has no ### Day one table');
|
||||
if (day.status === 'malformed') return fail('FIRST_USE_PLAN_UNREADY', day.reason ?? 'the day-one table is malformed');
|
||||
if (day.rows.length < FIRST_USE_ACTIONS) return fail('FIRST_USE_PLAN_UNREADY', `the day-one table has ${day.rows.length} row${day.rows.length === 1 ? '' : 's'}; the check needs ${FIRST_USE_ACTIONS}`);
|
||||
const words = parseOwnerWords(planText);
|
||||
if (words.status === 'none' || !words.quotes.length) return fail('FIRST_USE_PLAN_UNREADY', "the plan has no ### Owner's words section: quote each message of the owner's that states the job, with its time and a line each");
|
||||
if (words.status === 'malformed') return fail('FIRST_USE_PLAN_UNREADY', `### Owner's words is malformed: ${words.reason}`);
|
||||
const gaps = words.quotes.filter(q => quoteGaps(q).length);
|
||||
if (gaps.length) return fail('FIRST_USE_PLAN_UNREADY', `owner quote ${gaps.map(q => `${q.n} needs ${quoteGaps(q).join(' and ')}`).join('; ')}`);
|
||||
const rows = day.rows.slice(0, FIRST_USE_ACTIONS);
|
||||
const blank = rows.map((r, i) => [r.frequency, r.source, r.feature, r.route, r.first_build, r.check].some(c => !c.trim()) ? i + 1 : 0).filter(Boolean);
|
||||
if (blank.length) return fail('FIRST_USE_PLAN_UNREADY', `day-one row ${blank.join(', ')} has an empty cell; every column of the first ${FIRST_USE_ACTIONS} rows needs a value`);
|
||||
const assumed = rows.map((r, i) => r.assumed ? i + 1 : 0).filter(Boolean);
|
||||
if (assumed.length) return fail('FIRST_USE_PLAN_UNREADY', `day-one row ${assumed.join(', ')} is still marked assumed`);
|
||||
const actions = rows.map((r, i) => ({ n: i + 1, action: r.action, frequency: r.frequency, feature: r.feature, route: r.route, first_build: r.first_build, check: r.check, source: r.source }));
|
||||
return { actions, rows_sha256: sha256(JSON.stringify(actions)) };
|
||||
const cited = rows.map(r => Number(/^\W*owner words\s+(\d+)\b/i.exec(r.source)?.[1] ?? 0));
|
||||
const uncited = cited.map((n, i) => (words.quotes.some(q => q.n === n) ? 0 : i + 1)).filter(Boolean);
|
||||
if (uncited.length) return fail('FIRST_USE_PLAN_UNREADY', `day-one row ${uncited.join(', ')} cites none of the owner's quotes: its source must read "owner words <n>" (a row the owner confirmed at the gate cites his answer, added to Owner's words)`);
|
||||
const quotes = words.quotes.map(q => ({ n: q.n, who: q.who, when: quoteWhen(q), text: q.text, line: lineText(q) }));
|
||||
const actions = rows.map((r, i) => ({ n: i + 1, action: r.action, frequency: r.frequency, feature: r.feature, route: r.route, first_build: r.first_build, check: r.check, source: r.source, quote: cited[i]! }));
|
||||
return { actions, quotes, rows_sha256: sha256(JSON.stringify({ actions, quotes })) };
|
||||
}
|
||||
|
||||
/** Validates a build id; the fingerprint is the hash of platform, commit and the TestFlight build or deploy version. */
|
||||
export function buildFingerprint(b: Partial<BuildId>): Result<BuildId & { fingerprint: string }> {
|
||||
if (b.platform !== 'ios' && b.platform !== 'android' && b.platform !== 'web') return fail('FIRST_USE_RECORD_INVALID', '--platform must be ios, android or web');
|
||||
if (!(PLATFORMS as readonly string[]).includes(b.platform ?? '')) return fail('FIRST_USE_RECORD_INVALID', `--platform must be ${PLATFORMS.join(', ')}`);
|
||||
if (!/^[0-9a-f]{40}$/.test(b.commit ?? '')) return fail('FIRST_USE_RECORD_INVALID', '--commit must be the full 40-character commit the build was made from');
|
||||
const tf = b.testflight?.trim(), dep = b.deploy?.trim();
|
||||
if (!!tf === !!dep) return fail('FIRST_USE_RECORD_INVALID', 'give exactly one of --testflight <build number> or --deploy <version>');
|
||||
const id: BuildId = { platform: b.platform, commit: b.commit!, ...(tf ? { testflight: tf } : { deploy: dep }) };
|
||||
const id: BuildId = { platform: b.platform!, commit: b.commit!, ...(tf ? { testflight: tf } : { deploy: dep }) };
|
||||
return { ...id, fingerprint: sha256(JSON.stringify([id.platform, id.commit, id.testflight ?? '', id.deploy ?? ''])).slice(0, 16) };
|
||||
}
|
||||
export const buildLabel = (b: BuildId) => `${b.commit.slice(0, 12)}, ${b.testflight ? `TestFlight build ${b.testflight}` : `deploy ${b.deploy}`}`;
|
||||
@@ -126,8 +155,15 @@ const writeOnce = (file: string, value: unknown) => {
|
||||
};
|
||||
const readJson = <T>(file: string): T | undefined => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) as T; } catch { return undefined; } };
|
||||
|
||||
export interface StartInput { root: string; app: string; planPath: string; build: Partial<BuildId>; play: unknown; builder: string; checker: string; now?: Date }
|
||||
/** Freezes the day-one rows and writes the run's manifest once; returns the run directory. */
|
||||
/** The build the owner holds now and its known defects: `none` for a first build, else a label and a list or `none`. */
|
||||
function checkHolding(h: Partial<Holding> | undefined): Result<{ holding: Holding }> {
|
||||
const build = plainLine(h?.build), defects = plainLine(h?.defects);
|
||||
if (!build || !defects) return fail('FIRST_USE_RECORD_INVALID', 'name the build the owner holds now and its known defects: --holding "<build label>|none" --holding-defects "<each known defect>|none"');
|
||||
return { holding: { build, defects } };
|
||||
}
|
||||
|
||||
export interface StartInput { root: string; app: string; planPath: string; build: Partial<BuildId>; play: unknown; holding: Partial<Holding>; builder: string; checker: string; now?: Date }
|
||||
/** Freezes the owner's quotes, the steps and the try-it text, and writes the run's manifest once; returns the run directory. */
|
||||
export function startRun(o: StartInput): Result<{ dir: string; manifest: Manifest }> {
|
||||
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(o.app)) return fail('FIRST_USE_RECORD_INVALID', '--app must be a lowercase slug like ghome');
|
||||
let planText: string;
|
||||
@@ -138,24 +174,31 @@ export function startRun(o: StartInput): Result<{ dir: string; manifest: Manifes
|
||||
if ('error' in play) return play;
|
||||
const build = buildFingerprint(o.build);
|
||||
if ('error' in build) return build;
|
||||
const holding = checkHolding(o.holding);
|
||||
if ('error' in holding) return holding;
|
||||
const builder = modelFamily(o.builder), checker = modelFamily(o.checker);
|
||||
if (!builder || !checker) return fail('FIRST_USE_SAME_FAMILY', `unknown model family for ${!builder ? `--builder ${o.builder}` : `--checker ${o.checker}`}`);
|
||||
if (builder === checker) return fail('FIRST_USE_SAME_FAMILY', `builder and checker are both ${builder}`);
|
||||
const now = o.now ?? new Date();
|
||||
const manifest: Manifest = {
|
||||
schema_version: 1, kind: 'first-use-manifest', app: o.app, created_at: now.toISOString(),
|
||||
source: { path: path.resolve(o.planPath), rows_sha256: frozen.rows_sha256 }, actions: frozen.actions,
|
||||
build, play: play.spec, builder: { model: o.builder, family: builder }, checker: { model: o.checker, family: checker },
|
||||
};
|
||||
const steps: FrozenStep[] = [
|
||||
...play.spec.steps.map((s, i) => ({ n: i + 1, kind: 'step' as const, text: s.text, writes: s.writes, ...(s.approved_write ? { approved_write: s.approved_write } : {}) })),
|
||||
...frozen.actions.map((a, i) => ({ n: play.spec.steps.length + i + 1, kind: 'action' as const, text: a.action, ...(play.spec.action_writes?.[i] ?? { writes: 'unknown' }), check: a.check, quote: a.quote })),
|
||||
];
|
||||
const base = { schema_version: 2 as const, kind: 'first-use-manifest' as const, app: o.app, created_at: now.toISOString(),
|
||||
source: { path: path.resolve(o.planPath), rows_sha256: frozen.rows_sha256 }, quotes: frozen.quotes, actions: frozen.actions, steps,
|
||||
build, play: play.spec, holding: holding.holding, builder: { model: o.builder, family: builder }, checker: { model: o.checker, family: checker } };
|
||||
const try_text = renderTryText(base);
|
||||
const manifest: Manifest = { ...base, try_text, try_sha256: sha256(try_text) };
|
||||
const dir = path.join(o.root, o.app, `${stamp(now)}-${build.fingerprint.slice(0, 8)}`);
|
||||
try { writeOnce(path.join(dir, 'manifest.json'), manifest); } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${dir}/manifest.json: ${(e as Error).message}`); }
|
||||
return { dir, manifest };
|
||||
}
|
||||
|
||||
export function readManifest(dir: string): Result<{ manifest: Manifest }> {
|
||||
const m = readJson<Manifest>(path.join(dir, 'manifest.json'));
|
||||
if (!m || m.schema_version !== 1 || m.kind !== 'first-use-manifest' || !Array.isArray(m.actions) || !m.build?.fingerprint) return fail('FIRST_USE_RECORD_INVALID', `no readable manifest.json in ${dir}`);
|
||||
return { manifest: m };
|
||||
const m = readJson<Omit<Manifest, 'schema_version'> & { schema_version: number }>(path.join(dir, 'manifest.json'));
|
||||
if (m?.kind === 'first-use-manifest' && m.schema_version === 1) return fail('FIRST_USE_RECORD_INVALID', `${dir} is a schema-1 run from before the try-it steps and the owner's quotes were checked; start a new run`);
|
||||
if (!m || m.schema_version !== 2 || m.kind !== 'first-use-manifest' || !Array.isArray(m.steps) || !m.build?.fingerprint) return fail('FIRST_USE_RECORD_INVALID', `no readable manifest.json in ${dir}`);
|
||||
return { manifest: m as Manifest };
|
||||
}
|
||||
|
||||
/** The checker's own model, from its own family: the builder never grades its own build. */
|
||||
@@ -165,35 +208,39 @@ function checkerOf(m: Manifest, by: string): Result<{ by: { model: string; famil
|
||||
return { by: { model: by, family } };
|
||||
}
|
||||
|
||||
export interface RecordInput { dir: string; action: number; verdict: string; evidence: string; device: string; account: string; by: string; note?: string; now?: Date }
|
||||
/** One write-once result for one frozen action; the evidence file is copied into the run and hashed. */
|
||||
export function recordResult(o: RecordInput): Result<{ file: string; result: ActionResult }> {
|
||||
export interface RecordInput { dir: string; step: number; verdict: string; line: string; evidence: string; device: string; account: string; target: string; by: string; needsLookup?: string; notice?: string; now?: Date }
|
||||
/** One write-once result for one frozen step; the evidence file is copied into the run and hashed. */
|
||||
export function recordResult(o: RecordInput): Result<{ file: string; result: StepResult }> {
|
||||
const read = readManifest(o.dir);
|
||||
if ('error' in read) return read;
|
||||
const m = read.manifest;
|
||||
const action = m.actions.find(a => a.n === o.action);
|
||||
if (!action) return fail('FIRST_USE_RECORD_INVALID', `--action must be 1 to ${m.actions.length}`);
|
||||
if (o.verdict !== 'pass' && o.verdict !== 'fail') return fail('FIRST_USE_RECORD_INVALID', '--verdict must be pass or fail');
|
||||
const step = m.steps.find(s => s.n === o.step);
|
||||
if (!step) return fail('FIRST_USE_RECORD_INVALID', `--step must be 1 to ${m.steps.length}`);
|
||||
if (!(VERDICTS as readonly string[]).includes(o.verdict)) return fail('FIRST_USE_RECORD_INVALID', `--verdict must be ${VERDICTS.join(', ')}`);
|
||||
const line = plainLine(o.line);
|
||||
if (!line) return fail('FIRST_USE_RECORD_INVALID', '--line needs one line on what the owner would see at this step');
|
||||
if (!o.device.trim()) return fail('FIRST_USE_RECORD_INVALID', 'name the --device you played on');
|
||||
if (o.account.trim() !== m.play.account) return fail('FIRST_USE_RECORD_INVALID', `play on the owner-equivalent account and pass it exactly: --account "${m.play.account}"`);
|
||||
if (o.verdict === 'fail' && !o.note?.trim()) return fail('FIRST_USE_RECORD_INVALID', 'a fail needs --note saying what happened');
|
||||
if (o.target.trim() !== m.play.target.name) return fail('FIRST_USE_RECORD_INVALID', `play on the play spec's target and pass it exactly: --target "${m.play.target.name}"`);
|
||||
const who = checkerOf(m, o.by);
|
||||
if ('error' in who) return who;
|
||||
const ev = copyEvidence(o.dir, o.action, o.evidence);
|
||||
const ev = copyEvidence(o.dir, o.step, o.evidence);
|
||||
if ('error' in ev) return ev;
|
||||
const now = o.now ?? new Date();
|
||||
const result: ActionResult = {
|
||||
schema_version: 1, kind: 'first-use-result', action: o.action, action_text: action.action, build_fingerprint: m.build.fingerprint, at: now.toISOString(),
|
||||
verdict: o.verdict, evidence: ev.evidence, device: o.device.trim(), account: o.account.trim(), by: who.by, note: o.note?.trim() ?? '',
|
||||
const lookup = plainLine(o.needsLookup), notice = plainLine(o.notice);
|
||||
const result: StepResult = {
|
||||
schema_version: 2, kind: 'first-use-result', step: o.step, step_text: step.text, step_kind: step.kind, build_fingerprint: m.build.fingerprint, at: now.toISOString(),
|
||||
verdict: o.verdict as Verdict, line, ...(lookup ? { needs_lookup: lookup } : {}), ...(notice ? { notice } : {}),
|
||||
evidence: ev.evidence, device: o.device.trim(), account: o.account.trim(), target: o.target.trim(), by: who.by,
|
||||
};
|
||||
const file = path.join(o.dir, 'results', `${o.action}-${stamp(now)}-${crypto.randomBytes(3).toString('hex')}.json`);
|
||||
const file = path.join(o.dir, 'results', `${o.step}-${stamp(now)}-${crypto.randomBytes(3).toString('hex')}.json`);
|
||||
try { writeOnce(file, result); } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${file}: ${(e as Error).message}`); }
|
||||
return { file, result };
|
||||
}
|
||||
|
||||
function copyEvidence(dir: string, n: number, src: string): Result<{ evidence: ActionResult['evidence'] }> {
|
||||
function copyEvidence(dir: string, n: number, src: string): Result<{ evidence: StepResult['evidence'] }> {
|
||||
const kind = EVIDENCE_KINDS[path.extname(src).toLowerCase()];
|
||||
if (!kind) return fail('FIRST_USE_RECORD_INVALID', `evidence must be a screenshot or short video (${Object.keys(EVIDENCE_KINDS).join(' ')})`);
|
||||
if (!kind) return fail('FIRST_USE_RECORD_INVALID', `evidence must be a screenshot, a short video or a terminal capture (${Object.keys(EVIDENCE_KINDS).join(' ')})`);
|
||||
let st: fs.Stats;
|
||||
try { st = fs.lstatSync(src); } catch { return fail('FIRST_USE_RECORD_INVALID', `no evidence file at ${src}`); }
|
||||
if (!st.isFile()) return fail('FIRST_USE_RECORD_INVALID', 'the evidence must be a regular file, not a link or directory');
|
||||
@@ -249,7 +296,7 @@ export function predict(o: { dir: string; score: string; why: string; by: string
|
||||
if (n === undefined || !o.why.trim()) return fail('FIRST_USE_RECORD_INVALID', 'predict needs --score 1-10 and --why <one line>');
|
||||
const who = checkerOf(read.manifest, o.by);
|
||||
if ('error' in who) return who;
|
||||
const prediction: Prediction = { schema_version: 1, kind: 'first-use-prediction', score: n, why: o.why.trim(), by: who.by, at: (o.now ?? new Date()).toISOString(), build_fingerprint: read.manifest.build.fingerprint };
|
||||
const prediction: Prediction = { schema_version: 1, kind: 'first-use-prediction', score: n, why: plainLine(o.why), by: who.by, at: (o.now ?? new Date()).toISOString(), build_fingerprint: read.manifest.build.fingerprint };
|
||||
try { writeOnce(path.join(o.dir, 'prediction.json'), prediction); } catch { return fail('FIRST_USE_RECORD_INVALID', 'this run already has a predicted score; start a new run to predict again'); }
|
||||
return { prediction };
|
||||
}
|
||||
@@ -276,14 +323,17 @@ function readDir<T>(dir: string): { rows: T[]; unreadable: string[] } {
|
||||
}
|
||||
const newest = <T extends { at?: string; checked_at?: string }>(rows: T[]) => [...rows].sort((a, b) => (a.at ?? a.checked_at ?? '').localeCompare(b.at ?? b.checked_at ?? '')).at(-1);
|
||||
|
||||
export interface Decision { ok: boolean; reasons: string[]; manifest?: Manifest; passed: number; links: LinkReceipt[]; prediction?: Prediction; owner?: OwnerScore }
|
||||
export interface StepVerdict { n: number; kind: FrozenStep['kind']; text: string; verdict: Verdict; line: string; notice?: string }
|
||||
export interface Decision { ok: boolean; reasons: string[]; manifest?: Manifest; passed: number; verdicts: StepVerdict[]; links: LinkReceipt[]; prediction?: Prediction; owner?: OwnerScore }
|
||||
/**
|
||||
* Whether this run clears the build about to be sent: the same build, unchanged day-one rows, a pass with intact
|
||||
* evidence for every frozen action, a live receipt under 15 minutes old for every play link, and a predicted score.
|
||||
* Whether this run clears the build about to be sent: the same build, unchanged day-one rows and quotes, a newest result
|
||||
* with intact evidence for every step on the play spec's target, none wrong, broken or needing something an agent could
|
||||
* look up, no thin day-one action (each comes from the owner's words), a live receipt under 15 minutes old for every play
|
||||
* link, and a predicted score. A thin play step or a notice the owner would see passes and is named in the message.
|
||||
*/
|
||||
export function decide(dir: string, build: Partial<BuildId>, now: Date = new Date()): Decision {
|
||||
const read = readManifest(dir);
|
||||
if ('error' in read) return { ok: false, reasons: [read.error.detail], passed: 0, links: [] };
|
||||
if ('error' in read) return { ok: false, reasons: [read.error.detail], passed: 0, verdicts: [], links: [] };
|
||||
const m = read.manifest, reasons: string[] = [];
|
||||
const current = buildFingerprint(build);
|
||||
if ('error' in current) reasons.push(current.error.detail);
|
||||
@@ -293,19 +343,26 @@ export function decide(dir: string, build: Partial<BuildId>, now: Date = new Dat
|
||||
if (planText !== undefined) {
|
||||
const again = freezeActions(planText);
|
||||
if ('error' in again) reasons.push(`source_changed: ${again.error.detail}`);
|
||||
else if (again.rows_sha256 !== m.source.rows_sha256) reasons.push('source_changed: the day-one rows changed since the check started; start a new run');
|
||||
else if (again.rows_sha256 !== m.source.rows_sha256) reasons.push('source_changed: the day-one rows or the owner\'s quotes changed since the check started; start a new run');
|
||||
}
|
||||
if (m.builder.family === m.checker.family) reasons.push('same_family');
|
||||
const results = readDir<ActionResult>(path.join(dir, 'results'));
|
||||
if (sha256(m.try_text) !== m.try_sha256) reasons.push('try_text_changed: the frozen try-it text no longer matches its hash; start a new run');
|
||||
const results = readDir<StepResult>(path.join(dir, 'results'));
|
||||
if (results.unreadable.length) reasons.push(`record_unreadable: results/${results.unreadable.join(', results/')}`);
|
||||
let passed = 0;
|
||||
for (const a of m.actions) {
|
||||
const r = newest(results.rows.filter(x => x.action === a.n && x.build_fingerprint === m.build.fingerprint && x.by?.family === m.checker.family && x.account === m.play.account));
|
||||
if (!r) { reasons.push(`action_${a.n}_not_played`); continue; }
|
||||
if (r.verdict !== 'pass') { reasons.push(`action_${a.n}_failed: ${r.note}`); continue; }
|
||||
const verdicts: StepVerdict[] = [];
|
||||
for (const s of m.steps) {
|
||||
const r = newest(results.rows.filter(x => x.step === s.n && x.build_fingerprint === m.build.fingerprint && x.by?.family === m.checker.family
|
||||
&& x.account === m.play.account && x.target === m.play.target.name));
|
||||
if (!r) { reasons.push(`step_${s.n}_not_played`); continue; }
|
||||
let bytes: Buffer | undefined;
|
||||
try { bytes = fs.readFileSync(path.join(dir, r.evidence.file)); } catch { /* missing */ }
|
||||
if (!bytes || bytes.length !== r.evidence.bytes || sha256(bytes) !== r.evidence.sha256) { reasons.push(`action_${a.n}_evidence_stale`); continue; }
|
||||
if (!bytes || bytes.length !== r.evidence.bytes || sha256(bytes) !== r.evidence.sha256) { reasons.push(`step_${s.n}_evidence_stale`); continue; }
|
||||
verdicts.push({ n: s.n, kind: s.kind, text: s.text, verdict: r.verdict, line: r.line, ...(r.notice ? { notice: r.notice } : {}) });
|
||||
if (r.verdict === 'wrong' || r.verdict === 'broken') { reasons.push(`step_${s.n}_${r.verdict}: ${r.line}`); continue; }
|
||||
if (r.verdict !== 'useful' && r.verdict !== 'thin') { reasons.push(`step_${s.n}_verdict_unknown: ${String(r.verdict)}`); continue; }
|
||||
if (r.needs_lookup) { reasons.push(`step_${s.n}_needs_lookup: ${r.needs_lookup} (an agent looks it up or does it; the owner is never asked)`); continue; }
|
||||
if (r.verdict === 'thin' && s.kind === 'action') { reasons.push(`step_${s.n}_thin: ${r.line} (a day-one action comes from the owner's own words)`); continue; }
|
||||
passed++;
|
||||
}
|
||||
const receipts = readDir<LinkReceipt>(path.join(dir, 'links'));
|
||||
@@ -320,5 +377,5 @@ export function decide(dir: string, build: Partial<BuildId>, now: Date = new Dat
|
||||
const prediction = readJson<Prediction>(path.join(dir, 'prediction.json'));
|
||||
if (!prediction) reasons.push('no_predicted_score');
|
||||
const owner = newest(readDir<OwnerScore>(path.join(dir, 'owner')).rows);
|
||||
return { ok: reasons.length === 0, reasons, manifest: m, passed, links, prediction, owner };
|
||||
return { ok: reasons.length === 0, reasons, manifest: m, passed, verdicts, links, prediction, owner };
|
||||
}
|
||||
+5
-3
@@ -21,7 +21,7 @@
|
||||
* Rendered by bin/gstack-gate; rows land in decisions.jsonl (lib/headless-artifacts.ts).
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { ownerWordsLine } from './autoplan-owner-text';
|
||||
import { ownerWordsLine, type OwnerLine } from './autoplan-owner-text';
|
||||
import type { DecisionRow } from './headless-artifacts';
|
||||
|
||||
/** `changes_plan`: choosing this option is an accepted plan change (reopens its phase plus Eng, prints APPLY:). */
|
||||
@@ -49,7 +49,7 @@ export interface GateItem {
|
||||
finding?: string[];
|
||||
}
|
||||
export type ItemClass = 'challenge2' | 'challenge1' | 'disagree' | 'agent' | 'cap_deferred' | 'cap_blocker' | 'cap_delta' | 'finding' | 'p1'
|
||||
| 'proposal' | 'confirm_direction' | 'day_one' | 'cut' | 'cuts';
|
||||
| 'proposal' | 'confirm_direction' | 'day_one' | 'cut' | 'cuts' | 'owner_words' | 'owner_choice';
|
||||
export interface GateList { schema_version: 1; run: string; gate_rev: number; items: GateItem[]; title?: string;
|
||||
/** Bumped by every `recommend`, so a `rec` relayed before it no longer matches `recHash`. */
|
||||
rec_rev?: number;
|
||||
@@ -58,7 +58,9 @@ export interface GateList { schema_version: 1; run: string; gate_rev: number; it
|
||||
/** The plan's plain-language ask, read from the reviewed plan (lib/captain-brief.ts `buildEli5`); printed first. */
|
||||
eli5?: GateEli5;
|
||||
/** The plan's `### Owner's words` (lib/autoplan-owner-text.ts): the quotes a challenge must name to keep the plan's direction; `verified` when a recorded owner reply holds it. */
|
||||
owner_words?: { status: 'ok' | 'malformed' | 'none'; quotes: Array<{ n: number; who: string; text: string; verified: boolean }>; reason?: string; fix?: string };
|
||||
owner_words?: { status: 'ok' | 'malformed' | 'none'; quotes: Array<{ n: number; who: string; text: string; verified: boolean; line?: OwnerLine }>; reason?: string; fix?: string };
|
||||
/** A first version (a Day one section or `--first-version`): the owner brief adds the gstack-first-use line. */
|
||||
first_version?: boolean;
|
||||
/** The one-reviewer check of an unreviewed post-cap delta before a carry (lib/autoplan-carry.ts). */
|
||||
carry_check?: { attempt: string; model: string; verdict: 'passed' | 'failed' | 'unavailable'; max_severity: string; findings: number; at: string } }
|
||||
/** The captain approvals shape (crew/docs/captain.md § Approvals), section text taken from the reviewed plan; '' when absent. */
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { gateCost, gateCostSentence } from './autoplan-gate-cost';
|
||||
import { renderDayOne } from './autoplan-owner-text';
|
||||
import { renderOwnerPage } from './autoplan-owner-text';
|
||||
import { decisionId, PAGE_SIZE, renderGate, type GateList } from './gate-list';
|
||||
import { readJsonl, renderUrgentBlock, type DecisionRow } from './headless-artifacts';
|
||||
import type { ResultCodeName } from './result-codes';
|
||||
@@ -90,7 +90,7 @@ export function renderBrief(inputs: BriefInputs, o: { page?: number; summary?: s
|
||||
'',
|
||||
renderUrgentBlock(inputs.findings).trimEnd(),
|
||||
'',
|
||||
...renderDayOne(planText(o.outDir, inputs.run), inputs.gate.owner_words?.quotes),
|
||||
...renderOwnerPage(planText(o.outDir, inputs.run), inputs.gate.owner_words?.quotes, { firstVersion: inputs.gate.first_version }),
|
||||
'### Summary',
|
||||
'',
|
||||
plainSummary(inputs, o.summary),
|
||||
|
||||
@@ -207,8 +207,8 @@ export const CAPY_RESULT_CODES = {
|
||||
},
|
||||
FIRST_USE_PLAN_UNREADY: {
|
||||
anchor: 'first-use-plan-unready',
|
||||
summary: 'the plan has no usable ### Day one table to freeze (missing, malformed, fewer than five complete rows, or a row still marked assumed)',
|
||||
fix: 'add or fix the ### Day one table (action, frequency, source, feature, route, first build, check) and confirm every assumed row with the owner, then run start again',
|
||||
summary: 'the plan has no usable ### Day one table or ### Owner\'s words to freeze (missing, malformed, fewer than five complete rows, a row still marked assumed or citing no quote, or a quote with no time or line)',
|
||||
fix: 'quote the owner\'s messages that state the job under ### Owner\'s words (who, when, "words" → does it | choice), cite them from the five ### Day one rows as owner words <n>, then run start again',
|
||||
},
|
||||
FIRST_USE_PLAY_SPEC_INCOMPLETE: {
|
||||
anchor: 'first-use-play-spec-incomplete',
|
||||
@@ -232,7 +232,7 @@ export const CAPY_RESULT_CODES = {
|
||||
},
|
||||
FIRST_USE_REFUSED: {
|
||||
anchor: 'first-use-refused',
|
||||
summary: 'the build has not cleared its first-use check, so no "try this build" message or "v1 is ready" report may go out',
|
||||
fix: 'act on each reason the line lists: replay the failed or unplayed actions, rerun links within 15 minutes of sending, add the predicted score, or start a new run for a new build or changed day-one rows',
|
||||
summary: 'the build has not cleared its first-use check, so no try-it message or "v1 is ready" report may go out',
|
||||
fix: 'act on each reason the line lists: fix and replay each unplayed, broken, wrong, thin day-one or needs-lookup step, rerun links within 15 minutes of sending, add the predicted score, or start a new run for a new build or changed rows or quotes',
|
||||
},
|
||||
} satisfies Record<string, ResultCode>;
|
||||
Reference in new issue
Block a user