diff --git a/packages/website/src/lib/home-map-layout.ts b/packages/website/src/lib/home-map-layout.ts index 126f05b..f7d001d 100644 --- a/packages/website/src/lib/home-map-layout.ts +++ b/packages/website/src/lib/home-map-layout.ts @@ -215,7 +215,6 @@ export function formatPickerCoordinate(value: number): string { return Number(fixed) === 0 ? (0).toFixed(6) : fixed; } -// ---- The map's view: what part of the drawing the stage shows ------------- // A stage as wide as the drawing (200 by 88 map units) shows all of it. A // phone's stage is at least 60svh tall (docs/design/map-polish-audit.md § 5), // so it shows the drawing's full height and part of its width, centred on the @@ -292,7 +291,6 @@ export function panMapView(view: MapBox, edge: MapEdge, drawing: MapBox = MAP_DR return { ...view, x: Math.min(Math.max(drawing.x, x), drawing.x + drawing.width - view.width) }; } -// ---- The inspector over the map ------------------------------------------- // docs/design/map-polish-audit.md § 5: "When the node would sit under the // dock, the map pans it into the open area", and on a phone "The map pans // the node above the sheet." The map never resizes, so the view moves: it may @@ -393,7 +391,6 @@ export function pointsBeyondView(view: MapBox, points: readonly MapPoint[]): Rec return { west, east }; } -// ---- Pins on the drawing's edge ------------------------------------------- // docs/design/map-polish-audit.md § 5, "Edge pins": "A valid point on the // map's edge, such as a confirmed place on the 180th meridian, still draws // half outside the drawing. The build keeps the audit's clamp: the rendered @@ -473,7 +470,6 @@ export function badgeFallbackCenter( return keepCircleInside(beside, targetRadius, view, cornerRadius); } -// ---- Labels at rest ------------------------------------------------------- // § 5: "Chapter labels at rest ... The highest featuredWeight goes first. // Each label tries right, left, above and below its dot, and hides when it // would touch another label, a pin, a badge, a bar or the dock." diff --git a/scripts/chapter-image-fields.integration.ts b/scripts/chapter-image-fields.integration.ts index 2f94b1a..04a38cc 100644 --- a/scripts/chapter-image-fields.integration.ts +++ b/scripts/chapter-image-fields.integration.ts @@ -183,7 +183,6 @@ try { await sql.unsafe(await readMigration(file)); } - // --- Backfill ----------------------------------------------------------- // Rows as they exist before 029: description in media only, no new columns. const legacyUpload = await uploadFile(); await insertChapter('legacy-approved', { @@ -237,7 +236,6 @@ try { assert.equal(Object.hasOwn(published ?? {}, 'imageAlt'), false); assert.equal(Object.hasOwn(published ?? {}, 'imageFileId'), false); - // --- Update request alt text and credit ----------------------------------- for (const file of migrations.filter((name) => name > IMAGE_MIGRATION && name < REQUEST_MIGRATION)) { await sql.unsafe(await readMigration(file)); } @@ -323,7 +321,6 @@ try { await editRequest(blank, { proposed_image_alt: '', proposed_image_credit: null }); assert.deepEqual(await requestDescription(blank), [null, null]); - // --- New rows ------------------------------------------------------------ // A seeded or imported chapter describes its sourced image in media only. await insertChapter('new-from-media', { media: sourced('new-from-media', { imageAlt: 'Imported alt.', imageCredit: 'Imported credit' }) }); let row = await chapterRow('new-from-media'); @@ -334,7 +331,6 @@ try { row = await chapterRow('new-blank'); assert.deepEqual([row.image_alt, row.image_credit], [null, null]); - // --- Direct edits while the sourced image shows -------------------------- const slug = 'direct'; await insertChapter(slug, { image: '/images/chapters/direct.jpg', @@ -378,7 +374,6 @@ try { row = await chapterRow(slug); assert.deepEqual([row.image_alt, row.image_credit], ['Corrected alt for the second image.', 'Second credit']); - // --- Uploads -------------------------------------------------------------- const firstUpload = await uploadFile(); const secondUpload = await uploadFile(); @@ -455,7 +450,6 @@ try { assert.deepEqual([row.image_alt, row.image_credit], [null, null]); assert.equal(Object.hasOwn((await publicChapter('social-only'))?.media ?? {}, 'imageAlt'), false); - // --- Accepted update requests --------------------------------------------- // Without an image the request describes the image the chapter shows. await acceptRequest(slug, { alt: 'Reviewed alt.' }); row = await chapterRow(slug); @@ -515,7 +509,6 @@ try { assert.deepEqual([row.image_alt, row.image_credit], ['Second accepted alt.', 'Second Photographer']); assert.equal(row.seo.ogImage, social); - // --- Prepared steward sync drafts ------------------------------------------- // The prep script starts a draft from the chapter's current values. Until a // steward edits it, it proposes nothing: accepting it as prepared leaves the // chapter as it was, whether it shows a sourced image or an uploaded one. @@ -569,7 +562,6 @@ try { await sql!`update content.chapter_update_requests set request_status = 'accepted' where id = ${rewritten}::uuid`; assert.deepEqual(await chapterFacts('prepared-upload'), { ...beforeRewrite, summary: 'A summary the steward rewrote.' }); - // --- Alerts --------------------------------------------------------------- // An unreviewed sourced image is withheld; the chapter stays, with one alert. await insertChapter('unreviewed', { image: '/images/chapters/unreviewed.jpg', diff --git a/scripts/directus-text-fields.integration.ts b/scripts/directus-text-fields.integration.ts index 1ac0227..d98365c 100644 --- a/scripts/directus-text-fields.integration.ts +++ b/scripts/directus-text-fields.integration.ts @@ -169,7 +169,6 @@ try { await sql.unsafe(await readMigration(file)); } - // --- Before 033 ------------------------------------------------------------- // Rows shaped like production: a request with its child rows, an initiative, // and a project. await sql`insert into content.chapters ${sql({ slug: 'proof', name: 'Proof chapter' })}`; @@ -201,7 +200,6 @@ try { // An untouched chapter arrived as '' and met the foreign key. assert.equal(await refusal(() => insertInitiative({ slug: 'no-chapter', title: 'No chapter' })), FOREIGN_KEY); - // --- 033 -------------------------------------------------------------------- const beforeMigration = await digest(); await sql.unsafe(textFieldMigration); // Defaults only: no row changes, updated_at included, and no review email queued. @@ -246,7 +244,6 @@ try { assert.equal(await refusal(() => insertInitiative({ slug: 'new-initiative', chapter_slug: 'proof', title: 'New initiative' })), null); assert.equal(await refusal(() => insertProject({ slug: 'new-project', guild_slug: 'proof-guild', name: 'New project' })), null); - // --- Optional fields ------------------------------------------------------------ // An emptied optional field now arrives as '', and its column takes it. const emptied = await refusal(() => sql!` update content.chapter_update_requests diff --git a/scripts/lib/git-guardrails.mjs b/scripts/lib/git-guardrails.mjs new file mode 100644 index 0000000..428b64d --- /dev/null +++ b/scripts/lib/git-guardrails.mjs @@ -0,0 +1,55 @@ +// Git helpers for the diff-aware checks in scripts/quality. Adapted from Green Goods' +// scripts/lib/git-guardrails.mjs; the default base here is origin/main. +import { spawnSync } from 'node:child_process'; + +export function runGit(repoRoot, args, { allowFailure = false } = {}) { + const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); + if (result.error && !allowFailure) throw new Error(`git ${args.join(' ')} failed: ${result.error.message}`); + if (result.status !== 0 && !allowFailure) throw new Error(`git ${args.join(' ')} failed: ${result.stderr.trim()}`); + return result; +} + +function resolves(repoRoot, candidate) { + return ( + runGit(repoRoot, ['rev-parse', '--verify', '--quiet', `${candidate}^{commit}`], { allowFailure: true }).status === 0 + ); +} + +export function parseBaseArgs(argv) { + let base; + for (let index = 0; index < argv.length; index++) { + if (argv[index] === '--base') { + if (!argv[index + 1]) throw new Error('--base requires a Git ref'); + base = argv[++index]; + } else { + throw new Error(`unknown argument: ${argv[index]}`); + } + } + return { base }; +} + +export function resolveGitBase({ repoRoot, explicitBase, environmentVariables = [], fallback = 'origin/main' }) { + if (explicitBase) { + if (!resolves(repoRoot, explicitBase)) throw new Error(`base ref does not resolve to a commit: ${explicitBase}`); + return explicitBase; + } + for (const variable of environmentVariables) { + const candidate = process.env[variable]; + if (candidate && resolves(repoRoot, candidate)) return candidate; + } + return fallback && resolves(repoRoot, fallback) ? fallback : undefined; +} + +/** A Git environment for test fixtures: no user or system config, a fixed identity. */ +export function fixtureGitEnvironment(environment = process.env) { + const inherited = Object.entries(environment).filter(([variable]) => !variable.startsWith('GIT_')); + return { + ...Object.fromEntries(inherited), + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_CONFIG_SYSTEM: '/dev/null', + GIT_AUTHOR_NAME: 'Fixture', + GIT_AUTHOR_EMAIL: 'fixture@example.invalid', + GIT_COMMITTER_NAME: 'Fixture', + GIT_COMMITTER_EMAIL: 'fixture@example.invalid', + }; +} diff --git a/scripts/lib/vite-parse.mjs b/scripts/lib/vite-parse.mjs new file mode 100644 index 0000000..aab1744 --- /dev/null +++ b/scripts/lib/vite-parse.mjs @@ -0,0 +1,17 @@ +// Vite's Oxc parser, for the comment codemod. Vite is not a direct dependency of the repository; +// it comes with Astro, so it is found from the website's Astro install. Declaring it at the root +// instead would re-resolve Rolldown for the whole workspace. +import { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const repoRoot = resolve(fileURLToPath(new URL('../..', import.meta.url))); +const fromWebsite = createRequire(resolve(repoRoot, 'packages/website/package.json')); +const fromAstro = createRequire(fromWebsite.resolve('astro/package.json')); +const vitePackage = fromAstro.resolve('vite/package.json'); +const dot = JSON.parse(readFileSync(vitePackage, 'utf8')).exports['.']; +const entry = typeof dot === 'string' ? dot : (dot.import?.default ?? dot.import ?? dot.default); + +export const { parseSync } = await import(pathToFileURL(resolve(dirname(vitePackage), entry)).href); +if (typeof parseSync !== 'function') throw new Error(`Vite at ${dirname(vitePackage)} has no parseSync`); diff --git a/scripts/map-node-approval-guard.integration.ts b/scripts/map-node-approval-guard.integration.ts index 38dc0d5..4a3666c 100644 --- a/scripts/map-node-approval-guard.integration.ts +++ b/scripts/map-node-approval-guard.integration.ts @@ -199,7 +199,6 @@ try { await sql.unsafe(await readMigration(file)); } - // --- Rows saved before the guard ------------------------------------------ // Until now an approved node at 0,0 could be saved, as the June 2026 client // did for two nodes PRD-1409 later repaired. const legacyHidden = await insertNode({ status: 'approved', latitude: 0, longitude: 0, place_name: 'Port Harcourt' }); @@ -286,7 +285,6 @@ try { assert.deepEqual(await state(repairedFromZero), ['archived', '0.000000', '0.000000']); assert.deepEqual(await state(repairedFromEdge), ['approved', '90.000000', '97.762610']); - // --- Approving a pending node ---------------------------------------------- // At 0,0: refused with a readable error, and the node stays pending. const pendingAtZero = await insertNode({ latitude: 0, longitude: 0, place_name: 'Rotterdam, Netherlands' }); await assertRefused(() => editNode(pendingAtZero, { status: 'approved' }), pendingAtZero, 'null_island', 'approving at 0,0'); @@ -332,7 +330,6 @@ try { assert.equal(approved.status, 'approved'); assert.ok(approved.approved_at instanceof Date); - // --- Saving an approved node directly --------------------------------------- // Live onboarding and admin edits insert approved rows. Every problem the // shared rule names is refused with the guard's own message, before the // column checks from migrations 001 and 018 would refuse the row less clearly. @@ -357,7 +354,6 @@ try { // Pending rows may still hold 0,0, as the June 2026 client wrote them. await insertNode({ latitude: 0, longitude: 0 }); - // --- Owner update requests --------------------------------------------------- // A request that moves an approved node to 0,0 fails, and stays pending. const movedToZero = await insertNode({ status: 'approved', latitude: 6.5244, longitude: 3.3792, place_name: 'Lagos' }); const moveRequest = await insertUpdateRequest(movedToZero, { latitude: 0, longitude: 0 }); @@ -392,7 +388,6 @@ try { assert.equal(renamedNode.display_name, 'Renamed proof node'); assert.deepEqual(await state(renamed), ['approved', '-16.800000', '180.000000']); - // --- Applying it again ------------------------------------------------------- const settled = await everySubmission(); await sql.unsafe(guardMigration); assert.equal(await everySubmission(), settled, 'replaying the guard changed a stored row'); diff --git a/scripts/map-node-contract.test.ts b/scripts/map-node-contract.test.ts index 57a198b..2811f1d 100644 --- a/scripts/map-node-contract.test.ts +++ b/scripts/map-node-contract.test.ts @@ -3354,7 +3354,6 @@ test('home map inspector: the dock, the sheets and the compact tooltip (map-poli assert.doesNotMatch(component, /shouldRecoverMobileView/); }); -// --------------------------------------------------------------------------- // PRD-1409 (qa-map-data): nodes saved at impossible coordinates. // Live /map/state on 2026-11-06 held these public points. The June 2026 // add-node client produced them: a pin drag clamped to the mini-map edge gave @@ -3363,7 +3362,6 @@ test('home map inspector: the dock, the sheets and the compact tooltip (map-poli // are always refused. An exact edge point is refused from raw coordinates but // accepted from a confirmed place, because real places sit on the 180th // meridian (Fiji). Evidence: .plans/archive/website-qa-2026-11/handoffs/qa-map-data.md -// --------------------------------------------------------------------------- const LIVE_EDGE_POINTS = Object.freeze([ { place: 'Florida', lat: 90, long: 97.76261 }, { place: 'Taiwan', lat: 90, long: 176.912492 }, @@ -3816,7 +3814,6 @@ test('D2: the home map and footer drop the ecoregion layer and its credit', asyn }); // PRD-1409 review follow-ups: PostgreSQL rounding and chapter anchors. -// --------------------------------------------------------------------------- test('coordinates are judged at the six decimal places PostgreSQL stores', () => { // numeric(9, 6) rounds anything finer, so the rule judges the rounded value. diff --git a/scripts/pages-deploy-recovery.test.ts b/scripts/pages-deploy-recovery.test.ts index 22d5993..e911860 100644 --- a/scripts/pages-deploy-recovery.test.ts +++ b/scripts/pages-deploy-recovery.test.ts @@ -98,8 +98,6 @@ test('a re-run is not dated by a job it kept from the earlier attempt', () => { assert.equal(earliestJobStart(jobs, ''), null); }); -// --- Watching ----------------------------------------------------------------- - /** A scripted Pages pipeline on a virtual clock. Tests script GitHub's side through the hooks. */ function simulate(initialRuns: PagesRun[], startAt: string) { const clock = { nowMs: Date.parse(startAt) }; @@ -314,8 +312,6 @@ test('a fresh run that hangs in turn is cancelled and followed by another', asyn assert.equal(watch.startedReplacement, true); }); -// --- GitHub API ---------------------------------------------------------------- - type FakeResponse = { status?: number; body?: unknown }; function fakeGitHub( @@ -523,8 +519,6 @@ test('configuration names what is missing and rejects a malformed repository', ( assert.throws(() => readConfig({ ...env, PAGES_RUN_ID: 'latest' }), /must be a workflow run id/); }); -// --- Workflow wiring ----------------------------------------------------------- - test('the recovery workflow is wired to the Pages workflow it watches', () => { const workflows = new URL('../.github/workflows/', import.meta.url); const pages = readFileSync(new URL('github-pages.yml', workflows), 'utf8'); diff --git a/scripts/quality/comment-policy.mjs b/scripts/quality/comment-policy.mjs new file mode 100644 index 0000000..9adf480 --- /dev/null +++ b/scripts/quality/comment-policy.mjs @@ -0,0 +1,947 @@ +#!/usr/bin/env node +// Comment policy for TypeScript, JavaScript and Solidity sources, and the codemod for its narrow +// first pass. TypeScript and JavaScript comments are found with Vite's Oxc parser, so strings, +// regular expressions, template literals and JSX text are never mistaken for them; Solidity +// comments with a scanner that skips string literals. +// +// The narrow pass removes four kinds: banners, commented-out code, labels (a heading of a few +// words) and notes that only restate the name they sit on, except where a comment's place +// carries its meaning: one that ends a line of code, or is a block's whole content, always stays. +// Everything else stays too, for a triage +// pass that moves each comment into a type, test or lint, or the docs, or keeps or deletes it: +// licence headers, directives (compiler, linter, bundler, analyzer and repository markers), +// documentation on exported declarations and JSDoc types, all NatSpec, claimed constraints, +// reasons, and narration. `--report triage` lists what that pass reads and `--report +// constraints` the claims. The purge is idempotent, leaves rendered JSX text as it was, writes +// nothing when any file fails to parse, and never rewrites deployed contract sources +// (packages/contracts/src). +// +// node scripts/quality/comment-policy.mjs --write purge the files or folders +// node scripts/quality/comment-policy.mjs --check exit 1 when a purge would change them +// node scripts/quality/comment-policy.mjs --report constraints|triage JSON for review +import { execFileSync } from 'node:child_process'; +import { readFileSync, statSync, writeFileSync } from 'node:fs'; +import { relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseSync } from '../lib/vite-parse.mjs'; + +const repoRoot = resolve(fileURLToPath(new URL('../..', import.meta.url))); +const SOURCE = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts|sol|astro)$/; +const DEPLOYED_CONTRACT_SOURCE = /^packages\/contracts\/src\//; + +const LICENCE = + /SPDX-License-Identifier|@license|@preserve|\bcopyright\b|\blicen[cs]ed under\b|\b(apache|mit|bsd|isc|mpl|gpl|lgpl|agpl)(-\d(\.\d)?)?\s+licen[cs]e\b|\bapache-2\.0\b/i; +const DIRECTIVES = [ + /^\s*@ts-(expect-error|ignore|nocheck|check)\b/, + /^\s*(eslint|oxlint)-(disable|enable)/, + /^\s*eslint-env\b/, + /^\s*(biome|prettier)-ignore\b/, + /^\s*(istanbul|c8|v8) ignore\b/, + /^\s*@vite-ignore\b/, + /^\s*webpack[A-Z]\w*:/, + /[#@]__(PURE|NO_SIDE_EFFECTS)__/, + /^\s*@jsx(ImportSource|Runtime|Frag)?\b/, + /^\s*@(vitest|jest)-environment\b/, + /^\s*(global|exported)\s/, + /^\s*@refresh\b/, + /^\/\s* 2) names.add(part.toLowerCase()); + } + } + } + const escaped = [...names] + .sort((a, b) => b.length - a.length) + .map((term) => term.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')); + dependencyTerms = new RegExp(`(^|[^\\w@/-])(${escaped.join('|')})(?![\\w-])`, 'i'); + return dependencyTerms; +} + +// A comment that claims the code around it must stay as it is: important, temporary, a workaround, +// a warning against changing it. Each one goes to the owner's review table (`--report +// constraints`), where it is kept, dropped, or encoded as a type, test or lint. +const CLAIM = + /\b(important|temporar(y|ily)|workarounds?|work around|hacky?|do not|don't|never|must|should not|shouldn't|may not|has to|have to|keep (this|these|it|them|the)\b|order matters|ensures?\b|make sure|(load|import|register|mock|install|initiali[sz]e|set up|call|run)(s|ed|ing)? (before|after|first)\b|todo|fixme|xxx|remove (this|once|when|after)|until\b)/i; +// A reason, a consequence or a deliberate choice: why the code is this way rather than another. +// Not narration, so the purge keeps it; a named dependency with one is a dependency constraint. +const REASON = + /\b(because|since|so|so that|otherwise|would|without|unless|requires?|required|needs?|demands?|expects?|rejects?|refuses?|breaks?|broke|crash(es|ed)?|fails?|failed|throws?|bugs?|quirks?|only|cannot|can't|won't|doesn't|does not|rather than|instead|on purpose|deliberately|intentionally|by design|the whole point|load-bearing)\b/i; + +/** + * The kind a remaining comment takes: "constraint" for a claim the owner reviews, "dependency" for + * a reason an outside tool or platform forces, "rationale" for any other reason, else "remove". + */ +function constraintKind(text) { + if (CLAIM.test(text)) return 'constraint'; + if (!REASON.test(text)) return 'remove'; + return externalTerms().test(text) ? 'dependency' : 'rationale'; +} +// The JSDoc tags TypeScript reads when it checks JavaScript, with their aliases. +const JSDOC_TYPES = + /@((type|typedef|template|satisfies|import|callback|enum|deprecated|overload|this|extends|augments|implements|class|constructor|public|private|protected|readonly|override)\b|(param|arg|argument|returns?|property|prop)\s*\{)/; + +/** What the narrow pass removes; every other kind waits for the triage pass. */ +export const REMOVED_KINDS = new Set(['banner', 'code', 'label', 'restatement']); + +// Rule characters: ASCII punctuation, box drawing, the em and en dashes, middle dots and bullets. +const RULE_CHARS = '-=*#~_+/\\\\|.\\u2500-\\u257f\\u2013\\u2014\\u00b7\\u2022'; +const RULE_LINE = new RegExp(`^[${RULE_CHARS}]{3,}$`); +const TITLED_RULE = new RegExp(`^[${RULE_CHARS}]{2,}\\s+\\S.{0,60}?\\s+[${RULE_CHARS}]{2,}$`); + +/** A heading of one to three words with no sentence punctuation: `// Helpers`, `// Public API:`. */ +function isLabel(text) { + const line = text.trim(); + // A negation states something about the code (`maxTouchPoints not set` marks a deliberate + // omission, as does `Wallet isn't connected`); a label only names. + if (/\b(?:not|no|never|none|nothing|without)\b|n't\b/i.test(line)) return false; + return /^[A-Za-z][\w &/'()-]*:?$/.test(line) && line.split(/\s+/).length <= 3; +} + +/** Rules of punctuation, alone or around a title (`// ==== Helpers ====`), over one or more lines. */ +function isBanner(text) { + const lines = commentLines(text) + .map((line) => line.trim()) + .filter(Boolean); + const rule = (line) => RULE_LINE.test(line) || TITLED_RULE.test(line); + return lines.some(rule) && lines.every((line) => rule(line) || isLabel(line)); +} + +const CODE_HINT = /[;{}]|=>|^\s*<\/?[A-Za-z]|\b(const|let|var|return|import|export|await)\b|[\w)]\(.*\)\s*;?\s*$/m; + +/** + * Code a comment holds instead of running: it parses as statements, an expression or JSX. Prose + * that happens to parse as a label (`TODO: fix()`, `Note: x()`) is not code. + */ +function isCommentedOutCode(text) { + const body = commentLines(text).join('\n').trim(); + if (!body || !CODE_HINT.test(body)) return false; + // An object wrapper only for what ends like a property list (`foo: bar,`): it would read + // any `Word: text` as a property. + const candidates = [body, `(${body}\n)`, ...(/,\s*$/.test(body) ? [`({${body}\n})`] : [])]; + return candidates.some((candidate) => { + const { program, errors } = parseSync('comment.tsx', candidate, { lang: 'tsx', sourceType: 'module' }); + return ( + !errors.length && + program.body.length > 0 && + program.body.every((statement) => statement.type !== 'LabeledStatement') && + !isNotation(program) + ); + }); +} + +// One value or a mapping from a name to a value (`key => false`, a template showing a key's format) +// reads as notation in prose, not as code taken out. +function isNotation(program) { + const unwrap = (node) => (node?.type === 'ParenthesizedExpression' ? unwrap(node.expression) : node); + const only = + program.body.length === 1 && program.body[0].type === 'ExpressionStatement' + ? unwrap(program.body[0].expression) + : null; + const simple = (node) => + ['Identifier', 'Literal', 'StringLiteral', 'NumericLiteral', 'TemplateLiteral'].includes(unwrap(node)?.type); + return simple(only) || (only?.type === 'ArrowFunctionExpression' && simple(only.body)); +} + +/** Solidity code in a comment: every line ends a statement or a block, and one assigns or calls. */ +function isSolidityCode(text) { + const lines = commentLines(text) + .map((line) => line.trim()) + .filter(Boolean); + return lines.length > 0 && lines.every((line) => /[;{}]$/.test(line)) && lines.some((line) => /[=(]/.test(line)); +} + +const STOP_WORDS = new Set( + ( + 'a an the this that these those of for to in on at by with from as is are was be been it its and or into via per each new ' + + 'current given function method helper handler callback component hook class type interface constant variable value property ' + + 'prop field get gets return returns set sets create creates make makes handle handles render renders use uses do does' + ).split(' '), +); +const stem = (word) => word.replace(/ies$/, 'y').replace(/(es|s|ed|ing)$/, ''); +const wordsOf = (text) => + text + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') + .toLowerCase() + .match(/[a-z0-9]+/g) ?? []; + +/** A short note whose every word is in the name it sits on, or a stop word: `// Get the user` on `getUser`. */ +function restatesName(text, name) { + if (!name) return false; + const nameWords = new Set(wordsOf(name).map(stem)); + const words = wordsOf(text); + return ( + words.length > 0 && + words.length <= 8 && + words.filter((word) => !STOP_WORDS.has(word)).every((word) => nameWords.has(stem(word))) + ); +} + +const DECLARATIONS = [ + /\b(?:function\*?|class|interface|type|enum|namespace|struct|event|modifier|error|contract|library)\s+([A-Za-z_$][\w$]*)/, + /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/, + /^\s*<([A-Z][\w$.]*)/, + /^\s*(?:(?:export|default|public|private|protected|static|readonly|async|override|abstract|declare|get|set)\s+)*([A-Za-z_$][\w$]*)\s*[?!]?\s*[(:=]/, +]; +const NOT_NAMES = new Set([ + 'if', + 'for', + 'while', + 'switch', + 'return', + 'await', + 'catch', + 'case', + 'default', + 'else', + 'try', + 'throw', + 'require', + 'assert', + 'emit', +]); + +/** The name a comment sits on: the code before it on its line, or else the next line of code past any comments. */ +function subjectName(code, comment) { + const declared = (line) => { + for (const pattern of DECLARATIONS) { + const name = line.match(pattern)?.[1]; + if (name) return NOT_NAMES.has(name) ? null : name; + } + return null; + }; + const before = code.slice(lineStart(code, comment.start), comment.start); + if (before.trim()) return declared(before); + for (let from = comment.end; from < code.length; ) { + const end = lineEnd(code, from); + const line = code.slice(from, end); + if (line.trim() && !/^\s*(\/\/|\/\*|\*)/.test(line)) return declared(line); + from = end + 1; + } + return null; +} + +/** A comment no tool reads: a claim or a reason stays; else one of the removed kinds, or narration. */ +function narrowKind(text, name) { + const kind = constraintKind(text); + if (kind !== 'remove') return kind; + if (isBanner(text)) return 'banner'; + const body = commentLines(text) + .map((line) => line.trim()) + .filter(Boolean) + .join(' '); + if (isLabel(body)) return 'label'; + if (restatesName(body, name)) return 'restatement'; + return 'narration'; +} + +// A rule of punctuation stands alone, so a banner never hides inside the note under it. +const isRuleLine = (value) => RULE_LINE.test(value.trim()) || TITLED_RULE.test(value.trim()); + +function languageOf(file) { + if (file.endsWith('.tsx')) return 'tsx'; + if (file.endsWith('.jsx')) return 'jsx'; + if (/\.(ts|mts|cts)$/.test(file)) return 'ts'; + return 'js'; +} + +// Spans of exported declarations: documentation inside one, or right before one, is API documentation. +function declaredNames(statement) { + if (statement.type === 'VariableDeclaration') + return statement.declarations.map((declaration) => declaration.id?.name).filter(Boolean); + return statement.id?.name ? [statement.id.name] : []; +} + +// Whether an assignment, or any assignment it chains into, writes `module.exports` or an export +// (`const client = module.exports = createClient()`). +function assignsCommonJsExport(node) { + for (let at = node; at?.type === 'AssignmentExpression'; at = at.right) if (isCommonJsExport(at.left)) return true; + return false; +} + +// The value a chain of assignments ends in: `module.exports = exports.client = client` assigns `client`. +function chainedValue(node) { + let at = node; + while (at?.type === 'AssignmentExpression') at = at.right; + return at; +} + +// `module.exports`, `module.exports.name` or `exports.name`. +function isCommonJsExport(node) { + const isModuleExports = (target) => + target?.type === 'MemberExpression' && target.object?.name === 'module' && target.property?.name === 'exports'; + return ( + isModuleExports(node) || + (node?.type === 'MemberExpression' && (isModuleExports(node.object) || node.object?.name === 'exports')) + ); +} + +function exportedSpans(program) { + // Names a later `export { a, b }` or `export default a` makes public: their declarations are API too. + const exportedLater = new Set(); + for (const statement of program.body) { + if (statement.type === 'ExportNamedDeclaration' && !statement.declaration && !statement.source) { + for (const specifier of statement.specifiers) if (specifier.local?.name) exportedLater.add(specifier.local.name); + } + if (statement.type === 'ExportDefaultDeclaration' && statement.declaration?.type === 'Identifier') { + exportedLater.add(statement.declaration.name); + } + if (statement.type === 'TSExportAssignment' && statement.expression?.type === 'Identifier') + exportedLater.add(statement.expression.name); + // CommonJS: `module.exports = name`, `module.exports = { a, b }`, `exports.a = a`, and the same + // at the end of a chain (`module.exports = exports.a = a`, `const api = module.exports = a`). + const assignments = + statement.type === 'ExpressionStatement' + ? [statement.expression] + : statement.type === 'VariableDeclaration' + ? statement.declarations.map((declaration) => declaration.init) + : []; + for (const assignment of assignments.filter(assignsCommonJsExport)) { + const value = chainedValue(assignment); + if (value?.type === 'Identifier') exportedLater.add(value.name); + for (const property of value?.type === 'ObjectExpression' ? value.properties : []) { + if (property.value?.type === 'Identifier') exportedLater.add(property.value.name); + } + } + } + const spans = []; + let previousEnd = 0; + for (const statement of program.body) { + // An assignment to `exports.name` or `module.exports` exports what it assigns, so documentation + // above it, or inside the object it assigns, is API documentation too. + const commonJs = + (statement.type === 'ExpressionStatement' && assignsCommonJsExport(statement.expression)) || + (statement.type === 'VariableDeclaration' && + statement.declarations.some((declaration) => assignsCommonJsExport(declaration.init))); + const exported = + /^Export(Named|Default|All)Declaration$/.test(statement.type) || + statement.type === 'TSExportAssignment' || + commonJs || + declaredNames(statement).some((name) => exportedLater.has(name)); + if (exported) spans.push([previousEnd, statement.end]); + previousEnd = statement.end; + } + return spans; +} + +// JSX children that hold only comments (`{/* note */}`): removing the comment removes the braces +// too. One between two runs of text is marked: JSX trims each run on its own, so joining them +// changes what renders (`a{/* c */}` then `b` on the next line renders "ab"; without it, "a b"). +function emptyJsxContainers(program) { + const containers = []; + const hasText = (node) => node?.type === 'JSXText' && /\S/.test(node.value); + const visit = (node) => { + if (Array.isArray(node)) return node.forEach(visit); + if (!node || typeof node !== 'object') return; + if (node.type === 'JSXElement' || node.type === 'JSXFragment') { + node.children.forEach((child, index) => { + if (child.type !== 'JSXExpressionContainer' || child.expression?.type !== 'JSXEmptyExpression') return; + const betweenText = hasText(node.children[index - 1]) && hasText(node.children[index + 1]); + containers.push({ span: [child.start, child.end], betweenText }); + }); + } + for (const value of Object.values(node)) if (value && typeof value === 'object') visit(value); + }; + visit(program); + return containers; +} + +/** The comment's lines without the leading `*` a block comment's lines carry. */ +function commentLines(text) { + return text.split('\n').map((line) => line.replace(/^\s*\*+\s?/, '')); +} + +const isDirective = (text, patterns = DIRECTIVES) => + [text, ...commentLines(text)].some((line) => patterns.some((pattern) => pattern.test(line))); + +export function classifyComment(comment, { exported, name = null, marksIntent = false }) { + const text = comment.value; + const doc = comment.type === 'Block' && text.startsWith('*'); + if (LICENCE.test(text) || (comment.type === 'Block' && text.startsWith('!'))) return 'licence'; + if (isDirective(text)) return 'directive'; + if (doc && (exported || JSDOC_TYPES.test(text))) return 'documentation'; + const kind = isCommentedOutCode(text) ? 'code' : narrowKind(text, name); + return marksIntent && REMOVED_KINDS.has(kind) ? 'narration' : kind; +} + +/** + * A comment the narrow pass keeps whatever it says, since its place carries the meaning: the end of + * a line of code, where it annotates that line (`chainId: 11155111, // Sepolia`, a test case's + * `// Missing 0x`), not a heading; or the whole content of a block (`catch { // Ignore errors }` + * says the swallow is deliberate; without it the empty block reads as a mistake). JSX comment + * containers are not blocks. Other comments on the line are not code: a note after a banner + * (`/* ---- *\/ // Helpers`) is still a heading, so one pass removes both. + */ +function marksIntent(code, comment, { comments = [], inJsxContainer = false, solidity = false } = {}) { + if (inJsxContainer) return false; + const afterOnLine = code.slice(comment.end, lineEnd(code, comment.end)); + if (codeBefore(code, comment, comments).trim() && !afterOnLine.trim()) return true; + // Where a statement or value would go, with only comments and space between it and the + // delimiters around it: a block's content, an empty argument list, a tuple's unnamed slot. + const back = pastSpaceAndComments(code, comment.start, comments, -1); + const ahead = pastSpaceAndComments(code, comment.end, comments, 1); + const opener = code[back - 1] ?? ''; + const closer = code[ahead] ?? ''; + // Between two separators is a slot in any language: an omitted tuple position, an array hole. + if (closer === ',') return /[[(,]/.test(opener); + if (!/[}\])]/.test(closer)) return false; + // Before a closer, a comma opens a slot in a Solidity tuple. In JavaScript it is only a + // trailing comma there, unless it follows `[`, `(` or another comma: a leading array hole. + if (opener === ',') + return solidity || /[[(,]/.test(code[pastSpaceAndComments(code, back - 1, comments, -1) - 1] ?? ''); + return /[{[(]/.test(opener); +} + +/** A comment's line up to the comment, other comments blanked: a comment is not code. */ +function codeBefore(code, comment, comments) { + const start = lineStart(code, comment.start); + let before = code.slice(start, comment.start); + for (const other of comments) { + if (other.end <= start || other.start >= comment.start) continue; + const from = Math.max(other.start, start) - start; + const to = Math.min(other.end, comment.start) - start; + before = before.slice(0, from) + ' '.repeat(to - from) + before.slice(to); + } + return before; +} + +/** + * Where the code resumes from `index`, past space and whole comments, backwards (-1) or forwards + * (1). A line comment's span can end in trailing spaces the backward walk has already passed. + */ +function pastSpaceAndComments(code, index, comments, direction) { + let at = index; + for (;;) { + const from = at; + if (direction < 0) { + while (at > 0 && /\s/.test(code[at - 1])) at--; + const earlier = comments.find((other) => other.start < at && other.end >= at && other.end <= from); + if (!earlier) return at; + at = earlier.start; + } else { + while (at < code.length && /\s/.test(code[at])) at++; + const later = comments.find((other) => other.start === at); + if (!later) return at; + at = later.end; + } + } +} + +// A directive or licence line applies on its own, so it never joins a run. +const scriptStandalone = (value) => + LICENCE.test(value) || DIRECTIVES.some((pattern) => pattern.test(value)) || isRuleLine(value); +// Space around exactly one line break, in any of the four terminators, CRLF as one. +const ONE_LINE_BREAK = /^[ \t]*(?:\r\n|[\n\r\u2028\u2029])[ \t]*$/; + +/** + * Comments as readers see them: a run of line comments on consecutive lines is one comment, unless + * a line stands alone or `joins` keeps two kinds apart. A note that ends a line of code takes the + * lines under it as its continuation, but never commented-out code, which `isCode` recognises and + * which goes on its own. + */ +export function groupComments( + code, + comments, + { standalone = scriptStandalone, joins = () => true, isCode = isCommentedOutCode } = {}, +) { + const groups = []; + for (const comment of comments) { + const last = groups.at(-1); + const between = last ? code.slice(last.end, comment.start) : null; + if ( + last && + last.type === 'Line' && + comment.type === 'Line' && + ONE_LINE_BREAK.test(between) && + !codeBefore(code, comment, comments).trim() && + !(codeBefore(code, last, comments).trim() && isCode(comment.value)) && + !standalone(comment.value) && + !standalone(last.lastValue) && + joins(last.lastValue, comment.value) + ) { + last.end = comment.end; + last.value += `\n${comment.value}`; + last.lastValue = comment.value; + } else + groups.push({ + type: comment.type, + value: comment.value, + lastValue: comment.value, + start: comment.start, + end: comment.end, + }); + } + return groups; +} + +/** Comments in Solidity source, found lexically: string, unicode and hex literals are skipped. */ +export function solidityComments(code) { + const comments = []; + for (let index = 0; index < code.length; index++) { + const char = code[index]; + if (char === '"' || char === "'") { + for (index++; index < code.length && code[index] !== char && code[index] !== '\n'; index++) { + if (code[index] === '\\') index++; + } + } else if (char === '/' && code[index + 1] === '/') { + const end = lineEnd(code, index); + comments.push({ type: 'Line', value: code.slice(index + 2, end), start: index, end }); + index = end - 1; + } else if (char === '/' && code[index + 1] === '*') { + const close = code.indexOf('*/', index + 2); + const end = close < 0 ? code.length : close + 2; + comments.push({ type: 'Block', value: code.slice(index + 2, close < 0 ? end : close), start: index, end }); + index = end - 1; + } + } + return comments; +} + +const isNatSpec = (comment) => + comment.type === 'Line' ? comment.value.startsWith('/') : comment.value.startsWith('*'); + +export function classifySolidityComment(comment, { name = null, marksIntent = false } = {}) { + const text = comment.value; + if (LICENCE.test(text)) return 'licence'; + if (isDirective(text, SOLIDITY_DIRECTIVES)) return 'directive'; + // NatSpec documents the contract surface and carries tooling tags such as @custom:oz-upgrades. + if (isNatSpec(comment)) return 'documentation'; + const kind = isSolidityCode(text) ? 'code' : narrowKind(text, name); + return marksIntent && REMOVED_KINDS.has(kind) ? 'narration' : kind; +} + +function classifySoliditySource(code) { + const standalone = (value) => LICENCE.test(value) || isDirective(value, SOLIDITY_DIRECTIVES) || isRuleLine(value); + // A NatSpec line (`///`) and a plain line (`//`) never join: they are different kinds of comment. + const joins = (previous, next) => previous.startsWith('/') === next.startsWith('/'); + const comments = solidityComments(code); + return groupComments(code, comments, { standalone, joins, isCode: isSolidityCode }).map((comment) => ({ + ...comment, + kind: classifySolidityComment(comment, { + name: subjectName(code, comment), + marksIntent: marksIntent(code, comment, { comments, solidity: true }), + }), + })); +} + +// A `.cjs` file may `return` at its top level, which module parsing rejects, and so may a `.js` +// file in a CommonJS package; module syntax fails as CommonJS. A `.js` file may hold JSX. The +// extension's reading goes first. +function parse(file, code) { + let failure; + const langs = languageOf(file) === 'js' ? ['js', 'jsx'] : [languageOf(file)]; + for (const lang of langs) { + for (const sourceType of /\.c[jt]s$/.test(file) ? ['commonjs', 'module'] : ['module', 'commonjs']) { + const result = parseSync(file, code, { lang, sourceType }); + if (!result.errors.length) return result; + failure ??= result.errors[0]; + } + } + throw new Error(`${file}: does not parse (${failure.message})`); +} + +// An Astro component's code lives in its frontmatter and its ', + '', + '', + ].join('\n'); + const { code: purged, removed } = purgeSource(code, 'Example.astro'); + assert.deepEqual( + removed.map((comment) => comment.kind), + ['banner', 'banner'], + ); + assert.ok(!purged.includes('===== Props')); + assert.ok(!purged.includes('---------- Setup')); + assert.ok(purged.includes(''), 'template comments are markup, not code'); + assert.ok(purged.includes('"@context"'), 'a data script is not code'); + assert.ok(purged.startsWith('---\nconst { title } = Astro.props;\n---\n')); +}); + +test('a reason in Astro frontmatter survives the narrow pass', () => { + const code = + '---\n// Fetched at build time because the agent is not public during builds.\nconst data = await load();\n---\n

{data}

\n'; + assert.equal(purgeSource(code, 'Reason.astro').code, code); +}); + +test('a script tag inside a frontmatter string is not a second segment', () => { + const code = ['---', "const example = '';", '---', '

{example}

', ''].join( + '\n', + ); + assert.equal(purgeSource(code, 'Example.astro').code, code); +}); + +test('a data script with an unquoted type is left alone', () => { + const code = + '\n\n'; + const { code: purged, removed } = purgeSource(code, 'Data.astro'); + assert.deepEqual( + removed.map((comment) => comment.kind), + ['banner'], + ); + assert.ok(purged.includes('{"imports": {}}')); +}); diff --git a/scripts/snapshot-alert-episodes.integration.ts b/scripts/snapshot-alert-episodes.integration.ts index 806f648..7875ce1 100644 --- a/scripts/snapshot-alert-episodes.integration.ts +++ b/scripts/snapshot-alert-episodes.integration.ts @@ -197,7 +197,6 @@ try { await sql.unsafe(await readFile(resolve(migrationsDir, file), 'utf8')); } - // --- An agent released ahead of the migration ------------------------------ // A merge deploys the agent, and 030 is applied by hand. On the schema before // 030 the agent must keep alerting the way it did. await insertChapter('healthy'); @@ -237,7 +236,6 @@ try { ); assert.equal(alertFailures().some((failure: any) => failure.step === 'open'), false); - // --- Migration 030 --------------------------------------------------------- const beforeMigration = await alertFingerprints(); assert.equal(beforeMigration.allColumns.length, 4); await sql.unsafe(episodeMigration); @@ -262,7 +260,6 @@ try { warnings.length = 0; - // --- Episodes -------------------------------------------------------------- // Production's rows are weeks old by the time 030 lands. The first render // ends the two episodes that were already over and leaves the other two open. await anHourLater(); @@ -313,7 +310,6 @@ try { await render(); assert.deepEqual(await alerts('still-dropped'), ['record_quarantined resolved sent']); - // --- A withheld image on a chapter that is then dropped ---------------------- // The chapter has an open image alert. A mailto: link now drops the chapter. // A dropped chapter is not in the snapshot, so nothing is known about its // image, and the image alert stays open. @@ -354,7 +350,6 @@ try { ]); assert.deepEqual(await deliver(), ['quarantined chapters/just-broken']); - // --- A collection the contract and Directus name differently ----------------- // The alert is stored under the Directus name. A render must look for it // under that same name, or it would end and reopen the episode every time. const reviewed = new Date(); @@ -377,7 +372,6 @@ try { assert.deepEqual(await alerts('proof-initiative'), ['record_quarantined open queued']); assert.deepEqual(await deliver(), ['quarantined chapter_initiatives/proof-initiative']); - // --- Renders at the same moment -------------------------------------------- await insertChapter('raced', { links: mailto }); await Promise.all(Array.from({ length: 8 }, () => render(pool))); assert.deepEqual(await alerts('raced'), ['record_quarantined open queued']); @@ -469,7 +463,6 @@ try { { code: '23514' } ); - // --- A render that changes nothing writes nothing ---------------------------- // The snapshot route is a public read path. Three alerts are open and all of // them still hold, so the render's transaction never needs a transaction id. assert.equal(await openAlertCount(), 3); diff --git a/scripts/ui-verify.ts b/scripts/ui-verify.ts index b2c5a6f..bfaa9ee 100644 --- a/scripts/ui-verify.ts +++ b/scripts/ui-verify.ts @@ -285,7 +285,6 @@ async function waitForExpression(client: CdpClient, sessionId: string, expressio // Non-fatal: continue with whatever rendered (a route may legitimately never settle one channel). } -// ── Route discovery from the built dist (overridable via CLI) ── function discoverRoutes(): string[] { const routes = new Set(); const walk = (absDir: string, urlPrefix: string) => { @@ -309,7 +308,6 @@ function slugFor(route: string): string { return s || 'home'; } -// ── Source CSS standard check ─────────────────────────────────────────────── function sourceFilesToScan(): string[] { const files: string[] = []; const walk = (absDir: string) => { @@ -672,7 +670,6 @@ try { } catch {} `; -// ── Channel 2 — accessibility tree ── async function auditAccessibilityTree(client: CdpClient, sessionId: string): Promise { const out: Violation[] = []; let tree; @@ -809,7 +806,6 @@ async function discoverWebMcp(client: CdpClient, origin: string, routes: string[ } } -// ── Per-route × width verification ── async function verifyRouteAtWidth(client: CdpClient, origin: string, route: string, width: number): Promise { const target = await client.send('Target.createTarget', { url: 'about:blank' }); const attached = await client.send('Target.attachToTarget', { targetId: target.targetId, flatten: true });