Files
ECC/docker/context-profiles/ai-corpus.json
T

416 lines
85 KiB
JSON

{
"schemaVersion": "ecc.context-eval-corpus.v2",
"id": "coding-tasks@1",
"sampling": "Purposive coding-task corpus fixed before any provider call: 22 small JavaScript repairs paired with one plausibly helpful ECC skill, 8 trivial no-workflow fixes (some with misleading workflow vocabulary), and selection probes for exact names, paraphrases, no-workflow queries and policy blocks; equal weight per distinct task and no population-representativeness claim.",
"minimumDistinctTasks": 30,
"nonInferiorityMargin": 0.05,
"selection": [
{ "id":"exact-python", "category":"exact", "query":"Use python-patterns to review typed Python functions.", "expectedIds":["skill:python-patterns"] },
{ "id":"exact-api", "category":"exact", "query":"Use api-design for REST pagination.", "expectedIds":["skill:api-design"] },
{ "id":"paraphrase-tests", "category":"paraphrase", "query":"Write pytest fixtures and parametrized regression tests for a Python package.", "expectedIds":["skill:python-testing"] },
{ "id":"paraphrase-api", "category":"paraphrase", "query":"Design REST endpoints with pagination and status codes.", "expectedIds":["skill:api-design"] },
{ "id":"plain-arithmetic", "category":"no-workflow", "query":"What is 17 times 24?", "expectedIds":[] },
{ "id":"ambiguous-vocabulary", "category":"no-workflow", "query":"Count words in this literal text: database testing security review. Do not perform any of those activities.", "expectedIds":[] },
{ "id":"negative-skill-mention", "category":"no-workflow", "query":"Do not use python-patterns. Return only OK.", "expectedIds":[] },
{ "id":"explicit-no-workflow", "category":"no-workflow", "query":"Use python-patterns as plain text only. Add 7 and 5.", "noWorkflow":true,"expectedIds":[] },
{ "id":"excluded-name", "category":"policy", "query":"Use python-patterns to simplify Python code.", "exclude":["skill:python-patterns"],"expectedIds":[] },
{ "id":"excluded-explicit", "category":"policy", "query":"Use python-patterns.", "exclude":["skill:python-patterns"],"explicitIds":["skill:python-patterns"],"expectedBlock":"excluded" },
{ "id":"authority-boundary", "category":"policy", "query":"Use inherit-legacy-style to preserve conventions.", "explicitIds":["skill:inherit-legacy-style"],"expectedBlock":"native-authority" },
{ "id":"opt-out-conflict", "category":"policy", "query":"Use python-patterns.", "noWorkflow":true,"explicitIds":["skill:python-patterns"],"expectedBlock":"opt-out-conflict" },
{ "id":"unknown-explicit", "category":"policy", "query":"Use an unavailable workflow.", "explicitIds":["skill:ecc-eval-nonexistent"],"expectedBlock":"unknown-id" },
{ "id":"exact-security-review", "category":"exact", "query":"Use security-review to check this login handler for SQL injection and leaked secrets.", "expectedIds":["skill:security-review"] },
{ "id":"exact-error-handling", "category":"exact", "query":"Use error-handling to add typed error classes to the config loader.", "expectedIds":["skill:error-handling"] },
{ "id":"exact-database-migrations", "category":"exact", "query":"Use database-migrations to add a NOT NULL column to a large Postgres table.", "expectedIds":["skill:database-migrations"] },
{ "id":"exact-regex-structured-text", "category":"exact", "query":"Use regex-vs-llm-structured-text to decide how to parse vendor invoice lines.", "expectedIds":["skill:regex-vs-llm-structured-text"] },
{ "id":"exact-content-hash-cache", "category":"exact", "query":"Use content-hash-cache-pattern to cache PDF text extraction results.", "expectedIds":["skill:content-hash-cache-pattern"] },
{ "id":"exact-hexagonal", "category":"exact", "query":"Use hexagonal-architecture to separate the signup use case from its database and email adapters.", "expectedIds":["skill:hexagonal-architecture"] },
{ "id":"paraphrase-sql-injection", "category":"paraphrase", "query":"User input is concatenated into SQL strings in our login endpoint; audit the handler for injection and hardcoded credentials before release.", "expectedIds":["skill:security-review"] },
{ "id":"paraphrase-retry", "category":"paraphrase", "query":"Wrap a flaky payment provider call with exponential backoff retries and typed error classes so callers get useful failure messages.", "expectedIds":["skill:error-handling"] },
{ "id":"paraphrase-zero-downtime-rename", "category":"paraphrase", "query":"Rename a column on a busy PostgreSQL table without downtime, with reversible up and down schema changes.", "expectedIds":["skill:database-migrations"] },
{ "id":"paraphrase-redis-cache", "category":"paraphrase", "query":"Add a Redis cache-aside layer with key expiry and a distributed lock for our profile reads.", "expectedIds":["skill:redis-patterns"] },
{ "id":"paraphrase-token-decimals", "category":"paraphrase", "query":"Our dashboard shows USDC balances wrong on some EVM chains because token decimals differ; normalize amounts across chains safely.", "expectedIds":["skill:evm-token-decimals"] },
{ "id":"paraphrase-keccak", "category":"paraphrase", "query":"Compute Ethereum function selectors in Node without confusing NIST SHA3-256 with Keccak-256.", "expectedIds":["skill:nodejs-keccak256"] },
{ "id":"paraphrase-content-hash", "category":"paraphrase", "query":"Cache slow document parsing so results are keyed by the SHA-256 of file content instead of the file path.", "expectedIds":["skill:content-hash-cache-pattern"] },
{ "id":"paraphrase-ports-adapters", "category":"paraphrase", "query":"Refactor toward ports and adapters so the domain use case no longer imports the database driver directly.", "expectedIds":["skill:hexagonal-architecture"] },
{ "id":"paraphrase-structured-text", "category":"paraphrase", "query":"Should I parse these semi-structured quiz and invoice text lines with regular expressions or an LLM? Start with the cheapest reliable option.", "expectedIds":["skill:regex-vs-llm-structured-text"] },
{ "id":"rename-variable", "category":"no-workflow", "query":"Rename the local variable tmp to total in this three-line function.", "expectedIds":[] },
{ "id":"misleading-security-typo", "category":"no-workflow", "query":"Fix the spelling of \"recieve\" in the footer text of the security settings page. Nothing else.", "expectedIds":[] },
{ "id":"misleading-tests-heading", "category":"no-workflow", "query":"Change the README heading \"Running tests\" to \"Running checks\". Do not write or run any tests.", "expectedIds":[] },
{ "id":"explicit-no-workflow-migration", "category":"no-workflow", "query":"Treat database-migrations as plain words. Reverse the string abc.", "noWorkflow":true,"expectedIds":[] },
{ "id":"excluded-api-explicit", "category":"policy", "query":"Use api-design.", "exclude":["skill:api-design"],"explicitIds":["skill:api-design"],"expectedBlock":"excluded" },
{ "id":"authority-latency", "category":"policy", "query":"Use latency-critical-systems to tune the quote cache.", "explicitIds":["skill:latency-critical-systems"],"expectedBlock":"native-authority" },
{ "id":"authority-rust-testing", "category":"policy", "query":"Use rust-testing for property tests.", "explicitIds":["skill:rust-testing"],"expectedBlock":"native-authority" },
{ "id":"opt-out-conflict-security", "category":"policy", "query":"Use security-review.", "noWorkflow":true,"explicitIds":["skill:security-review"],"expectedBlock":"opt-out-conflict" },
{ "id":"unknown-typo-id", "category":"policy", "query":"Use security-reveiw.", "explicitIds":["skill:security-reveiw"],"expectedBlock":"unknown-id" },
{ "id":"explicit-allowed", "category":"policy", "query":"Use error-handling for the retry wrapper.", "explicitIds":["skill:error-handling"],"expectedIds":["skill:error-handling"] }
],
"tasks": [
{
"id": "sql-injection-query",
"category": "security",
"manualIds": [
"skill:security-review"
],
"query": "src/users.js builds SQL for a node-postgres style driver: each builder returns { text, values } where text uses $1, $2 placeholders. Both buildFindUserQuery(email) and buildSearchUsersQuery(nameFragment, limit) interpolate caller input into the SQL text. Fix them so no caller-supplied string is ever placed in the SQL text; pass it through values instead. The search must still match names containing the fragment case-insensitively. limit must be an integer from 1 to 100; throw a RangeError for anything else (including numeric strings). Keep both exports and the selected columns. Do not add dependencies.",
"files": {
"src/users.js": "'use strict';\n\n// Query builders used by the /users routes. The db layer calls\n// pool.query(q.text, q.values) with node-postgres.\nfunction buildFindUserQuery(email) {\n return {\n text: \"SELECT id, email, name FROM users WHERE email = '\" + email + \"'\",\n values: [],\n };\n}\n\nfunction buildSearchUsersQuery(nameFragment, limit) {\n return {\n text: \"SELECT id, email, name FROM users WHERE name ILIKE '%\" + nameFragment + \"%' ORDER BY name LIMIT \" + limit,\n values: [],\n };\n}\n\nmodule.exports = { buildFindUserQuery, buildSearchUsersQuery };\n",
"README.md": "# users-api\n\nSmall query-builder layer for the users service. Builders return\n{ text, values } objects that are passed directly to node-postgres.\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst m = require(path.join(process.cwd(), 'src/users.js'));\nconst evil = \"a' OR '1'='1\";\nconst q = m.buildFindUserQuery(evil);\nassert.ok(!q.text.includes(\"'1'='1\") && !q.text.includes(evil), 'email leaked into SQL text');\nassert.match(q.text, /\\$1/);\nassert.match(q.text, /FROM\\s+users/i);\nassert.ok(q.values.includes(evil));\nconst frag = \"bob'; DROP TABLE users;--\";\nconst s = m.buildSearchUsersQuery(frag, 10);\nassert.ok(!/DROP\\s+TABLE/i.test(s.text), 'fragment leaked into SQL text');\nassert.match(s.text, /ILIKE|lower\\s*\\(/i);\nassert.match(s.text, /LIMIT\\s+(\\$\\d+|10)\\b/i);\nassert.ok(s.values.some(v => typeof v === 'string' && v.includes(frag)));\nfor (const bad of [0, 101, 2.5, '10', '10; DROP TABLE users', NaN, undefined]) {\n assert.throws(() => m.buildSearchUsersQuery('x', bad), RangeError);\n}\nconst max = Math.max(0, ...[...s.text.matchAll(/\\$(\\d+)/g)].map(x => Number(x[1])));\nassert.equal(max, s.values.length, 'placeholders and values disagree');\n"
},
{
"id": "path-traversal-guard",
"category": "security",
"manualIds": [
"skill:security-review"
],
"query": "src/static.js exports resolvePublicPath(requestPath, root) used by our static file server. requestPath is the raw URL path (for example \"/css/site.css\", possibly percent-encoded). It currently joins it onto root, which allows escaping the public directory. Make it return the absolute file path when the decoded path stays inside root (root itself counts as inside), and return null (never throw) when the path escapes root, contains a NUL byte, or cannot be percent-decoded. Watch out for sibling directories that share root as a string prefix. Keep the export name and signature. Do not add dependencies.",
"files": {
"src/static.js": "'use strict';\nconst path = require('path');\n\nconst PUBLIC_ROOT = path.resolve(__dirname, '..', 'public');\n\n// Maps a request path such as \"/css/site.css\" to a file on disk.\nfunction resolvePublicPath(requestPath, root = PUBLIC_ROOT) {\n return path.join(root, decodeURIComponent(requestPath));\n}\n\nmodule.exports = { resolvePublicPath, PUBLIC_ROOT };\n",
"public/index.html": "<!doctype html><title>home</title>\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { resolvePublicPath } = require(path.join(process.cwd(), 'src/static.js'));\nconst root = path.resolve(path.sep + 'srv', 'app', 'public');\nassert.equal(resolvePublicPath('/css/site.css', root), path.join(root, 'css', 'site.css'));\nassert.equal(resolvePublicPath('/css/../index.html', root), path.join(root, 'index.html'));\nassert.equal(resolvePublicPath('/a%20b.txt', root), path.join(root, 'a b.txt'));\nfor (const bad of ['/../secret.env', '/%2e%2e/%2e%2e/etc/passwd', '/css/../../x', '/../public-evil/x',\n '/a%00.txt', '/%E0%A4%A', '..%2f..%2fetc%2fpasswd']) {\n let out;\n assert.doesNotThrow(() => { out = resolvePublicPath(bad, root); }, bad);\n assert.equal(out, null, bad);\n}\n"
},
{
"id": "escape-comment-html",
"category": "security",
"manualIds": [
"skill:security-review"
],
"query": "src/render.js exports renderComment({ author, body, website }) which returns an HTML string for a user comment. All three fields are untrusted user input and are currently inserted raw. Fix it so author and body are HTML-escaped (at least & < > \" and '), and website is only used as the link href when it is an absolute http: or https: URL; otherwise the href must be \"#\". The href value must also be escaped. Keep the existing markup structure (li.comment containing an a element and a p element). Do not add dependencies.",
"files": {
"src/render.js": "'use strict';\n\nfunction renderComment({ author, body, website }) {\n return '<li class=\"comment\"><a href=\"' + website + '\">' + author + '</a><p>' + body + '</p></li>';\n}\n\nmodule.exports = { renderComment };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { renderComment } = require(path.join(process.cwd(), 'src/render.js'));\nconst a = renderComment({ author: '<script>alert(1)</script>', body: 'Tom & \"Jerry\" \\'s', website: 'https://ex.com/' });\nassert.ok(a.startsWith('<li class=\"comment\">'));\nassert.ok(!a.includes('<script'));\nassert.ok(a.includes('&lt;script&gt;'));\nassert.ok(a.includes('&amp;') && a.includes('&quot;'));\nassert.ok(/&#0*39;|&#x0*27;|&apos;/i.test(a));\nassert.ok(a.includes('href=\"https://ex.com/\"'));\nfor (const w of ['javascript:alert(1)', ' JavaScript:alert(1)', 'data:text/html,x', 'vbscript:x', '//evil.com', '']) {\n const out = renderComment({ author: 'a', body: 'b', website: w });\n assert.ok(!/javascript:|data:|vbscript:/i.test(out), w);\n assert.ok(out.includes('href=\"#\"'), w);\n}\nconst q = renderComment({ author: 'a', body: 'b', website: 'https://ex.com/?a=1&b=\"x\"' });\nassert.ok(!q.includes('\"x\"'));\nassert.ok(/href=\"https:\\/\\/ex\\.com\\/\\?a=1&amp;b=/.test(q));\nassert.ok(/<a [^>]*>a<\\/a>/.test(q) && /<p>b<\\/p>/.test(q));\n"
},
{
"id": "list-pagination",
"category": "api",
"manualIds": [
"skill:api-design"
],
"query": "src/listProducts.js exports listProducts(query, store) for GET /products. query holds raw query-string values (strings or undefined); store.all() returns the full array. Implement offset pagination: limit defaults to 20 and must be an integer 1..100, offset defaults to 0 and must be an integer >= 0. Success returns { status: 200, body: { data, meta: { total, limit, offset, hasMore } } }. Invalid values return { status: 400, body: { error: { code: \"VALIDATION_ERROR\", message, details: [{ field, message }] } } } with one details entry per invalid field (\"limit\" or \"offset\"). Do not mutate the store array. Do not add dependencies.",
"files": {
"src/listProducts.js": "'use strict';\n\n// GET /products?limit=&offset=\nfunction listProducts(query, store) {\n const items = store.all();\n const page = items.slice(query.offset, query.offset + query.limit);\n return { status: 200, body: page };\n}\n\nmodule.exports = { listProducts };\n",
"src/store.js": "'use strict';\n\nfunction createStore(items) {\n return { all: () => items };\n}\n\nmodule.exports = { createStore };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { listProducts } = require(path.join(process.cwd(), 'src/listProducts.js'));\nconst items = Array.from({ length: 45 }, (_, i) => ({ id: i + 1 }));\nconst copy = JSON.stringify(items);\nconst store = { all: () => items };\nlet r = listProducts({}, store);\nassert.equal(r.status, 200);\nassert.equal(r.body.data.length, 20);\nassert.deepEqual(r.body.meta, { total: 45, limit: 20, offset: 0, hasMore: true });\nr = listProducts({ limit: '10', offset: '40' }, store);\nassert.deepEqual(r.body.data.map(x => x.id), [41, 42, 43, 44, 45]);\nassert.deepEqual(r.body.meta, { total: 45, limit: 10, offset: 40, hasMore: false });\nr = listProducts({ limit: '5', offset: '35' }, store);\nassert.equal(r.body.meta.hasMore, true);\nr = listProducts({ limit: '100', offset: '100' }, store);\nassert.equal(r.status, 200);\nassert.deepEqual(r.body.data, []);\nassert.equal(r.body.meta.hasMore, false);\nfor (const [q, fields] of [[{ limit: '0' }, ['limit']], [{ limit: '101' }, ['limit']], [{ limit: 'abc' }, ['limit']],\n [{ limit: '2.5' }, ['limit']], [{ offset: '-1' }, ['offset']], [{ limit: '-3', offset: 'x' }, ['limit', 'offset']]]) {\n const bad = listProducts(q, store);\n assert.equal(bad.status, 400, JSON.stringify(q));\n assert.equal(bad.body.error.code, 'VALIDATION_ERROR');\n assert.equal(typeof bad.body.error.message, 'string');\n assert.deepEqual(bad.body.error.details.map(d => d.field).sort(), fields);\n assert.ok(bad.body.error.details.every(d => typeof d.message === 'string'));\n}\nassert.equal(JSON.stringify(items), copy);\n"
},
{
"id": "create-user-status-codes",
"category": "api",
"manualIds": [
"skill:api-design"
],
"query": "src/usersRoute.js exports async createUser(req, repo) for POST /users and async getUser(req, repo) for GET /users/:id. Both return { status, headers?, body }. They currently return 200 for everything and 500 on duplicates. Fix them to use proper REST semantics. createUser: body { email, name }; email must be a string containing \"@\" and name a non-empty trimmed string, otherwise 400 with body { error: { code: \"VALIDATION_ERROR\", message, details: [{ field, message }] } } listing each bad field; if repo.findByEmail(email) returns a user, 409 with error code \"CONFLICT\"; otherwise call repo.create({ email, name }) and return 201 with headers { Location: \"/users/<id>\" } and body { data: user }. getUser: req.params.id; missing user gives 404 with error code \"NOT_FOUND\", found user gives 200 { data: user }. Do not add dependencies.",
"files": {
"src/usersRoute.js": "'use strict';\n\nasync function createUser(req, repo) {\n try {\n const { email, name } = req.body || {};\n const existing = await repo.findByEmail(email);\n if (existing) throw new Error('duplicate');\n const user = await repo.create({ email, name });\n return { status: 200, body: user };\n } catch (err) {\n return { status: 500, body: { message: err.message } };\n }\n}\n\nasync function getUser(req, repo) {\n const user = await repo.findById(req.params.id);\n return { status: 200, body: user };\n}\n\nmodule.exports = { createUser, getUser };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { createUser, getUser } = require(path.join(process.cwd(), 'src/usersRoute.js'));\nfunction repo() {\n const users = [{ id: 1, email: 'ada@example.com', name: 'Ada' }];\n return { created: 0, async findByEmail(e) { return users.find(u => u.email === e) || null; },\n async findById(id) { return users.find(u => String(u.id) === String(id)) || null; },\n async create(u) { this.created++; const user = { id: users.length + 1, ...u }; users.push(user); return user; } };\n}\n(async () => {\n const r = repo();\n let res = await createUser({ body: { email: 'lin@example.com', name: 'Lin' } }, r);\n assert.equal(res.status, 201);\n assert.equal(res.headers.Location, '/users/2');\n assert.deepEqual(res.body.data, { id: 2, email: 'lin@example.com', name: 'Lin' });\n res = await createUser({ body: { email: 'ada@example.com', name: 'Ada2' } }, r);\n assert.equal(res.status, 409);\n assert.equal(res.body.error.code, 'CONFLICT');\n res = await createUser({ body: { email: 'nope', name: ' ' } }, r);\n assert.equal(res.status, 400);\n assert.equal(res.body.error.code, 'VALIDATION_ERROR');\n assert.deepEqual(res.body.error.details.map(d => d.field).sort(), ['email', 'name']);\n res = await createUser({ body: { email: 'x@y.z' } }, r);\n assert.equal(res.status, 400);\n assert.deepEqual(res.body.error.details.map(d => d.field), ['name']);\n assert.equal(r.created, 1);\n res = await getUser({ params: { id: '99' } }, r);\n assert.equal(res.status, 404);\n assert.equal(res.body.error.code, 'NOT_FOUND');\n res = await getUser({ params: { id: '1' } }, r);\n assert.equal(res.status, 200);\n assert.equal(res.body.data.email, 'ada@example.com');\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "retry-with-backoff",
"category": "errors",
"manualIds": [
"skill:error-handling"
],
"query": "src/retry.js exports async withRetry(fn, options) used around calls to a flaky payments API. It currently retries every error immediately and throws a generic Error(\"failed\"), losing the cause. Rewrite it: options are { retries = 3, baseDelayMs = 100, maxDelayMs = 2000, sleep } where sleep(ms) returns a promise (default: a real setTimeout sleep). Call fn(attempt) with attempt starting at 1, for at most retries + 1 attempts. Only retry when the error is retryable: err.retryable === true, or err.status is 429 or >= 500. Non-retryable errors must be rethrown immediately (the same error object). Before retry n (n = 1, 2, ...) await sleep(d) where d is between half and all of min(baseDelayMs * 2^(n-1), maxDelayMs) (jitter optional). When retries are exhausted, rethrow the last error object. Return fn's resolved value on success. Do not add dependencies.",
"files": {
"src/retry.js": "'use strict';\n\nasync function withRetry(fn, options = {}) {\n const retries = options.retries || 3;\n for (let i = 0; i < retries; i++) {\n try {\n return await fn(i);\n } catch (err) {\n // try again\n }\n }\n throw new Error('failed');\n}\n\nmodule.exports = { withRetry };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { withRetry } = require(path.join(process.cwd(), 'src/retry.js'));\nconst mk = (status, extra = {}) => Object.assign(new Error('e' + status), { status }, extra);\n(async () => {\n let delays = [];\n const sleep = ms => { delays.push(ms); return Promise.resolve(); };\n let calls = [];\n const out = await withRetry(async a => { calls.push(a); if (a < 3) throw mk(503); return 'ok'; }, { sleep });\n assert.equal(out, 'ok');\n assert.deepEqual(calls, [1, 2, 3]);\n assert.equal(delays.length, 2);\n assert.ok(delays[0] >= 50 && delays[0] <= 100 && delays[1] >= 100 && delays[1] <= 200, String(delays));\n delays = []; calls = [];\n const last = mk(500);\n let n = 0;\n await assert.rejects(withRetry(async a => { calls.push(a); n++; throw n === 5 ? last : mk(502); },\n { retries: 4, baseDelayMs: 1000, maxDelayMs: 3000, sleep }), e => e === last);\n assert.deepEqual(calls, [1, 2, 3, 4, 5]);\n const caps = [1000, 2000, 3000, 3000];\n assert.equal(delays.length, 4);\n delays.forEach((d, i) => assert.ok(d >= caps[i] / 2 && d <= caps[i], 'delay ' + i + '=' + d));\n delays = []; calls = [];\n const bad = mk(400);\n await assert.rejects(withRetry(async a => { calls.push(a); throw bad; }, { sleep }), e => e === bad);\n assert.deepEqual(calls, [1]);\n assert.equal(delays.length, 0);\n calls = [];\n const plain = new Error('boom');\n await assert.rejects(withRetry(async a => { calls.push(a); throw plain; }, { sleep }), e => e === plain);\n assert.equal(calls.length, 1);\n calls = [];\n await withRetry(async a => { calls.push(a); if (a === 1) throw mk(429); if (a === 2) throw Object.assign(new Error('r'), { retryable: true }); return 1; }, { sleep });\n assert.deepEqual(calls, [1, 2, 3]);\n calls = [];\n await assert.rejects(withRetry(async a => { calls.push(a); throw mk(503); }, { retries: 0, sleep }));\n assert.deepEqual(calls, [1]);\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "typed-config-errors",
"category": "errors",
"manualIds": [
"skill:error-handling"
],
"query": "src/config.js exports loadConfig(text), which parses a JSON config string. Today it silently returns {} on bad JSON and accepts missing fields. Add and export a ConfigError class (extends Error, name \"ConfigError\") with a code property, and make loadConfig throw it: code \"CONFIG_PARSE\" for invalid JSON (with the original SyntaxError as error.cause); code \"CONFIG_MISSING\" with error.field set when a required field is missing (required: apiUrl, then timeoutMs, checked in that order); code \"CONFIG_INVALID\" with error.field = \"timeoutMs\" when timeoutMs is not a positive integer. On success return { apiUrl, timeoutMs, retries } where retries defaults to 2. Messages should be human readable. Do not add dependencies.",
"files": {
"src/config.js": "'use strict';\n\nfunction loadConfig(text) {\n let raw;\n try {\n raw = JSON.parse(text);\n } catch (e) {\n return {};\n }\n return { apiUrl: raw.apiUrl, timeoutMs: raw.timeoutMs, retries: raw.retries };\n}\n\nmodule.exports = { loadConfig };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { loadConfig, ConfigError } = require(path.join(process.cwd(), 'src/config.js'));\nassert.equal(typeof ConfigError, 'function');\nassert.deepEqual(loadConfig('{\"apiUrl\":\"https://x\",\"timeoutMs\":500}'), { apiUrl: 'https://x', timeoutMs: 500, retries: 2 });\nassert.deepEqual(loadConfig('{\"apiUrl\":\"https://x\",\"timeoutMs\":5,\"retries\":0}'), { apiUrl: 'https://x', timeoutMs: 5, retries: 0 });\nfunction thrown(text) { try { loadConfig(text); } catch (e) { return e; } assert.fail('expected throw for ' + text); }\nlet e = thrown('{bad json');\nassert.ok(e instanceof ConfigError && e instanceof Error);\nassert.equal(e.name, 'ConfigError');\nassert.equal(e.code, 'CONFIG_PARSE');\nassert.ok(e.cause instanceof SyntaxError);\nassert.ok(e.message.length > 0);\ne = thrown('{\"timeoutMs\":1}');\nassert.equal(e.code, 'CONFIG_MISSING');\nassert.equal(e.field, 'apiUrl');\ne = thrown('{\"apiUrl\":\"u\"}');\nassert.equal(e.code, 'CONFIG_MISSING');\nassert.equal(e.field, 'timeoutMs');\nfor (const t of ['0', '-5', '1.5', '\"100\"']) {\n e = thrown('{\"apiUrl\":\"u\",\"timeoutMs\":' + t + '}');\n assert.ok(e instanceof ConfigError);\n assert.equal(e.code, 'CONFIG_INVALID');\n assert.equal(e.field, 'timeoutMs');\n}\n"
},
{
"id": "batch-partial-failures",
"category": "errors",
"manualIds": [
"skill:error-handling"
],
"query": "src/batch.js exports async processAll(items, worker). items are objects with an id; worker(item) returns a promise. The current version swallows errors inside an empty catch and returns only a count, so failed webhook deliveries vanish. Change it to process every item (a failure must not stop the others) and resolve to { succeeded: [{ id, result }], failed: [{ id, error }] }, both in input order, where error is the thrown error's message (or String(value) if a non-Error was thrown). It must never reject because of a worker failure, and a worker that throws synchronously must be treated like a rejection. Do not add dependencies.",
"files": {
"src/batch.js": "'use strict';\n\nasync function processAll(items, worker) {\n let done = 0;\n for (const item of items) {\n try {\n await worker(item);\n done++;\n } catch (e) {}\n }\n return done;\n}\n\nmodule.exports = { processAll };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { processAll } = require(path.join(process.cwd(), 'src/batch.js'));\n(async () => {\n const seen = [];\n const items = [1, 2, 3, 4, 5].map(id => ({ id }));\n const out = await processAll(items, item => {\n seen.push(item.id);\n if (item.id === 2) throw new Error('sync boom');\n if (item.id === 4) return Promise.reject('plain string');\n if (item.id === 5) return Promise.reject(new TypeError('bad payload'));\n return Promise.resolve(item.id * 10);\n });\n assert.deepEqual(seen.slice().sort(), [1, 2, 3, 4, 5]);\n assert.deepEqual(out.succeeded, [{ id: 1, result: 10 }, { id: 3, result: 30 }]);\n assert.deepEqual(out.failed, [{ id: 2, error: 'sync boom' }, { id: 4, error: 'plain string' }, { id: 5, error: 'bad payload' }]);\n assert.deepEqual(await processAll([], () => 1), { succeeded: [], failed: [] });\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "access-log-parser",
"category": "parsing",
"manualIds": [
"skill:regex-vs-llm-structured-text"
],
"query": "src/parseLog.js parses web server access logs in Common Log Format, optionally extended to Combined Log Format with a quoted referrer and a quoted user agent. The current parseLine(line) splits on spaces and breaks on user agents and timestamps that contain spaces. Rewrite parseLine(line) to return { ip, user, time, method, path, protocol, status, bytes, referrer, userAgent } or null for any line that does not match the format. user, referrer and userAgent are null when the field is \"-\" or absent; time is the text inside the square brackets; status is a number (three digits); bytes is a number and \"-\" means 0. Also export parseLog(text) returning { entries, invalid } where blank lines (LF or CRLF endings) are skipped and invalid counts non-matching lines. See README.md for examples. Do not add dependencies.",
"files": {
"src/parseLog.js": "'use strict';\n\nfunction parseLine(line) {\n const parts = line.split(' ');\n return {\n ip: parts[0],\n user: parts[2],\n time: parts[3],\n method: parts[5],\n path: parts[6],\n protocol: parts[7],\n status: Number(parts[8]),\n bytes: Number(parts[9]),\n };\n}\n\nmodule.exports = { parseLine };\n",
"README.md": "# log-stats\n\nAccess log examples we must support:\n\n 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"\n 10.0.0.2 - - [11/Oct/2000:08:00:01 +0000] \"POST /api/login HTTP/1.1\" 401 -\n\nThe first is Combined Log Format, the second plain Common Log Format.\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { parseLine, parseLog } = require(path.join(process.cwd(), 'src/parseLog.js'));\nconst a = '127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"';\nassert.deepEqual(parseLine(a), { ip: '127.0.0.1', user: 'frank', time: '10/Oct/2000:13:55:36 -0700', method: 'GET',\n path: '/apache_pb.gif', protocol: 'HTTP/1.0', status: 200, bytes: 2326,\n referrer: 'http://www.example.com/start.html', userAgent: 'Mozilla/4.08 [en] (Win98; I ;Nav)' });\nconst b = '10.0.0.2 - - [11/Oct/2000:08:00:01 +0000] \"POST /api/login HTTP/1.1\" 401 -';\nassert.deepEqual(parseLine(b), { ip: '10.0.0.2', user: null, time: '11/Oct/2000:08:00:01 +0000', method: 'POST',\n path: '/api/login', protocol: 'HTTP/1.1', status: 401, bytes: 0, referrer: null, userAgent: null });\nconst c = '::1 - - [01/Jan/2024:00:00:00 +0000] \"DELETE /items/9?force=1 HTTP/2.0\" 204 0 \"-\" \"curl/8.4.0\"';\nconst pc = parseLine(c);\nassert.equal(pc.ip, '::1');\nassert.equal(pc.path, '/items/9?force=1');\nassert.equal(pc.referrer, null);\nassert.equal(pc.userAgent, 'curl/8.4.0');\nassert.equal(pc.status, 204);\nfor (const bad of ['garbage line', '', '10.0.0.2 - - 11/Oct/2000:08:00:01 +0000 \"GET / HTTP/1.1\" 200 5',\n '10.0.0.2 - - [11/Oct/2000:08:00:01 +0000] \"GET / HTTP/1.1\" 2000 5', '10.0.0.2 - - [x] \"GET / HTTP/1.1\" 200 abc',\n '\"GET / HTTP/1.1\" 200 12']) {\n assert.equal(parseLine(bad), null, bad);\n}\nconst log = [a, '', 'nonsense', b + '\\r', ' ', c, ''].join('\\n');\nconst out = parseLog(log);\nassert.equal(out.entries.length, 3);\nassert.equal(out.invalid, 1);\nassert.equal(out.entries[1].bytes, 0);\n"
},
{
"id": "invoice-field-extraction",
"category": "parsing",
"manualIds": [
"skill:regex-vs-llm-structured-text"
],
"query": "src/extract.js exports extractInvoice(text), which pulls fields out of plain-text invoices from several vendors. It only handles one vendor today. Make it return { invoiceNumber, date, total, currency } for all layouts documented in FORMATS.md: invoiceNumber is the identifier string; date is normalized to YYYY-MM-DD; total is a number (thousands separators removed) taken from the grand total line, never from Subtotal or Tax lines; currency is a three-letter code (\"$\" means USD). Any field that cannot be found is null. Labels are case-insensitive. Keep it deterministic and offline. Do not add dependencies.",
"files": {
"src/extract.js": "'use strict';\n\nfunction extractInvoice(text) {\n const num = /Invoice #: (\\S+)/.exec(text);\n const date = /Date: (\\d{4}-\\d{2}-\\d{2})/.exec(text);\n const total = /Total: \\$([\\d.]+)/.exec(text);\n return {\n invoiceNumber: num ? num[1] : null,\n date: date ? date[1] : null,\n total: total ? Number(total[1]) : null,\n currency: total ? 'USD' : null,\n };\n}\n\nmodule.exports = { extractInvoice };\n",
"FORMATS.md": "# Invoice layouts\n\nInvoice number labels: \"Invoice #:\", \"Invoice No.\", \"Invoice Number:\".\nIdentifiers use letters, digits and hyphens, for example INV-2024-0042, INV-7, A-19.\n\nDate labels: \"Date:\", \"Invoice Date:\", \"Issued:\". Values appear as\n2024-03-05 (ISO), 05/03/2024 (DD/MM/YYYY, day first) or 7 November 2023\n(day, full English month name, year).\n\nGrand total labels: \"Total:\", \"Total due:\", \"Amount due:\". Amounts look like\n$1,234.50 or EUR 99.00 (code before) or 1,000.00 GBP (code after).\nInvoices may also contain \"Subtotal:\" and \"Tax:\" lines, which are not totals.\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { extractInvoice } = require(path.join(process.cwd(), 'src/extract.js'));\nassert.deepEqual(extractInvoice(['ACME Corp', 'Invoice #: INV-2024-0042', 'Date: 2024-03-05', 'Subtotal: $1,100.00',\n 'Tax: $134.50', 'Total: $1,234.50'].join('\\n')), { invoiceNumber: 'INV-2024-0042', date: '2024-03-05', total: 1234.5, currency: 'USD' });\nassert.deepEqual(extractInvoice(['Globex GmbH', 'invoice no. INV-7', 'Invoice Date: 05/03/2024', 'Subtotal: EUR 90.00',\n 'TOTAL DUE: EUR 99.00'].join('\\r\\n')), { invoiceNumber: 'INV-7', date: '2024-03-05', total: 99, currency: 'EUR' });\nassert.deepEqual(extractInvoice(['Initech Ltd', 'Invoice Number: A-19', 'Issued: 7 November 2023', 'Tax: 0.00 GBP',\n 'Amount due: 1,000.00 GBP'].join('\\n')), { invoiceNumber: 'A-19', date: '2023-11-07', total: 1000, currency: 'GBP' });\nassert.deepEqual(extractInvoice('Thanks for your business!'), { invoiceNumber: null, date: null, total: null, currency: null });\nconst partial = extractInvoice('Invoice #: Z-1\\nSubtotal: $5.00');\nassert.equal(partial.invoiceNumber, 'Z-1');\nassert.equal(partial.total, null);\nassert.equal(partial.date, null);\n"
},
{
"id": "add-column-migration",
"category": "database",
"manualIds": [
"skill:database-migrations"
],
"query": "This repo keeps PostgreSQL migrations in migrations/ as NNN_name.up.sql plus NNN_name.down.sql (see README.md). Add migration 002 (one .up.sql and one .down.sql with the same NNN_name stem) that adds users.email_verified as a boolean that is NOT NULL with default false, and a unique index named users_email_lower_key on lower(email). The users table is large and takes writes constantly, so the index must be built without blocking writes, and the runner does not wrap files in a transaction. The down migration must fully reverse 002 and nothing else. Do not modify migration 001. Do not add dependencies.",
"files": {
"migrations/001_create_users.up.sql": "CREATE TABLE users (\n id bigserial PRIMARY KEY,\n email text NOT NULL,\n name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n",
"migrations/001_create_users.down.sql": "DROP TABLE users;\n",
"README.md": "# accounts-db\n\nPostgreSQL 15. Migrations live in migrations/ and are applied in filename order.\nEach migration is a pair: NNN_name.up.sql and NNN_name.down.sql.\nThe runner sends each file as-is (no implicit BEGIN/COMMIT).\nProduction: users has about 40 million rows and receives writes all day.\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst dir = path.join(process.cwd(), 'migrations');\nconst names = fs.readdirSync(dir);\nconst ups = names.filter(n => /^002_[A-Za-z0-9_-]+\\.up\\.sql$/.test(n));\nassert.equal(ups.length, 1, 'expected one 002 up migration');\nconst stem = ups[0].slice(0, -'.up.sql'.length);\nassert.ok(names.includes(stem + '.down.sql'), 'matching down migration missing');\nconst strip = s => s.replace(/--[^\\n]*/g, '').replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\nconst up = strip(fs.readFileSync(path.join(dir, ups[0]), 'utf8'));\nconst down = strip(fs.readFileSync(path.join(dir, stem + '.down.sql'), 'utf8'));\nconst add = /ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?\"?users\"?\\s+ADD\\s+(?:COLUMN\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?\"?email_verified\"?\\s+(?:boolean|bool)\\b([^;]*)/i.exec(up);\nassert.ok(add, 'ADD COLUMN email_verified boolean missing');\nconst col = '\"?email_verified\"?';\nassert.ok(/NOT\\s+NULL/i.test(add[1]) || new RegExp('ALTER\\\\s+COLUMN\\\\s+' + col + '\\\\s+SET\\\\s+NOT\\\\s+NULL', 'i').test(up), 'NOT NULL missing');\nassert.ok(/DEFAULT\\s+(?:false|'f'|'false')/i.test(add[1]) || new RegExp('ALTER\\\\s+COLUMN\\\\s+' + col + '\\\\s+SET\\\\s+DEFAULT\\\\s+false', 'i').test(up), 'DEFAULT false missing');\nassert.match(up, /CREATE\\s+UNIQUE\\s+INDEX\\s+CONCURRENTLY\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?\"?users_email_lower_key\"?\\s+ON\\s+(?:ONLY\\s+)?\"?users\"?\\s*(?:USING\\s+btree\\s*)?\\(\\s*lower\\s*\\(\\s*\"?email\"?\\s*\\)\\s*\\)/i);\nconst idx = up.search(/CREATE\\s+UNIQUE\\s+INDEX\\s+CONCURRENTLY/i);\nconst opened = [...up.slice(0, idx).matchAll(/\\b(BEGIN|START\\s+TRANSACTION|COMMIT|END|ROLLBACK)\\b\\s*;/gi)].map(x => x[1].toUpperCase());\nassert.ok(!opened.length || !/^(BEGIN|START)/.test(opened[opened.length - 1]), 'concurrent index inside a transaction');\nassert.doesNotMatch(up, /DROP\\s+(?:COLUMN|TABLE|INDEX)/i);\nassert.match(down, /DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+EXISTS\\s+)?\"?users_email_lower_key\"?/i);\nassert.match(down, /ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?\"?users\"?\\s+DROP\\s+(?:COLUMN\\s+)?(?:IF\\s+EXISTS\\s+)?\"?email_verified\"?/i);\nassert.doesNotMatch(down, /DROP\\s+TABLE/i);\nconst original = \"CREATE TABLE users (\\n id bigserial PRIMARY KEY,\\n email text NOT NULL,\\n name text NOT NULL,\\n created_at timestamptz NOT NULL DEFAULT now()\\n);\\n\";\nassert.equal(fs.readFileSync(path.join(dir, '001_create_users.up.sql'), 'utf8'), original);\nassert.equal(fs.readFileSync(path.join(dir, '001_create_users.down.sql'), 'utf8'), 'DROP TABLE users;\\n');\n"
},
{
"id": "rename-column-expand",
"category": "database",
"manualIds": [
"skill:database-migrations"
],
"query": "We want PostgreSQL column customers.full_name renamed to display_name, but old app instances keep reading and writing full_name for hours during the rolling deploy (see README.md). Do only the zero-downtime expand step. 1) Add migrations/002_<name>.up.sql and matching .down.sql: the up adds a nullable display_name text column and backfills it from full_name; it must not rename or drop full_name. The down removes display_name only. 2) Update src/customerRepo.js: buildInsert(customer) and buildUpdateName(id, name) must write the name to both full_name and display_name (still parameterized { text, values } with $n placeholders), and mapRow(row) must return name from display_name, falling back to full_name when display_name is null. Keep all exports. Do not add dependencies.",
"files": {
"migrations/001_create_customers.up.sql": "CREATE TABLE customers (\n id bigserial PRIMARY KEY,\n email text NOT NULL,\n full_name text NOT NULL\n);\n",
"migrations/001_create_customers.down.sql": "DROP TABLE customers;\n",
"src/customerRepo.js": "'use strict';\n\nfunction buildInsert(customer) {\n return { text: 'INSERT INTO customers (email, full_name) VALUES ($1, $2) RETURNING id', values: [customer.email, customer.name] };\n}\n\nfunction buildUpdateName(id, name) {\n return { text: 'UPDATE customers SET full_name = $1 WHERE id = $2', values: [name, id] };\n}\n\nfunction mapRow(row) {\n return { id: row.id, email: row.email, name: row.full_name };\n}\n\nmodule.exports = { buildInsert, buildUpdateName, mapRow };\n",
"README.md": "# customers-service\n\nPostgreSQL 15. Migrations: migrations/NNN_name.up.sql and NNN_name.down.sql.\nDeploys are rolling: the previous app version keeps serving traffic (reading\nand writing full_name) until every instance is replaced.\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst dir = path.join(process.cwd(), 'migrations');\nconst names = fs.readdirSync(dir);\nconst ups = names.filter(n => /^002_[A-Za-z0-9_-]+\\.up\\.sql$/.test(n));\nassert.equal(ups.length, 1);\nconst stem = ups[0].slice(0, -'.up.sql'.length);\nconst strip = s => s.replace(/--[^\\n]*/g, '').replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\nconst up = strip(fs.readFileSync(path.join(dir, ups[0]), 'utf8'));\nconst down = strip(fs.readFileSync(path.join(dir, stem + '.down.sql'), 'utf8'));\nconst add = /ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?\"?customers\"?\\s+ADD\\s+(?:COLUMN\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?\"?display_name\"?\\s+(?:text|varchar|character\\s+varying)\\b([^;]*)/i.exec(up);\nassert.ok(add, 'ADD COLUMN display_name missing');\nassert.doesNotMatch(add[1], /NOT\\s+NULL/i);\nassert.match(up, /UPDATE\\s+\"?customers\"?\\s+SET\\s+\"?display_name\"?\\s*=\\s*\"?full_name\"?/i);\nassert.doesNotMatch(up, /RENAME\\s+(?:COLUMN\\s+)?\"?full_name/i);\nassert.doesNotMatch(up, /DROP\\s+(?:COLUMN|TABLE)|DROP\\s+\"?full_name/i);\nassert.match(down, /DROP\\s+(?:COLUMN\\s+)?(?:IF\\s+EXISTS\\s+)?\"?display_name\"?/i);\nassert.doesNotMatch(down, /full_name|DROP\\s+TABLE/i);\nconst repo = require(path.join(process.cwd(), 'src/customerRepo.js'));\nconst maxParam = t => Math.max(0, ...[...t.matchAll(/\\$(\\d+)/g)].map(x => Number(x[1])));\nconst ins = repo.buildInsert({ email: 'a@x.io', name: \"O'Hara\" });\nassert.match(ins.text, /INSERT\\s+INTO\\s+\"?customers\"?/i);\nassert.match(ins.text, /full_name/);\nassert.match(ins.text, /display_name/);\nassert.ok(!ins.text.includes(\"O'Hara\"));\nassert.ok(ins.values.includes(\"O'Hara\") && ins.values.includes('a@x.io'));\nassert.equal(maxParam(ins.text), ins.values.length);\nconst upd = repo.buildUpdateName(7, 'Bo');\nassert.match(upd.text, /UPDATE\\s+\"?customers\"?\\s+SET/i);\nassert.match(upd.text, /full_name\\s*=\\s*\\$\\d+/);\nassert.match(upd.text, /display_name\\s*=\\s*\\$\\d+/);\nassert.match(upd.text, /WHERE\\s+\"?id\"?\\s*=\\s*\\$\\d+/i);\nassert.ok(upd.values.includes('Bo') && upd.values.includes(7));\nassert.equal(maxParam(upd.text), upd.values.length);\nassert.equal(repo.mapRow({ id: 1, email: 'e', full_name: 'Old', display_name: null }).name, 'Old');\nassert.equal(repo.mapRow({ id: 1, email: 'e', full_name: 'Old' }).name, 'Old');\nassert.equal(repo.mapRow({ id: 1, email: 'e', full_name: 'Old', display_name: 'New' }).name, 'New');\nassert.equal(repo.mapRow({ id: 2, email: 'e', full_name: 'Old', display_name: 'New' }).id, 2);\n"
},
{
"id": "keyset-feed-query",
"category": "database",
"manualIds": [
"skill:postgres-patterns"
],
"query": "src/feedQuery.js builds the PostgreSQL query for a user's post feed using OFFSET, which gets slow and skips rows on deep pages. Switch to keyset (cursor) pagination ordered by created_at DESC, id DESC. Export encodeCursor(row) (row has created_at as an ISO string and id) returning an opaque string, and buildFeedQuery({ userId, limit, cursor }) returning { text, values } for node-postgres ($n placeholders; no caller value inlined into text). cursor is undefined for the first page; otherwise it comes from encodeCursor and the query must return only rows strictly after that row in the sort order. Throw an Error for a malformed cursor and a RangeError unless limit is an integer 1..50. Also add migrations/002_<name>.sql creating a composite index on posts that supports this query (single-file migrations, see 001). Do not add dependencies.",
"files": {
"src/feedQuery.js": "'use strict';\n\n// page is 0-based\nfunction buildFeedQuery({ userId, limit, page = 0 }) {\n return {\n text: 'SELECT id, user_id, body, created_at FROM posts WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3',\n values: [userId, limit, page * limit],\n };\n}\n\nmodule.exports = { buildFeedQuery };\n",
"migrations/001_create_posts.sql": "CREATE TABLE posts (\n id bigserial PRIMARY KEY,\n user_id bigint NOT NULL,\n body text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { buildFeedQuery, encodeCursor } = require(path.join(process.cwd(), 'src/feedQuery.js'));\nconst maxParam = t => Math.max(0, ...[...t.matchAll(/\\$(\\d+)/g)].map(x => Number(x[1])));\nconst ORDER = /ORDER\\s+BY\\s+\"?created_at\"?\\s+DESC\\s*,\\s*\"?id\"?\\s+DESC/i;\nconst first = buildFeedQuery({ userId: 7, limit: 20 });\nassert.doesNotMatch(first.text, /OFFSET/i);\nassert.match(first.text, ORDER);\nassert.match(first.text, /user_id\\s*=\\s*\\$\\d+/i);\nassert.ok(first.values.includes(7));\nassert.match(first.text, /LIMIT\\s+(\\$\\d+|20)\\b/i);\nassert.equal(maxParam(first.text), first.values.length);\nconst cur = encodeCursor({ id: 42, user_id: 7, body: 'hi', created_at: '2024-05-01T10:00:00.000Z' });\nassert.equal(typeof cur, 'string');\nconst next = buildFeedQuery({ userId: 7, limit: 20, cursor: cur });\nassert.doesNotMatch(next.text, /OFFSET/i);\nassert.match(next.text, ORDER);\nassert.ok(!next.text.includes('2024-05-01') && !/\\b42\\b/.test(next.text));\nconst row = /\\(\\s*\"?created_at\"?\\s*,\\s*\"?id\"?\\s*\\)\\s*<\\s*\\(\\s*\\$(\\d+)(?:::\\w+)?\\s*,\\s*\\$(\\d+)(?:::\\w+)?\\s*\\)/i.exec(next.text);\nconst expanded = /\"?created_at\"?\\s*<\\s*\\$(\\d+)[\\s\\S]*\"?created_at\"?\\s*=\\s*\\$(\\d+)[\\s\\S]*\"?id\"?\\s*<\\s*\\$(\\d+)/i.exec(next.text);\nassert.ok(row || expanded, 'keyset predicate missing: ' + next.text);\nconst vals = next.values.map(v => (v instanceof Date ? v.toISOString() : String(v)));\nassert.ok(vals.includes('2024-05-01T10:00:00.000Z'));\nassert.ok(vals.includes('42'));\nassert.ok(next.values.includes(7));\nassert.equal(maxParam(next.text), next.values.length);\nassert.throws(() => buildFeedQuery({ userId: 7, limit: 20, cursor: 'not-a-cursor' }));\nfor (const bad of [0, 51, '20', 1.5]) assert.throws(() => buildFeedQuery({ userId: 7, limit: bad }), RangeError);\nconst dir = path.join(process.cwd(), 'migrations');\nconst mig = fs.readdirSync(dir).filter(n => /^002_[A-Za-z0-9_-]+\\.sql$/.test(n));\nassert.equal(mig.length, 1);\nconst sql = fs.readFileSync(path.join(dir, mig[0]), 'utf8').replace(/--[^\\n]*/g, '');\nassert.match(sql, /CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+[\\s\\S]*?ON\\s+(?:ONLY\\s+)?\"?posts\"?\\s*(?:USING\\s+btree\\s*)?\\(\\s*\"?user_id\"?\\s*,\\s*\"?created_at\"?(?:\\s+DESC)?\\s*,\\s*\"?id\"?(?:\\s+DESC)?\\s*\\)/i);\n"
},
{
"id": "upsert-inventory-sql",
"category": "database",
"manualIds": [
"skill:postgres-patterns"
],
"query": "src/inventory.js exports async syncStock(db, items), where items are { sku, quantity } and db.query(text, values) runs a parameterized PostgreSQL statement (node-postgres style, $n placeholders). It currently does a SELECT and then an UPDATE or INSERT per item, which is slow and races with concurrent syncs. Replace it with a single INSERT INTO inventory (sku, quantity, updated_at) ... ON CONFLICT (sku) DO UPDATE statement for the whole batch that sets quantity from the incoming row and updated_at to now(). Exactly one db.query call per non-empty batch and none for an empty batch. If the same sku appears more than once in items, the last occurrence wins (PostgreSQL rejects affecting a row twice in one statement). No caller value may be inlined into the SQL text. Resolve to the number of distinct skus written. Do not add dependencies.",
"files": {
"src/inventory.js": "'use strict';\n\nasync function syncStock(db, items) {\n let count = 0;\n for (const item of items) {\n const found = await db.query('SELECT sku FROM inventory WHERE sku = $1', [item.sku]);\n if (found.rows.length) {\n await db.query('UPDATE inventory SET quantity = $1, updated_at = now() WHERE sku = $2', [item.quantity, item.sku]);\n } else {\n await db.query('INSERT INTO inventory (sku, quantity, updated_at) VALUES ($1, $2, now())', [item.sku, item.quantity]);\n }\n count++;\n }\n return count;\n}\n\nmodule.exports = { syncStock };\n",
"schema.sql": "CREATE TABLE inventory (\n sku text PRIMARY KEY,\n quantity integer NOT NULL,\n updated_at timestamptz NOT NULL\n);\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { syncStock } = require(path.join(process.cwd(), 'src/inventory.js'));\nfunction fakeDb() {\n const calls = [];\n return { calls, async query(text, values) { calls.push({ text, values }); return { rows: [], rowCount: 0 }; } };\n}\n(async () => {\n let db = fakeDb();\n assert.equal(await syncStock(db, []), 0);\n assert.equal(db.calls.length, 0);\n db = fakeDb();\n const n = await syncStock(db, [{ sku: 'SKU-A', quantity: 11 }, { sku: \"SKU-'B\", quantity: 55 }, { sku: 'SKU-A', quantity: 7 }]);\n assert.equal(n, 2);\n assert.equal(db.calls.length, 1);\n const { text, values } = db.calls[0];\n assert.match(text, /INSERT\\s+INTO\\s+\"?inventory\"?/i);\n assert.match(text, /ON\\s+CONFLICT\\s*\\(\\s*\"?sku\"?\\s*\\)\\s*DO\\s+UPDATE\\s+SET/i);\n assert.match(text, /\"?quantity\"?\\s*=\\s*EXCLUDED\\.\"?quantity\"?/i);\n assert.match(text, /\"?updated_at\"?\\s*=\\s*(?:now\\(\\)|CURRENT_TIMESTAMP|EXCLUDED\\.\"?updated_at\"?)/i);\n assert.ok(!text.includes('SKU-'), 'sku inlined into SQL');\n const flat = values.flat(Infinity).map(v => (typeof v === 'string' && /^\\d+$/.test(v) ? Number(v) : v));\n assert.equal(flat.filter(v => v === 'SKU-A').length, 1);\n assert.equal(flat.filter(v => v === \"SKU-'B\").length, 1);\n assert.ok(flat.includes(7) && flat.includes(55));\n assert.ok(!flat.includes(11), 'stale duplicate quantity sent');\n const maxParam = Math.max(0, ...[...text.matchAll(/\\$(\\d+)/g)].map(x => Number(x[1])));\n assert.equal(maxParam, values.length);\n db = fakeDb();\n assert.equal(await syncStock(db, [{ sku: 'X', quantity: 1 }]), 1);\n assert.equal(db.calls.length, 1);\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "slugify-regression-tests",
"category": "testing",
"manualIds": [
"skill:tdd-workflow"
],
"query": "Bug report in BUGS.md: src/slugify.js produces leading and trailing hyphens and mangles accented letters. Work test-first: add test/slugify.test.js using the built-in node:test runner and node:assert, requiring ../src/slugify, with at least three separate test cases that reproduce the reported bugs and cover edge cases (empty input, repeated separators), then fix slugify(input) so they pass. Expected behavior: lowercase ASCII output; accented Latin letters lose their accents (e with grave becomes e); every run of non-alphanumeric characters becomes a single hyphen; no leading or trailing hyphens; empty or separator-only input returns an empty string. Do not add dependencies.",
"files": {
"src/slugify.js": "'use strict';\n\nfunction slugify(input) {\n return String(input).toLowerCase().replace(/[^a-z0-9]+/g, '-');\n}\n\nmodule.exports = { slugify };\n",
"BUGS.md": "# Open bugs\n\n1. slugify(' Hello, World! ') returns '-hello-world-' (expected 'hello-world').\n2. slugify('Cr\\u00e8me Br\\u00fbl\\u00e9e') (accented) returns 'cr-me-br-l-e' (expected 'creme-brulee').\n",
"package.json": "{\n \"name\": \"slugs\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": { \"test\": \"node --test test/\" }\n}\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { slugify } = require(path.join(process.cwd(), 'src/slugify.js'));\nassert.equal(slugify(' Hello, World! '), 'hello-world');\nassert.equal(slugify('Cr\\u00e8me Br\\u00fbl\\u00e9e'), 'creme-brulee');\nassert.equal(slugify('D\\u00e9j\\u00e0 Vu 2024'), 'deja-vu-2024');\nassert.equal(slugify('a--b__c'), 'a-b-c');\nassert.equal(slugify(''), '');\nassert.equal(slugify(' -- !! '), '');\nassert.equal(slugify('already-slugged'), 'already-slugged');\nconst testFile = path.join(process.cwd(), 'test', 'slugify.test.js');\nassert.ok(fs.existsSync(testFile), 'test/slugify.test.js missing');\nconst src = fs.readFileSync(testFile, 'utf8');\nassert.match(src, /node:test/);\nassert.match(src, /require\\(\\s*['\"]\\.\\.\\/src\\/slugify(?:\\.js)?['\"]\\s*\\)/);\nassert.ok((src.match(/\\b(?:test|it)\\s*\\(/g) || []).length >= 3, 'expected at least three test cases');\n"
},
{
"id": "content-hash-cache",
"category": "performance",
"manualIds": [
"skill:content-hash-cache-pattern"
],
"query": "src/extractor.js exports createExtractor({ readFile, parse }). readFile(filePath) returns a Buffer and parse(text) is an expensive document parser. The cache is keyed by file path, so edited files return stale results and renamed or copied files are parsed again. Re-key the cache by the SHA-256 hex digest of the file bytes (use node:crypto) so identical content at any path is parsed once and changed content is re-parsed. Also export cacheKeyFor(buffer) returning that hex digest. extract(filePath) must still return the parse result, and stats() must return { hits, misses } counting cache hits and parses. Do not add dependencies.",
"files": {
"src/extractor.js": "'use strict';\n\nfunction createExtractor({ readFile, parse }) {\n const cache = new Map();\n let hits = 0;\n let misses = 0;\n return {\n extract(filePath) {\n if (cache.has(filePath)) {\n hits++;\n return cache.get(filePath);\n }\n misses++;\n const result = parse(readFile(filePath).toString('utf8'));\n cache.set(filePath, result);\n return result;\n },\n stats: () => ({ hits, misses }),\n };\n}\n\nmodule.exports = { createExtractor };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { createExtractor, cacheKeyFor } = require(path.join(process.cwd(), 'src/extractor.js'));\nassert.equal(cacheKeyFor(Buffer.from('hello')), '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824');\nassert.notEqual(cacheKeyFor(Buffer.from('a')), cacheKeyFor(Buffer.from('b')));\nconst disk = { 'a.txt': Buffer.from('report one'), 'b.txt': Buffer.from('report one') };\nlet parses = 0;\nconst ex = createExtractor({ readFile: p => Buffer.from(disk[p]), parse: t => { parses++; return { words: t.split(' ').length, text: t }; } });\nassert.deepEqual(ex.extract('a.txt'), { words: 2, text: 'report one' });\nassert.deepEqual(ex.extract('b.txt'), { words: 2, text: 'report one' });\nassert.equal(parses, 1);\ndisk['a.txt'] = Buffer.from('report one edited');\nassert.deepEqual(ex.extract('a.txt'), { words: 3, text: 'report one edited' });\nassert.equal(parses, 2);\nex.extract('a.txt');\nex.extract('b.txt');\nassert.equal(parses, 2);\nassert.deepEqual(ex.stats(), { hits: 3, misses: 2 });\n"
},
{
"id": "batch-customer-lookup",
"category": "performance",
"manualIds": [
"skill:backend-patterns"
],
"query": "src/orders.js exports async getOrdersWithCustomers(repo) for the orders dashboard endpoint. It calls repo.findCustomerById once per order, which is an N+1 query pattern and times out for large accounts. The repo (see src/repo.js for the interface) also offers findCustomersByIds(ids), which resolves to the matching customers in any order and omits unknown ids. Rewrite the function to load all customers with a single findCustomersByIds call using the distinct customer ids (and no call at all when there are no orders), never calling findCustomerById. Return the orders in their original order, each as a new object with a customer property (null when the customer does not exist). Do not add dependencies.",
"files": {
"src/orders.js": "'use strict';\n\nasync function getOrdersWithCustomers(repo) {\n const orders = await repo.listOrders();\n const result = [];\n for (const order of orders) {\n const customer = await repo.findCustomerById(order.customerId);\n result.push({ ...order, customer });\n }\n return result;\n}\n\nmodule.exports = { getOrdersWithCustomers };\n",
"src/repo.js": "'use strict';\n\n// Interface implemented by the SQL repository in production.\n// listOrders(): Promise<Array<{ id, customerId, total }>>\n// findCustomerById(id): Promise<{ id, name } | null> -- one query per call\n// findCustomersByIds(ids): Promise<Array<{ id, name }>> -- one query, WHERE id = ANY($1)\nmodule.exports = {};\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { getOrdersWithCustomers } = require(path.join(process.cwd(), 'src/orders.js'));\nfunction repo(orders) {\n const customers = [{ id: 'c1', name: 'Ada' }, { id: 'c2', name: 'Lin' }, { id: 'c3', name: 'Bo' }];\n const r = { single: 0, batch: [], async listOrders() { return orders; },\n async findCustomerById(id) { r.single++; return customers.find(c => c.id === id) || null; },\n async findCustomersByIds(ids) { r.batch.push([...ids]); return customers.filter(c => ids.includes(c.id)).reverse(); } };\n return r;\n}\n(async () => {\n const orders = [{ id: 1, customerId: 'c2', total: 5 }, { id: 2, customerId: 'c1', total: 7 },\n { id: 3, customerId: 'c2', total: 1 }, { id: 4, customerId: 'gone', total: 2 }];\n const snapshot = JSON.stringify(orders);\n const r = repo(orders);\n const out = await getOrdersWithCustomers(r);\n assert.equal(r.single, 0);\n assert.equal(r.batch.length, 1);\n assert.deepEqual(r.batch[0].slice().sort(), ['c1', 'c2', 'gone']);\n assert.deepEqual(out.map(o => o.id), [1, 2, 3, 4]);\n assert.deepEqual(out.map(o => o.customer && o.customer.name), ['Lin', 'Ada', 'Lin', null]);\n assert.equal(out[0].total, 5);\n assert.equal(JSON.stringify(orders), snapshot);\n const empty = repo([]);\n assert.deepEqual(await getOrdersWithCustomers(empty), []);\n assert.equal(empty.batch.length + empty.single, 0);\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "rbac-middleware",
"category": "auth",
"manualIds": [
"skill:backend-patterns"
],
"query": "src/auth.js exports requirePermission(permission), an Express-style middleware factory, and ROLE_PERMISSIONS. It only checks that req.user exists and never checks the role. Implement role-based access control: calling requirePermission with a permission that no role grants must throw immediately. The returned middleware (req, res, next) must respond res.status(401).json({ error: { code: \"UNAUTHENTICATED\", message } }) when req.user is missing; res.status(403).json({ error: { code: \"FORBIDDEN\", message } }) when req.user.role is unknown or lacks the permission (role names must be looked up safely, so values such as \"constructor\" or \"__proto__\" are simply unknown roles); otherwise call next() exactly once without responding. Do not change ROLE_PERMISSIONS. Do not add dependencies.",
"files": {
"src/auth.js": "'use strict';\n\nconst ROLE_PERMISSIONS = {\n admin: ['read', 'write', 'delete'],\n editor: ['read', 'write'],\n viewer: ['read'],\n};\n\nfunction requirePermission(permission) {\n return (req, res, next) => {\n if (!req.user) return res.status(401).json({ error: 'unauthorized' });\n return next();\n };\n}\n\nmodule.exports = { requirePermission, ROLE_PERMISSIONS };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { requirePermission } = require(path.join(process.cwd(), 'src/auth.js'));\nfunction run(permission, user) {\n const res = { code: null, body: null, status(c) { this.code = c; return this; }, json(b) { this.body = b; return this; } };\n let nexts = 0;\n requirePermission(permission)(user === undefined ? {} : { user }, res, () => { nexts++; });\n return { res, nexts };\n}\nlet r = run('read');\nassert.equal(r.res.code, 401);\nassert.equal(r.res.body.error.code, 'UNAUTHENTICATED');\nassert.equal(typeof r.res.body.error.message, 'string');\nassert.equal(r.nexts, 0);\nr = run('write', { id: 1, role: 'viewer' });\nassert.equal(r.res.code, 403);\nassert.equal(r.res.body.error.code, 'FORBIDDEN');\nassert.equal(r.nexts, 0);\nfor (const role of ['root', 'constructor', '__proto__', 'toString', undefined, 'hasOwnProperty']) {\n let out;\n assert.doesNotThrow(() => { out = run('read', { id: 2, role }); }, String(role));\n assert.equal(out.res.code, 403, String(role));\n assert.equal(out.nexts, 0);\n}\nr = run('write', { id: 3, role: 'editor' });\nassert.equal(r.nexts, 1);\nassert.equal(r.res.code, null);\nr = run('delete', { id: 4, role: 'admin' });\nassert.equal(r.nexts, 1);\nr = run('delete', { id: 5, role: 'editor' });\nassert.equal(r.res.code, 403);\nassert.throws(() => requirePermission('fly'));\nassert.throws(() => requirePermission('constructor'));\n"
},
{
"id": "immutable-cart-update",
"category": "refactor",
"manualIds": [
"skill:coding-standards"
],
"query": "src/cart.js exports addItem(cart, item), removeItem(cart, sku), applyDiscount(cart, pct) and total(cart). A cart is { items: [{ sku, price, quantity }], discountPct }. The update functions mutate their arguments, which causes stale UI state bugs. Refactor them to be pure: never mutate the cart, its items array, any item object, or the item argument; always return a new cart object. Keep the behavior: addItem adds the item, or increases quantity when the sku already exists; removeItem drops the sku; applyDiscount sets discountPct and must throw a RangeError unless pct is a number from 0 to 100; total returns the discounted sum rounded to 2 decimal places. Do not add dependencies.",
"files": {
"src/cart.js": "'use strict';\n\nfunction addItem(cart, item) {\n const existing = cart.items.find(i => i.sku === item.sku);\n if (existing) existing.quantity += item.quantity;\n else cart.items.push(item);\n return cart;\n}\n\nfunction removeItem(cart, sku) {\n cart.items = cart.items.filter(i => i.sku !== sku);\n return cart;\n}\n\nfunction applyDiscount(cart, pct) {\n cart.discountPct = pct;\n return cart;\n}\n\nfunction total(cart) {\n const sum = cart.items.reduce((acc, i) => acc + i.price * i.quantity, 0);\n return Math.round(sum * (1 - (cart.discountPct || 0) / 100) * 100) / 100;\n}\n\nmodule.exports = { addItem, removeItem, applyDiscount, total };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst cart = require(path.join(process.cwd(), 'src/cart.js'));\nconst deepFreeze = o => { Object.values(o).forEach(v => { if (v && typeof v === 'object') deepFreeze(v); }); return Object.freeze(o); };\nconst base = deepFreeze({ items: [{ sku: 'a', price: 10, quantity: 1 }, { sku: 'b', price: 2.5, quantity: 2 }], discountPct: 0 });\nconst snap = JSON.stringify(base);\nconst item = deepFreeze({ sku: 'a', price: 10, quantity: 2 });\nconst c1 = cart.addItem(base, item);\nassert.notEqual(c1, base);\nassert.deepEqual(c1.items.find(i => i.sku === 'a').quantity, 3);\nassert.equal(c1.items.length, 2);\nconst newItem = deepFreeze({ sku: 'c', price: 1, quantity: 1 });\nconst c2 = cart.addItem(c1, newItem);\nassert.equal(c2.items.length, 3);\nassert.equal(c1.items.length, 2);\nconst c3 = cart.removeItem(c2, 'b');\nassert.deepEqual(c3.items.map(i => i.sku), ['a', 'c']);\nassert.equal(c2.items.length, 3);\nconst c4 = cart.applyDiscount(c3, 10);\nassert.equal(c4.discountPct, 10);\nassert.equal(c3.discountPct, 0);\nassert.equal(cart.total(c4), 27.9);\nassert.equal(cart.total(base), 15);\nfor (const bad of [-1, 101, '10', NaN]) assert.throws(() => cart.applyDiscount(base, bad), RangeError);\nassert.equal(JSON.stringify(base), snap);\nconst m = { items: [{ sku: 'z', price: 1, quantity: 1 }], discountPct: 0 };\nconst m2 = cart.addItem(m, { sku: 'z', price: 1, quantity: 4 });\nassert.equal(m.items[0].quantity, 1);\nassert.equal(m2.items[0].quantity, 5);\nconst added = { sku: 'y', price: 3, quantity: 1 };\nconst m3 = cart.addItem(m, added);\ncart.addItem(m3, { sku: 'y', price: 3, quantity: 5 });\nassert.equal(added.quantity, 1);\n"
},
{
"id": "inject-signup-deps",
"category": "refactor",
"manualIds": [
"skill:hexagonal-architecture"
],
"query": "src/signup.js hard-requires the Postgres and SMTP adapters in src/adapters/, which fail at import time without infrastructure, so the sign-up use case cannot be unit tested. Refactor to ports and adapters. src/signup.js must export createSignupService({ userRepository, mailer, clock }) returning { signUp({ email, name }) } and must not import anything from src/adapters or read environment variables. Ports: userRepository.findByEmail(email) and userRepository.save(user) (resolves to the stored user including id), mailer.sendWelcome({ to, name }), clock.now() returning a Date. signUp trims and lowercases the email; rejects with an error whose code is \"INVALID_EMAIL\" if it lacks \"@\", or \"EMAIL_TAKEN\" if findByEmail finds a user (without saving or mailing); otherwise saves { email, name, createdAt: clock.now().toISOString() }, sends the welcome email to the saved user, and resolves to the saved user. Add src/main.js as the composition root that wires the real adapters. Keep the adapters as they are. Do not add dependencies.",
"files": {
"src/signup.js": "'use strict';\nconst store = require('./adapters/pgUserStore');\nconst mailer = require('./adapters/smtpMailer');\n\nasync function signUp({ email, name }) {\n const normalized = email.trim().toLowerCase();\n if (await store.findByEmail(normalized)) throw new Error('taken');\n const user = await store.insert({ email: normalized, name, createdAt: new Date().toISOString() });\n await mailer.sendWelcome(user.email, user.name);\n return user;\n}\n\nmodule.exports = { signUp };\n",
"src/adapters/pgUserStore.js": "'use strict';\n// Connects at import time, like our real pool module.\nif (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not configured');\n\nmodule.exports = {\n async findByEmail(email) { throw new Error('not implemented in this repo snapshot: ' + email); },\n async insert(user) { throw new Error('not implemented in this repo snapshot: ' + user.email); },\n};\n",
"src/adapters/smtpMailer.js": "'use strict';\nif (!process.env.SMTP_URL) throw new Error('SMTP_URL is not configured');\n\nmodule.exports = {\n async sendWelcome(to, name) { throw new Error('not implemented in this repo snapshot: ' + to + name); },\n};\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst fs = require('node:fs');\nconst path = require('node:path');\ndelete process.env.DATABASE_URL;\ndelete process.env.SMTP_URL;\nconst file = path.join(process.cwd(), 'src/signup.js');\nconst source = fs.readFileSync(file, 'utf8');\nassert.doesNotMatch(source, /require\\([^)]*adapters|from\\s+['\"][^'\"]*adapters/, 'domain imports an adapter');\nassert.doesNotMatch(source, /process\\.env/, 'domain reads the environment');\nassert.ok(fs.existsSync(path.join(process.cwd(), 'src/main.js')), 'composition root missing');\nconst { createSignupService } = require(file);\nfunction setup(existing = []) {\n const users = [...existing];\n const log = { saved: [], mails: [] };\n const svc = createSignupService({\n userRepository: { async findByEmail(e) { return users.find(u => u.email === e) || null; },\n async save(u) { const s = { id: 'u' + (users.length + 1), ...u }; users.push(s); log.saved.push(u); return s; } },\n mailer: { async sendWelcome(msg) { log.mails.push(msg); } },\n clock: { now: () => new Date(Date.UTC(2024, 0, 2, 3, 4, 5)) },\n });\n return { svc, log };\n}\n(async () => {\n let { svc, log } = setup();\n const user = await svc.signUp({ email: ' Ada@Example.COM ', name: 'Ada' });\n assert.deepEqual(user, { id: 'u1', email: 'ada@example.com', name: 'Ada', createdAt: '2024-01-02T03:04:05.000Z' });\n assert.deepEqual(log.saved, [{ email: 'ada@example.com', name: 'Ada', createdAt: '2024-01-02T03:04:05.000Z' }]);\n assert.deepEqual(log.mails, [{ to: 'ada@example.com', name: 'Ada' }]);\n ({ svc, log } = setup([{ id: 'x', email: 'lin@example.com', name: 'Lin' }]));\n await assert.rejects(svc.signUp({ email: 'LIN@example.com', name: 'Lin 2' }), e => e.code === 'EMAIL_TAKEN');\n await assert.rejects(svc.signUp({ email: 'nope', name: 'N' }), e => e.code === 'INVALID_EMAIL');\n assert.equal(log.saved.length, 0);\n assert.equal(log.mails.length, 0);\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "cache-aside-user",
"category": "caching",
"manualIds": [
"skill:redis-patterns"
],
"query": "src/userCache.js exports createUserCache({ redis, db, ttlSeconds = 300 }). redis is a node-redis v4 style client (async get(key), set(key, value, { EX }), del(key)) and db has async findUser(id) and updateUser(id, patch). Profile reads are hammering the database. Implement cache-aside: getUser(id) uses key \"user:\" + id, returns the parsed cached JSON on a hit without touching db, and on a miss loads from db and caches JSON with an expiry of ttlSeconds (do not cache a missing user; return null). updateUser(id, patch) writes to db first, then deletes the cache key, and resolves to the updated user. Redis is an optimization, not a dependency: if any redis call rejects, getUser and updateUser must still return the correct db result. Do not add dependencies.",
"files": {
"src/userCache.js": "'use strict';\n\nfunction createUserCache({ redis, db, ttlSeconds = 300 }) {\n return {\n async getUser(id) {\n return db.findUser(id);\n },\n async updateUser(id, patch) {\n return db.updateUser(id, patch);\n },\n };\n}\n\nmodule.exports = { createUserCache };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { createUserCache } = require(path.join(process.cwd(), 'src/userCache.js'));\nfunction fakes(broken = false) {\n const store = new Map();\n const log = [];\n const redis = {\n async get(k) { log.push(['get', k]); if (broken) throw new Error('ECONNREFUSED'); return store.has(k) ? store.get(k) : null; },\n async set(k, v, opts) { log.push(['set', k, opts]); if (broken) throw new Error('ECONNREFUSED'); store.set(k, v); return 'OK'; },\n async del(k) { log.push(['del', k]); if (broken) throw new Error('ECONNREFUSED'); return store.delete(k) ? 1 : 0; },\n };\n const rows = { 1: { id: 1, name: 'Ada' } };\n const db = { reads: 0, async findUser(id) { db.reads++; return rows[id] ? { ...rows[id] } : null; },\n async updateUser(id, patch) { log.push(['db-update', id]); rows[id] = { ...rows[id], ...patch }; return { ...rows[id] }; } };\n return { store, log, redis, db };\n}\n(async () => {\n let f = fakes();\n const cache = createUserCache({ redis: f.redis, db: f.db, ttlSeconds: 60 });\n assert.deepEqual(await cache.getUser(1), { id: 1, name: 'Ada' });\n assert.equal(f.db.reads, 1);\n const set = f.log.find(e => e[0] === 'set');\n assert.equal(set[1], 'user:1');\n assert.deepEqual(set[2], { EX: 60 });\n assert.deepEqual(JSON.parse(f.store.get('user:1')), { id: 1, name: 'Ada' });\n assert.deepEqual(await cache.getUser(1), { id: 1, name: 'Ada' });\n assert.equal(f.db.reads, 1);\n assert.equal(await cache.getUser(2), null);\n assert.ok(!f.store.has('user:2'));\n const updated = await cache.updateUser(1, { name: 'Ada L' });\n assert.deepEqual(updated, { id: 1, name: 'Ada L' });\n const iUpd = f.log.findIndex(e => e[0] === 'db-update');\n const iDel = f.log.findIndex(e => e[0] === 'del' && e[1] === 'user:1');\n assert.ok(iUpd >= 0 && iDel > iUpd, 'must invalidate after the db write');\n assert.deepEqual(await cache.getUser(1), { id: 1, name: 'Ada L' });\n f = fakes();\n const dflt = createUserCache({ redis: f.redis, db: f.db });\n await dflt.getUser(1);\n assert.deepEqual(f.log.find(e => e[0] === 'set')[2], { EX: 300 });\n f = fakes(true);\n const broken = createUserCache({ redis: f.redis, db: f.db });\n assert.deepEqual(await broken.getUser(1), { id: 1, name: 'Ada' });\n assert.deepEqual(await broken.updateUser(1, { name: 'X' }), { id: 1, name: 'X' });\n})().catch(err => { console.error(err); process.exitCode = 1; });\n"
},
{
"id": "token-units-bigint",
"category": "data",
"manualIds": [
"skill:evm-token-decimals"
],
"query": "src/units.js converts ERC-20 token amounts for our portfolio dashboard, but it uses floating point, so 18-decimal balances lose precision. Rewrite it with exact BigInt math. formatUnits(raw, decimals): raw is a bigint or an integer string in base units; return a decimal string with no trailing fractional zeros and no trailing \".\", keeping a leading \"-\" for negatives. parseUnits(value, decimals): value is a decimal string such as \"1.5\" or \"-0.25\"; return a bigint in base units; throw a RangeError if it has more fractional digits than decimals, and throw an Error for anything that is not a plain decimal number (e.g. \"\", \"abc\", \"1e5\", \"1.2.3\"). Also export normalizeAmount(raw, fromDecimals, toDecimals) returning a bigint rescaled between token precisions, truncating toward zero when precision is reduced. Do not add dependencies.",
"files": {
"src/units.js": "'use strict';\n\nfunction formatUnits(raw, decimals) {\n return String(Number(raw) / 10 ** decimals);\n}\n\nfunction parseUnits(value, decimals) {\n return BigInt(Math.round(parseFloat(value) * 10 ** decimals));\n}\n\nmodule.exports = { formatUnits, parseUnits };\n",
"README.md": "# portfolio-units\n\nToken decimals differ per token and per chain: USDC uses 6 on Ethereum mainnet,\nWETH uses 18, and some bridged tokens differ from their native versions.\nAlways pass the decimals value read from the token contract.\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { formatUnits, parseUnits, normalizeAmount } = require(path.join(process.cwd(), 'src/units.js'));\nassert.equal(formatUnits(123456789012345678901234567n, 18), '123456789.012345678901234567');\nassert.equal(formatUnits('1000000', 6), '1');\nassert.equal(formatUnits(1500000n, 6), '1.5');\nassert.equal(formatUnits(0n, 18), '0');\nassert.equal(formatUnits(-1n, 18), '-0.000000000000000001');\nassert.equal(formatUnits(-1500000n, 6), '-1.5');\nassert.equal(formatUnits(5n, 0), '5');\nassert.equal(parseUnits('1.5', 6), 1500000n);\nassert.equal(parseUnits('0.000000000000000001', 18), 1n);\nassert.equal(parseUnits('123456789.012345678901234567', 18), 123456789012345678901234567n);\nassert.equal(parseUnits('-0.25', 6), -250000n);\nassert.equal(parseUnits('100', 0), 100n);\nassert.throws(() => parseUnits('1.1234567', 6), RangeError);\nfor (const bad of ['', 'abc', '1e5', '1.2.3', '0x10', ' 1']) assert.throws(() => parseUnits(bad, 6), Error, bad);\nassert.equal(normalizeAmount(1234567n, 6, 18), 1234567000000000000n);\nassert.equal(normalizeAmount(1234567890123456789n, 18, 6), 1234567n);\nassert.equal(normalizeAmount(-1234567890123456789n, 18, 6), -1234567n);\nassert.equal(normalizeAmount(42n, 8, 8), 42n);\nassert.equal(typeof normalizeAmount(1n, 6, 6), 'bigint');\n"
},
{
"id": "inclusive-range",
"category": "no-workflow",
"manualIds": [],
"query": "range(start, end) in src/range.js is documented as inclusive of end, but it stops one short. Fix it so range(1, 5) returns [1, 2, 3, 4, 5]; when start > end it must return an empty array. Do not add dependencies.",
"files": {
"src/range.js": "'use strict';\n\n/** Returns the integers from start to end, inclusive. */\nfunction range(start, end) {\n const out = [];\n for (let i = start; i < end; i++) out.push(i);\n return out;\n}\n\nmodule.exports = { range };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { range } = require(path.join(process.cwd(), 'src/range.js'));\nassert.deepEqual(range(1, 5), [1, 2, 3, 4, 5]);\nassert.deepEqual(range(3, 3), [3]);\nassert.deepEqual(range(-2, 0), [-2, -1, 0]);\nassert.deepEqual(range(5, 1), []);\n"
},
{
"id": "export-name-typo",
"category": "no-workflow",
"manualIds": [],
"query": "src/report.js crashes with \"formatDate is not a function\" because src/dates.js exports its formatter under a misspelled name. Export it as formatDate, and keep the misspelled export as an alias of the same function so older callers keep working. Do not add dependencies.",
"files": {
"src/dates.js": "'use strict';\n\nfunction formatDate(date) {\n const pad = n => String(n).padStart(2, '0');\n return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate());\n}\n\nmodule.exports = { fromatDate: formatDate };\n",
"src/report.js": "'use strict';\nconst { formatDate } = require('./dates');\n\nfunction reportHeader(title, date) {\n return title + ' (' + formatDate(date) + ')';\n}\n\nmodule.exports = { reportHeader };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst dates = require(path.join(process.cwd(), 'src/dates.js'));\nconst { reportHeader } = require(path.join(process.cwd(), 'src/report.js'));\nconst d = new Date(Date.UTC(2024, 0, 5, 12));\nassert.equal(dates.formatDate(d), '2024-01-05');\nassert.equal(dates.fromatDate, dates.formatDate);\nassert.equal(reportHeader('Weekly', d), 'Weekly (2024-01-05)');\n"
},
{
"id": "default-greeting",
"category": "no-workflow",
"manualIds": [],
"noWorkflow": true,
"query": "Small fix, no workflow needed. greet(name) in src/greet.js returns \"Hello, undefined!\" when called without a name. Make it trim the name and fall back to \"world\" when the name is missing, null, empty or only whitespace, so greet() returns \"Hello, world!\" and greet(\" Ada \") returns \"Hello, Ada!\". Do not add dependencies.",
"files": {
"src/greet.js": "'use strict';\n\nfunction greet(name) {\n return 'Hello, ' + name + '!';\n}\n\nmodule.exports = { greet };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { greet } = require(path.join(process.cwd(), 'src/greet.js'));\nassert.equal(greet(), 'Hello, world!');\nassert.equal(greet(null), 'Hello, world!');\nassert.equal(greet(''), 'Hello, world!');\nassert.equal(greet(' '), 'Hello, world!');\nassert.equal(greet(' Ada '), 'Hello, Ada!');\nassert.equal(greet('Lin'), 'Hello, Lin!');\n"
},
{
"id": "sum-form-values",
"category": "no-workflow",
"manualIds": [],
"query": "total(values) in src/total.js sums amounts typed into a form, but the inputs arrive as strings so it returns \"0123.5\" for [\"1\", \"2\", \"3.5\"]. Make it return the numeric sum (6.5 in that example). Empty strings count as 0, plain numbers must still work, and an empty array returns 0. Do not add dependencies.",
"files": {
"src/total.js": "'use strict';\n\nfunction total(values) {\n return values.reduce((sum, v) => sum + v, 0);\n}\n\nmodule.exports = { total };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { total } = require(path.join(process.cwd(), 'src/total.js'));\nassert.equal(total(['1', '2', '3.5']), 6.5);\nassert.equal(total([]), 0);\nassert.equal(total(['', '4']), 4);\nassert.equal(total([2, '3']), 5);\n"
},
{
"id": "changelog-capitalize",
"category": "no-workflow",
"manualIds": [],
"query": "The security team's release-notes script imports src/changelog.js, and it crashes when a changelog entry has an empty title because capitalize(\"\") throws. Fix capitalize so an empty string returns \"\", while other strings still get only their first character uppercased with the rest unchanged. formatEntry must keep its current output format. Do not add dependencies.",
"files": {
"src/changelog.js": "'use strict';\n\nfunction capitalize(text) {\n return text[0].toUpperCase() + text.slice(1);\n}\n\nfunction formatEntry(entry) {\n return '- ' + capitalize(entry.title) + ' (' + entry.type + ')';\n}\n\nmodule.exports = { capitalize, formatEntry };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { capitalize, formatEntry } = require(path.join(process.cwd(), 'src/changelog.js'));\nassert.equal(capitalize(''), '');\nassert.equal(capitalize('x'), 'X');\nassert.equal(capitalize('hello World'), 'Hello World');\nassert.equal(formatEntry({ title: 'fix xss in footer', type: 'security' }), '- Fix xss in footer (security)');\nassert.equal(formatEntry({ title: '', type: 'chore' }), '- (chore)');\n"
},
{
"id": "test-summary-plural",
"category": "no-workflow",
"manualIds": [],
"query": "Our test runner prints \"1 tests passed, 1 tests failed\". In src/summary.js, fix formatSummary(passed, failed) to use \"test\" when a count is exactly 1 and \"tests\" otherwise, e.g. \"1 test passed, 0 tests failed\". Keep the rest of the wording identical. Do not add dependencies.",
"files": {
"src/summary.js": "'use strict';\n\nfunction formatSummary(passed, failed) {\n return passed + ' tests passed, ' + failed + ' tests failed';\n}\n\nmodule.exports = { formatSummary };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { formatSummary } = require(path.join(process.cwd(), 'src/summary.js'));\nassert.equal(formatSummary(1, 0), '1 test passed, 0 tests failed');\nassert.equal(formatSummary(2, 1), '2 tests passed, 1 test failed');\nassert.equal(formatSummary(0, 0), '0 tests passed, 0 tests failed');\nassert.equal(formatSummary(12, 3), '12 tests passed, 3 tests failed');\n"
},
{
"id": "database-label-typo",
"category": "no-workflow",
"manualIds": [],
"noWorkflow": true,
"query": "No workflow needed. In src/options.js the settings dropdown shows \"Databse\" for the database option; correct the label to \"Database\". Also make labelFor(value) return the value itself when no option matches, instead of throwing. Do not change the option values or their order. Do not add dependencies.",
"files": {
"src/options.js": "'use strict';\n\nconst OPTIONS = [\n { value: 'database', label: 'Databse' },\n { value: 'api', label: 'API' },\n { value: 'cache', label: 'Cache' },\n];\n\nfunction labelFor(value) {\n return OPTIONS.find(o => o.value === value).label;\n}\n\nmodule.exports = { OPTIONS, labelFor };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { OPTIONS, labelFor } = require(path.join(process.cwd(), 'src/options.js'));\nassert.deepEqual(OPTIONS, [{ value: 'database', label: 'Database' }, { value: 'api', label: 'API' }, { value: 'cache', label: 'Cache' }]);\nassert.equal(labelFor('database'), 'Database');\nassert.equal(labelFor('api'), 'API');\nassert.equal(labelFor('queue'), 'queue');\n"
},
{
"id": "port-from-env",
"category": "no-workflow",
"manualIds": [],
"noWorkflow": true,
"query": "Do not select a workflow for this one-line style fix. getPort(env) in src/server-config.js returns env.PORT as a string or 3000. Make it return a number: the integer value of env.PORT when it consists only of decimal digits and is between 1 and 65535, otherwise 3000. Do not add dependencies.",
"files": {
"src/server-config.js": "'use strict';\n\nfunction getPort(env = process.env) {\n return env.PORT || 3000;\n}\n\nmodule.exports = { getPort };\n"
},
"check": "'use strict';\nconst assert = require('node:assert/strict');\nconst path = require('node:path');\nconst { getPort } = require(path.join(process.cwd(), 'src/server-config.js'));\nassert.equal(getPort({ PORT: '8080' }), 8080);\nassert.equal(getPort({}), 3000);\nassert.equal(getPort({ PORT: '' }), 3000);\nassert.equal(getPort({ PORT: 'abc' }), 3000);\nassert.equal(getPort({ PORT: '70000' }), 3000);\nassert.equal(getPort({ PORT: '0' }), 3000);\nassert.equal(getPort({ PORT: '80.5' }), 3000);\nassert.equal(getPort({ PORT: '65535' }), 65535);\n"
}
]
}