create-agent-rig 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +316 -11
- package/README.md +58 -19
- package/package.json +2 -1
- package/packages/cli/dist/commands/create.js +8 -3
- package/packages/cli/dist/commands/init.js +85 -34
- package/packages/cli/dist/commands/upgrade.js +112 -30
- package/packages/cli/dist/index.js +81 -19
- package/packages/cli/dist/lib/copy-tree.js +35 -6
- package/packages/cli/dist/lib/init-settings.js +12 -0
- package/packages/cli/dist/lib/install-set.js +6 -8
- package/packages/cli/dist/lib/manifest.js +31 -9
- package/packages/cli/dist/lib/safe-path.js +30 -0
- package/scripts/prepare.mjs +1 -1
- package/templates/agent-os/init/AGENTS.md +199 -0
- package/templates/agent-os/init/CLAUDE.md +69 -9
- package/templates/agent-os/stack/aws-cdk/.agents/skills/post-deploy-verify/SKILL.md +105 -0
- package/templates/agent-os/stack/aws-cdk/.agents/skills/ro-debug/SKILL.md +117 -0
- package/templates/agent-os/stack/aws-cdk/.claude/agents/cdk-diff-reviewer.md +41 -3
- package/templates/agent-os/stack/aws-cdk/.claude/rules/aws-cdk.md +1 -1
- package/templates/agent-os/stack/aws-cdk/.claude/skills/post-deploy-verify/SKILL.md +41 -0
- package/templates/agent-os/stack/aws-cdk/.codex/agents/cdk-diff-reviewer.toml +4 -0
- package/templates/agent-os/stack/node-ts/.claude/rules/node-ts.md +29 -0
- package/templates/agent-os/universal/.agents/skills/check-premises/SKILL.md +236 -0
- package/templates/agent-os/universal/.agents/skills/loop/SKILL.md +958 -0
- package/templates/agent-os/universal/.agents/skills/new-invariant/SKILL.md +102 -0
- package/templates/agent-os/universal/.agents/skills/new-invariant/guard-invariant.example.mjs +78 -0
- package/templates/agent-os/universal/.agents/skills/new-invariant/guard-invariant.example.test.mjs +89 -0
- package/templates/agent-os/universal/.agents/skills/pr-ship/SKILL.md +396 -0
- package/templates/agent-os/universal/.agents/skills/worktree-task/SKILL.md +73 -0
- package/templates/agent-os/universal/.claude/agents/code-reviewer.md +40 -1
- package/templates/agent-os/universal/.claude/agents/prose-reviewer.md +71 -1
- package/templates/agent-os/universal/.claude/agents/security-scanner.md +40 -0
- package/templates/agent-os/universal/.claude/hooks/gate-stop-dod.mjs +301 -26
- package/templates/agent-os/universal/.claude/hooks/guard-bash.mjs +43 -5
- package/templates/agent-os/universal/.claude/hooks/guard-core-purity.mjs +25 -11
- package/templates/agent-os/universal/.claude/hooks/guard-rulebook.mjs +127 -0
- package/templates/agent-os/universal/.claude/hooks/guard-secret-file.mjs +180 -0
- package/templates/agent-os/universal/.claude/hooks/guard-web-boundary.mjs +32 -13
- package/templates/agent-os/universal/.claude/hooks/inject-rules.mjs +175 -7
- package/templates/agent-os/universal/.claude/hooks/lib/edit-input.mjs +503 -0
- package/templates/agent-os/universal/.claude/rules/autonomy.md +69 -1
- package/templates/agent-os/universal/.claude/rules/invariants.md +104 -19
- package/templates/agent-os/universal/.claude/rules/workflow.md +55 -5
- package/templates/agent-os/universal/.claude/scripts/decision-router.mjs +1260 -0
- package/templates/agent-os/universal/.claude/scripts/detect-missed-gate.mjs +65 -2
- package/templates/agent-os/universal/.claude/scripts/doctor.mjs +351 -0
- package/templates/agent-os/universal/.claude/scripts/git-env.mjs +49 -0
- package/templates/agent-os/universal/.claude/scripts/lib/gate-coverage.mjs +306 -0
- package/templates/agent-os/universal/.claude/scripts/lib/revalidation-points.mjs +28 -0
- package/templates/agent-os/universal/.claude/scripts/lib/secrets.mjs +490 -0
- package/templates/agent-os/universal/.claude/scripts/lib/verdict.mjs +462 -0
- package/templates/agent-os/universal/.claude/scripts/preflight.mjs +33 -17
- package/templates/agent-os/universal/.claude/scripts/queue/as-of.mjs +51 -0
- package/templates/agent-os/universal/.claude/scripts/queue/checkout.mjs +149 -0
- package/templates/agent-os/universal/.claude/scripts/queue/core.mjs +809 -28
- package/templates/agent-os/universal/.claude/scripts/queue/gate-rounds.mjs +160 -0
- package/templates/agent-os/universal/.claude/scripts/queue/github-issues.mjs +95 -16
- package/templates/agent-os/universal/.claude/scripts/queue/index.mjs +543 -15
- package/templates/agent-os/universal/.claude/scripts/queue/jira.mjs +457 -47
- package/templates/agent-os/universal/.claude/scripts/queue/plan-md.mjs +289 -25
- package/templates/agent-os/universal/.claude/scripts/queue/state.mjs +197 -0
- package/templates/agent-os/universal/.claude/scripts/revalidate.mjs +316 -0
- package/templates/agent-os/universal/.claude/scripts/revalidation-report.mjs +180 -0
- package/templates/agent-os/universal/.claude/scripts/run-journal.mjs +435 -0
- package/templates/agent-os/universal/.claude/scripts/run-state.mjs +539 -0
- package/templates/agent-os/universal/.claude/scripts/stop-flag.mjs +15 -8
- package/templates/agent-os/universal/.claude/scripts/unattended-flag.mjs +239 -0
- package/templates/agent-os/universal/.claude/scripts/verdict.mjs +198 -0
- package/templates/agent-os/universal/.claude/settings.json +11 -2
- package/templates/agent-os/universal/.claude/skills/check-premises/SKILL.md +118 -7
- package/templates/agent-os/universal/.claude/skills/loop/SKILL.md +667 -38
- package/templates/agent-os/universal/.claude/skills/pr-ship/SKILL.md +359 -26
- package/templates/agent-os/universal/.codex/agents/code-reviewer.toml +4 -0
- package/templates/agent-os/universal/.codex/agents/prose-reviewer.toml +4 -0
- package/templates/agent-os/universal/.codex/agents/security-scanner.toml +4 -0
- package/templates/agent-os/universal/.codex/agents/test-writer.toml +4 -0
- package/templates/agent-os/universal/.codex/hooks.json +70 -0
- package/templates/agent-os/universal/AGENTS.md +166 -0
- package/templates/agent-os/universal/CLAUDE.md +49 -14
- package/templates/agent-os/universal/PLAN.md +7 -40
- package/templates/agent-os/universal/docs/decisions/closing-a-task.md +98 -0
- package/templates/agent-os/universal/docs/decisions/codex-adapter.md +108 -0
- package/templates/agent-os/universal/docs/decisions/fail-open-guards.md +43 -0
- package/templates/agent-os/universal/docs/decisions/gate-coverage.md +83 -0
- package/templates/agent-os/universal/docs/decisions/review-lanes.md +72 -0
- package/templates/agent-os/universal/docs/decisions/run-directory.md +44 -0
- package/templates/agent-os/universal/docs/decisions/spacing-rations-mechanisms.md +125 -0
- package/templates/agent-os/universal/docs/decisions/stop-conditions-in-a-file.md +46 -0
- package/templates/agent-os/universal/docs/decisions/two-empty-endings.md +74 -0
- package/templates/agent-os/universal/journal/README.md +101 -0
- package/templates/agent-os/universal/layers.json +45 -2
- package/templates/hash-history.json +310 -49
- package/templates/release-ledger.json +9 -0
- package/templates/skeleton/aws-serverless/.github/workflows/deploy.yml +34 -1
- package/templates/skeleton/aws-serverless/README.md +91 -9
- package/templates/skeleton/aws-serverless/apps/web/src/lib/api.ts +9 -2
- package/templates/skeleton/aws-serverless/gitignore +37 -0
- package/templates/skeleton/aws-serverless/infra/bin/app.ts +73 -13
- package/templates/skeleton/aws-serverless/infra/lib/app-stack.ts +136 -4
- package/templates/skeleton/aws-serverless/infra/lib/web-stack.ts +14 -1
- package/templates/skeleton/aws-serverless/infra/test/allowed-origins.test.ts +301 -0
- package/templates/skeleton/aws-serverless/infra/test/app-composition.test.ts +137 -0
- package/templates/skeleton/aws-serverless/infra/test/app-stack.test.ts +36 -20
- package/templates/skeleton/aws-serverless/infra/test/web-stack.test.ts +15 -12
- package/templates/skeleton/aws-serverless/services/api/src/handlers/create-note.ts +33 -6
- package/templates/skeleton/aws-serverless/services/api/src/handlers/list-notes.ts +18 -5
- package/templates/skeleton/aws-serverless/services/api/src/usecases/create-note.ts +11 -0
- package/templates/skeleton/aws-serverless/services/api/test/create-note.handler.test.ts +120 -1
- package/templates/skeleton/aws-serverless/services/api/test/list-notes.test.ts +72 -1
- package/templates/skeleton/node-service/README.md +11 -1
- package/templates/skeleton/node-service/gitignore +34 -0
- package/templates/skeleton/node-service/packages/db/src/note-store.ts +47 -10
- package/templates/skeleton/node-service/packages/db/test/note-store.test.ts +20 -0
- package/templates/skeleton/node-service/services/api/src/main.ts +2 -9
- package/templates/skeleton/node-service/services/api/src/server.ts +93 -10
- package/templates/skeleton/node-service/services/api/src/static-dir.ts +20 -0
- package/templates/skeleton/node-service/services/api/test/server.test.ts +98 -13
- package/templates/skeleton/node-service/services/api/test/static-dir.test.ts +28 -0
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
// The handler translates transport ⇄ domain and nothing else: decode the
|
|
2
2
|
// payload, call the usecase, map the result (or the typed error) to HTTP.
|
|
3
|
-
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';
|
|
3
|
+
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2, Context } from 'aws-lambda';
|
|
4
4
|
import { InvalidNoteError } from '@app/core';
|
|
5
5
|
import { AppError } from '@app/shared';
|
|
6
6
|
import { createNoteUsecase, type CreateNoteDeps } from '../usecases/create-note.js';
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Lambda passes the context as the second argument; the handler takes the one
|
|
10
|
+
* field it needs, so a log line can be tied back to the invocation that wrote
|
|
11
|
+
* it. Optional because the context is Lambda's to supply, not the caller's.
|
|
12
|
+
*/
|
|
13
|
+
type Handler = (
|
|
14
|
+
event: APIGatewayProxyEventV2,
|
|
15
|
+
context?: Pick<Context, 'awsRequestId'>,
|
|
16
|
+
) => Promise<APIGatewayProxyResultV2>;
|
|
9
17
|
|
|
10
18
|
const json = (statusCode: number, body: unknown): APIGatewayProxyResultV2 => ({
|
|
11
19
|
statusCode,
|
|
@@ -14,7 +22,7 @@ const json = (statusCode: number, body: unknown): APIGatewayProxyResultV2 => ({
|
|
|
14
22
|
});
|
|
15
23
|
|
|
16
24
|
export function makeCreateNoteHandler(deps: CreateNoteDeps): Handler {
|
|
17
|
-
return async (event) => {
|
|
25
|
+
return async (event, context) => {
|
|
18
26
|
let payload: unknown;
|
|
19
27
|
try {
|
|
20
28
|
const raw = event.isBase64Encoded
|
|
@@ -32,11 +40,30 @@ export function makeCreateNoteHandler(deps: CreateNoteDeps): Handler {
|
|
|
32
40
|
if (error instanceof InvalidNoteError) {
|
|
33
41
|
return json(400, { error: 'invalid note', issues: error.issues });
|
|
34
42
|
}
|
|
35
|
-
|
|
43
|
+
// A 4xx message was written for the caller to read. A 5xx one was not:
|
|
44
|
+
// `AppError` defaults to 500/INTERNAL, so a table name, a host or an SDK
|
|
45
|
+
// message arrives here wearing the same type as "title is required".
|
|
46
|
+
// Typed does not mean safe to show — the status decides.
|
|
47
|
+
//
|
|
48
|
+
// The status itself is kept: 503 tells a caller to retry and 500 does
|
|
49
|
+
// not, and that distinction is transport, not disclosure. Only the
|
|
50
|
+
// message is withheld.
|
|
51
|
+
if (error instanceof AppError && error.statusCode < 500) {
|
|
36
52
|
return json(error.statusCode, { error: error.message, code: error.code });
|
|
37
53
|
}
|
|
38
|
-
|
|
39
|
-
|
|
54
|
+
// Everything past here is withheld, so it has to be kept somewhere: the
|
|
55
|
+
// message AND its frames, because a message with no stack is not
|
|
56
|
+
// something anyone can debug from a log aggregator, and the request id,
|
|
57
|
+
// because a line nobody can tie to an invocation is barely a line.
|
|
58
|
+
deps.log.error('unhandled error in create-note', {
|
|
59
|
+
error: error instanceof Error ? error.message : String(error),
|
|
60
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
61
|
+
// The one field of a withheld AppError worth keeping: it says WHICH
|
|
62
|
+
// internal failure this was, and it never reaches the caller.
|
|
63
|
+
code: error instanceof AppError ? error.code : undefined,
|
|
64
|
+
awsRequestId: context?.awsRequestId,
|
|
65
|
+
});
|
|
66
|
+
return json(error instanceof AppError ? error.statusCode : 500, { error: 'internal error' });
|
|
40
67
|
}
|
|
41
68
|
};
|
|
42
69
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { APIGatewayProxyResultV2 } from 'aws-lambda';
|
|
1
|
+
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2, Context } from 'aws-lambda';
|
|
2
2
|
import { AppError } from '@app/shared';
|
|
3
3
|
import type { Logger } from '@app/shared';
|
|
4
4
|
import { listNotesUsecase, type ListNotesDeps } from '../usecases/list-notes.js';
|
|
@@ -10,15 +10,28 @@ const json = (statusCode: number, body: unknown): APIGatewayProxyResultV2 => ({
|
|
|
10
10
|
});
|
|
11
11
|
|
|
12
12
|
export function makeListNotesHandler(deps: ListNotesDeps & { log: Logger }) {
|
|
13
|
-
return async (
|
|
13
|
+
return async (
|
|
14
|
+
_event?: APIGatewayProxyEventV2,
|
|
15
|
+
context?: Pick<Context, 'awsRequestId'>,
|
|
16
|
+
): Promise<APIGatewayProxyResultV2> => {
|
|
14
17
|
try {
|
|
15
18
|
return json(200, { notes: await listNotesUsecase(deps) });
|
|
16
19
|
} catch (error) {
|
|
17
|
-
|
|
20
|
+
// Same contract as create-note: a 4xx message was written for the caller,
|
|
21
|
+
// a 5xx one was not. The status survives — 503 tells a caller to retry
|
|
22
|
+
// and 500 does not — and only the message is withheld.
|
|
23
|
+
if (error instanceof AppError && error.statusCode < 500) {
|
|
18
24
|
return json(error.statusCode, { error: error.message, code: error.code });
|
|
19
25
|
}
|
|
20
|
-
deps.log.error('unhandled error in list-notes', {
|
|
21
|
-
|
|
26
|
+
deps.log.error('unhandled error in list-notes', {
|
|
27
|
+
error: error instanceof Error ? error.message : String(error),
|
|
28
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
29
|
+
// The one field of a withheld AppError worth keeping: it says WHICH
|
|
30
|
+
// internal failure this was, and it never reaches the caller.
|
|
31
|
+
code: error instanceof AppError ? error.code : undefined,
|
|
32
|
+
awsRequestId: context?.awsRequestId,
|
|
33
|
+
});
|
|
34
|
+
return json(error instanceof AppError ? error.statusCode : 500, { error: 'internal error' });
|
|
22
35
|
}
|
|
23
36
|
};
|
|
24
37
|
}
|
|
@@ -21,6 +21,17 @@ export interface CreateNoteDeps {
|
|
|
21
21
|
log: Logger;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* ⚠ These are **two writes and they are not atomic** — a dual write. The put
|
|
26
|
+
* can succeed and the publish then fail, which leaves a stored note whose event
|
|
27
|
+
* never happened: the worker does not run, nothing downstream hears about it,
|
|
28
|
+
* and nothing here compensates. The caller sees a 500 for a note that exists.
|
|
29
|
+
*
|
|
30
|
+
* That is a deliberate simplification for a skeleton, not a pattern to copy at
|
|
31
|
+
* scale. The two ways out, when it starts to matter: an **outbox** (write the
|
|
32
|
+
* event into the same transaction as the note, relay it after), or DynamoDB
|
|
33
|
+
* Streams feeding the worker, which removes the second write entirely.
|
|
34
|
+
*/
|
|
24
35
|
export async function createNoteUsecase(input: unknown, deps: CreateNoteDeps): Promise<Note> {
|
|
25
36
|
const note = createNote(input, { id: deps.newId(), createdAt: deps.now() });
|
|
26
37
|
await deps.notes.put(note);
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
APIGatewayProxyEventV2,
|
|
3
|
+
APIGatewayProxyStructuredResultV2,
|
|
4
|
+
Context,
|
|
5
|
+
} from 'aws-lambda';
|
|
2
6
|
import { AppError, createLogger } from '@app/shared';
|
|
3
7
|
import { describe, expect, it } from 'vitest';
|
|
4
8
|
import { makeCreateNoteHandler } from '../src/handlers/create-note.js';
|
|
@@ -7,6 +11,9 @@ import type { CreateNoteDeps } from '../src/usecases/create-note.js';
|
|
|
7
11
|
const event = (body: string): APIGatewayProxyEventV2 =>
|
|
8
12
|
({ body, isBase64Encoded: false }) as APIGatewayProxyEventV2;
|
|
9
13
|
|
|
14
|
+
/** Lambda always passes a context; the handler only ever needs the request id. */
|
|
15
|
+
const lambdaContext = (awsRequestId: string): Context => ({ awsRequestId }) as Context;
|
|
16
|
+
|
|
10
17
|
function stubDeps(overrides: Partial<CreateNoteDeps> = {}) {
|
|
11
18
|
const deps: CreateNoteDeps = {
|
|
12
19
|
notes: { put: async () => {} },
|
|
@@ -89,4 +96,116 @@ describe('POST /notes handler', () => {
|
|
|
89
96
|
expect(result.body).not.toContain('secret detail');
|
|
90
97
|
expect(logs.join('\n')).toContain('secret detail');
|
|
91
98
|
});
|
|
99
|
+
|
|
100
|
+
// AppError defaults to statusCode 500 / code INTERNAL, so "typed" does not
|
|
101
|
+
// mean "safe to show": a table name, a host, an SDK message all arrive this
|
|
102
|
+
// way. Only a 4xx AppError is a message the caller was meant to read.
|
|
103
|
+
it('hides a typed error that carries the default status behind the same constant 500', async () => {
|
|
104
|
+
const handler = makeCreateNoteHandler(
|
|
105
|
+
stubDeps({
|
|
106
|
+
notes: {
|
|
107
|
+
put: () => Promise.reject(new AppError('table NotesTable-prod is not authorised')),
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
);
|
|
111
|
+
const result = asResult(await handler(event(JSON.stringify({ title: 'T' }))));
|
|
112
|
+
expect(result.statusCode).toBe(500);
|
|
113
|
+
expect(result.body).not.toContain('NotesTable-prod');
|
|
114
|
+
expect(JSON.parse(result.body!)).toEqual({ error: 'internal error' });
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
// Withholding the message is not the same decision as flattening the status.
|
|
118
|
+
// 503 tells a caller to retry and 500 tells it not to bother, and that
|
|
119
|
+
// distinction is transport, not disclosure — the sibling handler pins it
|
|
120
|
+
// (`list-notes.test.ts`), and this one did not, so collapsing the status here
|
|
121
|
+
// passed the whole suite.
|
|
122
|
+
it('keeps a 5xx status the caller can act on, while still hiding the message', async () => {
|
|
123
|
+
const handler = makeCreateNoteHandler(
|
|
124
|
+
stubDeps({
|
|
125
|
+
notes: {
|
|
126
|
+
put: () =>
|
|
127
|
+
Promise.reject(
|
|
128
|
+
new AppError('table NotesTable-prod is throttling', {
|
|
129
|
+
statusCode: 503,
|
|
130
|
+
code: 'X',
|
|
131
|
+
}),
|
|
132
|
+
),
|
|
133
|
+
},
|
|
134
|
+
}),
|
|
135
|
+
);
|
|
136
|
+
const result = asResult(await handler(event(JSON.stringify({ title: 'T' }))));
|
|
137
|
+
expect(result.statusCode).toBe(503);
|
|
138
|
+
expect(result.body).not.toContain('NotesTable-prod');
|
|
139
|
+
expect(JSON.parse(result.body!)).toEqual({ error: 'internal error' });
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it('logs the typed internal error it hid, so the detail is kept and not lost', async () => {
|
|
143
|
+
const logs: string[] = [];
|
|
144
|
+
const handler = makeCreateNoteHandler(
|
|
145
|
+
stubDeps({
|
|
146
|
+
notes: {
|
|
147
|
+
put: () => Promise.reject(new AppError('table NotesTable-prod is not authorised')),
|
|
148
|
+
},
|
|
149
|
+
log: createLogger({}, (line) => logs.push(line)),
|
|
150
|
+
}),
|
|
151
|
+
);
|
|
152
|
+
await handler(event(JSON.stringify({ title: 'T' })));
|
|
153
|
+
expect(logs.join('\n')).toContain('NotesTable-prod');
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('logs the failure with its stack, not only its message', async () => {
|
|
157
|
+
const logs: string[] = [];
|
|
158
|
+
const boom = new Error('secret detail');
|
|
159
|
+
const handler = makeCreateNoteHandler(
|
|
160
|
+
stubDeps({
|
|
161
|
+
notes: { put: () => Promise.reject(boom) },
|
|
162
|
+
log: createLogger({}, (line) => logs.push(line)),
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
await handler(event(JSON.stringify({ title: 'T' })));
|
|
166
|
+
// `String(error)` is "Error: secret detail" — a message with no frames is
|
|
167
|
+
// not something anyone can debug from CloudWatch.
|
|
168
|
+
expect(JSON.parse(logs[0]!)).toMatchObject({ stack: boom.stack });
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// The response withholds everything about a 5xx AppError, so the log line is
|
|
172
|
+
// the only place left that can say WHICH internal failure it was — and `code`
|
|
173
|
+
// is the one field of that error which is safe to keep verbatim. Losing it
|
|
174
|
+
// flattens DATA_CORRUPT, INTERNAL and every future code into one shape nobody
|
|
175
|
+
// can triage. The body assertion lives here on purpose: the two halves of the
|
|
176
|
+
// contract ("kept in the log", "still absent from the response") must not
|
|
177
|
+
// drift apart.
|
|
178
|
+
it('logs the code of the internal error it withheld, and still keeps it out of the response', async () => {
|
|
179
|
+
const logs: string[] = [];
|
|
180
|
+
const handler = makeCreateNoteHandler(
|
|
181
|
+
stubDeps({
|
|
182
|
+
notes: {
|
|
183
|
+
put: () =>
|
|
184
|
+
Promise.reject(
|
|
185
|
+
new AppError('table NotesTable-prod returned a torn item', {
|
|
186
|
+
code: 'DATA_CORRUPT',
|
|
187
|
+
}),
|
|
188
|
+
),
|
|
189
|
+
},
|
|
190
|
+
log: createLogger({}, (line) => logs.push(line)),
|
|
191
|
+
}),
|
|
192
|
+
);
|
|
193
|
+
const result = asResult(await handler(event(JSON.stringify({ title: 'T' }))));
|
|
194
|
+
expect(JSON.parse(logs[0]!)).toMatchObject({ code: 'DATA_CORRUPT' });
|
|
195
|
+
expect(result.body).not.toContain('DATA_CORRUPT');
|
|
196
|
+
expect(JSON.parse(result.body!)).toEqual({ error: 'internal error' });
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('carries the Lambda request id into the line it logs', async () => {
|
|
200
|
+
const logs: string[] = [];
|
|
201
|
+
const handler = makeCreateNoteHandler(
|
|
202
|
+
stubDeps({
|
|
203
|
+
notes: { put: () => Promise.reject(new Error('secret detail')) },
|
|
204
|
+
log: createLogger({}, (line) => logs.push(line)),
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
// Without it a log line cannot be tied to the invocation that produced it.
|
|
208
|
+
await handler(event(JSON.stringify({ title: 'T' })), lambdaContext('req-42'));
|
|
209
|
+
expect(JSON.parse(logs[0]!)).toMatchObject({ awsRequestId: 'req-42' });
|
|
210
|
+
});
|
|
92
211
|
});
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
APIGatewayProxyEventV2,
|
|
3
|
+
APIGatewayProxyStructuredResultV2,
|
|
4
|
+
Context,
|
|
5
|
+
} from 'aws-lambda';
|
|
2
6
|
import { AppError, createLogger } from '@app/shared';
|
|
3
7
|
import { describe, expect, it } from 'vitest';
|
|
4
8
|
import { makeListNotesHandler } from '../src/handlers/list-notes.js';
|
|
@@ -14,6 +18,10 @@ const note = {
|
|
|
14
18
|
|
|
15
19
|
const asResult = (r: unknown) => r as APIGatewayProxyStructuredResultV2;
|
|
16
20
|
|
|
21
|
+
/** Lambda always passes the event and the context; this route needs no body. */
|
|
22
|
+
const getEvent = () => ({ isBase64Encoded: false }) as APIGatewayProxyEventV2;
|
|
23
|
+
const lambdaContext = (awsRequestId: string): Context => ({ awsRequestId }) as Context;
|
|
24
|
+
|
|
17
25
|
describe('listNotesUsecase', () => {
|
|
18
26
|
it('returns what the model lists', async () => {
|
|
19
27
|
expect(await listNotesUsecase({ notes: { list: async () => [note] } })).toEqual([note]);
|
|
@@ -49,3 +57,66 @@ describe('GET /notes handler', () => {
|
|
|
49
57
|
expect(logs.join('')).toContain('secret');
|
|
50
58
|
});
|
|
51
59
|
});
|
|
60
|
+
|
|
61
|
+
// The same leak create-note was fixed for, and this handler had it too:
|
|
62
|
+
// `AppError` defaults to 500/INTERNAL, so a table name, a host or an SDK
|
|
63
|
+
// message arrives wearing the same type as "title is required", and every one
|
|
64
|
+
// of them used to reach the caller. Typed does not mean safe to show — the
|
|
65
|
+
// status decides, and these pin that both handlers decide it the same way.
|
|
66
|
+
describe('GET /notes keeps its internals to itself', () => {
|
|
67
|
+
const failWith = (error: unknown, sink: (line: string) => void = () => {}) =>
|
|
68
|
+
makeListNotesHandler({
|
|
69
|
+
notes: { list: () => Promise.reject(error) },
|
|
70
|
+
log: createLogger({}, sink),
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('hides a typed error that carries the default status behind a constant 500', async () => {
|
|
74
|
+
const handler = failWith(new AppError('table NotesTable-prod is not authorised'));
|
|
75
|
+
const result = asResult(await handler(getEvent(), lambdaContext('req-1')));
|
|
76
|
+
expect(result.statusCode).toBe(500);
|
|
77
|
+
expect(result.body).not.toContain('NotesTable-prod');
|
|
78
|
+
expect(JSON.parse(result.body!)).toEqual({ error: 'internal error' });
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('still forwards a 4xx message, which was written for the caller to read', async () => {
|
|
82
|
+
const handler = failWith(new AppError('unknown tag filter', { statusCode: 400, code: 'BAD' }));
|
|
83
|
+
const result = asResult(await handler(getEvent(), lambdaContext('req-2')));
|
|
84
|
+
expect(result.statusCode).toBe(400);
|
|
85
|
+
expect(JSON.parse(result.body!)).toEqual({ error: 'unknown tag filter', code: 'BAD' });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('logs the internal error it hid with its stack, so the detail is kept and not lost', async () => {
|
|
89
|
+
const logs: string[] = [];
|
|
90
|
+
const boom = new AppError('table NotesTable-prod is not authorised');
|
|
91
|
+
await failWith(boom, (line) => logs.push(line))(getEvent(), lambdaContext('req-3'));
|
|
92
|
+
// `String(error)` is a message with no frames — not something anyone can
|
|
93
|
+
// debug from a log aggregator.
|
|
94
|
+
expect(JSON.parse(logs[0]!)).toMatchObject({ stack: boom.stack });
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// Same contract as create-note: the response withholds everything about a 5xx
|
|
98
|
+
// AppError, so the log line is the only place that can still say WHICH
|
|
99
|
+
// internal failure it was, and `code` is the one field safe to keep verbatim.
|
|
100
|
+
// The body assertion stays beside it so the two halves cannot drift apart.
|
|
101
|
+
it('logs the code of the internal error it withheld, and still keeps it out of the response', async () => {
|
|
102
|
+
const logs: string[] = [];
|
|
103
|
+
const handler = failWith(
|
|
104
|
+
new AppError('table NotesTable-prod returned a torn item', { code: 'DATA_CORRUPT' }),
|
|
105
|
+
(line) => logs.push(line),
|
|
106
|
+
);
|
|
107
|
+
const result = asResult(await handler(getEvent(), lambdaContext('req-4')));
|
|
108
|
+
expect(JSON.parse(logs[0]!)).toMatchObject({ code: 'DATA_CORRUPT' });
|
|
109
|
+
expect(result.body).not.toContain('DATA_CORRUPT');
|
|
110
|
+
expect(JSON.parse(result.body!)).toEqual({ error: 'internal error' });
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('carries the Lambda request id into the line it logs', async () => {
|
|
114
|
+
const logs: string[] = [];
|
|
115
|
+
const handler = failWith(new AppError('table NotesTable-prod is not authorised'), (line) =>
|
|
116
|
+
logs.push(line),
|
|
117
|
+
);
|
|
118
|
+
// Without it a log line cannot be tied to the invocation that produced it.
|
|
119
|
+
await handler(getEvent(), lambdaContext('req-42'));
|
|
120
|
+
expect(JSON.parse(logs[0]!)).toMatchObject({ awsRequestId: 'req-42' });
|
|
121
|
+
});
|
|
122
|
+
});
|
|
@@ -87,7 +87,17 @@ diagnose second.
|
|
|
87
87
|
layer is mandatory even when it looks like ceremony.
|
|
88
88
|
- `packages/core` is pure — the `guard-core-purity` hook refuses I/O, clock,
|
|
89
89
|
randomness, and environment access at the tool layer.
|
|
90
|
-
- `packages/db` is the only module that touches the stored data.
|
|
90
|
+
- `packages/db` is the only module that touches the stored data. It is a
|
|
91
|
+
**single-instance store**: writes serialise inside one `JsonFileNoteStore`
|
|
92
|
+
object, and that is the whole of it. Two stores over the same file lose
|
|
93
|
+
notes to each other whether they sit in one process or two — share the one
|
|
94
|
+
instance, and reach for a real lock before you share the file.
|
|
95
|
+
A hard kill between the temp write and the rename leaves a `*.tmp` file
|
|
96
|
+
behind; nothing sweeps them.
|
|
97
|
+
- `POST /notes` buffers at most **1 MB** of request body and answers `413` past
|
|
98
|
+
that. The cap lives in that route, not in the shell: a new route that reads a
|
|
99
|
+
body adds its own. Raise it in `services/api/src/server.ts` if your payloads
|
|
100
|
+
are bigger; do not remove it.
|
|
91
101
|
- A failing queue message is poison: it throws, the spool retries ×3, then the
|
|
92
102
|
DLQ gets it and the ALARM line fires. Never wrap the worker in a broad catch.
|
|
93
103
|
|
|
@@ -9,10 +9,44 @@ out/
|
|
|
9
9
|
next-env.d.ts
|
|
10
10
|
dist/
|
|
11
11
|
.claude/worktrees/
|
|
12
|
+
# per-checkout queue state: the tier the last close recorded. The queue CONFIG
|
|
13
|
+
# is composed and tracked; this is runtime state and must never be committed.
|
|
14
|
+
.claude/queue.state.json
|
|
15
|
+
# gate rounds, one count per branch
|
|
16
|
+
.claude/gate-rounds.json
|
|
17
|
+
# per-run machine trace (.claude/scripts/run-journal.mjs): forensics that churn
|
|
18
|
+
# on every gate and collide across concurrent sessions. Unlike a committed
|
|
19
|
+
# evidence directory, this one is per-run and stays out of the repository.
|
|
20
|
+
.claude/runs/
|
|
12
21
|
|
|
13
22
|
# secrets — never commit these
|
|
23
|
+
*.env
|
|
14
24
|
.env
|
|
15
25
|
.env.*
|
|
16
26
|
!.env.example
|
|
27
|
+
.envrc
|
|
28
|
+
.npmrc
|
|
29
|
+
.netrc
|
|
30
|
+
.pgpass
|
|
31
|
+
id_rsa
|
|
32
|
+
id_ed25519
|
|
17
33
|
*.pem
|
|
18
34
|
*.key
|
|
35
|
+
*.p12
|
|
36
|
+
*.pfx
|
|
37
|
+
*.keystore
|
|
38
|
+
*.jks
|
|
39
|
+
*.secret
|
|
40
|
+
*.secrets
|
|
41
|
+
*.token
|
|
42
|
+
*.tokens
|
|
43
|
+
*.password
|
|
44
|
+
*.passwords
|
|
45
|
+
*.credential
|
|
46
|
+
*.credentials
|
|
47
|
+
*.apikey
|
|
48
|
+
*.apikeys
|
|
49
|
+
*.passwd
|
|
50
|
+
*.creds
|
|
51
|
+
*.jwt
|
|
52
|
+
*.bearer
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// The model boundary, same contract as any other target — only the medium
|
|
2
2
|
// differs: one JSON file. This is the ONLY module that knows how notes are
|
|
3
3
|
// persisted; nothing else composes a path into the data file.
|
|
4
|
-
import {
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
5
6
|
import path from 'node:path';
|
|
6
7
|
import { NoteSchema, type Note } from '@app/core';
|
|
7
8
|
import { AppError, NotFoundError } from '@app/shared';
|
|
@@ -9,15 +10,28 @@ import { AppError, NotFoundError } from '@app/shared';
|
|
|
9
10
|
type NoteTable = Record<string, unknown>;
|
|
10
11
|
|
|
11
12
|
export class JsonFileNoteStore {
|
|
13
|
+
/**
|
|
14
|
+
* Writes run one at a time — **per instance, which is the whole extent of
|
|
15
|
+
* it**. A write is load → mutate → save, and that is not atomic: two
|
|
16
|
+
* concurrent `put()`s would both read the same table and the second save
|
|
17
|
+
* would drop the first note. This chain serialises the ones going through
|
|
18
|
+
* *this* object. Two `JsonFileNoteStore`s over the same file lose notes to
|
|
19
|
+
* each other exactly as before — in one process as readily as in two — so
|
|
20
|
+
* share the instance, and reach for a real lock before sharing the file.
|
|
21
|
+
*/
|
|
22
|
+
private writes: Promise<unknown> = Promise.resolve();
|
|
23
|
+
|
|
12
24
|
constructor(private readonly file: string) {}
|
|
13
25
|
|
|
14
26
|
async put(note: Note): Promise<void> {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
27
|
+
return this.serialised(async () => {
|
|
28
|
+
const table = await this.load();
|
|
29
|
+
if (note.id in table) {
|
|
30
|
+
throw new AppError(`note ${note.id} already exists`, { code: 'CONFLICT', statusCode: 409 });
|
|
31
|
+
}
|
|
32
|
+
table[note.id] = note;
|
|
33
|
+
await this.save(table);
|
|
34
|
+
});
|
|
21
35
|
}
|
|
22
36
|
|
|
23
37
|
async get(id: string): Promise<Note> {
|
|
@@ -38,6 +52,20 @@ export class JsonFileNoteStore {
|
|
|
38
52
|
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
39
53
|
}
|
|
40
54
|
|
|
55
|
+
/** Queues `work` behind the writes already in flight on this instance. */
|
|
56
|
+
private serialised<T>(work: () => Promise<T>): Promise<T> {
|
|
57
|
+
const result = this.writes.then(work);
|
|
58
|
+
// The caller gets the rejection; the chain gets a settled promise. Without
|
|
59
|
+
// this line one failed write (a 409, say) would reject every write queued
|
|
60
|
+
// behind it, and this store object would stay broken for as long as it is
|
|
61
|
+
// held — the chain is per instance, so a fresh store would still work.
|
|
62
|
+
this.writes = result.then(
|
|
63
|
+
() => undefined,
|
|
64
|
+
() => undefined,
|
|
65
|
+
);
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
|
|
41
69
|
private async load(): Promise<NoteTable> {
|
|
42
70
|
let content: string;
|
|
43
71
|
try {
|
|
@@ -56,8 +84,17 @@ export class JsonFileNoteStore {
|
|
|
56
84
|
private async save(table: NoteTable): Promise<void> {
|
|
57
85
|
await mkdir(path.dirname(this.file), { recursive: true });
|
|
58
86
|
// Write-then-rename keeps readers from ever seeing a half-written file.
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
87
|
+
// The temp name is unique per write: a shared one lets two writers scribble
|
|
88
|
+
// over each other's file and lose a rename to ENOENT.
|
|
89
|
+
const tmp = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
|
|
90
|
+
try {
|
|
91
|
+
await writeFile(tmp, JSON.stringify(table, null, 2));
|
|
92
|
+
await rename(tmp, this.file);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
// Best-effort tidy-up: a failure to remove the temp file must not
|
|
95
|
+
// replace the failure that actually matters.
|
|
96
|
+
await rm(tmp, { force: true }).catch(() => undefined);
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
62
99
|
}
|
|
63
100
|
}
|
|
@@ -40,6 +40,17 @@ describe('JsonFileNoteStore', () => {
|
|
|
40
40
|
await expect(store.put(note)).rejects.toMatchObject({ statusCode: 409 });
|
|
41
41
|
});
|
|
42
42
|
|
|
43
|
+
it('a rejected write does not block the writes queued behind it', async () => {
|
|
44
|
+
// The 409 above cannot see this: a poisoned write chain rejects the next
|
|
45
|
+
// put() with the very same AppError the duplicate would have raised.
|
|
46
|
+
const store = new JsonFileNoteStore(file);
|
|
47
|
+
await store.put(note);
|
|
48
|
+
await expect(store.put(note)).rejects.toThrow(AppError);
|
|
49
|
+
|
|
50
|
+
await expect(store.put({ ...note, id: 'n2' })).resolves.toBeUndefined();
|
|
51
|
+
expect((await store.list()).map((n) => n.id).sort()).toEqual(['n1', 'n2']);
|
|
52
|
+
});
|
|
53
|
+
|
|
43
54
|
it('throws NotFoundError on a miss', async () => {
|
|
44
55
|
await expect(new JsonFileNoteStore(file).get('nope')).rejects.toThrow(NotFoundError);
|
|
45
56
|
});
|
|
@@ -69,6 +80,15 @@ describe('JsonFileNoteStore', () => {
|
|
|
69
80
|
expect(listed.map((n) => n.id)).toEqual(['b', 'a']);
|
|
70
81
|
});
|
|
71
82
|
|
|
83
|
+
it('keeps every concurrently written note (no lost update)', async () => {
|
|
84
|
+
const store = new JsonFileNoteStore(file);
|
|
85
|
+
const ids = Array.from({ length: 20 }, (_, i) => `n${i}`);
|
|
86
|
+
await Promise.all(ids.map((id) => store.put({ ...note, id })));
|
|
87
|
+
|
|
88
|
+
expect((await store.list()).map((n) => n.id).sort()).toEqual([...ids].sort());
|
|
89
|
+
expect(Object.keys(JSON.parse(await readFile(file, 'utf8'))).sort()).toEqual([...ids].sort());
|
|
90
|
+
});
|
|
91
|
+
|
|
72
92
|
it('refuses to list corrupt entries instead of skipping them silently', async () => {
|
|
73
93
|
const store = new JsonFileNoteStore(file);
|
|
74
94
|
await store.put(note);
|
|
@@ -7,17 +7,10 @@ import { JsonFileNoteStore } from '@app/db';
|
|
|
7
7
|
import { createLogger, loadEnv } from '@app/shared';
|
|
8
8
|
import { SpoolEventPublisher } from './adapters/spool-publisher.js';
|
|
9
9
|
import { makeServer } from './server.js';
|
|
10
|
+
import { defaultStaticDirFor } from './static-dir.js';
|
|
10
11
|
|
|
11
12
|
// The built web bundle (pnpm build:web) lives here; served when present.
|
|
12
|
-
const defaultStaticDir =
|
|
13
|
-
path.dirname(new URL(import.meta.url).pathname),
|
|
14
|
-
'..',
|
|
15
|
-
'..',
|
|
16
|
-
'..',
|
|
17
|
-
'apps',
|
|
18
|
-
'web',
|
|
19
|
-
'out',
|
|
20
|
-
);
|
|
13
|
+
const defaultStaticDir = defaultStaticDirFor(import.meta.url);
|
|
21
14
|
|
|
22
15
|
const env = loadEnv(
|
|
23
16
|
z.object({
|