Skip to content

100x is a skill by a former Cursor engineer that turns prompts into formally verified, production-ready code

Add the properties kind and a verification ledger that every run uses by default

Dead Internet097585106db4
diff --git a/docs/design.md b/docs/design.md
index f235083..9985b1d 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -71,7 +71,7 @@ Decisions columns. `ts phase decision why evidence result`, tab separated, appen
## CLI
-`100x init|install|config|clock|log|status|run|shots|port|prompt|ref|brief|review-call|review-run|review-verify|helper|triage|eval|report|finish|registry|morning|night|watchdog|upstream|browsers|text|doctor|validate`. Run `100x help` for flags.
+`100x init|install|config|clock|log|status|run|shots|port|prompt|ref|verify|brief|review-call|review-run|review-verify|helper|triage|eval|report|finish|registry|morning|night|watchdog|upstream|browsers|text|doctor|validate`. Run `100x help` for flags.
## Guardrails
diff --git a/docs/examples/budget-app-prompt.md b/docs/examples/budget-app-prompt.md
index a01443d..9d4f087 100644
--- a/docs/examples/budget-app-prompt.md
+++ b/docs/examples/budget-app-prompt.md
@@ -1,6 +1,6 @@
# What 100x does with a very bad prompt
-The prompt was four words: `make me a budget app`. Below is the whole prompt 100x writes from it, saved as `.100x/project.md`. It was written by following the 100x skill and it passes `100x prompt check` ("12 written, 1 marked none, 9 asks"). Back to the [README](../../README.md).
+The prompt was four words: `make me a budget app`. Below is the whole prompt 100x writes from it, saved as `.100x/project.md`. It was written by following the 100x skill and it passes `100x prompt check` ("13 written, 1 marked none, 9 asks"). Back to the [README](../../README.md).
Each part changes something the builder does. The rules say what to trade off. The asks carry a proof for each claim the stages cannot see for themselves. The hard test and the judge questions are the ones the second model presses on.
@@ -58,6 +58,14 @@ none: no outside files are needed, because the tests run on fixed amounts and a
## Must not break
Kind numbers. The money left equals the limit minus the sum of the purchases, to the cent, after any mix of adds, edits, deletes and reloads.
+## Properties
+- State: the limit in cents, a list of purchases each with a whole number of cents, and the money left.
+- Transitions: add, edit and delete a purchase, change the limit, reload.
+- Preconditions: an amount is a whole number of cents above zero. A delete needs a purchase that exists.
+- Postconditions: after any step, money left equals the limit minus the sum of the purchases.
+- Invariants: money left is an integer, and a reload gives the same state.
+- Liveness: every add, edit and delete shows its new total, under a browser that keeps its storage.
+
## Moment
You type 4.35 and Enter, and the money left for Food ticks down while the coffee slides into the list.
diff --git a/docs/examples/stock-comparison-prompt.md b/docs/examples/stock-comparison-prompt.md
index f969ec3..1538092 100644
--- a/docs/examples/stock-comparison-prompt.md
+++ b/docs/examples/stock-comparison-prompt.md
@@ -1,6 +1,6 @@
# What 100x writes from a one-line request
-The request was one line: `Let me compare any stock with the S&P 500 in my stock market research app` Below is the prompt 100x writes from it before it builds anything, saved as `.100x/project.md`. It is an illustrated example for a research app we made up, and it passes `100x prompt check` ("13 written, 0 marked none, 9 asks"). Back to the [README](../../README.md).
+The request was one line: `Let me compare any stock with the S&P 500 in my stock market research app` Below is the prompt 100x writes from it before it builds anything, saved as `.100x/project.md`. It is an illustrated example for a research app we made up, and it passes `100x prompt check` ("14 written, 0 marked none, 9 asks"). Back to the [README](../../README.md).
Each part changes what the builder does. The rules settle the trade-offs. The asks end in something you can open or run, and two of them are tests that must first be shown to fail. The judge questions are what the second model presses on.
@@ -57,6 +57,14 @@ In: one chart screen inside the existing research app, its data adjustment and i
## Must not break
Percent change across a split and from a shared start day. Kind: numbers.
+## Properties
+- State: for each ticker, a list of dated closes and the splits with their dates and ratios.
+- Transitions: pick a start day, add or remove a ticker, change the range.
+- Preconditions: a percent change needs a close on the start day for every ticker shown.
+- Postconditions: every line starts at 0 percent on the shared start day, and a split changes no percent.
+- Invariants: adjusting for a split twice gives the same series as once, and a longer range never changes an earlier percent.
+- Liveness: a chart is drawn or a named reason is shown for every ticker and range, under a data source that answers.
+
## Moment
Type a ticker and both lines start at 0% on the same day, so the gap is the whole story.
diff --git a/lib/commands/index.mjs b/lib/commands/index.mjs
index cecf3f7..5c3e99d 100644
--- a/lib/commands/index.mjs
+++ b/lib/commands/index.mjs
@@ -26,13 +26,14 @@ import text from './text.mjs';
import triage from './triage.mjs';
import upstream from './upstream.mjs';
import validate from './validate.mjs';
+import verify from './verify.mjs';
import watchdog from './watchdog.mjs';
-export const commands = [init, install, config, clock, log, status, run, shots, port, prompt, ref, brief, reviewCall, reviewRun, reviewVerify, helper, triage, report, finish, registry, morning, night, watchdog, upstream, browsers, text, evalCommand, doctor, validate];
+export const commands = [init, install, config, clock, log, status, run, shots, port, prompt, ref, verify, brief, reviewCall, reviewRun, reviewVerify, helper, triage, report, finish, registry, morning, night, watchdog, upstream, browsers, text, evalCommand, doctor, validate];
export const commandNames = commands.map((command) => command.name);
// The headings and the order of `100x help`. A test fails when a command is missing here or listed twice.
export const helpGroups = [
- ['During a run', ['init', 'prompt', 'status', 'log', 'run', 'clock', 'port', 'shots', 'text', 'ref', 'report', 'finish']],
+ ['During a run', ['init', 'prompt', 'status', 'log', 'run', 'clock', 'port', 'shots', 'text', 'ref', 'verify', 'report', 'finish']],
['Judging', ['brief', 'review-call', 'review-run', 'review-verify', 'helper', 'triage', 'eval']],
['Nights and mornings', ['night', 'watchdog', 'morning', 'registry']],
['Setup and health', ['install', 'config', 'browsers', 'doctor', 'validate', 'upstream']],
diff --git a/lib/commands/verify.mjs b/lib/commands/verify.mjs
new file mode 100644
index 0000000..7c0c54b
--- /dev/null
+++ b/lib/commands/verify.mjs
@@ -0,0 +1,147 @@
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { parseArgs } from 'node:util';
+import { CliError } from '../errors.mjs';
+import { findProjectRoot } from '../paths.mjs';
+import { addRow, amendRow, covering, gaps, KINDS, LEVELS, PROCEDURE, readHistory, readLedger, retireRow, rowState, runRow, syncRow, waive, writeLedger } from '../verify.mjs';
+
+const usage = `
+100x verify status
+100x verify cover <path>...
+100x verify gaps [--base <ref>]
+100x verify add <id> --kind <kind> --property "<sentence>" --covers <paths> --command "<cmd>" --level <level>
+100x verify run [<id>]
+100x verify sync <id> --note "<what you read>"
+100x verify amend <id> --evidence "<why the promise changed>" [--property ...] [--covers ...] [--command ...] [--level ...]
+100x verify retire <id> --why "<why it no longer applies>"
+100x verify waive <path>... --why "<why no property can be written>"
+100x verify history [<id>]
+
+The ledger keeps what is verified, in the project and in git, so it travels with every branch.
+ verify/ledger.tsv one row per property: the code it covers, a hash of that code, the command, the level, the last result
+ verify/history.tsv every add, run, sync, amend, waive and retire, appended and never rewritten
+ verify/red/<id>.txt the failing run on a seeded defect, with a FAIL line. A property that never failed proves nothing
+kinds: ${KINDS.join(", ")}. levels: ${LEVELS.join(", ")}. A level says what the check really does, and run refuses exhaustive when the checker says BOUNDED.
+
+holds green, the covered code is the code that was last synced, and a failing run is on file
+stale the covered code changed after the last sync. Read the change, run, then sync
+broken the last run failed. Fix the code or, when the promise changed on purpose, amend with the evidence
+unproven green, but no failing run is on file
+unchecked never run
+
+cover and gaps say which rule covers code. Code with no rule and no waiver starts the verification procedure (100x ref properties).
+Options. --root <folder> to use another project. status and gaps exit 1 and cover exits 2 when something needs work.
+`;
+
+const rootOf = (values) => {
+ if (values.root) return path.resolve(values.root);
+ const found = findProjectRoot(process.cwd());
+ if (found) return found;
+ try {
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd: process.cwd(), stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
+ } catch {
+ return process.cwd();
+ }
+};
+const need = (result) => { if (result.errors?.length) throw new CliError(result.errors.join('. ') + '.'); return result; };
+const asRel = (root, file) => path.relative(root, path.resolve(process.cwd(), file)).split(path.sep).join('/');
+
+export default {
+ name: 'verify',
+ summary: 'Keep the verified properties of the code in a ledger in the project, and say which rule covers a piece of code.',
+ usage,
+ async run(argv) {
+ const { values, positionals } = parseArgs({
+ args: argv,
+ allowPositionals: true,
+ options: { root: { type: 'string' }, base: { type: 'string' }, kind: { type: 'string' }, property: { type: 'string' }, covers: { type: 'string' }, command: { type: 'string' }, level: { type: 'string' }, note: { type: 'string' }, evidence: { type: 'string' }, why: { type: 'string' } },
+ });
+ const [sub, ...rest] = positionals;
+ const root = rootOf(values);
+ const rows = readLedger(root);
+ const find = (id) => { const row = rows.find((item) => item.id === id); if (!row) throw new CliError('no property called ' + id + '. 100x verify status lists them.'); return row; };
+
+ if (sub === 'add') {
+ if (!rest[0]) throw new CliError('Usage: 100x verify add <id> --kind <kind> --property "<sentence>" --covers <paths> --command "<cmd>" --level <level>');
+ const { row } = need(addRow(root, { id: rest[0], kind: values.kind, property: values.property, covers: values.covers, command: values.command, level: values.level }));
+ console.log('added ' + row.id + '. Next: save a failing run in verify/red/' + row.id + '.txt, then 100x verify run ' + row.id);
+ return undefined;
+ }
+ if (sub === 'waive') {
+ if (!rest.length) throw new CliError('Usage: 100x verify waive <path>... --why "<why no property can be written>"');
+ const { added } = need(waive(root, rest.map((file) => asRel(root, file)), values.why));
+ console.log(added.length ? 'waived ' + added.join(', ') : 'already waived');
+ return undefined;
+ }
+ if (sub === 'run') {
+ const list = rest[0] ? [find(rest[0])] : rows.filter((row) => row.kind !== 'waived');
+ if (!list.length) throw new CliError('the ledger holds no property to run. Add one with 100x verify add.');
+ let failed = 0;
+ for (const row of list) {
+ const result = runRow(root, row);
+ console.log((result.ok ? 'pass' : 'FAIL') + ' ' + row.id + '. ' + row.kind + ', ' + row.level + ', ' + result.note);
+ if (!result.ok) {
+ failed += 1;
+ console.log(result.output.trim().split('\n').slice(-15).map((line) => ' ' + line).join('\n'));
+ }
+ }
+ writeLedger(root, rows);
+ for (const row of list) {
+ const { state, why } = rowState(root, row);
+ if (state !== 'holds' && state !== 'broken') console.log('needs ' + row.id + '. ' + state + '. ' + why);
+ }
+ process.exitCode = failed ? 1 : 0;
+ return undefined;
+ }
+ if (sub === 'sync') {
+ const row = find(rest[0]);
+ need(syncRow(root, row, values.note));
+ writeLedger(root, rows);
+ console.log('synced ' + row.id + ' to the code as it is now');
+ return undefined;
+ }
+ if (sub === 'amend') {
+ const row = find(rest[0]);
+ need(amendRow(root, row, { property: values.property, covers: values.covers, command: values.command, level: values.level }, values.evidence));
+ writeLedger(root, rows);
+ console.log('amended ' + row.id + ', and it is unchecked until it runs again. The old wording is in verify/history.tsv');
+ return undefined;
+ }
+ if (sub === 'retire') {
+ need(retireRow(root, rest[0], values.why));
+ console.log('retired ' + rest[0] + '. verify/history.tsv keeps the row');
+ return undefined;
+ }
+ if (sub === 'history') {
+ const list = readHistory(root).filter((row) => !rest[0] || row.id === rest[0]);
+ console.log(list.length ? list.map((row) => [row.ts, row.id, row.event, row.commit, row.result, row.note].join(' ')).join('\n') : '(no history yet)');
+ return undefined;
+ }
+ if (sub === 'cover' || sub === 'gaps') {
+ const files = sub === 'cover' ? rest.map((file) => asRel(root, file)) : gaps(root, values.base).files;
+ if (sub === 'cover' && !files.length) throw new CliError('Usage: 100x verify cover <path>...');
+ let uncovered = 0;
+ for (const file of files) {
+ const hit = covering(rows, file);
+ if (hit.length) console.log('covered ' + file + ' by ' + hit.map((row) => row.id + (row.kind === 'waived' ? ' (waived)' : '')).join(', '));
+ else { uncovered += 1; console.log('NO RULE ' + file); }
+ }
+ if (sub === 'gaps' && !files.length) console.log('No changed code since ' + gaps(root, values.base).base + '.');
+ if (uncovered) console.log('\n' + PROCEDURE);
+ process.exitCode = uncovered ? (sub === 'cover' ? 2 : 1) : 0;
+ return undefined;
+ }
+ if (sub === 'status' || sub === undefined) {
+ if (!rows.length) { console.log('The ledger is empty. ' + PROCEDURE); process.exitCode = sub === 'status' ? 1 : 0; return undefined; }
+ let needs = 0;
+ for (const row of rows) {
+ const { state, why } = rowState(root, row);
+ if (state !== 'holds' && state !== 'waived') needs += 1;
+ console.log(state.padEnd(9) + ' ' + row.id + ' ' + (row.kind === 'waived' ? 'waived' : row.kind + ', ' + row.level) + ' ' + (state === 'holds' || state === 'waived' ? row.property : why));
+ }
+ process.exitCode = needs ? 1 : 0;
+ return undefined;
+ }
+ throw new CliError('unknown verify command "' + sub + '". Run `100x verify --help`.');
+ },
+};
diff --git a/lib/config.defaults.json b/lib/config.defaults.json
index 44f19a8..2656168 100644
--- a/lib/config.defaults.json
+++ b/lib/config.defaults.json
@@ -17,6 +17,7 @@
"quick": { "provider": null, "model": null, "options": {} },
"overnight": { "provider": null, "model": null, "options": {} },
"core": { "enabled": true },
+ "verify": { "enabled": true },
"polish": { "passes": 3, "dudPasses": 1 },
"depth": { "predictedFollowups": true, "max": 5 },
"variants": { "count": 1, "parallel": false },
diff --git a/lib/config.mjs b/lib/config.mjs
index 9c80938..beee6d3 100644
--- a/lib/config.mjs
+++ b/lib/config.mjs
@@ -30,6 +30,7 @@ const SCHEMA = {
'overnight.model': { type: ['string', 'null'] },
'overnight.options': { type: 'object' },
'core.enabled': { type: 'boolean' },
+ 'verify.enabled': { type: 'boolean' },
'polish.passes': { type: 'number', min: 0, max: 10 },
'polish.dudPasses': { type: 'number', min: 0, max: 10 },
'depth.predictedFollowups': { type: 'boolean' },
diff --git a/lib/finish.mjs b/lib/finish.mjs
index a6b9c87..018ceb9 100644
--- a/lib/finish.mjs
+++ b/lib/finish.mjs
@@ -7,9 +7,9 @@ import { CliError } from './errors.mjs';
import { git, stageTags } from './git.mjs';
import { inspectImage } from './image.mjs';
import { finalMatrix, passNames, readAsks, readRun, runRows, stateFile, startedAt, targetIsOurs, targetMatchesRun, writeFinished, writeRun } from './project.mjs';
-import { checkPrompt } from './prompt.mjs';
+import { checkPrompt, verifyOn } from './prompt.mjs';
import { runId, upsert } from './registry.mjs';
-import { runCmdProblem } from './run-command.mjs';
+import { runCmdProblem } from './run-command.mjs';import { checkLedger } from './verify.mjs';
import { listProblems, modern } from './runfile.mjs';
import { buildReport, buildReportHtml, chatSummary } from './report.mjs';
import { checkTriage, judgeRoom, pointsAtSomething, reviewCall } from './review.mjs';
@@ -243,6 +243,13 @@ export function validateRun(root, { now = new Date() } = {}) {
// A mockup needs no must-not-break check, because only its moment has to work. One that is recorded is still checked.
if (!(mockup && mustNotBreakList(run).length === 0)) errors.push(...checkMustNotBreak(root, run, { after: Date.parse(startedAt(root)) }).errors);
+ // The ledger travels with the branch. A property whose covered code changed after its last sync, or whose last run failed, is a claim nobody backs.
+ const verifying = verifyOn(root) && !mockup;
+ const ledger = checkLedger(root, { required: mustNotBreakList(run).some((check) => check.kind === 'properties') ? 'properties' : verifying ? 'any' : false });
+ if (!verifying && !mockup) warnings.push('verify. property checks are switched off (verify.enabled false), so nothing was verified and the report must say so');
+ errors.push(...ledger.errors.map((error) => `verify. ${error}`));
+ warnings.push(...ledger.warnings.map((warning) => `verify. ${warning}`));
+
const { found, asks } = readAsks(root);
if (!found || asks.length === 0) errors.push('project.md has no "## Asks" ledger. List every ask as "- [ ] text" and close each one.');
const unfinished = checkPrompt(root).problems.filter((problem) => problem.section !== 'Asks' || (found && asks.length > 0));
diff --git a/lib/prompt.mjs b/lib/prompt.mjs
index 7bec0e1..09fb02f 100644
--- a/lib/prompt.mjs
+++ b/lib/prompt.mjs
@@ -1,5 +1,6 @@
import fs from 'node:fs';
import path from 'node:path';
+import { load } from './config.mjs';
import { git } from './git.mjs';
import { headingCount, readAsks, readRun, scan, section, sectionLines, stateFile } from './project.mjs';
import { triggerHits } from './triggers.mjs';
@@ -28,6 +29,7 @@ export const SECTIONS = [
{ name: 'Do not', none: true, says: 'The hazards of this problem, and what it may not run, install or write. The standing rules are in the skill, so leave them out.' },
{ name: 'Assumptions', none: true, says: 'One line per thing you decided instead of asking.' },
{ name: 'Must not break', says: 'The one thing that must not be wrong, and its kind from references/must-not-break.md.' },
+ { name: 'Properties', none: true, min: { lines: 3, tip: 'Write one line each for state, transitions, preconditions, postconditions, invariants and liveness, or none with the reason.' }, says: 'The verifiable properties of the part that has logic, one line each for state, transitions, preconditions, postconditions, invariants and liveness with its assumption, in the repo\'s names (references/properties.md). Write "none: <reason>" when nothing can be stated, such as a page of copy.' },
{ name: 'Moment', says: 'The moment that makes someone say they want this. One sentence.' },
{ name: 'Judge focus', min: { lines: 2, tip: 'Write two to six questions, one per line.' }, says: 'Two to six questions the judge must press, each one answerable by running the thing, such as the math, the first minute or the error messages.' },
{ name: 'Stack and run', extra: true, says: 'Stack, run command, URL.' },
@@ -105,6 +107,15 @@ export function promptStyle(root) {
return fs.existsSync(stateFile(root, PROMPT_MARKER)) ? 'prompt' : 'older';
}
+// Property checks are on unless the owner turned them off with verify.enabled false, in this project or globally.
+export function verifyOn(root) {
+ try {
+ return load({ cwd: root }).effective.verify?.enabled !== false;
+ } catch {
+ return true;
+ }
+}
+
export function checkPrompt(root) {
const file = stateFile(root, 'project.md');
const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
@@ -115,7 +126,10 @@ export function checkPrompt(root) {
const { unclosed } = scan(text);
if (unclosed) problem('file', unclosedMessage(unclosed));
for (const spec of SECTIONS.filter((one) => one.extra && headingCount(text, one.name) > 1)) problem(spec.name, MESSAGES.twice(spec));
+ const verifying = verifyOn(root);
for (const spec of SECTIONS.filter((one) => !one.extra)) {
+ // The owner can switch property checks off for a project or for every project. Then the section is not asked for.
+ if (spec.name === 'Properties' && !verifying) continue;
if (spec.name === 'Asks') {
const headings = headingCount(text, spec.name);
const { asks } = readAsks(root);
@@ -143,7 +157,7 @@ export function writtenSection(text, name) {
}
// The exported text starts with the goal and has no title, so it reads as the first message of a chat.
-const EXPORT_ORDER = ['Read first', 'Rules', 'Riskiest unknown', 'Asks', 'Scope', 'Test material', 'Do not', 'Assumptions', 'Must not break', 'Moment', 'Judge focus'];
+const EXPORT_ORDER = ['Read first', 'Rules', 'Riskiest unknown', 'Asks', 'Scope', 'Test material', 'Do not', 'Assumptions', 'Must not break', 'Properties', 'Moment', 'Judge focus'];
const EXPORT_TITLE = { Assumptions: 'Choices already made' };
// The notes at the end of an ask, "(evidence: x)" or "(dropped: x)", when they are the last things on the line. Brackets inside one nest.
diff --git a/lib/triggers.mjs b/lib/triggers.mjs
index 10d246d..7ca28e0 100644
--- a/lib/triggers.mjs
+++ b/lib/triggers.mjs
@@ -7,6 +7,7 @@ const PHRASES = [
{ word: 'versions', turns: 'several versions of the idea', re: new RegExp(`\\b${COUNT} versions?\\b`) },
{ word: 'a length of work', turns: 'a clock that uses all the time', re: new RegExp(`\\bfor ${COUNT} (?:hours?|days?)\\b|\\buntil \\d{1,2}(?::\\d{2})? ?(?:am|pm)\\b|\\buse all (?:the )?(?:night|day)\\b`) },
{ word: 'rounds of judging', turns: 'a number of judge rounds', re: new RegExp(`\\b${COUNT} rounds? of judging\\b`) },
+ { word: 'verification', turns: 'no property checks', re: /\bno verification\b/ },
{ word: 'subagents', turns: 'a cap on helpers', re: new RegExp(`\\bmax(?:imum)? ${COUNT} subagents?\\b`) },
];
diff --git a/lib/verify.mjs b/lib/verify.mjs
new file mode 100644
index 0000000..2b63e14
--- /dev/null
+++ b/lib/verify.mjs
@@ -0,0 +1,239 @@
+import { spawnSync } from 'node:child_process';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import { cell, timestamp } from './decisions.mjs';
+import { git } from './git.mjs';
+
+// The verification ledger. It lives in the project, next to the code and tracked by git, so it travels with every branch.
+// verify/ledger.tsv what is claimed now: one row per property, with the code it covers and a hash of that code
+// verify/history.tsv every add, run, sync, amend and retire, appended and never rewritten, like the decisions log
+// verify/red/<id>.txt the failing run on a seeded defect. A property that never failed proves nothing
+export const KINDS = ['state', 'transition', 'precondition', 'postcondition', 'invariant', 'liveness'];
+export const LEVELS = ['exhaustive', 'bounded', 'sampled'];
+export const LEDGER_COLUMNS = ['id', 'kind', 'property', 'covers', 'covers_hash', 'command', 'level', 'red', 'status', 'checked_at', 'commit', 'ran_hash'];
+export const HISTORY_COLUMNS = ['ts', 'id', 'event', 'commit', 'hash', 'note', 'result'];
+const ID = /^[a-z0-9][a-z0-9-]*$/;
+const SKIP_DIRS = new Set(['node_modules', '.git', '.100x', 'dist', 'build', 'coverage', '.next', 'vendor']);
+const CODE = /\.(?:mjs|cjs|js|jsx|ts|tsx|py|go|rs|java|kt|swift|rb|c|cc|cpp|h|hpp|cs|php|lua|gd|scala|ex|exs|clj|dart|zig)$/i;
+const TEST_FILE = /(?:^|\/)(?:tests?|__tests__|spec|specs|e2e|fixtures)\/|\.(?:test|spec)\.[a-z]+$|(?:^|\/)[^/]*\.config\.[a-z]+$/i;
+
+export const ledgerDir = (root) => path.join(root, 'verify');
+export const ledgerFile = (root) => path.join(ledgerDir(root), 'ledger.tsv');
+export const historyFile = (root) => path.join(ledgerDir(root), 'history.tsv');
+export const redFile = (root, id) => path.join(ledgerDir(root), 'red', id + '.txt');
+const short = (hash) => (hash ?? '').slice(0, 16);
+const rel = (root, file) => path.relative(root, file).split(path.sep).join('/');
+
+function readTsv(file, columns) {
+ if (!fs.existsSync(file)) return [];
+ const lines = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).slice(1);
+ return lines.map((line) => { const cells = line.split('\t'); return Object.fromEntries(columns.map((name, index) => [name, cells[index] ?? ''])); });
+}
+export const readLedger = (root) => readTsv(ledgerFile(root), LEDGER_COLUMNS);
+export const readHistory = (root) => readTsv(historyFile(root), HISTORY_COLUMNS);
+export function writeLedger(root, rows) {
+ fs.mkdirSync(ledgerDir(root), { recursive: true });
+ const body = rows.map((row) => LEDGER_COLUMNS.map((name) => cell(row[name])).join('\t'));
+ fs.writeFileSync(ledgerFile(root), [LEDGER_COLUMNS.join('\t'), ...body].join('\n') + '\n');
+}
+export function appendHistory(root, row, now = new Date()) {
+ fs.mkdirSync(ledgerDir(root), { recursive: true });
+ const file = historyFile(root);
+ const fresh = !fs.existsSync(file) || fs.statSync(file).size === 0;
+ const line = [timestamp(now), row.id, row.event, row.commit ?? '', row.hash ?? '', row.note ?? '', row.result ?? ''].map(cell).join('\t');
+ fs.appendFileSync(file, (fresh ? HISTORY_COLUMNS.join('\t') + '\n' : '') + line + '\n');
+}
+
+export const headShort = (root) => git(root, ['rev-parse', '--short', 'HEAD']) ?? 'no-commit';
+export const splitCovers = (text) => String(text ?? '').split(',').map((part) => part.trim().replace(/^\.\//, '').replace(/\/+$/, '')).filter(Boolean);
+
+function walk(root, entry, out) {
+ const full = path.join(root, entry);
+ let stat;
+ try { stat = fs.statSync(full); } catch { return false; }
+ if (stat.isFile()) { out.push(entry); return true; }
+ if (!stat.isDirectory()) return false;
+ for (const name of fs.readdirSync(full).sort()) {
+ if (SKIP_DIRS.has(name) || name.startsWith('.')) continue;
+ walk(root, entry + '/' + name, out);
+ }
+ return true;
+}
+
+// A hash of what the property covers: every file's path and bytes. Any edit to covered code changes it.
+export function hashCovers(root, covers) {
+ const files = [];
+ const missing = [];
+ for (const entry of covers) if (!walk(root, entry, files)) missing.push(entry);
+ const hash = crypto.createHash('sha256');
+ for (const file of [...new Set(files)].sort()) hash.update(file + '\0').update(fs.readFileSync(path.join(root, file))).update('\0');
+ return { hash: short(hash.digest('hex')), files: files.length, missing };
+}
+
+export function redProof(root, id) {
+ const file = redFile(root, id);
+ if (!fs.existsSync(file)) return { ok: false, why: 'no failing run in ' + rel(root, file) + '. Seed one defect in a throwaway copy of the covered code, run the check, and save the failing output there' };
+ const text = fs.readFileSync(file, 'utf8');
+ if (!/^FAIL\s+\S/m.test(text)) return { ok: false, why: rel(root, file) + ' has no FAIL line, so it does not show the check failing' };
+ return { ok: true };
+}
+
+// holds: green, current, and it has failed on a seeded defect. Everything else needs work.
+// broken: the last run failed. stale: the covered code changed since the last sync, or a covered file is gone.
+// unproven: green but no failing run on file. unchecked: never run. waived: a recorded decision that this code has no property.
+export function rowState(root, row) {
+ if (row.kind === 'waived') return { state: 'waived', why: row.property };
+ const now = hashCovers(root, splitCovers(row.covers));
+ if (row.status === 'broken') return { state: 'broken', why: 'the last run failed at ' + row.commit };
+ if (now.missing.length) return { state: 'stale', why: 'covered path is gone: ' + now.missing.join(', ') };
+ if (now.hash !== row.covers_hash) return { state: 'stale', why: 'the covered code changed after the last sync. Read what changed, run the check, then sync' };
+ if (row.status !== 'holds') return { state: 'unchecked', why: 'never run' };
+ const red = redProof(root, row.id);
+ if (!red.ok) return { state: 'unproven', why: red.why };
+ return { state: 'holds', why: '' };
+}
+
+export function checkRow(root, row) {
+ const errors = [];
+ if (!ID.test(row.id ?? '')) errors.push('id must be lowercase words joined by hyphens');
+ if (!KINDS.includes(row.kind)) errors.push('kind must be one of ' + KINDS.join(', '));
+ if (!String(row.property ?? '').trim() || String(row.property).trim().length < 12) errors.push('property must be one plain sentence that says what always holds');
+ if (!LEVELS.includes(row.level)) errors.push('level must be one of ' + LEVELS.join(', ') + '. Say what the check really does: exhaustive visits every state of the model, bounded stopped at a limit, sampled is random cases');
+ if (!String(row.command ?? '').trim()) errors.push('command is missing. It runs from the project root and exits 0 when the property holds');
+ const covers = splitCovers(row.covers);
+ if (!covers.length) errors.push('covers is missing. List the files or folders whose code the property is about');
+ const gone = covers.filter((entry) => !fs.existsSync(path.join(root, entry)));
+ if (gone.length) errors.push('covers names paths that do not exist: ' + gone.join(', '));
+ if (covers.some((entry) => path.isAbsolute(entry) || entry.split('/').includes('..'))) errors.push('covers must stay inside the project');
+ return errors;
+}
+
+export function addRow(root, fields, now = new Date()) {
+ const rows = readLedger(root);
+ const row = { id: fields.id, kind: fields.kind, property: String(fields.property ?? '').trim(), covers: splitCovers(fields.covers).join(','), command: String(fields.command ?? '').trim(), level: fields.level, red: 'verify/red/' + fields.id + '.txt', status: 'unchecked', checked_at: '', commit: '', ran_hash: '' };
+ const errors = checkRow(root, row);
+ if (rows.some((existing) => existing.id === row.id)) errors.push('the id ' + row.id + ' is already in the ledger. Amend it, or pick another id');
+ if (errors.length) return { errors };
+ row.covers_hash = hashCovers(root, splitCovers(row.covers)).hash;
+ rows.push(row);
+ writeLedger(root, rows);
+ appendHistory(root, { id: row.id, event: 'add', commit: headShort(root), hash: row.covers_hash, note: row.property, result: 'unchecked' }, now);
+ return { errors: [], row };
+}
+
+export function waive(root, paths, why, now = new Date()) {
+ const rows = readLedger(root);
+ const reason = String(why ?? '').trim();
+ if (reason.length < 12) return { errors: ['--why must say, in a sentence, why no property can be written for this code'] };
+ const added = [];
+ for (const entry of paths.flatMap(splitCovers)) {
+ if (!fs.existsSync(path.join(root, entry))) return { errors: ['no such path: ' + entry] };
+ const id = 'waived-' + entry.replace(/[^a-z0-9]+/gi, '-').toLowerCase().replace(/^-|-$/g, '');
+ if (rows.some((row) => row.id === id)) continue;
+ rows.push({ id, kind: 'waived', property: reason, covers: entry, covers_hash: hashCovers(root, [entry]).hash, command: '', level: '', red: '', status: 'waived', checked_at: timestamp(now), commit: headShort(root), ran_hash: '' });
+ appendHistory(root, { id, event: 'waive', commit: headShort(root), hash: '', note: reason, result: 'waived' }, now);
+ added.push(id);
+ }
+ writeLedger(root, rows);
+ return { errors: [], added };
+}
+
+// Runs the check. It records the result and the commit, and leaves the sync hash alone: a green run does not prove the model still
+// describes new code, only that the old description still holds. sync is the step that says someone read the change.
+export function runRow(root, row, { timeoutMs = 600000, now = new Date() } = {}) {
+ const started = Date.now();
+ const result = spawnSync('sh', ['-c', row.command], { cwd: root, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, NODE_TEST_CONTEXT: '' } });
+ const output = (result.stdout ?? '') + (result.stderr ?? '');
+ let ok = result.status === 0;
+ let note = ok ? 'exit 0' : result.error?.code === 'ETIMEDOUT' ? 'timed out after ' + Math.round(timeoutMs / 1000) + ' s' : 'exit ' + result.status;
+ if (ok && row.level === 'exhaustive' && /^BOUNDED\b/m.test(output)) { ok = false; note = 'the ledger says exhaustive but the checker reported BOUNDED. Raise its limits, or change the level to bounded'; }
+ if (ok && /^FAIL\s+\S/m.test(output)) { ok = false; note = 'exit 0 but the output has a FAIL line'; }
+ row.status = ok ? 'holds' : 'broken';
+ row.checked_at = timestamp(now);
+ row.commit = headShort(root);
+ row.ran_hash = hashCovers(root, splitCovers(row.covers)).hash;
+ appendHistory(root, { id: row.id, event: 'run', commit: row.commit, hash: row.ran_hash, note: note + ', ' + Math.round((Date.now() - started) / 100) / 10 + ' s', result: ok ? 'holds' : 'broken' }, now);
+ return { ok, note, output };
+}
+
+export function syncRow(root, row, note, now = new Date()) {
+ const said = String(note ?? '').trim();
+ if (said.length < 12) return { errors: ['--note must say what you read and why the property still describes the code'] };
+ if (row.kind === 'waived') return { errors: ['a waiver has nothing to sync'] };
+ if (row.status !== 'holds') return { errors: ['the last run of ' + row.id + ' is ' + row.status + '. Run it and get green before moving the sync forward'] };
+ const hash = hashCovers(root, splitCovers(row.covers));
+ if (hash.missing.length) return { errors: ['covered path is gone: ' + hash.missing.join(', ') + '. Amend the covers first'] };
+ if (row.ran_hash !== hash.hash) return { errors: ['the covered code changed after the last green run of ' + row.id + '. Run it again on the code as it is now, then sync'] };
+ row.covers_hash = hash.hash;
+ appendHistory(root, { id: row.id, event: 'sync', commit: headShort(root), hash: hash.hash, note: said, result: 'holds' }, now);
+ return { errors: [] };
+}
+
+export function amendRow(root, row, changes, evidence, now = new Date()) {
+ const said = String(evidence ?? '').trim();
+ if (said.length < 12) return { errors: ['--evidence must cite why the promise changed on purpose: a commit, a test, a doc line'] };
+ const before = { property: row.property, covers: row.covers, command: row.command, level: row.level };
+ const next = { ...row, ...Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== undefined)) };
+ next.covers = splitCovers(next.covers).join(',');
+ const errors = checkRow(root, next);
+ if (errors.length) return { errors };
+ Object.assign(row, next, { covers_hash: hashCovers(root, splitCovers(next.covers)).hash, status: 'unchecked' });
+ appendHistory(root, { id: row.id, event: 'amend', commit: headShort(root), hash: row.covers_hash, note: 'was ' + JSON.stringify(before) + ' evidence: ' + said, result: 'unchecked' }, now);
+ return { errors: [] };
+}
+
+export function retireRow(root, id, why, now = new Date()) {
+ const said = String(why ?? '').trim();
+ if (said.length < 12) return { errors: ['--why must say why this property no longer applies'] };
+ const rows = readLedger(root);
+ const keep = rows.filter((row) => row.id !== id);
+ if (keep.length === rows.length) return { errors: ['no such property: ' + id] };
+ writeLedger(root, keep);
+ appendHistory(root, { id, event: 'retire', commit: headShort(root), note: said, result: 'retired' }, now);
+ return { errors: [] };
+}
+
+// Which rows cover a path. A row covers a file when it names the file or a folder above it.
+export const covering = (rows, file) => rows.filter((row) => splitCovers(row.covers).some((entry) => file === entry || file.startsWith(entry + '/')));
+
+// Code that changed on this branch since base, that a reader would expect a rule for. Tests, config and the ledger itself are left out.
+export function changedCode(root, base) {
+ const ref = base ?? ['main', 'master'].find((name) => git(root, ['rev-parse', '--verify', '--quiet', name]) !== null) ?? 'HEAD';
+ const mergeBase = ref === 'HEAD' ? 'HEAD' : git(root, ['merge-base', ref, 'HEAD']) ?? ref;
+ const changed = (git(root, ['diff', '--name-only', mergeBase]) ?? '').split('\n');
+ const fresh = (git(root, ['ls-files', '--others', '--exclude-standard']) ?? '').split('\n');
+ return { base: ref, files: [...new Set([...changed, ...fresh])].filter((file) => file && CODE.test(file) && !TEST_FILE.test(file) && !file.startsWith('verify/') && !file.split('/').some((part) => SKIP_DIRS.has(part)) && fs.existsSync(path.join(root, file))).sort() };
+}
+
+export function gaps(root, base) {
+ const rows = readLedger(root);
+ const { files, base: used } = changedCode(root, base);
+ return { base: used, files, uncovered: files.filter((file) => covering(rows, file).length === 0) };
+}
+
+export const PROCEDURE = 'No rule covers this code, so start the verification procedure: read skills/100x/references/properties.md (100x ref properties). Extract what can exist (state), how it changes (transitions), when a step is allowed (preconditions), what is true after it (postconditions), what always holds (invariants) and what must eventually happen under stated assumptions (liveness). Check them with assets/property-checker.mjs or a tool that fits, show each fail on a seeded defect, then 100x verify add. Code with no rule to extract, such as layout or copy, gets 100x verify waive with the reason.';
+
+// What 100x finish asks of the ledger. required is 'properties' when the one thing that must not break is its properties (a real property is
+// needed), 'any' when property checks are on (a property or a waiver with its reason is needed), or false when the owner switched them off.
+export function checkLedger(root, { required = false, base } = {}) {
+ const errors = [];
+ const warnings = [];
+ const rows = readLedger(root);
+ const proper = rows.filter((row) => row.kind !== 'waived');
+ if (required === 'properties' && proper.length === 0) errors.push('the must-not-break kind is properties, but verify/ledger.tsv holds no property. Extract them (100x ref properties) and record each with 100x verify add');
+ else if (required && rows.length === 0) errors.push('verify/ledger.tsv is empty. Property checks are on, so every run records the properties of the code that has logic with 100x verify add, or a waiver with its reason for code with none (100x verify waive <path> --why "<reason>"). The owner turns this off with 100x config set verify.enabled false');
+ for (const row of proper) {
+ const { state, why } = rowState(root, row);
+ if (state !== 'holds') errors.push('property ' + row.id + ' is ' + state + '. ' + why + '. Fix it with 100x verify run ' + row.id + (state === 'stale' ? ' and then 100x verify sync ' + row.id + ' --note "<what you read>"' : ''));
+ }
+ if (rows.length || required) {
+ const found = gaps(root, base);
+ if (found.uncovered.length) {
+ const text = found.uncovered.length + ' changed code file' + (found.uncovered.length === 1 ? ' has' : 's have') + ' no rule and no waiver since ' + found.base + ': ' + found.uncovered.slice(0, 6).join(', ') + (found.uncovered.length > 6 ? ' and ' + (found.uncovered.length - 6) + ' more' : '') + '. 100x verify gaps says what to do';
+ if (required === 'properties') errors.push(text);
+ else warnings.push(text);
+ }
+ }
+ return { errors, warnings, rows };
+}
diff --git a/skills/100x-setup/SKILL.md b/skills/100x-setup/SKILL.md
index 4c60019..2ffd19a 100644
--- a/skills/100x-setup/SKILL.md
+++ b/skills/100x-setup/SKILL.md
@@ -80,7 +80,7 @@ Shortest possible. One idea per line, no paragraphs, no preamble. Use the phrase
Quick jobs: <model>, <effort>
Overnight: <model>, <effort>
```
-6. Write each job with `100x config role <builder|review|fallback|quick|overnight> --provider <instance> --model <id> --option <id=value> --global` (or `--local`). Repeat `--option` for each option. A model only starts under the provider that offers it, so write the pair, and use the option ids exactly as the app's list gives them: one model says `effort`, another says `reasoning_effort`. For every job but the judge, "None" or "same as this chat" is `100x config role <role> --clear`. The judge cannot be cleared, because a second model has to be another one. For "no judge" run `100x config set review.enabled false --global`, and say in one line that runs will then finish with no judge looking. When the judge's vendor is only reachable through another app's command line, also write the judge as a command, using the template for that app in `100x ref apps`: `100x config set review.command '<template>' --global`.
+6. Write each job with `100x config role <builder|review|fallback|quick|overnight> --provider <instance> --model <id> --option <id=value> --global` (or `--local`). Repeat `--option` for each option. A model only starts under the provider that offers it, so write the pair, and use the option ids exactly as the app's list gives them: one model says `effort`, another says `reasoning_effort`. For every job but the judge, "None" or "same as this chat" is `100x config role <role> --clear`. The judge cannot be cleared, because a second model has to be another one. For "no judge" run `100x config set review.enabled false --global`, and say in one line that runs will then finish with no judge looking. Property checks are on by default. For "no property checks" run `100x config set verify.enabled false --global`, and say in one line that runs will then verify nothing. When the judge's vendor is only reachable through another app's command line, also write the judge as a command, using the template for that app in `100x ref apps`: `100x config set review.command '<template>' --global`.
7. A small plan, or a plan standard. A plan standard from step 4 also runs the preset and the helper settings its table in `100x ref plans` names, with the same scope as the jobs, and says in one line that deploys are not part of it. When the owner says they are on a small or $20 plan, are short on usage, or want a cheaper run, offer lite in one line: "Lite does 1 polish round and 2 judge rounds, about 3 judge looks a run and not 8. Say lite to turn it on." On "lite", run `100x config preset lite --global` (or `--local`), and say in one line that the models and the judge stay as they are. "Usual" runs `100x config preset standard` with the same scope. "Medium" runs `100x config preset medium`: 2 polish rounds and 3 judge rounds, about 5 judge looks a run.
8. Only when the owner says "more", list the other settings in plain words, one short line each. Rounds of polish, rounds of judging, features built ahead, how much testing, subagents at once, preview and live deploys, overnight nudges, parallel versions. No keys. Write the answers with `100x config set <key> <value> --global` (or `--local`), translating with the words table.
9. No planner question. One thread plans. If the owner asks for a planner, say in one line there is none and offer to add it.
diff --git a/skills/100x/SKILL.md b/skills/100x/SKILL.md
index 24b9d05..54fe883 100644
--- a/skills/100x/SKILL.md
+++ b/skills/100x/SKILL.md
@@ -61,8 +61,7 @@ These phrases change a run, in `100x` and in `100x-overnight`. Nothing else in a
| `for 10 hours`, `for 2 days`, `until 6am` | use all that time. Finish refuses before it is over |
| `5 rounds of judging` | that many judge rounds |
| `max 5 subagents` | at most 5 helpers at the same time. Default 1 |
-
-`100x-judge` and `100x-grind` read the rounds phrase too, and in a grind it sets the rounds that come before the extra ones. `100x-mockup` ignores all of them and says in its first line what it dropped. Name the phrases you read in the pre-flight, or say there are none. That line is how the owner catches a wrong reading.
+One more phrase works the same way, and it removes work: `no verification` skips the property checks for the run, as `100x config set verify.enabled false --local`. They are on by default. `100x-judge` and `100x-grind` read the rounds phrase too, and in a grind it sets the rounds that come before the extra ones. `100x-mockup` ignores all of them and says in its first line what it dropped. Name the phrases you read in the pre-flight, or say there are none. That line is how the owner catches a wrong reading.
## When you are not sure
@@ -126,6 +125,7 @@ At the end of every stage, update `.100x/STATE.md` (`Stage:`, `Next:`, `Open ris
- **Context.** Long runs fill the window. Keep `STATE.md` true, send long output to files under `.100x/`, open `contact-sheet.png` before single screenshots.
- **Deploy.** Preview when configured. Production only when the brief says so in words.
- **Money and secrets.** No paid service the project does not already have keys for. No secrets in the repo.
+- **No rule, no guess.** On by default, and the planner always does it. The prompt has a `Properties` section, and before you build or change code that carries logic you run `100x verify cover <file>`. Only the owner's words `no verification`, `100x config set verify.enabled false` (`--local` or `--global`) and `100x-mockup` turn it off. A `NO RULE` answer starts the verification procedure in `references/properties.md`: extract the six properties (state, transitions, preconditions, postconditions, invariants, liveness), check them, show each one fail, record them with `100x verify add`. Code with nothing to state gets `100x verify waive` and a reason. The ledger is `verify/ledger.tsv`, kept in git with the code, and `100x finish` refuses a property that is stale, broken or never failed.
- **Claims.** Mark each as measured, inferred or guess in the evidence column of the log. The report states measured things as facts.
- **A judge in every loop.** Every polish pass and every fill round ends by asking a fresh judge, a different model, the brutal question. Write `.100x/loops/<name>/ask.md`, start it with `100x review-call --loop <name>`, answer every finding in `answers.md` before the next loop. One model grading its own loop loses direction. `100x finish` refuses a loop with no judge.
- **In Cursor every helper starts through the SDK, at a 300k window and never in MAX mode.** A judge, a bake-off arm and a child start with `100x helper run` (or `100x review-run`), always with `--context 300k`. Never the Task tool, never `cursor-agent`. `references/apps.md` says why and how.- **The judge always runs.** Stage 6 starts it with `100x review-call`, by your app's subagent tool or by a command. No setting about helpers or counts limits it. Outside `100x-mockup`, only `review.enabled false` turns it off. Never finish UNREVIEWED because you expect to be limited. Try to start it. UNREVIEWED is for a start that failed, with the failure in the note, and `100x finish` refuses it when no attempt is logged.
@@ -135,7 +135,7 @@ At the end of every stage, update `.100x/STATE.md` (`Stage:`, `Next:`, `Open ris
## Where things are
-The other modes are the skills in the table above, next to this one. Helpers: `references/must-not-break.md` (stage 5, with `references/kinds.md` for each kind in detail and `references/shots.md` for the screen runs), `references/watchdog.md` (unattended runs and fill clocks), `references/plans.md` (Claude plan setups), `references/unattended.md` (deciding without the owner), `references/apps.md` (how each agent app differs), `references/open.md` (steps 5, 6 and 8 of Stage 0 in full), `references/looks.md` (the named looks the core and the variants pick from) and `references/mobile-web.md` (read before the first screen when the target is a phone, a touch screen or a game). The judge of stage 6 is the `100x-judge` skill. The other skills of the suite read these guides with `100x ref <name>`, such as `100x ref apps`, so a skill installed on its own still finds them.
+The other modes are the skills in the table above, next to this one. Helpers: `references/must-not-break.md` (stage 5, with `references/kinds.md` for each kind in detail and `references/shots.md` for the screen runs), `references/properties.md` (the verification procedure and the ledger, for stage 5 and for any code no rule covers), `references/watchdog.md` (unattended runs and fill clocks), `references/plans.md` (Claude plan setups), `references/unattended.md` (deciding without the owner), `references/apps.md` (how each agent app differs), `references/open.md` (steps 5, 6 and 8 of Stage 0 in full), `references/looks.md` (the named looks the core and the variants pick from) and `references/mobile-web.md` (read before the first screen when the target is a phone, a touch screen or a game). The judge of stage 6 is the `100x-judge` skill. The other skills of the suite read these guides with `100x ref <name>`, such as `100x ref apps`, so a skill installed on its own still finds them.
`references/decisions.md` for how to write rows. `references/principles.md` for the working principles behind the stance. `100x help` lists every command and `100x help <command>` lists its flags.
diff --git a/skills/100x/assets/property-checker.mjs b/skills/100x/assets/property-checker.mjs
new file mode 100644
index 0000000..aeb2b3d
--- /dev/null
+++ b/skills/100x/assets/property-checker.mjs
@@ -0,0 +1,369 @@
+#!/usr/bin/env node
+// Property checker. Copy into the project, for example .100x/must-not-break/property-checker.mjs.
+// It explores every state a small model of the software can reach and checks the properties you wrote.
+// This is explicit-state model checking with the project's own functions as the transitions.
+// Replace the implementation block and the model block. Keep the engine below the line that says ENGINE.
+//
+// node property-checker.mjs [--json]
+// MAX_STATES=500000 MAX_DEPTH=40 node property-checker.mjs
+//
+// The six kinds of property, and where each one goes in the model.
+// state init() and the shape of the state. Plain JSON data only, because states are compared as text.
+// transitions actions[]. Each has pre (when it may run), apply (the project's own function, pure) and params (values to try).
+// preconditions action.pre. The checker runs the real apply on every state and every parameter. It must accept when
+// pre says yes and refuse (throw, or return the state unchanged) when pre says no. A step the code accepts
+// against the spec is followed too, marked with a !, so the invariants judge what the code really does.
+// postconditions action.post(before, after, param). Checked on every transition that the exploration finds.
+// invariants invariants[]. Checked on every reachable state.
+// liveness liveness[]. "From any state where from holds, a state where to holds is reached". It is decided under
+// fairness: strong (the default) means every step that stays possible is eventually taken, so a run
+// can only stay away from to forever by getting stuck. fairness 'none' also counts a loop that could
+// be left but is never left. Liveness is decided only when the exploration was exhaustive.
+//
+// What the checks claim.
+// exhaustive every reachable state of the model was visited. A pass is a proof for this model and these bounds
+// (the parameter values you listed and the state size you chose).
+// bounded the exploration stopped at MAX_STATES or MAX_DEPTH. A pass means no violation was found in what was
+// visited. It is not a proof, and every liveness line says "not decided".
+// The model is a claim about the software. The proof covers the model, and the checks named guard and post tie the real
+// functions to it. Say in the assumptions what the model leaves out.
+const env = (name, fallback) => (process.env[name] === undefined ? fallback : Number(process.env[name]));
+const MAX_STATES = env('MAX_STATES', 200000);
+const MAX_DEPTH = env('MAX_DEPTH', Infinity);
+
+// ---- The implementation under test. Replace with imports of the project's own functions, which must be pure. ----
+function pay(state, amount) {
+ if (state.status !== 'open') throw new Error('the order is not open');
+ if (!Number.isInteger(amount) || amount < 1) throw new Error('the amount must be a positive whole number');
+ if (state.paid + amount > state.total) throw new Error('the payment is more than what is owed');
+ const paid = state.paid + amount;
+ return { ...state, paid, status: paid === state.total ? 'paid' : 'open' };
+}
+function ship(state) {
+ if (state.status !== 'paid') throw new Error('only a paid order ships');
+ return { ...state, status: 'shipped' };
+}
+function deliver(state) {
+ if (state.status !== 'shipped') throw new Error('only a shipped order is delivered');
+ return { ...state, status: 'delivered' };
+}
+function cancel(state) {
+ if (state.status !== 'open' && state.status !== 'paid') throw new Error('this order can no longer be cancelled');
+ return { ...state, status: 'cancelled' };
+}
+function refund(state) {
+ if (state.status !== 'cancelled') throw new Error('only a cancelled order is refunded');
+ if (state.refunded >= state.paid) throw new Error('nothing is left to refund');
+ return { ...state, refunded: state.paid };
+}
+
+// ---- The model. Replace with the properties of the project. ----
+const settled = (s) => s.status === 'delivered' || (s.status === 'cancelled' && s.refunded === s.paid);
+const model = {
+ name: 'order workflow, total 3',
+ // Say what the model leaves out. Each line is printed with the result.
+ assumptions: [
+ 'payments are whole units from 1 to 3 and the total is 3',
+ 'one order at a time, with no concurrent callers',
+ 'every step that stays possible is eventually taken (strong fairness)',
+ ],
+ init: () => ({ total: 3, status: 'open', paid: 0, refunded: 0 }),
+ // terminal(state) says where the software may stop. Any other state with no possible step is a deadlock.
+ terminal: settled,
+ actions: [
+ {
+ name: 'pay',
+ params: () => [0, 1, 2, 3, 4], // include values that must be refused
+ pre: (s, amount) => s.status === 'open' && amount >= 1 && s.paid + amount <= s.total,
+ apply: pay,
+ post: (before, after, amount) => after.paid === before.paid + amount || 'paid must grow by exactly the amount',
+ },
+ {
+ name: 'ship',
+ pre: (s) => s.status === 'paid',
+ apply: ship,
+ post: (before, after) => after.paid === before.paid || 'shipping must not change the money',
+ },
+ {
+ name: 'deliver',
+ pre: (s) => s.status === 'shipped',
+ apply: deliver,
+ post: (before, after) => after.status === 'delivered' || 'delivering must end in delivered',
+ },
+ {
+ name: 'cancel',
+ pre: (s) => s.status === 'open' || s.status === 'paid',
+ apply: cancel,
+ post: (before, after) => after.paid === before.paid || 'cancelling must not change what was paid',
+ },
+ {
+ name: 'refund',
+ pre: (s) => s.status === 'cancelled' && s.refunded < s.paid,
+ apply: refund,
+ post: (before, after) => after.refunded === before.paid || 'a refund must return exactly what was paid',
+ },
+ ],
+ invariants: [
+ { name: 'money-in-bounds', holds: (s) => (s.refunded >= 0 && s.refunded <= s.paid && s.paid <= s.total) || 'refunded <= paid <= total broke' },
+ { name: 'shipped-means-paid', holds: (s) => !['shipped', 'delivered'].includes(s.status) || s.paid === s.total || 'an order left without full payment' },
+ { name: 'refund-only-after-cancel', holds: (s) => s.refunded === 0 || s.status === 'cancelled' || 'money was refunded on an order that is not cancelled' },
+ ],
+ liveness: [
+ { name: 'every-started-order-settles', from: (s) => s.paid > 0 || s.status !== 'open', to: settled },
+ { name: 'a-cancelled-order-is-refunded', from: (s) => s.status === 'cancelled' && s.paid > 0, to: (s) => s.refunded === s.paid },
+ ],
+};
+
+// ---- ENGINE. No need to edit below this line. ----
+const canon = (value) => JSON.stringify(value, (key, item) => (item && typeof item === 'object' && !Array.isArray(item)
+ ? Object.fromEntries(Object.keys(item).sort().map((name) => [name, item[name]]))
+ : item));
+const say = (value) => { const text = JSON.stringify(value); return text.length > 150 ? `${text.slice(0, 147)}...` : text; };
+const labelOf = (action, param) => (param === undefined ? action.name : `${action.name}(${JSON.stringify(param)})`);
+const verdict = (value) => (value === true || value === undefined ? null : typeof value === 'string' ? value : 'it is false');
+
+const keys = [];
+const states = [];
+const depths = [];
+const out = [];
+const parent = [];
+const open = [];
+const seen = new Map();
+let truncated = false;
+let transitions = 0;
+
+const results = new Map(); // check name -> { ok, detail, trace, count }
+const register = (name) => { if (!results.has(name)) results.set(name, { ok: true, more: 0, count: 0 }); return results.get(name); };
+// The steps to a failure are built only for the first one, because a long run of failures must not cost a path each.
+function fail(name, message, at, extra) {
+ const entry = register(name);
+ if (!entry.ok) { entry.more += 1; return; }
+ entry.ok = false;
+ entry.message = message;
+ entry.labels = at === null ? [] : [...pathTo(at), ...(extra ? [extra] : [])];
+ entry.at = at;
+}
+const pathTo = (index) => { const labels = []; for (let at = index; parent[at]; at = parent[at][0]) labels.unshift(parent[at][1]); return labels; };
+
+function discover(state, from, label) {
+ const key = canon(state);
+ const known = seen.get(key);
+ if (known !== undefined) return known;
+ if (states.length >= MAX_STATES) { truncated = true; return -1; }
+ const index = states.length;
+ seen.set(key, index);
+ keys.push(key);
+ states.push(state);
+ depths.push(from === null ? 0 : depths[from] + 1);
+ out.push([]);
+ open.push(false);
+ parent.push(from === null ? null : [from, label]);
+ return index;
+}
+
+const initial = model.init();
+for (const state of Array.isArray(initial) ? initial : [initial]) discover(state, null, null);
+for (const invariant of model.invariants ?? []) register('inv:' + invariant.name);
+for (const action of model.actions) { register('guard:' + action.name); register('post:' + action.name); }
+register('pure');
+register('deadlock');
+register('coverage');
+const fired = new Set();
+const terminal = model.terminal ?? (() => false);
+
+for (let i = 0; i < states.length; i += 1) {
+ const state = states[i];
+ for (const invariant of model.invariants ?? []) {
+ const entry = register('inv:' + invariant.name);
+ entry.count += 1;
+ const bad = verdict(invariant.holds(state));
+ if (bad) fail('inv:' + invariant.name, bad, i);
+ }
+ if (depths[i] >= MAX_DEPTH) { open[i] = true; truncated = true; continue; }
+ let enabledCount = 0;
+ for (const action of model.actions) {
+ const guard = register('guard:' + action.name);
+ for (const param of action.params ? action.params(state) : [undefined]) {
+ const label = labelOf(action, param);
+ if (action.pre(state, param)) {
+ enabledCount += 1;
+ let next;
+ try {
+ next = action.apply(state, param);
+ } catch (error) {
+ fail('guard:' + action.name, 'the model allows ' + label + ' but the implementation refused it: ' + error.message, i, label);
+ continue;
+ }
+ guard.count += 1;
+ if (canon(state) !== keys[i]) {
+ fail('pure', label + ' changed the state it was given. Return a new state and leave the old one alone', i, label);
+ states[i] = JSON.parse(keys[i]);
+ }
+ fired.add(action.name);
+ const post = register('post:' + action.name);
+ post.count += 1;
+ const bad = action.post ? verdict(action.post(state, next, param)) : null;
+ if (bad) fail('post:' + action.name, bad, i, label);
+ const target = discover(next, i, label);
+ transitions += 1;
+ if (target === -1) open[i] = true;
+ else out[i].push([label, target]);
+ } else if (action.refuses !== false) {
+ let applied = null;
+ try {
+ applied = action.apply(state, param);
+ } catch {
+ guard.count += 1;
+ continue;
+ }
+ if (canon(applied) === keys[i]) guard.count += 1;
+ else {
+ fail('guard:' + action.name, 'the model forbids ' + label + ' but the implementation accepted it and changed the state to ' + say(applied), i, label);
+ // What the code really does is reachable too, so the invariants judge it. A step the code accepts and the spec forbids is marked with a !.
+ const target = discover(applied, i, '!' + label);
+ transitions += 1;
+ if (target === -1) open[i] = true;
+ else out[i].push(['!' + label, target]);
+ }
+ }
+ }
+ }
+ if (enabledCount === 0 && !terminal(state)) fail('deadlock', 'no step is possible and the model does not call this a stopping point', i);
+}
+
+const exhaustive = !truncated;
+const never = model.actions.filter((action) => !fired.has(action.name) && action.optional !== true).map((action) => action.name);
+if (never.length && exhaustive) fail('coverage', 'these steps were never possible in any reachable state: ' + never.join(', ') + '. Check the model, or mark one optional', null);
+
+// Liveness. Strong fairness: a run that avoids to forever must end in a closed set of states that all avoid to.
+function components(allowed) {
+ const index = new Array(states.length).fill(-1);
+ const low = new Array(states.length).fill(0);
+ const onStack = new Array(states.length).fill(false);
+ const comp = new Array(states.length).fill(-1);
+ const stack = [];
+ const comps = [];
+ let counter = 0;
+ for (let root = 0; root < states.length; root += 1) {
+ if (!allowed(root) || index[root] !== -1) continue;
+ index[root] = low[root] = counter; counter += 1;
+ stack.push(root);
+ onStack[root] = true;
+ const work = [[root, 0]];
+ while (work.length) {
+ const frame = work[work.length - 1];
+ const v = frame[0];
+ if (frame[1] < out[v].length) {
+ const w = out[v][frame[1]][1];
+ frame[1] += 1;
+ if (!allowed(w)) continue;
+ if (index[w] === -1) {
+ index[w] = low[w] = counter; counter += 1;
+ stack.push(w);
+ onStack[w] = true;
+ work.push([w, 0]);
+ } else if (onStack[w]) low[v] = Math.min(low[v], index[w]);
+ } else {
+ work.pop();
+ if (work.length) { const u = work[work.length - 1][0]; low[u] = Math.min(low[u], low[v]); }
+ if (low[v] === index[v]) {
+ const members = [];
+ let w;
+ do { w = stack.pop(); onStack[w] = false; comp[w] = comps.length; members.push(w); } while (w !== v);
+ comps.push(members);
+ }
+ }
+ }
+ }
+ return { comp, comps };
+}
+
+const reverse = states.map(() => []);
+states.forEach((_, i) => { for (const [, j] of out[i]) if (j >= 0) reverse[j].push(i); });
+let fullGraph = null;
+
+function checkLiveness(property) {
+ const name = 'live:' + property.name;
+ const entry = register(name);
+ if (!exhaustive) { entry.ok = false; entry.message = 'not decided. The exploration stopped at a bound, so a state that looks stuck may only be unexplored. Raise MAX_STATES and MAX_DEPTH, or shrink the model'; entry.labels = []; entry.at = null; return; }
+ const goal = states.map((state) => Boolean(property.to(state)));
+ const starts = states.map((state, i) => !goal[i] && Boolean(property.from(state)));
+ const count = states.filter((state) => property.from(state)).length;
+ entry.count = count;
+ if (count === 0) { entry.ok = false; entry.message = 'vacuous. No reachable state satisfies from, so nothing was checked'; entry.labels = []; entry.at = null; return; }
+ const seeds = new Set();
+ if ((property.fairness ?? 'strong') === 'strong') {
+ fullGraph ??= components(() => true);
+ fullGraph.comps.forEach((members, id) => {
+ const closed = members.every((v) => out[v].every(([, w]) => fullGraph.comp[w] === id));
+ if (closed && members.every((v) => !goal[v])) for (const v of members) seeds.add(v);
+ });
+ } else {
+ const { comp, comps } = components((v) => !goal[v]);
+ comps.forEach((members) => {
+ const loops = members.length > 1 || out[members[0]].some(([, w]) => w === members[0]);
+ if (loops) for (const v of members) seeds.add(v);
+ });
+ states.forEach((_, v) => { if (!goal[v] && out[v].length === 0) seeds.add(v); });
+ void comp;
+ }
+ // Every state that can reach a seed without passing through to.
+ const doomed = new Set(seeds);
+ const queue = [...seeds];
+ while (queue.length) {
+ const v = queue.shift();
+ for (const u of reverse[v]) if (!goal[u] && !doomed.has(u)) { doomed.add(u); queue.push(u); }
+ }
+ const bad = starts.findIndex((isStart, i) => isStart && doomed.has(i));
+ if (bad === -1) return;
+ // The way from the bad state into the trap, staying away from to.
+ const via = new Map([[bad, null]]);
+ const walk = [bad];
+ let trapped = seeds.has(bad) ? bad : -1;
+ for (let at = 0; at < walk.length && trapped === -1; at += 1) {
+ for (const [label, w] of out[walk[at]]) {
+ if (goal[w] || via.has(w)) continue;
+ via.set(w, [walk[at], label]);
+ walk.push(w);
+ if (seeds.has(w)) { trapped = w; break; }
+ }
+ }
+ const tail = [];
+ for (let at = trapped; via.get(at); at = via.get(at)[0]) tail.unshift(via.get(at)[1]);
+ entry.ok = false;
+ entry.message = 'from ' + say(states[bad]) + ' the run can stay away from to forever. It gets stuck at ' + say(states[trapped]);
+ entry.labels = [...pathTo(bad), ...tail];
+ entry.at = trapped;
+}
+for (const property of model.liveness ?? []) checkLiveness(property);
+
+const level = exhaustive ? 'exhaustive' : 'bounded';
+const deepest = depths.reduce((most, depth) => Math.max(most, depth), 0);
+const describe = (name, entry) => {
+ if (!entry.ok) {
+ const trace = entry.labels?.length ? ' Steps: ' + entry.labels.join(', ') + '.' : '';
+ const more = entry.more ? ' (and ' + entry.more + ' more)' : '';
+ return entry.message + more + '.' + trace;
+ }
+ if (name.startsWith('inv:')) return entry.count + ' states checked, ' + level;
+ if (name.startsWith('guard:')) return entry.count + ' enabled and refused cases agree with the implementation, ' + level;
+ if (name.startsWith('post:')) return entry.count + ' transitions checked, ' + level;
+ if (name === 'pure') return 'no apply changed its input';
+ if (name === 'deadlock') return 'every state has a step or is a stopping point, ' + level;
+ if (name === 'coverage') return exhaustive ? 'every step was possible somewhere, ' + fired.size + ' of ' + model.actions.length : fired.size + ' of ' + model.actions.length + ' steps reached so far. Not decided on a bounded search';
+ if (name.startsWith('live:')) return 'holds from ' + entry.count + ' states under ' + ((model.liveness.find((p) => 'live:' + p.name === name).fairness ?? 'strong')) + ' fairness, exhaustive';
+ return 'ok';
+};
+const checks = [...results].map(([name, entry]) => ({ name, ok: entry.ok, level: name.startsWith('live:') || exhaustive ? level : 'bounded', detail: describe(name, entry) }));
+
+if (process.argv.includes('--json')) {
+ console.log(JSON.stringify({ model: model.name, exhaustive, states: states.length, transitions, depth: deepest, assumptions: model.assumptions ?? [], checks }, null, 2));
+} else {
+ console.log('Model ' + model.name + '. ' + states.length + ' states, ' + transitions + ' transitions, deepest path ' + deepest + '.');
+ console.log(exhaustive
+ ? 'Exhaustive. Every reachable state was visited, so a pass is a proof for this model and these bounds.'
+ : 'BOUNDED. The exploration stopped at ' + MAX_STATES + ' states or depth ' + MAX_DEPTH + '. A pass means nothing was found in what was visited, not a proof.');
+ for (const line of model.assumptions ?? []) console.log(' assumes ' + line);
+ for (const check of checks) console.log((check.ok ? 'pass' : 'FAIL') + ' ' + check.name + '. ' + check.detail);
+}
+process.exitCode = checks.every((check) => check.ok) ? 0 : 1;
diff --git a/skills/100x/references/kinds.md b/skills/100x/references/kinds.md
index 7a86950..2d27167 100644
--- a/skills/100x/references/kinds.md
+++ b/skills/100x/references/kinds.md
@@ -44,6 +44,17 @@ Idle and incremental games live or die on how fast things come.
Done means all simulator checks pass and the late game screenshots have no broken findings. Show the check can fail with `TAPS=0` (dead start) or a growth rate of 2 (stall).
+## properties
+
+Anything with logic that can be stated: a workflow, a permission rule, a state machine, a parser, a protocol, a money flow.
+
+1. Find the well defined part and pull it into functions that only use their inputs.
+2. Write the six properties in plain sentences with the repo's names: state, transitions, preconditions, postconditions, invariants and liveness under named assumptions. [properties.md](properties.md) has the table and the procedure.
+3. Start from `assets/property-checker.mjs`. Replace the implementation block with imports of the project's own functions and the model block with the properties. The checker visits every reachable state and prints `pass` or `FAIL` for each invariant, each step's guard and postcondition, deadlock, coverage and each liveness line, with the shortest steps to a failure.
+4. Record each property with `100x verify add`, with a failing run on a seeded defect in `verify/red/<id>.txt`, then `100x verify run`.
+
+Done means every property holds at the level the ledger names, `100x verify status` shows no stale, broken or unproven row, and the output says whether the search was exhaustive. Show the check can fail: remove a guard, change a limit, or make one step loop, and watch a named property go red. `FAIL guard:pay` means the code and the spec disagree about when a step is allowed. `FAIL live:...` gives the steps into the state the run never leaves.
+
## fresh-data
Apps that show fetched or cached data.
diff --git a/skills/100x/references/must-not-break.md b/skills/100x/references/must-not-break.md
index 1d9cdc1..253cebf 100644
--- a/skills/100x/references/must-not-break.md
+++ b/skills/100x/references/must-not-break.md
@@ -14,13 +14,14 @@ Write one sentence under `## Must not break` in `.100x/project.md`. "If X is wro
|---|---|---|---|
| `screen-sizes` | apps you touch, games, dashboards, anything with a canvas | `100x shots --matrix all-rotate --resize-test` on every important screen state | 0 broken, every weak line fixed or explained, and you looked at `contact-sheet.png` |
| `numbers` | money, prices, scores, tax, units, contracts | tests on functions that only use their inputs: rules that must always hold, plus cases with a known right answer | all pass, and the check goes red when you put a bug in on purpose |
+| `properties` | anything with real logic: workflows, permissions, state machines, parsers, protocols, money flows | the six properties (state, transitions, preconditions, postconditions, invariants, liveness) pulled out of the code and checked exhaustively on a small model that runs the project's own functions, kept in `verify/ledger.tsv` | every property holds, each failed on a seeded defect, each row says its level (`exhaustive`, `bounded` or `sampled`) |
| `game-economy` | idle and incremental games | the economy simulator, plus late game saves through `--init-script` | all checks pass and the table of times between buys rises like a curve |
| `fresh-data` | anything that shows fetched or saved data | the fresh-data check on each source, plus the empty, error and offline screens | fresh data passes, old data fails with a clear message |
| `assets` | art, sound or models are the product | `assets/asset-check.mjs`, then look at every asset where it is used | the script passes and the set looks like one person made it |
| `text` | apps with lots of words, marketing, docs | `100x shots` per state, `100x text lint` on its `texts.txt`, then read the strings as a stranger | lint clean and nothing vague left |
| `main-flow` | nothing above fits | the main flow from start to end with `100x shots --steps`, console clean | the flow finishes at phone and desktop sizes |
-More detail for each kind is in [kinds.md](kinds.md). How to run the screen shots is in [shots.md](shots.md).
+More detail for each kind is in [kinds.md](kinds.md). The `properties` kind and the verification ledger are in [properties.md](properties.md), which also says when to start that procedure outside this stage: any time `100x verify cover <file>` finds no rule. How to run the screen shots is in [shots.md](shots.md).
## Step 2. Write the check as code
@@ -30,6 +31,7 @@ More detail for each kind is in [kinds.md](kinds.md). How to run the screen shot
- `assets/economy-simulator.mjs` and `assets/seed-localstorage.js` for `game-economy`.
- `assets/fresh-data-check.mjs` for `fresh-data`.
- `assets/asset-check.mjs` for `assets`.
+ - `assets/property-checker.mjs` for `properties`, recorded with `100x verify add` as [properties.md](properties.md) says.
- When the rules sit inside screen code, pull them out first into functions that only use their inputs. That is the most useful change in this stage. It makes the rules testable at all.
- Run the check and save what it prints to `.100x/must-not-break/<kind>.txt`. One way is to end the command with `| tee .100x/must-not-break/<kind>.txt`. A `screen-sizes` check rests on its `all-rotate` run of the prototype, which `100x shots` writes and signs. It needs no output file, and typed words do not count for it.
- That file holds the passing run and nothing else. Keep the failing run from Step 3 in `.100x/must-not-break/<kind>-red.txt`. `100x finish` refuses a pass when that file still has a line that starts with `FAIL`.
diff --git a/skills/100x/references/open.md b/skills/100x/references/open.md
index 5639d17..d7ef412 100644
--- a/skills/100x/references/open.md
+++ b/skills/100x/references/open.md
@@ -4,11 +4,11 @@ Steps 5, 6 and 8 of Stage 0 in `SKILL.md`, in full. Read this when you reach ste
## Step 5. The prompt
-Write the prompt in `.100x/project.md`. The brief is a few lines, so first read what it names, what is already here and what the owner built that is alike. Then write the longer prompt the owner would have written: the brief word for word, the goal, what you read first, the rules, the riskiest unknown, the **Asks** ledger with a proof ask for each claim the stages cannot see, the scope, the test material, what not to do, the assumptions you made instead of asking, the one thing that must not break and its kind (`references/must-not-break.md` lists the kinds), the moment, and the judge focus. Add the stack, the run command, and the modifiers in effect. `references/prompt.md` says how and `references/prompt-example.md` shows two. Run `100x prompt check` and fix what it names. Take about 15 minutes, plus the reading the brief names. The question from "When you are not sure" comes before this step, so inside the prompt you decide and log, and never ask.
+Write the prompt in `.100x/project.md`. The brief is a few lines, so first read what it names, what is already here and what the owner built that is alike. Then write the longer prompt the owner would have written: the brief word for word, the goal, what you read first, the rules, the riskiest unknown, the **Asks** ledger with a proof ask for each claim the stages cannot see, the scope, the test material, what not to do, the assumptions you made instead of asking, the one thing that must not break and its kind (`references/must-not-break.md` lists the kinds), the properties of the part with logic (`references/properties.md`: state, transitions, preconditions, postconditions, invariants and liveness, or `none: <reason>`), the moment, and the judge focus. Add the stack, the run command, and the modifiers in effect. `references/prompt.md` says how and `references/prompt-example.md` shows two. Run `100x prompt check` and fix what it names. Take about 15 minutes, plus the reading the brief names. The question from "When you are not sure" comes before this step, so inside the prompt you decide and log, and never ask.
## Step 6. Modifiers
-Modifiers. `3 versions` runs `100x config set variants.count 3 --local` and reads `references/variants.md`. `5 rounds of judging` runs `100x config set review.rounds 5 --local`. `max 5 subagents` runs `100x config set subagents.atOnce 5 --local`. A length of work (`for 10 hours`, `for 2 days`, `until 6am`) means use all of it: run `100x clock set "<the owner's words>" --fill`, for example `100x clock set "for 10 hours" --fill`, and arm the watchdog, see `references/watchdog.md`. Call the skill the way your app does when you tell the owner what to say, `/100x` in Claude Code and Cursor and `$100x` in Codex. Record every number phrase in effect under Modifiers in `project.md`. Add `Mode: overnight` when `100x-overnight` sent you here, and `Grind: yes` when `100x-grind` did, and then run `100x config set review.grind true --local`.
+Modifiers. `3 versions` runs `100x config set variants.count 3 --local` and reads `references/variants.md`. `5 rounds of judging` runs `100x config set review.rounds 5 --local`. `max 5 subagents` runs `100x config set subagents.atOnce 5 --local`. A length of work (`for 10 hours`, `for 2 days`, `until 6am`) means use all of it: run `100x clock set "<the owner's words>" --fill`, for example `100x clock set "for 10 hours" --fill`, and arm the watchdog, see `references/watchdog.md`. Call the skill the way your app does when you tell the owner what to say, `/100x` in Claude Code and Cursor and `$100x` in Codex. `no verification` runs `100x config set verify.enabled false --local`, and then the prompt has no Properties section and the final message says nothing was verified. Property checks are on otherwise, whatever the owner's global setting says unless it is `false`. Record every number phrase in effect under Modifiers in `project.md`. Add `Mode: overnight` when `100x-overnight` sent you here, and `Grind: yes` when `100x-grind` did, and then run `100x config set review.grind true --local`.
## Step 8. The pre-flight
diff --git a/skills/100x/references/prompt-example.md b/skills/100x/references/prompt-example.md
index a834954..6607aa6 100644
--- a/skills/100x/references/prompt-example.md
+++ b/skills/100x/references/prompt-example.md
@@ -57,6 +57,14 @@ none: no outside files are needed, because the tests run on a fixed clock
## Must not break
Kind game-economy, then screen-sizes. Away earnings equal the same time of play, capped at 8 hours, and never go negative or drop after a reload.
+## Properties
+- State: coins, owned counts per upgrade, last seen time and prestige points, all finite numbers.
+- Transitions: tap, buy one upgrade, tick for a number of seconds, go away and return, prestige reset.
+- Preconditions: a buy needs coins at or above the price. Prestige needs at least one earned point.
+- Postconditions: a buy lowers coins by exactly the price. Returning pays what the same seconds of play would have paid.
+- Invariants: coins never go negative or past 1e300, and owned counts never drop except by prestige.
+- Liveness: from any save the player can buy again within the stall limit, under a player who taps three times a second.
+
## Moment
The lamp lights, the beam sweeps across the water, and a small ship turns toward it.
@@ -123,6 +131,14 @@ Three of the owner's TypeScript repos, found with `ls ~/Documents/GitHub/*/tscon
## Must not break
Never call a used export dead. If it does, the owner deletes working code and stops trusting the tool. Kind main-flow, with the planted case and the control as the check, and the real input run for the count of wrong findings.
+## Properties
+- State: the set of exports found, the references found and the report lines.
+- Transitions: scan a file, resolve one import, classify one export.
+- Preconditions: classify runs only after every file of the scan was read.
+- Postconditions: every reported export has no reference in the scanned files.
+- Invariants: an export with any reference is never reported dead, and the same input gives the same report.
+- Liveness: a scan ends within the size cap on any folder, under a disk that answers every read.
+
## Moment
The first run on a repo the owner knows well: the list is short and every line is right.
diff --git a/skills/100x/references/prompt.md b/skills/100x/references/prompt.md
index 85fce31..5d670a2 100644
--- a/skills/100x/references/prompt.md
+++ b/skills/100x/references/prompt.md
@@ -32,9 +32,10 @@ Write `none: <reason>` when there is nothing to read, such as an empty folder an
- **Test material.** The exact inputs: paths, sizes, counts. Say which you may only read, which you copy before you change them, what is made anonymous in anything that ships, and where raw output stays. Write into no other project.
- **Do not.** The hazards of this problem, and what the work may not run, install or write: the audited project's own commands, git state, anything outside this folder. The standing rules are in the skill already, so leave them out.
- **Assumptions.** One line per thing you decided instead of asking.
+- **Properties.** The verifiable properties of the part that has logic, one line each, in the repo's own names: state (what can exist), transitions (how it changes), preconditions (when a step is allowed), postconditions (what is true after), invariants (what always holds) and liveness (what must eventually happen, and the assumption it needs). `references/properties.md` says how to find them and what checks them. Write `none: <reason>` for a project with nothing to state, such as a page of copy, and then waive its code with `100x verify waive`. The section is not asked for when the owner turned property checks off with `verify.enabled false`.
- **Must not break, Moment, Judge focus.** As stage 0 says. The judge focus is two to six questions a judge can answer by running the thing, such as "does the total match a hand count?"
-The check wants every section written and not left as the template's hint, at least three rule lines, three asks that count (a dropped one does not), two judge focus lines and a question mark in the riskiest unknown. Lines in a code fence are a quotation and subheadings are titles, so neither counts toward those numbers. Stack and run, Modifiers and Pre-flight are not part of the prompt, so it does not ask for them. Stage 0 records them beside it. Only Read first, Test material, Do not and Assumptions may say `none: <reason>`, and are then left out of the exported text. The other sections cannot, because every build has them.
+The check wants every section written and not left as the template's hint, at least three rule lines, three asks that count (a dropped one does not), two judge focus lines and a question mark in the riskiest unknown. Lines in a code fence are a quotation and subheadings are titles, so neither counts toward those numbers. Stack and run, Modifiers and Pre-flight are not part of the prompt, so it does not ask for them. Stage 0 records them beside it. Properties needs three lines, one per property it states. Only Read first, Test material, Do not, Properties and Assumptions may say `none: <reason>`, and are then left out of the exported text. The other sections cannot, because every build has them.
## 3. Proof asks
diff --git a/skills/100x/references/properties.md b/skills/100x/references/properties.md
new file mode 100644
index 0000000..d09c3fb
--- /dev/null
+++ b/skills/100x/references/properties.md
@@ -0,0 +1,64 @@
+# Properties
+
+The way to turn software into claims that a program can check, and to keep those claims true as the code changes. Used when the one thing that must not break has logic in it, and whenever 100x is about to build or change code that no rule covers.
+
+You cannot formally verify a whole program. You can pull verifiable properties out of almost any well-defined part of one. Find that part, state what it promises in six kinds of property, check each with the cheapest tool that can fail, and write the result in the ledger so it stays true on every branch.
+
+## When this starts
+
+Always, unless the owner turned it off. Property checks are on by default for every run, and the planner writes a `Properties` section into the prompt at Stage 0. The owner turns them off by saying `no verification` in the brief, with `100x config set verify.enabled false --local` for one project, or with `--global` for every project. `100x-mockup` skips them. When they are off, the final message says nothing was verified. Do not turn them off yourself.
+
+- **No rule covers the code.** Before you build or change code that carries logic, run `100x verify cover <file>`. It prints the property or the waiver that covers each file, or `NO RULE`. `NO RULE` is not a reason to guess. It starts this procedure. `100x verify gaps` lists every changed code file with no rule.
+- **Stage 0.** The one thing that must not break has logic, such as rules, workflows, money, scores, permissions, a state machine, a parser or a protocol. Name kind `properties` in [must-not-break.md](must-not-break.md).
+- **A property goes stale.** `100x verify status` says `stale`: the covered code changed after the last sync. Do the upkeep pass below.
+
+Code with nothing to state, such as layout, copy and glue, gets `100x verify waive <path> --why "<reason>"`. A waiver is a recorded decision, so the next run does not ask again.
+
+## The procedure
+
+1. **Find the part that is well defined.** Look for the functions of state: rules that take inputs and give outputs, steps that move an object between states, limits and permissions. If the rules sit inside screen code, pull them into functions that only use their inputs first. That is most of the work, and it is the most useful change.
+2. **Write the six properties.** For the part you found, answer each question in one plain sentence per item, using the repo's own names.
+
+| Question | What you write | Where it goes in the checker |
+|---|---|---|
+| State. What can exist? | The shape of the state and the values each field may take | `init` and the state object |
+| Transitions. How can it change? | Each step that changes state, and the values it is tried with | `actions[]` with `params` and `apply` |
+| Preconditions. When is a step allowed? | The condition under which each step may run | `action.pre`. The checker runs the real code on every allowed and every refused case |
+| Postconditions. What is true after a step? | What the step guarantees about the result, and what it leaves alone | `action.post` |
+| Invariants. What always holds? | Facts true in every reachable state | `invariants[]` |
+| Liveness. What must eventually happen, under which assumptions? | "From any state where A holds, B is reached", and the fairness it needs | `liveness[]`, `terminal` and `assumptions` |
+
+ Write each as something that can be false. "Money is handled correctly" is not a property. "Refunded never exceeds paid, and paid never exceeds the total" is.
+3. **Pick the tool that can answer.** The ladder, cheapest first, stopping at the first that fits.
+ - `assets/property-checker.mjs`. A dependency-free explicit-state checker. It runs the project's own pure functions as the transitions, visits every reachable state of a small model, and checks all six kinds of property. A pass is a proof for the model and its bounds. It needs a model small enough to enumerate: a few thousand to a few hundred thousand states.
+ - Property tests (`assets/money-checks.test.mjs`). For rules over large input ranges where enumeration is out of reach. The level is `sampled`.
+ - A model checker such as TLA+ with TLC, Alloy or Apalache, when events can happen in a bad order across several actors and Java and the tool are installed. Write the model from the code, name the code each step stands for, and put the command in the ledger.
+ - A prover or code-level verifier (Dafny, Lean, Kani, Frama-C) for a property that must hold at every size. Use one only when the repo's developers can install and run it.
+ When none fits, say so in the ledger as a `sampled` check with real inputs from the code, never a hand model of the function.
+4. **Tie the model to the code.** In the checker, `apply` is the project's own function and `pre` and `post` are the spec. The `guard` lines fail when the code accepts what the spec forbids or refuses what the spec allows. This is what stops a model from describing code that does not exist. In another tool, name the file and function each step stands for.
+5. **Make it fail.** For each property, seed one defect in a throwaway copy of the covered code (`mkdir -p /tmp/red && git archive HEAD | tar -x -C /tmp/red`): remove a guard, reorder a step, drop a limit. Run the check there and save the output to `verify/red/<id>.txt`. It must hold a `FAIL` line that names the defect. If the check stays green, it checks nothing: fix the check, not the defect.
+6. **Record it.** `100x verify add <id> --kind <kind> --property "<sentence>" --covers <paths> --command "<cmd>" --level <level>`, then `100x verify run <id>`. One row per property. Copy the checker into the project (for example `verify/check.mjs`) so the command is cheap and the ledger lives with the code. Add `| tee .100x/must-not-break/properties.txt` to the run when this is the must-not-break check.
+7. **Read findings as findings.** When the current code breaks a property, say it as the shortest list of steps in the code's own words and the harm in one sentence. Do not weaken the property, the model or the bound to get green, and do not change product code to hide it. A fix is a separate change.
+
+## What a pass means
+
+- `exhaustive`. Every reachable state of the model was visited. The property holds for this model, these parameter values and this size. The model is a claim about the software, so a pass covers the model, plus the real functions the guard and post checks ran.
+- `bounded`. The search stopped at a limit. No violation was found in what was visited. Liveness is never decided on a bounded search, and the checker says so.
+- `sampled`. Random or chosen cases. A pass finds nothing in those cases and proves nothing about the rest.
+- **Assumptions.** Say what the model leaves out: concurrency you did not model, the clock, the network, the values you did not try. Every liveness line holds only under the fairness you named: strong means every step that stays possible is eventually taken.
+- Never write "verified" for a `sampled` or `bounded` check. Write the level.
+
+## Keeping it true
+
+The ledger (`verify/ledger.tsv`, tracked by git) and the log (`verify/history.tsv`, append only) travel with the branch. Each row holds a hash of the code it covers, so drift is found by the machine and not by anyone's memory.
+
+- `100x verify status` says `holds`, `stale`, `broken`, `unproven` or `unchecked` for every row and exits 1 unless all hold. Run it in CI. `100x finish` refuses a run with a property that is not holding.
+- **Stale** (covered code changed). Read every change to the covered files. For each change decide one of four things: no effect on what the model describes, the model no longer describes the code, the promise changed on purpose, or the promise may be broken. Update the model and checker from the code, never from the result. Run the check. Seed one new defect and watch the check catch it. Then `100x verify sync <id> --note "<what you read>"`, which moves the hash forward and is logged.
+- **Broken** (the last run failed). Replay the counterexample against the real code, step by step. A step the code cannot take means the model is wrong: fix the model and say what was wrong. Every step possible means a bug: report it with the steps, the harm and the commit that introduced it.
+- **The promise changed on purpose.** `100x verify amend <id> --evidence "<commit, test or doc>" --property "<new sentence>"`. The old wording and the evidence go to the log, and the row is unchecked until it runs again. A property is never edited in place to get green.
+- **No longer applies.** `100x verify retire <id> --why "<reason>"`.
+- A green run does not move the hash. Only `sync` does, and it needs a green run and a written note.
+
+## Report it
+
+Say what was verified in plain words, the level of each property, the assumptions, what the check found, the one command that reruns it, and what it does not cover. Put the counts in the must-not-break summary, for example "18 checks pass, exhaustive over 13 states, 5 steps, 3 invariants, 2 liveness lines". Never write more certainty than the level.
diff --git a/skills/100x/references/words.md b/skills/100x/references/words.md
index 8838824..52f6769 100644
--- a/skills/100x/references/words.md
+++ b/skills/100x/references/words.md
@@ -58,6 +58,7 @@ Say "max effort" or "high effort". Never say `reasoning_effort` or `effort=max`.
| `watchdog.mode` `schedule` | a timer that nudges a stalled overnight build every N minutes |
| `watchdog.mode` `off` | no nudges |
| `review.enabled` false | no judge, every project says so |
+| `verify.enabled` false | no property checks, every project says nothing was verified |
| `review.grind` true | judging goes on after the usual rounds until a judge says it is ready to ship |
| `review.timeoutMinutes` N | the judge gets N minutes |
diff --git a/test/projects.mjs b/test/projects.mjs
index 5862a18..a4640af 100644
--- a/test/projects.mjs
+++ b/test/projects.mjs
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { cli, write } from './helpers.mjs';
import { PROMPT_MARKER } from '../lib/prompt.mjs';
+import { writeLedger } from '../lib/verify.mjs';
import { sealFile } from '../lib/seal.mjs';
import { gradientPng } from './png.mjs';
@@ -85,6 +86,11 @@ none: no outside files are needed
## Must not break
The glow stays on after a reload, and the total never goes down.
+## Properties
+- State: the glow is on or off, and the total is a whole number of cents.
+- Transitions: tap turns the glow on, reload keeps it, reset turns it off.
+- Invariants: the total never goes down.
+
## Moment
The first tap lights the whole screen.
@@ -137,8 +143,10 @@ export const TRIAGE = `F1 accept. fixed in a1b2c3d, the row wraps at 320px
F2 reject. intentional, the hint is decorative and the real label passes AA at 4.6:1
`;
-export function makeProject(box, { run = runJson(), projectMd = PROJECT_MD, root = box.project, findings = FINDINGS, triage = TRIAGE, matrix = {}, checkFiles = { 'screen-sizes': CHECK_OUTPUT }, hero = PNG, judge = true, rounds = 1, sealed = true, loops = true, reviewRow = true, polished = Number.isInteger(run.polishPasses) ? run.polishPasses : 3, prompted = false } = {}) {
+export function makeProject(box, { run = runJson(), projectMd = PROJECT_MD, root = box.project, findings = FINDINGS, triage = TRIAGE, matrix = {}, checkFiles = { 'screen-sizes': CHECK_OUTPUT }, hero = PNG, judge = true, rounds = 1, sealed = true, loops = true, reviewRow = true, polished = Number.isInteger(run.polishPasses) ? run.polishPasses : 3, prompted = false, ledger = true } = {}) {
cli(['init', '--no-git'], { cwd: root, env: box.env });
+ // Property checks are on by default, so a finishable run has a ledger. The fixture has nothing to state, and says so in a waiver.
+ if (ledger) writeLedger(root, [{ id: 'waived-fixture', kind: 'waived', property: 'the fixture has no logic to state', covers: 'fixture', covers_hash: '', status: 'waived' }]);
// The run command the fixture names has to be one this folder can start.
const manifest = path.join(root, 'package.json');
if (/^(?:\w+=\S+\s+)*(?:npm|pnpm|yarn|bun)\s/.test(run.runCmd ?? '') && !fs.existsSync(manifest)) fs.writeFileSync(manifest, JSON.stringify({ scripts: { dev: 'vite', start: 'node server.js' } }));
diff --git a/test/prompt.test.mjs b/test/prompt.test.mjs
index 5621853..3b4e61a 100644
--- a/test/prompt.test.mjs
+++ b/test/prompt.test.mjs
@@ -54,7 +54,7 @@ test('check names every section that is still the template, and exits 1', () =>
assert.equal(result.code, 1);
const report = JSON.parse(result.out);
assert.equal(report.style, 'prompt');
- assert.deepEqual(report.problems.map((problem) => problem.section), ['Brief', 'Goal', 'Read first', 'Rules', 'Riskiest unknown', 'Asks', 'Scope', 'Test material', 'Do not', 'Assumptions', 'Must not break', 'Moment', 'Judge focus']);
+ assert.deepEqual(report.problems.map((problem) => problem.section), ['Brief', 'Goal', 'Read first', 'Rules', 'Riskiest unknown', 'Asks', 'Scope', 'Test material', 'Do not', 'Assumptions', 'Must not break', 'Properties', 'Moment', 'Judge focus']);
const text = run(box, 'prompt', 'check');
assert.match(text.out, /## Rules in project\.md is still the template's hint\. Write it\./);
assert.match(text.out, /## Read first in project\.md is still the template's hint\. Write it, or put "none: <reason>" under it\./);
@@ -69,7 +69,7 @@ test('a finished prompt passes, in any line ending, and the report counts it', (
assert.deepEqual(result.problems, []);
assert.equal(result.asks, 3, 'the asks that count, with CRLF too, and not the dropped one');
assert.deepEqual(result.none, [{ name: 'Test material', reason: 'no outside files are needed' }]);
- assert.match(run(box, 'prompt', 'check').out, /^prompt ok\. 12 written, 1 marked none, 3 asks/);
+ assert.match(run(box, 'prompt', 'check').out, /^prompt ok\. 13 written, 1 marked none, 3 asks/);
box.cleanup();
}
});
@@ -505,6 +505,8 @@ test('the phrases the lint looks for are the phrases in the router\'s number tab
}
const phrases = rows.flatMap((cell) => [...cell.matchAll(/`([^`]+)`/g)].map((hit) => hit[1]));
assert.deepEqual(phrases, ['3 versions', 'for 10 hours', 'for 2 days', 'until 6am', '5 rounds of judging', 'max 5 subagents']);
+ assert.ok(lines.join('\n').includes('`no verification`'), 'the router names the phrase that switches property checks off');
+ assert.equal(triggerHits('Keep it small, no verification please.')[0]?.word, 'verification');
for (const phrase of phrases) assert.ok(triggerHits(phrase).length > 0, `"${phrase}" is in the router's table and the lint does not know it`);
const modeWords = 'a status page for my shop, an overnight oats app, a mockup tool, wrap up the resume builder, report cards, explain this page, morning habits, continue reading, judge a contest, setup guide, an adhd planner, a quick fast rapid prototype mvp';
assert.deepEqual(triggerHits(modeWords), [], 'a word that names a mode is a plain word in a brief');
diff --git a/test/templates.test.mjs b/test/templates.test.mjs
index a942cdb..e0a1728 100644
--- a/test/templates.test.mjs
+++ b/test/templates.test.mjs
@@ -159,3 +159,87 @@ test('the asset check passes a clean folder and names empty, corrupt, oversized,
assert.equal(node([path.join(TEMPLATES, 'asset-check.mjs')]).status, 2);
box.cleanup();
});
+
+// ---- property checker ----
+const CHECKER = path.join(TEMPLATES, 'property-checker.mjs');
+const mutate = (box, from, to, name = 'mutant.mjs') => {
+ const source = fs.readFileSync(CHECKER, 'utf8');
+ assert.ok(source.includes(from), 'the mutation target exists in the template: ' + from);
+ const file = path.join(box.dir, name);
+ fs.writeFileSync(file, source.replace(from, () => to));
+ return file;
+};
+const failing = (result) => result.stdout.split('\n').filter((line) => line.startsWith('FAIL')).map((line) => line.split('.')[0].replace(/^FAIL {2}/, ''));
+
+test('the property checker proves the example workflow exhaustively, and says what it proved', () => {
+ const ok = node([CHECKER]);
+ assert.equal(ok.status, 0, ok.stdout);
+ assert.match(ok.stdout, /Exhaustive\. Every reachable state was visited/);
+ const json = JSON.parse(node([CHECKER, '--json']).stdout);
+ assert.equal(json.exhaustive, true);
+ assert.deepEqual(json.checks.map((c) => c.name), ['inv:money-in-bounds', 'inv:shipped-means-paid', 'inv:refund-only-after-cancel', 'guard:pay', 'post:pay', 'guard:ship', 'post:ship', 'guard:deliver', 'post:deliver', 'guard:cancel', 'post:cancel', 'guard:refund', 'post:refund', 'pure', 'deadlock', 'coverage', 'live:every-started-order-settles', 'live:a-cancelled-order-is-refunded']);
+ assert.ok(json.checks.every((c) => c.ok && c.level === 'exhaustive'));
+ assert.ok(json.assumptions.length >= 3);
+});
+
+test('the property checker goes red on a missing guard, naming the property and the steps', () => {
+ const box = sandbox();
+ const red = node([mutate(box, " if (state.paid + amount > state.total) throw new Error('the payment is more than what is owed');\n", '')]);
+ assert.equal(red.status, 1);
+ const names = failing(red);
+ assert.ok(names.includes('guard:pay'), red.stdout);
+ assert.ok(names.includes('inv:money-in-bounds'), red.stdout);
+ assert.match(red.stdout, /FAIL {2}guard:pay\. the model forbids pay\(\d\) but the implementation accepted it/);
+ assert.match(red.stdout, /Steps: .*pay\(\d\)/);
+ box.cleanup();
+});
+
+test('the property checker catches a postcondition that does not hold and a step that changes its input', () => {
+ const box = sandbox();
+ const post = node([mutate(box, 'return { ...state, refunded: state.paid };', 'return { ...state, refunded: state.paid + 1 };')]);
+ assert.ok(failing(post).includes('post:refund'), post.stdout);
+ const impure = node([mutate(box, " return { ...state, status: 'shipped' };", " state.status = 'shipped';\n return state;", 'impure.mjs')]);
+ assert.ok(failing(impure).includes('pure'), impure.stdout);
+ box.cleanup();
+});
+
+test('the property checker finds a deadlock and a state the run can never leave', () => {
+ const box = sandbox();
+ const deadlock = node([mutate(box, "const settled = (s) => s.status === 'delivered' ||", "const settled = (s) => false ||")]);
+ assert.ok(failing(deadlock).includes('deadlock'), deadlock.stdout);
+ assert.match(deadlock.stdout, /FAIL {2}deadlock\. no step is possible and the model does not call this a stopping point/);
+ const stuck = node([mutate(box, "return { ...state, status: 'delivered' };", "return { ...state, status: 'shipped' };", 'stuck.mjs')]);
+ const names = failing(stuck);
+ assert.ok(names.includes('live:every-started-order-settles'), stuck.stdout);
+ assert.match(stuck.stdout, /can stay away from to forever\. It gets stuck at/);
+ box.cleanup();
+});
+
+test('the property checker decides liveness under fairness, and a loop that could be left only fails without it', () => {
+ const box = sandbox();
+ // A retry step that goes back to open. With strong fairness the way out is eventually taken, so settling still holds.
+ const retry = " name: 'retry',\n pre: (s) => s.status === 'paid',\n apply: (s) => { if (s.status !== 'paid') throw new Error('only a paid order is retried'); return { ...s, status: 'open', paid: 1 }; },\n post: () => true,\n },\n {\n name: 'ship',";
+ const withRetry = mutate(box, " name: 'ship',", retry, 'retry.mjs');
+ const strong = node([withRetry]);
+ assert.equal(strong.status, 0, strong.stdout);
+ const source = fs.readFileSync(withRetry, 'utf8').replace("{ name: 'every-started-order-settles', from:", "{ name: 'every-started-order-settles', fairness: 'none', from:");
+ const noFairness = path.join(box.dir, 'nofair.mjs');
+ fs.writeFileSync(noFairness, source);
+ const weak = node([noFairness]);
+ assert.ok(failing(weak).includes('live:every-started-order-settles'), weak.stdout);
+ box.cleanup();
+});
+
+test('the property checker never calls a bounded search a proof, and never decides liveness on one', () => {
+ const bounded = node([CHECKER], { MAX_STATES: '6' });
+ assert.equal(bounded.status, 1);
+ assert.match(bounded.stdout, /BOUNDED\. The exploration stopped/);
+ assert.match(bounded.stdout, /FAIL {2}live:every-started-order-settles\. not decided/);
+ assert.match(bounded.stdout, /pass {2}inv:money-in-bounds\. \d+ states checked, bounded/);
+ const box = sandbox();
+ const vacuous = node([mutate(box, "from: (s) => s.paid > 0 || s.status !== 'open'", 'from: (s) => s.paid > 99')]);
+ assert.match(vacuous.stdout, /FAIL {2}live:every-started-order-settles\. vacuous/);
+ const unused = node([mutate(box, "pre: (s) => s.status === 'shipped',\n apply: deliver,", "pre: (s) => false,\n apply: deliver,", 'unused.mjs')]);
+ assert.match(unused.stdout, /FAIL {2}coverage\. these steps were never possible in any reachable state: deliver/);
+ box.cleanup();
+});
diff --git a/test/verify.test.mjs b/test/verify.test.mjs
new file mode 100644
index 0000000..3ec821b
--- /dev/null
+++ b/test/verify.test.mjs
@@ -0,0 +1,204 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import test from 'node:test';
+import { checkLedger, hashCovers, readLedger } from '../lib/verify.mjs';
+import { cli, ROOT, sandbox, write } from './helpers.mjs';
+
+const CHECKER = path.join(ROOT, 'skills', '100x', 'assets', 'property-checker.mjs');
+const sh = (cwd, command) => spawnSync('sh', ['-c', command], { cwd, encoding: 'utf8' });
+const verify = (box, ...args) => cli(['verify', '--root', box.project, ...args], { cwd: box.project, env: box.env });
+const RED = 'FAIL guard:pay. the model forbids pay(3) but the implementation accepted it\n';
+
+function project() {
+ const box = sandbox();
+ fs.mkdirSync(path.join(box.project, 'verify'), { recursive: true });
+ fs.copyFileSync(CHECKER, path.join(box.project, 'verify', 'check.mjs'));
+ const add = (extra = []) => verify(box, 'add', 'order-money', '--kind', 'invariant', '--property', 'Refunded never exceeds paid and paid never exceeds the total', '--covers', 'verify/check.mjs', '--command', 'node verify/check.mjs', '--level', 'exhaustive', ...extra);
+ return { box, add };
+}
+
+test('a property is unchecked until it runs, unproven until it has failed once, and holds only then', () => {
+ const { box, add } = project();
+ assert.equal(add().code, 0, add().err);
+ assert.match(verify(box, 'status').out, /^unchecked +order-money/);
+ assert.equal(verify(box, 'status').code, 1);
+
+ const run = verify(box, 'run');
+ assert.equal(run.code, 0, run.out);
+ assert.match(run.out, /^pass {2}order-money\. invariant, exhaustive, exit 0/);
+ const unproven = verify(box, 'status');
+ assert.match(unproven.out, /^unproven +order-money.*no failing run in verify\/red\/order-money\.txt/);
+ assert.equal(unproven.code, 1);
+
+ write(path.join(box.project, 'verify', 'red', 'order-money.txt'), 'no failing line here\n');
+ assert.match(verify(box, 'status').out, /has no FAIL line/);
+ write(path.join(box.project, 'verify', 'red', 'order-money.txt'), RED);
+ const holds = verify(box, 'status');
+ assert.match(holds.out, /^holds +order-money/);
+ assert.equal(holds.code, 0);
+ box.cleanup();
+});
+
+test('a change to covered code makes the property stale, and only a fresh green run plus a written note moves it forward', () => {
+ const { box, add } = project();
+ add();
+ write(path.join(box.project, 'verify', 'red', 'order-money.txt'), RED);
+ verify(box, 'run');
+ assert.equal(verify(box, 'status').code, 0);
+
+ const file = path.join(box.project, 'verify', 'check.mjs');
+ fs.writeFileSync(file, fs.readFileSync(file, 'utf8') + '\n// a later edit\n');
+ const stale = verify(box, 'status');
+ assert.match(stale.out, /^stale +order-money.*covered code changed after the last sync/);
+ assert.equal(stale.code, 1);
+
+ const early = verify(box, 'sync', 'order-money', '--note', 'read the edit, it only adds a comment');
+ assert.equal(early.code, 1);
+ assert.match(early.err, /changed after the last green run of order-money\. Run it again/);
+
+ assert.equal(verify(box, 'run', 'order-money').code, 0);
+ assert.match(verify(box, 'status').out, /^stale/, 'a green run alone does not move the sync');
+ assert.equal(verify(box, 'sync', 'order-money', '--note', 'short').code, 1, 'a sync needs a real note');
+ assert.equal(verify(box, 'sync', 'order-money', '--note', 'read the edit, it only adds a comment').code, 0);
+ assert.match(verify(box, 'status').out, /^holds/);
+ const history = verify(box, 'history', 'order-money').out;
+ assert.match(history, /add/);
+ assert.match(history, /sync.*read the edit/);
+ box.cleanup();
+});
+
+test('a failing check is broken, and an exhaustive claim is refused when the checker says it was bounded', () => {
+ const { box, add } = project();
+ add();
+ write(path.join(box.project, 'verify', 'red', 'order-money.txt'), RED);
+ const ledger = path.join(box.project, 'verify', 'ledger.tsv');
+ fs.writeFileSync(ledger, fs.readFileSync(ledger, 'utf8').replace('node verify/check.mjs', 'echo BOUNDED. stopped at 6 states; echo pass x. ok'));
+ const bounded = verify(box, 'run');
+ assert.equal(bounded.code, 1);
+ assert.match(bounded.out, /FAIL {2}order-money\. invariant, exhaustive, the ledger says exhaustive but the checker reported BOUNDED/);
+ assert.match(verify(box, 'status').out, /^broken +order-money/);
+
+ verify(box, 'amend', 'order-money', '--evidence', 'the model is too big for a full search, commit abc1234', '--level', 'bounded');
+ const honest = verify(box, 'run');
+ assert.equal(honest.code, 0, honest.out);
+ assert.match(honest.out, /^pass {2}order-money\. invariant, bounded, exit 0/);
+ assert.match(verify(box, 'status').out, /^holds +order-money +invariant, bounded/);
+ box.cleanup();
+});
+
+test('amend needs evidence, keeps the old wording in the log and leaves the property unchecked', () => {
+ const { box, add } = project();
+ add();
+ write(path.join(box.project, 'verify', 'red', 'order-money.txt'), RED);
+ verify(box, 'run');
+ assert.equal(verify(box, 'amend', 'order-money', '--property', 'Refunds may now exceed what was paid, up to a fee').code, 1);
+ const done = verify(box, 'amend', 'order-money', '--property', 'Refunded never exceeds paid plus the fee', '--evidence', 'fee policy change, commit 9f2c1d0');
+ assert.equal(done.code, 0, done.err);
+ assert.match(verify(box, 'status').out, /^unchecked +order-money/);
+ const history = fs.readFileSync(path.join(box.project, 'verify', 'history.tsv'), 'utf8');
+ assert.match(history, /amend.*Refunded never exceeds paid and paid never exceeds the total.*fee policy change/);
+ assert.equal(verify(box, 'retire', 'order-money', '--why', 'orders moved to another service').code, 0);
+ assert.equal(readLedger(box.project).length, 0);
+ assert.match(fs.readFileSync(path.join(box.project, 'verify', 'history.tsv'), 'utf8'), /retire.*orders moved/);
+ box.cleanup();
+});
+
+test('code with no rule starts the procedure, and a waiver or a property ends the question', () => {
+ const { box, add } = project();
+ sh(box.project, 'git init -q -b main && git config user.email t@t && git config user.name t && git add -A && git commit -qm base');
+ sh(box.project, 'git checkout -q -b feature');
+ write(path.join(box.project, 'src', 'rules.mjs'), 'export const fee = (cents) => Math.floor(cents * 0.03);\n');
+ write(path.join(box.project, 'src', 'rules.test.mjs'), 'import "./rules.mjs";\n');
+ write(path.join(box.project, 'src', 'view.mjs'), 'export const label = () => "hi";\n');
+
+ const cover = verify(box, 'cover', 'src/rules.mjs');
+ assert.equal(cover.code, 2);
+ assert.match(cover.out, /^NO RULE {2}src\/rules\.mjs/m);
+ assert.match(cover.out, /No rule covers this code, so start the verification procedure: read skills\/100x\/references\/properties\.md/);
+
+ const gaps = verify(box, 'gaps');
+ assert.equal(gaps.code, 1);
+ assert.match(gaps.out, /NO RULE {2}src\/rules\.mjs/);
+ assert.match(gaps.out, /NO RULE {2}src\/view\.mjs/);
+ assert.doesNotMatch(gaps.out, /rules\.test\.mjs/, 'a test is not code that needs a rule');
+
+ assert.equal(verify(box, 'waive', 'src/view.mjs', '--why', 'copy and layout, nothing to state').code, 0);
+ assert.equal(verify(box, 'waive', 'src/rules.mjs').code, 1, 'a waiver needs its reason');
+ add(['--covers', 'src/rules.mjs']);
+ const after = verify(box, 'gaps');
+ assert.equal(after.code, 0, after.out);
+ assert.match(verify(box, 'cover', 'src/view.mjs').out, /covered {2}src\/view\.mjs {2}by waived-src-view-mjs \(waived\)/);
+ box.cleanup();
+});
+
+test('finish asks for a ledger only when the run says properties, and refuses a property that is stale or never failed', () => {
+ const { box, add } = project();
+ assert.deepEqual(checkLedger(box.project).errors, [], 'no ledger and no claim is no error');
+ assert.match(checkLedger(box.project, { required: 'properties' }).errors[0], /holds no property/);
+ assert.match(checkLedger(box.project, { required: 'any' }).errors[0], /ledger\.tsv is empty\. Property checks are on/);
+ assert.deepEqual(checkLedger(box.project, { required: false }).errors, [], 'switched off means no ledger is asked for');
+
+ add();
+ const before = checkLedger(box.project).errors;
+ assert.match(before[0], /property order-money is unchecked\. never run\. Fix it with 100x verify run order-money/);
+ write(path.join(box.project, 'verify', 'red', 'order-money.txt'), RED);
+ verify(box, 'run');
+ assert.deepEqual(checkLedger(box.project).errors, []);
+
+ fs.appendFileSync(path.join(box.project, 'verify', 'check.mjs'), '\n// edit\n');
+ const stale = checkLedger(box.project).errors;
+ assert.match(stale[0], /property order-money is stale\..*and then 100x verify sync order-money --note/);
+ assert.notEqual(hashCovers(box.project, ['verify/check.mjs']).hash, readLedger(box.project)[0].covers_hash);
+ box.cleanup();
+});
+
+test('the planner asks for Properties by default, and the owner can turn that off for a project or for every project', async () => {
+ const { PROMPT_MD, makeProject } = await import('./projects.mjs');
+ const { checkPrompt, verifyOn } = await import('../lib/prompt.mjs');
+ const without = PROMPT_MD.replace(/## Properties[\s\S]*?(?=## Moment)/, '');
+ assert.notEqual(without, PROMPT_MD);
+ const box = sandbox();
+ makeProject(box, { projectMd: without, prompted: true, ledger: false });
+ const env = { ...process.env, ...box.env };
+ const keep = Object.fromEntries(Object.keys(box.env).map((key) => [key, process.env[key]]));
+ Object.assign(process.env, box.env);
+ try {
+ assert.equal(verifyOn(box.project), true, 'on unless the owner says otherwise');
+ assert.deepEqual(checkPrompt(box.project).problems.map((problem) => problem.section), ['Properties']);
+
+ assert.equal(cli(['config', 'set', 'verify.enabled', 'false', '--local'], { cwd: box.project, env: box.env }).code, 0);
+ assert.equal(verifyOn(box.project), false);
+ assert.deepEqual(checkPrompt(box.project).problems, [], 'switched off for this project, so the section is not asked for');
+ assert.equal(cli(['config', 'set', 'verify.enabled', 'true', '--local'], { cwd: box.project, env: box.env }).code, 0);
+ assert.equal(verifyOn(box.project), true);
+
+ assert.equal(cli(['config', 'set', 'verify.enabled', 'false', '--global'], { cwd: box.project, env: box.env }).code, 0);
+ assert.equal(cli(['config', 'unset', 'verify.enabled', '--local'], { cwd: box.project, env: box.env }).code, 0);
+ assert.equal(verifyOn(box.project), false, 'switched off for every project');
+ assert.deepEqual(checkPrompt(box.project).problems, []);
+ } finally {
+ for (const [key, value] of Object.entries(keep)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; }
+ void env;
+ box.cleanup();
+ }
+});
+
+test('finish asks for a ledger row by default, accepts a waiver with its reason, and asks for nothing when checks are off', async () => {
+ const { makeProject } = await import('./projects.mjs');
+ const box = sandbox();
+ makeProject(box, { ledger: false });
+ fs.writeFileSync(path.join(box.project, 'index.html'), '<p>copy</p>\n');
+ const asks = cli(['finish', '--check'], { cwd: box.project, env: box.env });
+ assert.match(asks.out + asks.err, /verify\. verify\/ledger\.tsv is empty\. Property checks are on/);
+ verify(box, 'waive', 'index.html', '--why', 'a page of copy, nothing to state');
+ const waived = cli(['finish', '--check'], { cwd: box.project, env: box.env });
+ assert.doesNotMatch(waived.out + waived.err, /verify\./);
+ fs.rmSync(path.join(box.project, 'verify'), { recursive: true });
+ cli(['config', 'set', 'verify.enabled', 'false', '--local'], { cwd: box.project, env: box.env });
+ const off = cli(['finish', '--check'], { cwd: box.project, env: box.env });
+ assert.doesNotMatch(off.out + off.err, /ledger\.tsv is empty/);
+ assert.match(off.out + off.err, /property checks are switched off \(verify\.enabled false\), so nothing was verified/);
+ box.cleanup();
+});