axstack 0.64.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/docs/workflows.md +21 -0
  2. package/package.json +1 -1
  3. package/skills/axstack/references/candidate-publication.md +6 -0
  4. package/skills/axstack/references/contracts.md +4 -0
  5. package/skills/axstack/references/design-lens.md +10 -0
  6. package/skills/axstack/references/lifecycle.md +2 -0
  7. package/skills/axstack/references/t3-runtime.md +8 -0
  8. package/skills/axstack/references/workspace-hygiene.md +5 -0
  9. package/skills/axstack/scripts/check-staged-file-tokens.js +1 -0
  10. package/skills/axstack/scripts/default-policy.js +1 -0
  11. package/skills/axstack/scripts/fleet-route-cli.js +2 -2
  12. package/skills/axstack/scripts/fleet-route-plan.js +2 -1
  13. package/skills/axstack/scripts/fleet-sample-io.js +1 -0
  14. package/skills/axstack/scripts/hub-usage.js +1 -1
  15. package/skills/axstack/scripts/readiness-run.js +2 -0
  16. package/skills/axstack/scripts/readiness.js +10 -5
  17. package/skills/axstack/scripts/resolve-models.js +3 -1
  18. package/skills/axstack/scripts/sync-default.js +1 -0
  19. package/skills/axstack/scripts/test-repository.js +1 -0
  20. package/skills/axstack/scripts/usage-split.js +286 -0
  21. package/skills/axstack-align/SKILL.md +11 -1
  22. package/skills/axstack-explain/SKILL.md +3 -0
  23. package/skills/axstack-explain/references/delivery.md +9 -0
  24. package/skills/axstack-explain/references/inline-pages.md +21 -0
  25. package/skills/axstack-implement/SKILL.md +8 -0
  26. package/skills/axstack-review/references/review-receipt.md +1 -1
  27. package/skills/axstack-spec/SKILL.md +7 -1
  28. package/skills/axstack-spec/references/format.md +11 -0
  29. package/skills/axstack-spec/references/prototype.md +125 -0
  30. package/skills/axstack-tickets/SKILL.md +2 -0
package/docs/workflows.md CHANGED
@@ -84,6 +84,27 @@ multi-PR or stacked work. Unclear work is clarified, then classified. A deeper p
84
84
  the same identity before action; missing preparation names the gap and holds
85
85
  only affected work.
86
86
 
87
+ ## Spec prototypes and downstream use
88
+
89
+ In delivery runs continuing to Spec, Align may defer an open look, behaviour
90
+ or state-model question as `Open (prototype):`. Before the first draft adviser
91
+ round, Spec's [prototype step](../skills/axstack-spec/references/prototype.md)
92
+ uses one isolated author to build a throwaway UI variant or logic demo. Only
93
+ prototype authors use its completion exemption from red/green logs. User
94
+ verdicts become binding `Decisions` rows; the prototype illustrates those rows.
95
+
96
+ At the verdict the driver makes one create-only `prototype-axstack-<slug>`
97
+ push, outside candidate-publication diligence, review and PR rules because
98
+ the ref never merges. Prototype authors remain retained until capture or
99
+ abandonment. Guarded worktree removal keeps the local branch.
100
+
101
+ Tickets copy the prototype record into each affected task. Implement reads
102
+ the pinned SHA as reference only, never merging or cherry-picking the branch.
103
+ Copied code goes through strict TDD and ordinary cross-model review. Follow
104
+ the rows for details they do not capture; an unfetchable SHA makes the
105
+ reference unavailable without holding implementation. Brainstorm remains
106
+ report-only under its existing rules.
107
+
87
108
  ## Weekly test-audit activation
88
109
 
89
110
  The packaged [weekly prompt](../skills/axstack/references/test-audit-weekly.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "axstack",
3
- "version": "0.64.0",
3
+ "version": "0.66.0",
4
4
  "description": "Axstack installer and setup CLI: installs owned chat skills and role data, configures supported harness settings, and checks T3 Code capabilities.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -1,5 +1,11 @@
1
1
  # Candidate publication
2
2
 
3
+ Only the driver's create-only `prototype-axstack-<slug>` push skips
4
+ candidate-publication diligence, review and PR rules, because that ref never merges.
5
+ This push is not candidate publication. Follow
6
+ [Spec prototypes](../../axstack-spec/references/prototype.md) for its capture
7
+ guards; no other push or candidate receives this exemption.
8
+
3
9
  Follow [Parallel-first delivery](parallel-first.md) for joined candidates: verify
4
10
  every required package and integration receipt before final publication. Partial
5
11
  assembly checks are provisional; package commits need no phantom package PRs.
@@ -32,6 +32,10 @@ Confirm the identity for the selected mode from the
32
32
  without an Axstack-created spec.
33
33
  - Read-only research, explanation, improvement discovery, and handoff: no baseline.
34
34
 
35
+ The sole pre-baseline prototype exception is bounded by
36
+ [Spec 3a](../../axstack-spec/references/prototype.md#authority-and-build);
37
+ it grants no candidate implementation or publication authority.
38
+
35
39
  Substantial means substantial features, multi-PR work, or stacked work; a
36
40
  bounded small feature is not substantial merely because it is called a
37
41
  feature. Clarify unclear size, then classify it. Alignment, spec writing, and
@@ -65,6 +65,16 @@ Rejected: <alternative -> why>
65
65
  Open: <question?>
66
66
  ```
67
67
 
68
+ Defer a look, behave, or state-model question discussion cannot settle only in
69
+ delivery runs whose substantial work continues to Spec, regardless of rung.
70
+ Otherwise settle it by discussion: no deferral for small-change, planning-only,
71
+ read-only or stop-after-phase work (including "write the spec and stop").
72
+ Tag the sketch's Open line or a read-back item `Open (prototype): <question>`.
73
+ A plain `Open:` retains its existing meaning. A deferral never blocks Align
74
+ completion. Ask questions on deferred items in Spec within Align's cumulative
75
+ count. Questions on deferred items need no refinement opt-in; follow
76
+ [Spec 3a](../../axstack-spec/references/prototype.md).
77
+
68
78
  Keep settled choices in `Decisions` rows. `CONTEXT.md` stays a glossary; ADRs
69
79
  keep their existing test. Add no design document or phase.
70
80
 
@@ -111,6 +111,8 @@ Delegated notifications wake the driver; a launched
111
111
  writer sends its marker with `t3_thread_send` using `mode: queue` to the recorded driver thread.
112
112
  Delegated completion requires persisted `task_status` before `t3_thread_read`, terminal `completed`, `result_available`, `hasPendingChildRuns:false`, and final `AXSTACK-DONE`.
113
113
  Delegated author completion requires delegated terminal checks plus candidate checks: non-empty diff, clean tree and named red/green logs.
114
+ Only prototype authors use the no-red/green-log completion exemption in
115
+ [Spec prototypes](../../axstack-spec/references/prototype.md).
114
116
  A delegated repair uses a stable clientRequestId with `t3_thread_send(childThreadId, mode:queue, clientRequestId)` to the same author in the same worktree and branch, records the returned taskId and verifies the existing candidate head.
115
117
  Repairs never repeat fresh checkout step 1.
116
118
  Launched fallback writer completion requires `AXSTACK-DONE` plus terminal `t3_thread_wait` on the recorded run and candidate checks: non-empty diff, clean tree, and named red/green logs.
@@ -223,6 +223,10 @@ a missing or equal path holds review.
223
223
 
224
224
  The UI verifier checkout row applies to candidate checks, while a page without
225
225
  a candidate follows [UI verification](ui-verification.md).
226
+ For a prototype, the `axstack-ui-verifier` dispatch binds to the prototype SHA
227
+ on a detached checkout under [Spec prototypes](../../axstack-spec/references/prototype.md).
228
+ The author retention endpoint for prototypes is capture or abandonment under
229
+ that reference; keep the author worktree and thread until then.
226
230
 
227
231
  The driver must be the sole run-record writer and enforce one writer per
228
232
  candidate; it never writes tracked candidate source or tests or repairs an author's source.
@@ -253,6 +257,8 @@ during recovery. Substring matches do not establish identity. Branch and task
253
257
  identity continue to use the original dispatch key. On title regeneration preserve
254
258
  explicit role-labelled dispatch keys and `Needs you:` notices unchanged.
255
259
  Each dispatch binds the approved spec or small-change intent, brief, authority, role snapshot, base and candidate to its dispatch key.
260
+ The prototype author dispatch binds to the deferred question and current draft
261
+ revision in place of an approved identity; all other bindings remain required.
256
262
  Every dispatch brief must state that dispatched roles never call `html_render`.
257
263
  Dispatched roles may call `html_preview` within [UI verification](ui-verification.md).
258
264
 
@@ -311,6 +317,8 @@ incomplete even when native status says completed.
311
317
 
312
318
  Delegated author completion requires delegated terminal checks plus candidate checks:
313
319
  non-empty diff, clean tree and named red/green logs.
320
+ Only prototype authors use the no-red/green-log completion exemption in
321
+ [Spec prototypes](../../axstack-spec/references/prototype.md).
314
322
 
315
323
  Launched writer completion must require terminal `t3_thread_wait` on that run,
316
324
  then candidate checks: non-empty diff, clean tree and named red/green logs.
@@ -74,6 +74,11 @@ For close-out holds, follow the [run-record acceptance rules](run-record.md#clos
74
74
  A missing or failed settle readback never triggers author repair: it holds only that dispatch's next advancement (publication, review routing, merge-ready) until resolved.
75
75
  Settling never removes, archives or abandons the thread or worktree.
76
76
  Retain each author worktree and thread unarchived until the PR merges or closes.
77
+ For prototype authors only, capture or abandonment replaces that endpoint under
78
+ [Spec prototypes](../../axstack-spec/references/prototype.md). A prototype
79
+ worktree is removable when remote readback matches the author head, or when
80
+ the prototype is abandoned and its tree is clean. Keep the local branch.
81
+ Existing terminal, ownership and evidence guards still apply.
77
82
  Repairs return to the responsible package or integration author in that author's
78
83
  existing session and worktree.
79
84
  On forge-confirmed merge or closure, follow [Native PR links and watches](t3-runtime.md#native-pr-links-and-watches)
@@ -46,6 +46,7 @@ try {
46
46
  ${advisories.join('\n')}
47
47
  Review file structure and responsibilities; no size-only split or approval is required.`);
48
48
  }
49
+ console.log('Staged-file token check passed.');
49
50
  } catch (error) {
50
51
  console.error(`Staged-file token check failed: ${error.message}`);
51
52
  process.exit(1);
@@ -22,6 +22,7 @@ function pool(accounts, driver, now) {
22
22
  const rows = members.map((a) => {
23
23
  const u = a.usageLimits;
24
24
  if (u?.unavailable || !fresh(u?.checkedAt, now, 300000) || !Array.isArray(u?.windows)) throw Error(`unknown ${driver} telemetry`);
25
+ /** @type {{ used: number, elapsed: number | null, resetKnown?: boolean }[]} */
25
26
  const windows = ['session', 'weekly'].map((kind) => {
26
27
  const found = u.windows.filter((w) => w.kind === kind && !(driver === 'claudeAgent' && w.id?.startsWith('seven_day_')));
27
28
  const weeklyOnly = driver === 'codex' ? 'verified Codex weekly-only response' : 'verified Claude weekly-only response';
@@ -78,8 +78,8 @@ export async function main(argv) {
78
78
  const result = (planning ? planIntake : recommend)({ ...input, configText, configDigest,
79
79
  request: args['--task'] ? { ...input.request, task: args['--task'] } : input.request }, now);
80
80
  process.stdout.write(args['--json'] || planning ? `${JSON.stringify(result)}\n`
81
- : `${result.stage}: ${result.selected?.hostId ?? 'no host'} (${result.reason})\n`);
82
- return planning ? result.disposition === 'hold' ? 2 : 0 : result.selected ? 0 : 2;
81
+ : `${/** @type {ReturnType<typeof recommend>} */ (result).stage}: ${result.selected?.hostId ?? 'no host'} (${result.reason})\n`);
82
+ return planning ? /** @type {ReturnType<typeof planIntake>} */ (result).disposition === 'hold' ? 2 : 0 : result.selected ? 0 : 2;
83
83
  } catch (error) {
84
84
  process.stderr.write(`${JSON.stringify({ error: { code: error.message.split(':')[0], message: error.message } })}\n`);
85
85
  return 1;
@@ -45,6 +45,7 @@ export function planIntake(input, now) {
45
45
  const config = parseFleetConfig(input.configText, input.configDigest);
46
46
  if (input.request?.role !== 'driver') throw new Error('driver-role-required');
47
47
  const initial = recommend(input, now); // Validate and rank the unchanged supplied facts.
48
+ /** @type {{ code: string, state: string, environmentId?: string, evidence: unknown }[]} */
48
49
  const terms = initial.excluded.map((e) => ({ code: 'route-eligibility',
49
50
  state: e.reasons.some((r) => /unproven|missing/.test(r)) ? 'unknown' : 'fail',
50
51
  environmentId: e.environmentId, evidence: e }));
@@ -54,7 +55,7 @@ export function planIntake(input, now) {
54
55
  terms.push(...localTerms.map((t) => ({ ...t, environmentId: input.origin.environmentId })));
55
56
  return localTerms.every((t) => t.state === 'pass');
56
57
  };
57
- const result = (disposition, reason, selected = null, extra = {}) => structuredClone({
58
+ const result = (disposition, reason, selected = null, extra = /** @type {{ launch?: object }} */ ({})) => structuredClone({
58
59
  schemaVersion: 1, kind: 'intake-plan', configDigest: input.configDigest, evaluatedAt: now,
59
60
  request: input.request, disposition, reason, selected, terms,
60
61
  counts: Object.fromEntries(['pass', 'fail', 'unknown', 'n/a'].map((s) => [s, terms.filter((t) => t.state === s).length])),
@@ -7,6 +7,7 @@ export function sshArgv(host) {
7
7
  '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no',
8
8
  ...(host.user ? ['-l', host.user] : []), '--', host.destination, PROC_COMMAND];
9
9
  }
10
+ /** @returns {Promise<void>} */
10
11
  export function wait(ms, signal) {
11
12
  return new Promise((resolve, reject) => {
12
13
  const cancel = () => { clearTimeout(timer); signal.removeEventListener('abort', cancel); reject(signal.reason); };
@@ -11,7 +11,7 @@ function claudeWeeklyOnly(usage, now) {
11
11
  || usage.seven_day_opus != null || usage.seven_day_sonnet != null) return false;
12
12
  const aggregate = usage.limits.filter((w) => w?.kind === 'weekly_all');
13
13
  return aggregate.length === 1 && usage.limits.every((w) => {
14
- if (!w || w.group !== 'weekly' || typeof w.is_active !== 'boolean' || !percent(w.percent)
14
+ if (w?.group !== 'weekly' || typeof w.is_active !== 'boolean' || !percent(w.percent)
15
15
  || !reset(w.resets_at)) return false;
16
16
  if (w.kind === 'weekly_all') return w.is_active === true && w.scope === null
17
17
  && w.percent === weekly.utilization && w.resets_at === weekly.resets_at;
@@ -5,6 +5,7 @@ const installs = {
5
5
  bun: ['install', '--frozen-lockfile'], npm: ['ci'],
6
6
  pnpm: ['install', '--frozen-lockfile'], yarn: ['install', '--immutable'],
7
7
  };
8
+ /** @type {[string, string[]][]} */
8
9
  const groups = [['env.build', ['build']], ['testing.test', ['test']], ['testing.lint-typecheck', ['lint', 'typecheck']]];
9
10
  const drainGraceMs = 200;
10
11
  // No shell interpolation, and the wrapper preserves the command's allowlisted env.
@@ -57,6 +58,7 @@ async function runCommand(commands, paths, kind, argv, cwd, env, limits, state,
57
58
  clearTimeout(timer);
58
59
  killGroup(proc);
59
60
  });
61
+ /** @type {Promise<void>} */
60
62
  const timeout = new Promise((resolve) => {
61
63
  timer = setTimeout(() => { step.timedOut = true; killGroup(proc); resolve(); }, limits.timeoutMs);
62
64
  });
@@ -6,6 +6,7 @@ import { executeDeclared } from './readiness-run.js';
6
6
  const scriptVersion = '1.1.0';
7
7
  const criteriaVersion = 1;
8
8
 
9
+ /** @param {"ignore" | Uint8Array} [stdin] */
9
10
  function gitOutput(repo, args, stdin = 'ignore') {
10
11
  const argv = gitArgv('-C', repo, ...args);
11
12
  const result = Bun.spawnSync(argv, { stdout: 'pipe', stderr: 'pipe', stdin });
@@ -110,10 +111,12 @@ const definitions = [
110
111
  ];
111
112
 
112
113
  function packageManager(files, pkg) {
113
- const locks = [
114
+ /** @type {[string, string[]][]} */
115
+ const lockfiles = [
114
116
  ['bun', ['bun.lock', 'bun.lockb']], ['npm', ['package-lock.json', 'npm-shrinkwrap.json']],
115
117
  ['pnpm', ['pnpm-lock.yaml']], ['yarn', ['yarn.lock']],
116
- ].filter(([, names]) => names.some(files.has));
118
+ ];
119
+ const locks = lockfiles.filter(([, names]) => names.some(files.has));
117
120
  if (!locks.length) {
118
121
  const dependencyFields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'bundledDependencies', 'bundleDependencies', 'workspaces'];
119
122
  if (!files.has('pnpm-workspace.yaml') && dependencyFields.every((field) => !pkg?.[field] || Object.keys(pkg[field]).length === 0)) {
@@ -130,7 +133,9 @@ function packageManager(files, pkg) {
130
133
 
131
134
  function declaredCommands(files, pkg, manager, set, invalidPackage) {
132
135
  const prose = files.paths.filter((path) => /\.md$/i.test(path)).map((path) => files.read(path)).join('\n');
133
- for (const [id, names] of [['env.build', ['build']], ['testing.test', ['test']], ['testing.lint-typecheck', ['lint', 'typecheck']]]) {
136
+ /** @type {[string, string[]][]} */
137
+ const groups = [['env.build', ['build']], ['testing.test', ['test']], ['testing.lint-typecheck', ['lint', 'typecheck']]];
138
+ for (const [id, names] of groups) {
134
139
  if (invalidPackage) {
135
140
  set(id, 'unknown', [`git show ${files.revision}:package.json`], 'invalid package.json');
136
141
  continue;
@@ -189,9 +194,9 @@ function assess(files) {
189
194
  const codeql = [];
190
195
  for (const path of workflows) {
191
196
  try {
192
- const workflow = Bun.YAML.parse(files.read(path));
197
+ const workflow = /** @type {{ on?: string | string[] | Record<string, unknown>, jobs?: Record<string, { steps?: { run?: string, uses?: string }[] }> }} */ (Bun.YAML.parse(files.read(path)));
193
198
  const trigger = workflow?.on;
194
- const pr = trigger === 'pull_request' || (Array.isArray(trigger) ? trigger.includes('pull_request') : trigger && Object.hasOwn(trigger, 'pull_request'));
199
+ const pr = trigger === 'pull_request' || (Array.isArray(trigger) ? trigger.includes('pull_request') : trigger && Object.hasOwn(/** @type {Record<string, unknown>} */ (trigger), 'pull_request'));
195
200
  const steps = Object.values(workflow?.jobs ?? {}).flatMap((job) => job?.steps ?? []);
196
201
  const runs = steps.map((step) => step?.run).filter((run) => typeof run === 'string');
197
202
  if (steps.some((step) => typeof step?.uses === 'string' && /^github\/codeql-action\//.test(step.uses))) codeql.push(path);
@@ -48,7 +48,9 @@ function providerFrom(catalog, provider) {
48
48
  return instance;
49
49
  }
50
50
 
51
- function modelFrom(models, { provider, model: pin, class: modelClass, excluded }) {
51
+ /** @param {{ provider?: string, model?: string, class?: string, excluded: string[] }} options */
52
+ function modelFrom(models, options) {
53
+ const { provider, model: pin, class: modelClass, excluded } = options;
52
54
  if (pin && pin !== 'null') {
53
55
  const model = models.find((model) => model.id === pin && !excluded.includes(model.id));
54
56
  if (!model) throw new Error(`missing requested model ${pin}`);
@@ -60,6 +60,7 @@ async function main() {
60
60
  try { history = JSON.parse(fs.readFileSync(options['--history-file'], 'utf8')); }
61
61
  catch { history = { unavailable: 'history file unavailable or malformed' }; }
62
62
  } else history = readHistory(path, now, options['--history-db']);
63
+ /** @type {ReturnType<typeof decide> & { mode?: string }} */
63
64
  const result = decide(settings, usage, catalogs, now, history);
64
65
  if (result.action === 'update' && options['--apply']) {
65
66
  const status = commit(path, original, result.selection);
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env bun
2
+ export {};
2
3
  // Repository test entry point: keep DAC permission fixtures meaningful as root.
3
4
  const args = process.argv.slice(2);
4
5
  if (args[0] === '--help') {
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env bun
2
+ import { Database } from 'bun:sqlite';
3
+ import { existsSync, writeFileSync } from 'node:fs';
4
+
5
+ const HELP = `usage-split — offline cost baseline (R2 fact mode)
6
+ bun usage-split.js --cache FILE --rates FILE --state FILE --prs FILE --start ISO --end ISO [--billed FILE] [--out FILE]
7
+ --cache FILE Saved usage-scan-cache JSON, version 11; models/sessions/files dictionaries.
8
+ Rows: [timestampMs, modelIndex, sessionIndex, input, cacheRead, cacheWrite, output, reasoning, requestId].
9
+ Reasoning is included in output, never added again. Interval is [start,end).
10
+ --rates FILE Saved model-rates JSON: {document:{exactModelName:{input_cost_per_token,
11
+ cache_read_input_token_cost, cache_creation_input_token_cost, output_cost_per_token}}}.
12
+ --state FILE Saved standalone statev2 SQLite (no WAL), or JSON array of provider-thread rows,
13
+ or {providers:[],threads:[],runs:[]}. Provider rows: thread_id and payload_json
14
+ with nativeThreadRef.nativeId; normalized {thread,native} also accepted.
15
+ Optional thread metadata: thread_id,title,lineage,prs (URLs or {url}); runs: thread_id,turns.
16
+ SQLite reads provider_threads, optional threads, and interval-filtered aggregate runs.
17
+ Without a runs export/table, turn and usage coverage remain unknown.
18
+ JSON payload_json metadata accepted.
19
+ Export titles/lineage/PR links for full role inference. Absent metadata stays unknown.
20
+ --prs FILE JSON array of ten {url,mergedAt,mergeCommit} identities (40-char SHA).
21
+ Merge dates must lie in the interval. Supplied identities are not verified online.
22
+ --start ISO Inclusive timestamp, with timezone.
23
+ --end ISO Exclusive timestamp, with timezone.
24
+ --billed FILE Optional {usd,start,end,evidence} for this exact interval; otherwise billed cost unknown.
25
+ --out FILE Exclusively create this report; existing files are refused. Default: stdout only.
26
+ --help Show flags, formats, effects and limitations.
27
+ Side effects: none by default. --out creates only the caller-named report (also printed to stdout).
28
+ No network, dispatch, subprocess, live cache refresh, database sidecar, scheduling or persistent state.
29
+ SQLite is deserialized read-only in memory; supply a saved export, not a live database.
30
+ Role precedence follows the token-split audit: explicit roles, delegated title, coordinator titles, root driver.
31
+ PR links are thread-level associations, not request-level proof; shared work is never divided.
32
+ Proxy: exact-name base API rates only, excluding subscription/tier/priority premiums; never a bill.
33
+ Exit: 0 measured (including failed terms), 1 invalid input/error, 2 incomplete (unknown terms).
34
+ `;
35
+ const fields = ['input', 'cacheRead', 'cacheWrite', 'output'];
36
+ const rateFields = ['input_cost_per_token', 'cache_read_input_token_cost', 'cache_creation_input_token_cost', 'output_cost_per_token'];
37
+ const validNumber = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
38
+ const validCount = (n) => Number.isSafeInteger(n) && n >= 0;
39
+ const sha256 = (bytes) => new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
40
+ const add = (a, b) => a === null || b === null ? null : a + b;
41
+ const timestamp = (s) => typeof s === 'string' && /T.*(?:Z|[+-]\d\d:\d\d)$/.test(s) ? Date.parse(s) : NaN;
42
+
43
+ function decoded(s) {
44
+ for (let n = 0; n < 3; n++) {
45
+ try { const next = decodeURIComponent(s); if (next === s) break; s = next; } catch { break; }
46
+ }
47
+ return s;
48
+ }
49
+
50
+ // Order is intentional: identical to the audited measure.ts classifier.
51
+ function classify(t) {
52
+ const title = (t.title ?? '').toLowerCase(), id = decoded(t.thread_id).toLowerCase(), text = `${title} ${id}`;
53
+ const role = text.match(/axstack-(?:author|reviewer|review|verifier|verify|diligence|readiness|advisor|adviser|escalation|auditor|owner|research|explainer|explore|scout|judge|brainstorm)[a-z0-9-]*/)?.[0] ?? null;
54
+ const delegated = t.lineage?.relationshipToParent === 'subagent' || t.thread_id.startsWith('thread:delegated-task:');
55
+ const result = (cls, type) => ({ class: cls, type, role });
56
+ if (t.unmatched) return result('other', 'Unmapped transcripts');
57
+ if (/axstack-author\b/.test(role ?? '')) return result('authoring', 'Authors');
58
+ if (/axstack-owner\b/.test(role ?? '')) return result('orchestration overhead', 'PR owners');
59
+ if (/axstack-(verifier|verify|diligence|readiness)\b/.test(role ?? '') || /axstack-reviewer[^: ]*verif/.test(role ?? '')) return result('verification', 'Verification / diligence');
60
+ if (/axstack-review(?:er)?\b/.test(role ?? '') || /axstack-explainer-review\b/.test(role ?? '')) return result('review', 'Reviewers');
61
+ if (/axstack-(advisor|adviser|escalation)\b/.test(role ?? '')) return result('orchestration overhead', 'Advisers / escalation');
62
+ if (/axstack-auditor\b/.test(role ?? '')) return result('other', 'Audits');
63
+ if (/axstack-(research|explore|scout)\b/.test(role ?? '')) return result('other', 'Research / exploration');
64
+ if (/axstack-explainer\b/.test(role ?? '')) return result('other', 'Explainers');
65
+ if (/collector/.test(title)) return result('orchestration overhead', 'Fleet collectors');
66
+ if (/axstack review manager|review manager pass/.test(title)) return result('orchestration overhead', 'Review-manager passes');
67
+ if (delegated && /review-mgr.*owner/.test(id)) return result('orchestration overhead', 'PR owners');
68
+ if ((delegated && /\b(author|implement)\b/.test(title)) || /^(worker|author):/.test(title)) return result('authoring', 'Authors');
69
+ if (delegated && /\b(verif|uiv|readiness|pentest|test[- :]|diligence)/.test(`${title} ${id.split('delegate-task:').pop()}`)) return result('verification', 'Verification / diligence');
70
+ if ((delegated && /\b(review|rev[- :])/.test(title)) || /^reviewer:/.test(title)) return result('review', 'Reviewers');
71
+ if (delegated && /\b(adviser|advisor|escalation)\b/.test(title)) return result('orchestration overhead', 'Advisers / escalation');
72
+ if (/settle|settlement|close.?out|cleanup/.test(title)) return result('orchestration overhead', 'Settlement / cleanup');
73
+ if (/watch|babysit|monitor.*pr|run[- ]wake/.test(title)) return result('orchestration overhead', 'Watches / PR monitoring');
74
+ if (/review github and linear activity|^voa$|scheduled|schedule|periodic|status sweep|automation/.test(title)) return result('orchestration overhead', 'Schedules / status sweeps');
75
+ if (!t.title && !role) return result('other', 'Unknown metadata');
76
+ if (!role && !/^(researcher|subagent):/.test(title) && !delegated) return result('orchestration overhead', 'Drivers (mixed work)');
77
+ if (delegated && /research|scout/.test(title)) return result('other', 'Research / exploration');
78
+ return result('other', 'Other role / unresolved');
79
+ }
80
+
81
+ function readState(bytes, start, end) {
82
+ if (bytes.subarray(0, 16).toString() !== 'SQLite format 3\0') {
83
+ const saved = JSON.parse(bytes.toString());
84
+ return Array.isArray(saved) ? { providers: saved, threads: saved } : saved;
85
+ }
86
+ // Deserialization cannot create journals, WAL/SHM files or mutate the saved DB.
87
+ const db = Database.deserialize(bytes, { readonly: true });
88
+ try {
89
+ const table = (name) => db.query('SELECT name FROM sqlite_master WHERE type=\'table\' AND name=?').get(name);
90
+ return {
91
+ providers: db.query('SELECT thread_id,payload_json FROM orchestration_v2_projection_provider_threads').all(),
92
+ threads: table('orchestration_v2_projection_threads')
93
+ ? db.query('SELECT thread_id,title,payload_json FROM orchestration_v2_projection_threads').all() : [],
94
+ runs: table('orchestration_v2_projection_runs')
95
+ ? db.query('SELECT thread_id,count(*) AS turns FROM orchestration_v2_projection_runs WHERE requested_at>=? AND requested_at<? GROUP BY thread_id').all(start, end) : undefined,
96
+ };
97
+ } finally { db.close(); }
98
+ }
99
+
100
+ const payload = (row) => typeof row.payload_json === 'string' ? JSON.parse(row.payload_json) : row.payload_json ?? {};
101
+ const prUrl = (p) => typeof p === 'string' ? p : p?.url;
102
+ const meter = () => ({ input: 0, cacheRead: 0, cacheWrite: 0, output: 0, tokens: 0, observedTokens: 0,
103
+ records: 0, knownRateProxyUsd: 0, unpricedTokens: 0 });
104
+ function accumulate(target, source) {
105
+ for (const key of Object.keys(meter())) target[key] = add(target[key], source[key]);
106
+ }
107
+
108
+ function measure(cache, rates, state, prs, start, end, term) {
109
+ const threads = new Map();
110
+ for (const row of state.threads ?? []) {
111
+ const p = payload(row), id = row.thread_id ?? row.thread;
112
+ if (typeof id !== 'string') continue;
113
+ const prior = threads.get(id);
114
+ threads.set(id, { ...p, ...row, thread_id: id, lineage: row.lineage ?? p.lineage,
115
+ prs: row.prs ?? [p.linkedPullRequest, p.branchPullRequest, ...p.pullRequests ?? []].filter(Boolean),
116
+ turns: prior?.turns ?? (Array.isArray(state.runs) ? 0 : null), usage: prior?.usage ?? meter() });
117
+ }
118
+ const native = new Map();
119
+ for (const row of state.providers ?? []) {
120
+ const id = row.thread_id ?? row.thread, session = row.native ?? payload(row).nativeThreadRef?.nativeId;
121
+ if (typeof id !== 'string' || typeof session !== 'string') continue;
122
+ const ids = native.get(session) ?? new Set(); ids.add(id); native.set(session, ids);
123
+ if (!threads.has(id)) threads.set(id, { thread_id: id, turns: Array.isArray(state.runs) ? 0 : null, usage: meter(), prs: [] });
124
+ }
125
+ const invalidRows = [], unknownThreads = [];
126
+ for (const [index, run] of (state.runs ?? []).entries()) {
127
+ const id = run?.thread_id;
128
+ let t = threads.get(id);
129
+ if (!t) {
130
+ unknownThreads.push({ index, threadId: id ?? null });
131
+ if (typeof id !== 'string') continue;
132
+ t = { thread_id: id, turns: null, uncertainTurns: true, usage: meter(), prs: [] };
133
+ threads.set(id, t);
134
+ }
135
+ if (!validCount(run.turns)) {
136
+ invalidRows.push({ index, threadId: id, turns: run.turns ?? null });
137
+ t.turns = null; t.uncertainTurns = true;
138
+ } else t.turns = add(t.turns, run.turns);
139
+ }
140
+ const runsSupplied = Array.isArray(state.runs);
141
+ const runDataComplete = runsSupplied && !invalidRows.length && !unknownThreads.length;
142
+ term('run-counts', runDataComplete ? 'pass' : 'unknown',
143
+ { invalidRows, unknownThreads, note: 'Absent or invalid aggregate turns and unknown-thread turns remain null.' });
144
+ const totals = meter(), seen = new Set();
145
+ let duplicatesRemoved = 0, ambiguousRecords = 0, invalidRecords = 0, missingComponents = 0, unpricedRecords = 0, maxTs = null;
146
+ for (const v of Object.values(cache.files)) {
147
+ if (!Array.isArray(v?.r)) { invalidRecords++; continue; }
148
+ for (const row of v.r) {
149
+ if (!Array.isArray(row) || !validNumber(row[0])) { invalidRecords++; continue; }
150
+ if (row[0] < start || row[0] >= end) continue;
151
+ const session = cache.sessions[row[2]], model = cache.models[row[1]];
152
+ const key = JSON.stringify([v.p, session, row[8] || row[0], row[1], ...row.slice(3, 8)]);
153
+ if (seen.has(key)) { duplicatesRemoved++; continue; }
154
+ seen.add(key); maxTs = Math.max(maxTs ?? row[0], row[0]);
155
+ const ids = typeof session === 'string' ? native.get(session) : null;
156
+ if (ids?.size > 1) {
157
+ ambiguousRecords++;
158
+ for (const candidate of ids) threads.get(candidate).uncertainUsage = true;
159
+ }
160
+ const id = ids?.size === 1 ? [...ids][0] : `UNMAPPED:${v.p}:${session ?? key}`;
161
+ if (!threads.has(id)) threads.set(id, { thread_id: id, unmatched: true, turns: null, usage: meter(), prs: [] });
162
+ const usage = meter(), parts = fields.map((_, i) => validCount(row[i + 3]) ? row[i + 3] : null);
163
+ for (let i = 0; i < fields.length; i++) usage[fields[i]] = parts[i];
164
+ usage.tokens = parts.reduce(add, 0); usage.observedTokens = parts.reduce((n, x) => n + (x ?? 0), 0); usage.records = 1;
165
+ if (usage.tokens === null) missingComponents++;
166
+ const rate = rates.document?.[model];
167
+ const priced = usage.tokens !== null && rate && validNumber(rate.input_cost_per_token) && validNumber(rate.output_cost_per_token)
168
+ && parts.every((n, i) => n === 0 || validNumber(rate[rateFields[i]]));
169
+ if (priced) usage.knownRateProxyUsd = parts.reduce((sum, n, i) => sum + n * (rate[rateFields[i]] ?? 0), 0);
170
+ else { usage.unpricedTokens = usage.tokens; unpricedRecords++; }
171
+ accumulate(totals, usage); accumulate(threads.get(id).usage, usage);
172
+ }
173
+ }
174
+ const classes = new Map(), roleMapping = [], shared = [], unattributed = [], exclusive = new Map(), perPrShared = new Map();
175
+ const attribution = { exclusiveTokens: 0, sharedTokens: 0, unattributedTokens: 0, unmatchedTokens: 0, observedUnattributedTokens: 0 };
176
+ let missingUsageThreads = 0, unknownMetadata = 0;
177
+ for (const t of threads.values()) {
178
+ if (!t.turns && !t.usage.records && !t.uncertainUsage && !t.uncertainTurns) continue;
179
+ const role = classify(t), missing = !t.usage.records;
180
+ const row = { threadId: t.thread_id, ...role, tokens: missing || t.uncertainUsage ? null : t.usage.tokens,
181
+ observedTokens: t.usage.observedTokens, turns: t.turns, records: t.usage.records };
182
+ roleMapping.push(row);
183
+ if (missing) missingUsageThreads++;
184
+ if (role.type === 'Unknown metadata') unknownMetadata++;
185
+ const cls = classes.get(role.class) ?? { class: role.class, ...meter(), threads: 0, turns: 0, unmatchedSessions: 0, missingUsageThreads: 0 };
186
+ cls.threads += t.unmatched ? 0 : 1; cls.unmatchedSessions += t.unmatched ? 1 : 0;
187
+ if (!t.unmatched) cls.turns = add(cls.turns, t.turns);
188
+ cls.missingUsageThreads += missing ? 1 : 0;
189
+ accumulate(cls, t.usage); classes.set(role.class, cls);
190
+ const links = [...new Set((t.prs ?? []).map(prUrl).filter(Boolean))];
191
+ if (t.unmatched) attribution.unmatchedTokens = add(attribution.unmatchedTokens, row.tokens);
192
+ if (links.length > 1) {
193
+ shared.push({ ...row, prs: links }); attribution.sharedTokens = add(attribution.sharedTokens, row.tokens);
194
+ for (const link of links) perPrShared.set(link, add(perPrShared.has(link) ? perPrShared.get(link) : 0, row.tokens));
195
+ } else if (links.length === 1 && prs.some((p) => p.url === links[0])) {
196
+ exclusive.set(links[0], add(exclusive.has(links[0]) ? exclusive.get(links[0]) : 0, row.tokens));
197
+ attribution.exclusiveTokens = add(attribution.exclusiveTokens, row.tokens);
198
+ } else {
199
+ unattributed.push({ ...row, prs: links }); attribution.unattributedTokens = add(attribution.unattributedTokens, row.tokens);
200
+ attribution.observedUnattributedTokens += row.observedTokens;
201
+ }
202
+ }
203
+ term('token-components', missingComponents || invalidRecords ? 'unknown' : 'pass', { missingComponents, invalidRecords, formula: fields.join(' + '), reasoningIncludedInOutput: true });
204
+ term('native-join', ambiguousRecords ? 'unknown' : 'pass', { ambiguousRecords, unmatchedTokens: attribution.unmatchedTokens });
205
+ term('usage-coverage', !runDataComplete || missingUsageThreads ? 'unknown' : 'pass', { runsSupplied, missingUsageThreads, note: 'Class tokens count observed cache records only; missing-thread tokens remain null.' });
206
+ term('role-mapping', unknownMetadata ? 'unknown' : 'pass', { unknownMetadata, method: 'audit role precedence; inferred roles; root drivers contain mixed work' });
207
+ term('rates', unpricedRecords ? 'unknown' : 'pass', { unpricedRecords, unpricedTokens: totals.unpricedTokens, method: 'exact model name, base per-token rates; premiums unknown' });
208
+ term('attribution', unattributed.length || shared.length ? 'unknown' : 'pass', { ...attribution, note: 'Thread associations only; shared work is reported without allocation.' });
209
+ const prReports = prs.map((pr, i) => {
210
+ const hasData = exclusive.has(pr.url) || perPrShared.has(pr.url), empty = runDataComplete && !totals.records && !missingUsageThreads;
211
+ const ex = hasData || empty ? exclusive.has(pr.url) ? exclusive.get(pr.url) : 0 : null;
212
+ const sh = hasData || empty ? perPrShared.has(pr.url) ? perPrShared.get(pr.url) : 0 : null;
213
+ const observed = add(ex, sh), fraction = observed ? ex / observed : null;
214
+ term(`pr:${i + 1}`, !runDataComplete ? 'unknown' : empty ? 'n/a' : !hasData || observed === null ? 'unknown' : 'pass', { url: pr.url, exclusiveTokens: ex, sharedTokens: sh, exclusiveFraction: fraction, denominator: 'only observed tokens linked to this PR; total real PR cost unknown' });
215
+ return { ...pr, exclusiveTokens: ex, sharedTokens: sh, observedTokens: observed, exclusiveFraction: fraction };
216
+ });
217
+ return { totals, classes: [...classes.values()].sort((a, b) => b.observedTokens - a.observedTokens), roleMapping,
218
+ shared, unattributed, attribution, prs: prReports, duplicatesRemoved, ambiguousRecords,
219
+ maxUsageTimestamp: maxTs === null ? null : new Date(maxTs).toISOString() };
220
+ }
221
+
222
+ async function main(argv) {
223
+ if (argv.includes('--help')) {
224
+ if (argv.length !== 1) throw Error('Use --help alone');
225
+ console.log(HELP); return 0;
226
+ }
227
+ const flags = {}, allowed = ['cache', 'rates', 'state', 'prs', 'start', 'end', 'billed', 'out'];
228
+ for (let i = 0; i < argv.length; i += 2) {
229
+ const key = argv[i].slice(2), value = argv[i + 1];
230
+ if (!argv[i].startsWith('--') || !allowed.includes(key) || !value || value.startsWith('--')) throw Error(`Invalid flag/value: ${argv[i]}`);
231
+ if (Object.hasOwn(flags, key)) throw Error(`Repeated flag: --${key}`);
232
+ flags[key] = value;
233
+ }
234
+ for (const key of allowed.slice(0, 6)) if (!flags[key]) throw Error(`Required --${key}; see --help`);
235
+ const start = timestamp(flags.start), end = timestamp(flags.end);
236
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start >= end) throw Error('Require valid --start < --end with timezone');
237
+ const interval = { start: new Date(start).toISOString(), end: new Date(end).toISOString(), endExclusive: true };
238
+ const terms = [], inputs = {}, data = {};
239
+ const term = (id, status, evidence) => terms.push({ id, status, evidence: [evidence] });
240
+ for (const key of ['cache', 'rates', 'state', 'prs', 'billed']) {
241
+ if (!flags[key]) continue;
242
+ try {
243
+ if (key === 'state' && (existsSync(`${flags[key]}-wal`) || existsSync(`${flags[key]}-shm`))) {
244
+ term('input:state', 'unknown', 'Require standalone saved SQLite, without WAL/SHM sidecars'); continue;
245
+ }
246
+ const bytes = Buffer.from(await Bun.file(flags[key]).arrayBuffer());
247
+ inputs[key] = { path: flags[key], bytes: bytes.length, sha256: sha256(bytes) };
248
+ data[key] = key === 'state' ? readState(bytes, interval.start, interval.end) : JSON.parse(bytes.toString());
249
+ term(`input:${key}`, 'pass', inputs[key]);
250
+ } catch (error) {
251
+ if (['ENOENT', 'EACCES', 'EPERM', 'EBUSY'].includes(error.code)) term(`input:${key}`, 'unknown', { path: flags[key], error: error.code });
252
+ else throw error;
253
+ }
254
+ }
255
+ const snapshot = { inputs, sha256: sha256(JSON.stringify({ interval, inputs: Object.entries(inputs).map(([k, v]) => [k, v.sha256]) })) };
256
+ const report = { interval, snapshot, terms, billedCost: null };
257
+ if (['cache', 'rates', 'state', 'prs'].every((key) => Object.hasOwn(data, key))) {
258
+ if (!Array.isArray(data.prs)) throw Error('--prs must contain an array');
259
+ const identities = data.prs.every((p) => p && /^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/.test(p.url)
260
+ && /^[a-f0-9]{40}$/i.test(p.mergeCommit) && timestamp(p.mergedAt) >= start && timestamp(p.mergedAt) < end);
261
+ term('merged-prs', data.prs.length === 10 && new Set(data.prs.map((p) => p?.url)).size === 10 && identities ? 'pass' : 'fail',
262
+ { identities: data.prs, source: 'caller-supplied merged PR snapshot; no online verification' });
263
+ const supported = data.cache?.version === 11 && Array.isArray(data.cache.models) && Array.isArray(data.cache.sessions)
264
+ && data.cache.files && typeof data.cache.files === 'object' && !Array.isArray(data.cache.files);
265
+ const stateSupported = Array.isArray(data.state?.providers) && ['threads', 'runs'].every((key) =>
266
+ data.state[key] === undefined || Array.isArray(data.state[key]));
267
+ const ratesSupported = data.rates?.document && typeof data.rates.document === 'object' && !Array.isArray(data.rates.document);
268
+ term('cache-format', supported ? 'pass' : 'unknown', { version: data.cache?.version ?? null, supportedVersions: [11] });
269
+ term('state-format', stateSupported ? 'pass' : 'unknown', 'Require exported provider rows with optional thread metadata and aggregate turns');
270
+ term('rates-format', ratesSupported ? 'pass' : 'unknown', 'Require a saved model-rates document keyed by exact model name');
271
+ if (supported && stateSupported && ratesSupported) Object.assign(report,
272
+ measure(data.cache, data.rates, data.state, data.prs.filter(Boolean), start, end, term));
273
+ }
274
+ if (data.billed && validNumber(data.billed.usd) && timestamp(data.billed.start) === start
275
+ && timestamp(data.billed.end) === end && typeof data.billed.evidence === 'string' && data.billed.evidence.trim()) {
276
+ report.billedCost = data.billed; term('billed-cost', 'pass', data.billed);
277
+ } else term('billed-cost', 'unknown', 'No matching interval statement supplied; list-price proxy is not billed spend');
278
+ report.summary = Object.fromEntries(['pass', 'fail', 'unknown', 'n/a'].map((status) => [status, terms.filter((t) => t.status === status).length]));
279
+ const output = `${JSON.stringify(report, null, 2)}\n`;
280
+ if (flags.out) writeFileSync(flags.out, output, { flag: 'wx', mode: 0o600 });
281
+ process.stdout.write(output);
282
+ return report.summary.unknown ? 2 : 0;
283
+ }
284
+
285
+ try { process.exitCode = await main(process.argv.slice(2)); }
286
+ catch (error) { console.error(`usage-split: ${error.message}`); process.exitCode = 1; }
@@ -132,6 +132,16 @@ question budget. The user still decides; reuse unchanged receipts.
132
132
 
133
133
  ## Bound the interview
134
134
 
135
+ Defer a look, behave, or state-model question discussion cannot settle only in
136
+ delivery runs whose substantial work continues to Spec; rung does not gate it.
137
+ Otherwise settle it by discussion, including small-change, planning-only,
138
+ read-only and stop-after-phase runs (even "write the spec and stop").
139
+ Mark the sketch's Open line or a read-back item with the carrier
140
+ `Open (prototype): <question>`. A plain `Open:` keeps its existing meaning.
141
+ A deferral does not block Align completion. Ask questions on deferred items in
142
+ Spec inside Align's cumulative count. Questions on deferred items need no
143
+ refinement opt-in; follow [Spec 3a](../axstack-spec/references/prototype.md).
144
+
135
145
  Twenty cumulative presented questions is the normal ceiling, not a target.
136
146
  Follow-ups, reopened questions, and separate decisions bundled into one prompt
137
147
  each count; never discount a presented question later. Before extending beyond
@@ -142,7 +152,7 @@ remains; 20 is not a quota.
142
152
 
143
153
  At completion or the 35-question cap, read back the result.
144
154
  Never make a deeper-refinement offer a completion requirement.
145
- Ask no further interview or refinement questions
155
+ Except for the deferred prototype items above, ask no further interview or refinement questions
146
156
  without opt-in; this does not replace required spec approval or a clarification
147
157
  prompt when a configured model is unavailable. An opted-in refinement names
148
158
  one area and a separate finite budget of at most five questions; it preserves
@@ -137,6 +137,9 @@ through [Anatomy](../axstack-anatomy/SKILL.md).
137
137
  ## 3. Verify and deliver
138
138
 
139
139
  1. For inline pages, follow [Inline pages](references/inline-pages.md).
140
+ For prototype pages, follow Inline pages' prototype-page rules and
141
+ [Delivery](references/delivery.md), including their four exemptions and bounded repairs;
142
+ they govern the review and word-cap requirements for those pages.
140
143
  For every explicitly requested HTML or visual artifact
141
144
  outside inline T3 pages, follow [Visual QA](references/visual-qa.md).
142
145
  2. Require independent `axstack-explainer-review` for consequential or complex
@@ -18,6 +18,15 @@ and resume condition.
18
18
  Missing access, tool, model or evidence, or material new scope, holds the
19
19
  specific dependency with its reason and resume condition.
20
20
 
21
+ For prototype pages, a check still failing at a cap holds the page as a
22
+ Delivery scope hold with its reason and resume condition, and the question
23
+ takes a no-verdict exit under [prototype.md](../../axstack-spec/references/prototype.md).
24
+ For a prototype, where the cap question applies, ask once first as a Qn if
25
+ budget remains; follow that reference's options before recording the cap hold.
26
+ This applies the existing scope hold rules rather than adding an exemption.
27
+ Inline pages' four prototype exemptions govern the review, word-cap and
28
+ design-and-decency loop requirements below; all other holds and repairs remain.
29
+
21
30
  If the reviewer is unavailable, hold the whiteboard-defense explanation and name the unavailable reviewer.
22
31
  Never deliver a held whiteboard-defense explanation unreviewed or describe it as reviewed.
23
32
  Visual-only findings follow the visual rule, and claim findings hold the whiteboard-defense explanation.
@@ -3,6 +3,27 @@
3
3
  Use this reference for Explain's inline T3 answer path.
4
4
  The driver publishes the page in its own thread.
5
5
 
6
+ ## Prototype pages
7
+
8
+ Prototype pages follow every inline-pages.md rule except `axstack-explainer-review`,
9
+ design review, the word cap, and Delivery's design and decency repair loop.
10
+ For prototype pages, repair every other failed check within
11
+ [prototype.md caps](../../axstack-spec/references/prototype.md).
12
+ At the top, prototype pages say "prototype" and use colours with
13
+ `var(--x, <fallback>)` so they also work standalone.
14
+
15
+ Prototype pages retain self-contained bytes, no network, no storage (including
16
+ cookies), no modals or popups, and the exact-byte scan.
17
+ Prototype pages retain both driver previews for layout, theme, height, network,
18
+ zero console errors, and empty `missingImages`.
19
+ Prototype pages require semantic, accessible markup and the interactive
20
+ `axstack-ui-verifier` pass.
21
+ Prototype pages retain driver-only `html_render` using precisely the bytes checked
22
+ by these gates.
23
+ These kept rules cannot be exempted; every unlisted rule also stays in force.
24
+ For prototype pages, never treat an ambiguous or unknown `html_render` result
25
+ as passed or retry it.
26
+
6
27
  ## Shape and theme
7
28
 
8
29
  Use T3 theme variables and follow the live theme.
@@ -161,6 +161,14 @@ driver decisions within approved scope; size alone requires no user approval.
161
161
 
162
162
  ## 3. Establish test-first evidence
163
163
 
164
+ When the spec links a prototype, read the pinned prototype commit as reference
165
+ only under [Spec prototypes](../axstack-spec/references/prototype.md).
166
+ Code may be copied into the real change. Copied prototype code must pass strict
167
+ TDD and ordinary review, including cross-model review.
168
+ Never merge the prototype branch. Never cherry-pick the prototype branch.
169
+ `Decisions` rows bind. Where the prototype shows something no row captures,
170
+ follow the rows. An unfetchable SHA makes the reference unavailable, not a hold.
171
+
164
172
  For authorized UI improvement work, load [UI improvement loop](../axstack/references/ui-improvement-loop.md).
165
173
 
166
174
  For performance work only, load [Performance loop](../axstack/references/perf-loop.md).
@@ -3,7 +3,7 @@
3
3
  ```text
4
4
  Mode: <peer | authored>
5
5
  Reviewer: <reviewer role + provider/model/effort receipt> session <id> rev <candidate sha> base <current base>
6
- Workspace: <T3 taskId/childThreadId/runId + authored: native worktree absolute path | peer: detached checkout absolute path>
6
+ Workspace: <authored: native worktree absolute path | peer: detached checkout absolute path>
7
7
  Evidence: <run dir>/evidence/<dispatch>/ (report and probe paths)
8
8
  Verdict: <APPROVE | REQUEST_CHANGES | INCOMPLETE>
9
9
  Scope: <PASS | FINDINGS | UNKNOWN | n/a — separate diligence>
@@ -58,7 +58,13 @@ Before drafting, load and follow [Independent delivery](../axstack/references/in
58
58
  independent assessment. For questions, consult advisers only for consequential
59
59
  decisions and disagreements. Never dispatch advisers for every question,
60
60
  routine factual clarification or settled preferences.
61
- For those consequential decisions and disagreements and the required draft
61
+
62
+ **3a. Prototype first.** Before the first draft adviser round,
63
+ follow [Prototype](references/prototype.md) for `Open (prototype):` items.
64
+ Return later deferred questions to 3a within the same caps; after approval,
65
+ use Material revisions instead.
66
+
67
+ **Review the draft.** For those consequential decisions and disagreements and the required draft
62
68
  rounds below, load
63
69
  [T3 runtime](../axstack/references/t3-runtime.md) before dispatching the
64
70
  configured `axstack-advisor-codex` and `axstack-advisor-claude` independently,
@@ -45,6 +45,17 @@ a duplicate whole spec with separate requirements.
45
45
 
46
46
  ## Evidence and history
47
47
 
48
+ Per prototyped question, put this record line in `Design`, or Evidence and
49
+ history when there is no sketch:
50
+
51
+ ```text
52
+ Prototype: <branch> (never-merge) | https://github.com/<owner>/<repo>/tree/<sha> | entry: <command or file> | question: <question> | verdict: <decision> (Qn)
53
+ ```
54
+
55
+ Pin the author commit SHA in the tree URL. Each verdict's `Decisions` row cites
56
+ its `Qn`; the rows bind and the prototype illustrates. Follow
57
+ [Prototype capture](prototype.md#capture) for a capture-held record.
58
+
48
59
  Keep history, evidence and adviser receipts separate from current requirements.
49
60
  Place provenance, commands, review-round dispositions and change logs here or
50
61
  link their existing records. They explain the requirements, not override them.
@@ -0,0 +1,125 @@
1
+ # Spec 3a: prototype a deferred question
2
+
3
+ Use only for `Open (prototype):` questions under
4
+ [Align's delivery gate](../../axstack-align/SKILL.md#bound-the-interview),
5
+ before the first draft adviser round. This is a bounded step, not a new phase
6
+ or standalone skill. Brainstorm stays report-only: when its question overlaps,
7
+ run Brainstorm first, then test the chosen candidate with the user.
8
+
9
+ Before dispatch, write one sentence naming the question. Put it at the top of
10
+ the prototype. One prototype answers one question. Choose the smallest
11
+ presentation that answers it; if kind is unclear, match the surrounding code
12
+ (page/component: UI; module: logic) and state the assumption at the top.
13
+
14
+ ## Kinds and shared constraints
15
+
16
+ - **UI:** include about three variants (at most five), differing in structure
17
+ rather than colour, in the real page. UI variants require a switcher, such
18
+ as `?variant=` or a floating bar.
19
+ - Run the documented start command first. If the start command fails, use
20
+ tier 2 in the same dispatch. Also use tier 2 when the user must interact and
21
+ cannot reach the app: one self-contained HTML mock with a variant switcher,
22
+ shown inline with fidelity limits at the top. Never re-route the run.
23
+ If neither real page nor mock answers the question, take tier 3: no verdict.
24
+ - **Logic:** show one self-contained HTML file inline under
25
+ [Inline pages](../../axstack-explain/references/inline-pages.md), using its
26
+ prototype-page rules. Include visible state, controls and useful examples.
27
+ Keep logic in a small pure module without DOM code, in its own script block.
28
+ - Label it "prototype" and place it next to the code it informs. Start it
29
+ with one command or double-click. Keep state in memory; for a persistence
30
+ question only, use a local scratch file/database named `PROTOTYPE-wipe-me`.
31
+ Inline copies never use storage. Add no automated test suite or speculative
32
+ reusable framework; runnable and interaction checks below still apply.
33
+ - Keep variants read-only and stub every mutation. Use only repository-
34
+ documented dev or test data sources, never production secrets. Prototype
35
+ status grants no production data, credential, transaction or infrastructure
36
+ authority.
37
+
38
+ ## Authority and build
39
+
40
+ The pre-baseline exception applies only in delivery runs: one author per
41
+ question, only named files from the brief and one create-only push of a
42
+ never-merged ref. Bind the dispatch to the deferred question and current draft
43
+ revision in place of an approved identity. The driver records this exception
44
+ on the run record's `Authority:` line.
45
+
46
+ ```text
47
+ Authority: Spec 3a prototype | question: <deferred item> | draft: <revision> | author: <attempt> | files: <exclusive paths> | one create-only never-merged ref push
48
+ ```
49
+
50
+ The driver dispatches `axstack-author` via `delegate_task` with
51
+ `isolation:"worktree"`, on its encoded branch from a pinned base SHA. The author
52
+ commits with `[skip ci]`. Only the driver pushes the author SHA. The author
53
+ never pushes. Record sends and rounds per question, including the caps below
54
+ in the brief.
55
+
56
+ Only prototype authors skip red/green logs. For completion require terminal
57
+ checks, non-empty diff, clean tree and run evidence of the start command and
58
+ observed output. This exemption changes no other author completion rule.
59
+
60
+ ## Show and review
61
+
62
+ For static look, dispatch `axstack-ui-verifier` on a detached checkout of the
63
+ prototype SHA: capture one screenshot per variant at both 390x844 and
64
+ 1440x900 and show them inline. For observed behaviour, add a short GIF.
65
+ For interaction, use a reachable real app directly; otherwise show the tier 2
66
+ mock or logic page inline under the linked prototype-page rules. Those rules
67
+ retain their checks and exactly their four exemptions; repair other failures
68
+ within these caps. A check still failing at a cap holds the inline page after
69
+ the cap question below; take a no-verdict exit.
70
+
71
+ Present each decision, including the cap question, as one Qn under Align's
72
+ focused-round rule with a driver recommendation, reason and trade-off.
73
+ Prototype review is not an advised hold. Keep `Autopilot: on`, record the wait
74
+ in `Next:`, and use `paused` only when no other authorized work can advance.
75
+
76
+ Per question allow one author, at most 3 review rounds and at most 3
77
+ build-or-revise sends, each with at most one verification repair. Per spec
78
+ allow at most 2 prototyped questions. Stop before spending the last Qn of 20
79
+ or the justified 35. At any cap ask once, as a Qn if budget remains: extend by
80
+ one bounded round, settle by discussion or drop. Record the user's choice
81
+ and the bounded extension before advancing.
82
+
83
+ Tier 3, abandonment, drop, a spent budget or a held inline page take a
84
+ no-verdict exit to discussion as an ordinary Qn. With the budget spent put the
85
+ question under "Decisions needed from the user" so spec approval settles it.
86
+ A no-verdict question never appears settled. Abandoned prototypes are not pushed.
87
+
88
+ Later deferred questions found in drafting or adviser review re-enter 3a within
89
+ the same caps. A verdict changing draft meaning refreshes adviser and diligence
90
+ receipts under Spec's existing rules. A verdict never approves the spec.
91
+ After approval, questions follow Material revisions.
92
+
93
+ ## Capture
94
+
95
+ Normalise the slug as for encoded branch segments. Before the push scan the
96
+ diff for secrets and personal data. A failed scan holds the push.
97
+ At the verdict, the driver pushes once, create-only:
98
+
99
+ ```bash
100
+ git push --force-with-lease=refs/heads/prototype-axstack-<slug>: origin <sha>:refs/heads/prototype-axstack-<slug>
101
+ ```
102
+
103
+ Create an absent ref; never change an existing ref. If rejection says the ref
104
+ exists, use the next suffix (`-2`, `-3`). An identical existing tip reporting
105
+ up to date is also insufficient: use the next suffix. Require `[new branch]`
106
+ in the output to prove creation, rather than the exit code. Then read the
107
+ remote ref back and confirm it equals the author head. A protected or
108
+ ambiguous result holds capture only; record `Prototype: capture held (<reason>)`
109
+ and inspect remote state before any retry. Never open a PR or merge.
110
+
111
+ Only the never-merged prototype ref push skips candidate-publication diligence,
112
+ review and PR rules. This is not candidate publication; the exception exists
113
+ only because the ref never merges. Never base a candidate on the prototype SHA.
114
+
115
+ Record: per question, in the spec's `Design` or Evidence and history if there
116
+ is no sketch, write the [prototype record line](format.md#evidence-and-history):
117
+ branch (never-merge), pinned GitHub `tree/<sha>` URL, entry point, question and
118
+ verdict with its Qn. Each verdict's `Decisions` row cites its Qn; the rows bind,
119
+ the prototype illustrates.
120
+
121
+ The author worktree is removable when remote readback matches the author head,
122
+ or when the prototype is abandoned and its tree is clean. Keep the local
123
+ branch. Apply existing terminal, ownership and evidence guards in
124
+ [Workspace hygiene](../../axstack/references/workspace-hygiene.md); this step
125
+ grants no prototype-branch cleanup authority.
@@ -59,6 +59,8 @@ Before mapping, load and follow [Independent delivery](../axstack/references/ind
59
59
  in the existing map, including packages feeding one PR. Choose the earliest
60
60
  sufficient immutable interface, verified terminal internal package tip, review,
61
61
  merge or deployment milestone; retain reviewed-parent rules across PRs.
62
+ Copy the prototype record line from the spec into each affected task under
63
+ [Spec prototypes](../axstack-spec/references/prototype.md).
62
64
  Package count alone neither escalates small work nor changes diligence depth.
63
65
  For each task the driver records
64
66
  one theme and a coarse size estimate from the ownership, interface, and