@macedon-technologies/batman 1.32.0 → 1.33.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/.jsii +3 -3
- package/README.md +15 -3
- package/lib/BatmanProject.js +1 -1
- package/lib/BootcampProject.js +1 -1
- package/lib/CodeOwnersFile.js +1 -1
- package/lib/PrAutoMergeWorkflow.js +1 -1
- package/lib/ProductionDeployWorkflow.js +1 -1
- package/lib/SoftwareFactoryFiles.js +1 -1
- package/lib/StagingDeployWorkflow.js +1 -1
- package/package.json +2 -1
- package/templates/app/architecture-rules/README.md +97 -0
- package/templates/app/architecture-rules/check.ts +218 -0
- package/templates/app/architecture-rules/rules.json +3 -0
- package/templates/app/architecture-rules/tsconfig.json +14 -0
- package/templates/app/openspec-gates/check-tasks-complete.ts +44 -0
- package/templates/app/openspec-gates/tsconfig.json +13 -0
- package/templates/app/package.json +74 -0
- package/templates/app/pnpm-lock.yaml +3888 -0
- package/templates/app/pnpm-workspace.yaml +7 -0
- package/templates/app/src/aspects/DataDogAspect.ts +14 -0
- package/templates/app/src/constructs/Secret.ts +50 -0
- package/templates/app/src/constructs/handler/Secret.Function.ts +38 -0
- package/templates/app/src/constructs/handler/secret/client.ts +5 -0
- package/templates/app/src/constructs/handler/secret/createSecretValue.ts +30 -0
- package/templates/app/src/constructs/handler/secret/didRandomPropertiesChange.ts +13 -0
- package/templates/app/src/constructs/handler/secret/updateSecretValue.ts +71 -0
- package/templates/app/swamp-bootstrap/pull-extensions.ts +68 -0
- package/templates/app/swamp-bootstrap/tsconfig.json +13 -0
- package/templates/app/test/DataDogAspect.test.ts +31 -0
- package/templates/app/test/Secret.test.ts +40 -0
- package/templates/app/test/didRandomPropertiesChange.test.ts +19 -0
- package/templates/app/test/tsconfig.json +13 -0
- package/templates/app/tsconfig.json +50 -0
- package/openspec/changes/pr-workflow-concurrency-group/.openspec.yaml +0 -2
- package/openspec/changes/pr-workflow-concurrency-group/design.md +0 -47
- package/openspec/changes/pr-workflow-concurrency-group/proposal.md +0 -27
- package/openspec/changes/pr-workflow-concurrency-group/specs/pr-workflow-concurrency/spec.md +0 -23
- package/openspec/changes/pr-workflow-concurrency-group/tasks.md +0 -15
package/.jsii
CHANGED
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
},
|
|
98
98
|
"name": "@macedon-technologies/batman",
|
|
99
99
|
"readme": {
|
|
100
|
-
"markdown": "# Platform Common Projen\n\nA baseline architecture template for new projects using Projen. This project provides a standardized foundation that includes both frontend and backend components with authentication.\n\n## Project Intention\n\nThis template serves as a starting point for new projects, providing:\n- Consistent project structure and configuration\n- Pre-configured development tooling\n- Integrated authentication system\n- Full-stack application foundation\n\n## Components Created\n\nThe BatmanProject generates:\n\n### Frontend\n- **React Application** - Modern React app with TypeScript\n- **Clerk Authentication** - Integrated user authentication and management\n- **Playwright e2e Testing** - `@playwright/test` + `@clerk/testing` devDeps, a `test:e2e` task, and a scaffolded `playwright.config.ts` + `e2e/` starter suite (see the generated `web/e2e/README.md`); disable with `e2eTesting: false`. The generated `pr-deploy.yml` workflow also runs this suite against each PR's deployed URL unless `e2eTesting: false` is set.\n\n### Backend/Infrastructure\n- **AWS Infrastructure** - CDK-based cloud resources\n- **API Gateway** - RESTful API endpoints\n- **Lambda Functions** - Serverless compute\n- **Database** - Persistent data storage\n\n## Usage Examples\n\n### Basic Project Creation\n\nCreate a `.projenrc.ts` file in your project root:\n\n```typescript\nimport { BatmanProject } from '@macedon-technologies/batman';\n\nconst project = new BatmanProject({\n name: 'my-new-app',\n defaultReleaseBranch: 'main',\n});\n\nproject.synth();\n```\n\nThen run:\n```bash\nnpx projen\n```\n\n### With Custom Configuration\n\nCreate a `.projenrc.ts` file with additional options:\n\n```typescript\nimport { BatmanProject } from '@macedon-technologies/batman';\n\nconst project = new BatmanProject({\n name: 'my-enterprise-app',\n defaultReleaseBranch: 'main',\n description: 'Enterprise application with authentication',\n authorName: 'Your Name',\n authorEmail: 'your.email@company.com',\n});\n\nproject.synth();\n```\n\nThen run:\n```bash\nnpx projen\n```\n\n### Development Workflow\n\n```bash\n# Install dependencies\nyarn install\n\n# Start development server\nyarn dev\n\n# Deploy infrastructure\nyarn deploy\n\n# Run tests\nyarn test\n```\n\n## Deploying staging on demand\n\nThe generated `Staging Deploy` workflow runs on every push to `main` and can also be run manually from the Actions tab (\"Run workflow\"). Use that to redeploy `main` when a merge raised no push event or a deploy needs re-running. Pick `main` as the branch: the workflow deploys whichever branch you select.\n\n## Auto-merging pull requests with a GitHub App\n\nSetting `prAutoMerge: true` generates `.github/workflows/pr-auto-merge.yml`. It turns on GitHub's squash auto-merge for every pull request into the default branch when the pull request is opened, reopened or marked ready for review. Drafts and pull requests into other branches are left alone. The pull request then merges by itself once your branch ruleset is satisfied.\n\nThe workflow arms the merge with a GitHub App token, not `GITHUB_TOKEN`. GitHub attributes an auto-merge to whoever armed it and raises no events for anything `GITHUB_TOKEN` does, so a merge armed with it would never trigger `Staging Deploy` or `PR Cleanup`.\n\nThe App's private key can mint tokens for every repository the App is installed on, so it lives in an `auto-merge` environment that only `main` can use, not in the repository's secrets. Anyone with write access can read repository secrets from a workflow on their own branch. The workflow runs on `pull_request_target`, which uses the workflow file from the default branch and so passes the environment's branch rule; it never checks out pull request code. Use one App per repository so a leaked key reaches only that repository.\n\nSet it up in this order. Until the App and credentials exist, every pull request's `pr-auto-merge` run fails.\n\n1. **Create a GitHub App** in the organization (Settings → Developer settings → GitHub Apps → New GitHub App). It needs no webhook. Under Repository permissions give it **Read and write** on Contents, Pull requests, Workflows and Issues. Workflows is needed because Batman upgrades change files under `.github/workflows/`. Issues lets the merge close linked issues.\n2. **Generate a private key** on the App's page, and note its **Client ID**.\n3. **Install the App** on the repository (the App's page → Install App → Only select repositories).\n4. **Create an `auto-merge` environment** (Settings → Environments → New environment). Under Deployment branches and tags choose **Selected branches and tags** and add `main`. Then add to the environment:\n - an environment **variable** `AUTO_MERGE_APP_CLIENT_ID` set to the Client ID;\n - an environment **secret** `AUTO_MERGE_APP_PRIVATE_KEY` set to the full contents of the `.pem` file.\n\n Don't add them as repository variables or secrets.\n5. **Turn on \"Allow auto-merge\"** in the repository's Settings → General → Pull Requests.\n6. **Protect the default branch** with a ruleset that requires an approving review and your required status checks. `prAutoMerge` doesn't create one. Without it, an armed pull request merges as soon as it can, unreviewed.\n7. Set `prAutoMerge: true` in `.projenrc.ts` and run projen.\n\nIf the variable or the secret is missing from the environment, the run fails with an error naming both. If the App's installation lacks one of the four permissions, minting the token fails. Pull requests from forks are armed like any other, since the workflow runs from the default branch, and still wait for the ruleset's review. Dependabot pull requests don't receive the environment's secret, so their runs fail the credential check. Merge those by hand. Each run also records a deployment to the `auto-merge` environment.\n\n## Upgrading\n\n### Datadog tracing defaults changed\n\n`BaseApplicationStack` now defaults `datadog.nodeLayerVersion` to 143 (dd-trace 6.x) instead of 132, and passes `enableMergeXrayTraces: false` to `DatadogLambda`. These reach every project on its next `npx projen`. With merging off, the `aws.apigateway` span Datadog infers starts the API trace; API Gateway stage X-Ray tracing stays on. A stack that set its own `nodeLayerVersion` keeps it. To merge X-Ray traces again, override `createDatadogExtension()` in your `ApplicationStack`:\n\n```ts\nprotected override createDatadogExtension() {\n super.createDatadogExtension();\n Object.assign(this.datadog.props, { enableMergeXrayTraces: true });\n}\n```\n\nNew projects' `src/constructs/Api.ts` installs `express` and `pg` into the Lambda artifact instead of bundling them, so dd-trace can trace router and `pg.query` calls. `Api.ts` is yours once generated, so existing projects add `express` and `pg` to `bundling.nodeModules` on the `NodejsFunction` in `createLambdaFunction()`, creating the block if it has none:\n\n```ts\nbundling: {\n nodeModules: ['express', 'pg'],\n},\n```\n\nCDK installs each package at the version spec in your root `package.json`, so `express` and `pg` must have plain version ranges there. A `catalog:` spec fails synth.\n\n### The base stack no longer creates a VPC\n\n`BaseApplicationStack` used to create a VPC with a NAT gateway and attach the API Lambda to it.\nIt now creates neither unless the stack props set `enableVpc: true`. A stack that upgrades\nwithout it deletes its VPC and NAT gateway on the next deploy.\n\nAdd `enableVpc: true` to every `ApplicationStack` in `src/main.ts` and `src/LocalDevApp.ts` (new projects: `additionalStackProps: { enableVpc: true }` on each environment) if any of these apply:\n\n- your `ApplicationStack` uses `this.vpc` or overrides `createVpc()`; the override is not called otherwise;\n- the Lambda reaches anything private, such as RDS or a VPC endpoint;\n- another stack imports this stack's VPC outputs; CloudFormation refuses to delete them.\n\n`this.vpc` is now typed `IVpc | undefined`, even with `enableVpc: true`, so code that passes it where an `IVpc` is required (such as `new SecurityGroup(this, 'Sg', { vpc: this.vpc })`) stops compiling. With `enableVpc: true` the VPC is created before your `ApplicationStack` constructor runs, so use `this.vpc!` there, or check it and throw if it's missing.\n\nOtherwise, make `vpc` optional in `src/constructs/Api.ts` (`readonly vpc?: IVpc;`) so the project compiles. Deleting the VPC can take a while as Lambda releases its network interfaces.\n\nWith `enableVpc: true`, the Lambda is attached only if your `Api.ts` still accepts a `vpc` prop and your stack doesn't override `createApi()` without passing it.\n\n### n8n support is removed\n\n`BatmanProject` and `BootcampProject` no longer generate any n8n wiring. The base stacks have no `n8nEndpoint` prop, `src/constructs/WorkflowProvider.ts` and a construct per `src/workflows/*.json` are no longer generated, and new projects get an `Api.ts`, `main.ts` and `LocalDevApp.ts` without n8n. The `n8nWorkflows` option, the `n8nEndpoint` environment config field and the exported `WorkflowAutoDiscover` class are gone, so every project removes `n8nWorkflows` and `n8nEndpoint` from its `.projenrc.ts`.\n\nA project that doesn't use n8n stops compiling until it also removes:\n\n- `n8nEndpoint` from every `ApplicationStack` in `src/main.ts` and `src/LocalDevApp.ts`;\n- the `n8nEndpoint` prop, the n8n JWT key secret and its `grantRead` from `src/constructs/Api.ts`;\n- any `n8nEndpoint: this.props.n8nEndpoint` in a `createApi()` override;\n- any generated `src/constructs/*Workflow.ts` files and `src/workflows/`, which import the now-deleted `WorkflowProvider`.\n\nA project that uses n8n takes ownership of it:\n\n1. Upgrading makes projen delete `src/constructs/WorkflowProvider.ts`. Restore it from the last commit that had it, which works whether or not the deletion is already committed:\n\n ```bash\n git checkout \"$(git log -n1 --format=%H --diff-filter=AM -- src/constructs/WorkflowProvider.ts)\" -- src/constructs/WorkflowProvider.ts\n ```\n\n Then delete the `~~ Generated by projen` header line from it and from your per-workflow constructs (such as `AlfredWorkflow.ts`). They're yours from now on, and a new workflow needs its construct written by hand.\n2. Move `n8nEndpoint` from `Api` to your `ApplicationStack`. Remove the `n8nEndpoint` prop and its `N8N_ENDPOINT` environment entry from `src/constructs/Api.ts`, add `readonly n8nEndpoint: string;` to `ApplicationStackProps` (your `main.ts` and `LocalDevApp.ts` already pass it), and set the variable after `super()`:\n\n ```typescript\n this.api.lambdaFunction.addEnvironment('N8N_ENDPOINT', props.n8nEndpoint);\n ```\n\n## SoftwareFactoryFiles (standalone, non-Batman projects)\n\n`SoftwareFactoryFiles` is independently exported and can be attached to any\n`projen` `NodeProject` — it does not require `BatmanProject` or\n`BootcampProject`. It generates the `@swamp/software-factory` state machine,\nthe architecture rule registry, the pre-PR attestation gate, the OpenSpec\ntask-completion gate, and the swamp workflows that wire them together.\n\n```typescript\nimport { javascript } from 'projen';\nimport { SoftwareFactoryFiles } from '@macedon-technologies/batman';\n\nconst project = new javascript.NodeProject({\n name: 'my-other-project',\n defaultReleaseBranch: 'main',\n});\n\nnew SoftwareFactoryFiles(project, {\n repoName: 'my-other-project',\n githubOwner: 'my-github-org', // defaults to 'macedon-technologies' if omitted\n baseBranch: 'main', // defaults to 'main'\n});\n\nproject.synth();\n```\n\nAfter running `npx projen`, follow the printed `swamp:bootstrap` task to pull\nthe required swamp extensions and create the project's secrets vault.\n\n### Work items and `factory/work-item-sources.md`\n\nA factory run's `workItem` is the ticket's bare key in its own tracker, such as\n`108` for a GitHub issue or `AI-123`, with nothing naming the tracker. The run's\nrecords and scratch paths are named after it, so a run is always started with\nthe bare key, even when the request names the tracker.\n\nThe factory's intake stage resolves the work item by following the managed\n`factory/work-item-sources.md`: which sources' key formats fit it, which model\nand method fetch it, how its fields map into the `issue-context` artifact, and\nwhich link line `open-pr` writes in the PR body (`Closes #<key>` for GitHub).\nWhen more than one source finds the key, intake stops and asks which was meant. Batman regenerates this file on every\nsynth, so supporting another tracker never needs a factory definition edit. The\nfile is part of the PR attestation manifest. The first synth that adds it changes\n`attestation/manifest.ts`, so any factory PR that's already open needs\nre-attesting.\n\n#### Updating an already-scaffolded factory\n\nThe factory definition (`models/@swamp/software-factory/<repo>-factory.yaml`)\nis written once, so a repo scaffolded before the routing file existed\nregenerates it:\n\n1. Note the file's `id:` line and any changes the repo has made to it since it\n was scaffolded (`git log -p -- <file>`).\n2. Delete the file and run `npx projen`, which writes the current template.\n3. Put the old `id:` line back, so swamp still treats it as the same model, and\n re-apply the repo's changes.\n\nRuns that recorded the old `issue-context` (`number` instead of `source`/`key`)\nkeep working: the routing file tells later stages to treat them as GitHub issues."
|
|
100
|
+
"markdown": "# Platform Common Projen\n\nA baseline architecture template for new projects using Projen. This project provides a standardized foundation that includes both frontend and backend components with authentication.\n\n## Project Intention\n\nThis template serves as a starting point for new projects, providing:\n- Consistent project structure and configuration\n- Pre-configured development tooling\n- Integrated authentication system\n- Full-stack application foundation\n\n## Components Created\n\nThe BatmanProject generates:\n\n### Frontend\n- **React Application** - Modern React app with TypeScript\n- **Clerk Authentication** - Integrated user authentication and management\n- **Playwright e2e Testing** - `@playwright/test` + `@clerk/testing` devDeps, a `test:e2e` task, and a scaffolded `playwright.config.ts` + `e2e/` starter suite (see the generated `web/e2e/README.md`); disable with `e2eTesting: false`. The generated `pr-deploy.yml` workflow also runs this suite against each PR's deployed URL unless `e2eTesting: false` is set.\n\n### Backend/Infrastructure\n- **AWS Infrastructure** - CDK-based cloud resources\n- **API Gateway** - RESTful API endpoints\n- **Lambda Functions** - Serverless compute\n- **Database** - Persistent data storage\n\n## Usage Examples\n\n### Basic Project Creation\n\nCreate a `.projenrc.ts` file in your project root:\n\n```typescript\nimport { BatmanProject } from '@macedon-technologies/batman';\n\nconst project = new BatmanProject({\n name: 'my-new-app',\n defaultReleaseBranch: 'main',\n});\n\nproject.synth();\n```\n\nThen run:\n```bash\nnpx projen\n```\n\n### With Custom Configuration\n\nCreate a `.projenrc.ts` file with additional options:\n\n```typescript\nimport { BatmanProject } from '@macedon-technologies/batman';\n\nconst project = new BatmanProject({\n name: 'my-enterprise-app',\n defaultReleaseBranch: 'main',\n description: 'Enterprise application with authentication',\n authorName: 'Your Name',\n authorEmail: 'your.email@company.com',\n});\n\nproject.synth();\n```\n\nThen run:\n```bash\nnpx projen\n```\n\n### Development Workflow\n\n```bash\n# Install dependencies\nyarn install\n\n# Start development server\nyarn dev\n\n# Deploy infrastructure\nyarn deploy\n\n# Run tests\nyarn test\n```\n\n## Deploying staging on demand\n\nThe generated `Staging Deploy` workflow runs on every push to `main` and can also be run manually from the Actions tab (\"Run workflow\"). Use that to redeploy `main` when a merge raised no push event or a deploy needs re-running. Pick `main` as the branch: the workflow deploys whichever branch you select.\n\n## Auto-merging pull requests with a GitHub App\n\nSetting `prAutoMerge: true` generates `.github/workflows/pr-auto-merge.yml`. It turns on GitHub's squash auto-merge for every pull request into the default branch when the pull request is opened, reopened or marked ready for review. Drafts and pull requests into other branches are left alone. The pull request then merges by itself once your branch ruleset is satisfied.\n\nThe workflow arms the merge with a GitHub App token, not `GITHUB_TOKEN`. GitHub attributes an auto-merge to whoever armed it and raises no events for anything `GITHUB_TOKEN` does, so a merge armed with it would never trigger `Staging Deploy` or `PR Cleanup`.\n\nThe App's private key can mint tokens for every repository the App is installed on, so it lives in an `auto-merge` environment that only `main` can use, not in the repository's secrets. Anyone with write access can read repository secrets from a workflow on their own branch. The workflow runs on `pull_request_target`, which uses the workflow file from the default branch and so passes the environment's branch rule; it never checks out pull request code. Use one App per repository so a leaked key reaches only that repository.\n\nSet it up in this order. Until the App and credentials exist, every pull request's `pr-auto-merge` run fails.\n\n1. **Create a GitHub App** in the organization (Settings → Developer settings → GitHub Apps → New GitHub App). It needs no webhook. Under Repository permissions give it **Read and write** on Contents, Pull requests, Workflows and Issues. Workflows is needed because Batman upgrades change files under `.github/workflows/`. Issues lets the merge close linked issues.\n2. **Generate a private key** on the App's page, and note its **Client ID**.\n3. **Install the App** on the repository (the App's page → Install App → Only select repositories).\n4. **Create an `auto-merge` environment** (Settings → Environments → New environment). Under Deployment branches and tags choose **Selected branches and tags** and add `main`. Then add to the environment:\n - an environment **variable** `AUTO_MERGE_APP_CLIENT_ID` set to the Client ID;\n - an environment **secret** `AUTO_MERGE_APP_PRIVATE_KEY` set to the full contents of the `.pem` file.\n\n Don't add them as repository variables or secrets.\n5. **Turn on \"Allow auto-merge\"** in the repository's Settings → General → Pull Requests.\n6. **Protect the default branch** with a ruleset that requires an approving review and your required status checks. `prAutoMerge` doesn't create one. Without it, an armed pull request merges as soon as it can, unreviewed.\n7. Set `prAutoMerge: true` in `.projenrc.ts` and run projen.\n\nIf the variable or the secret is missing from the environment, the run fails with an error naming both. If the App's installation lacks one of the four permissions, minting the token fails. Pull requests from forks are armed like any other, since the workflow runs from the default branch, and still wait for the ruleset's review. Dependabot pull requests don't receive the environment's secret, so their runs fail the credential check. Merge those by hand. Each run also records a deployment to the `auto-merge` environment.\n\n## Upgrading\n\nEach note names the Batman release that introduced it. Read every note newer than the version you're upgrading from. A note is removed once every known Batman project is on that release or later.\n\n### Datadog tracing defaults changed (v1.32.0)\n\n`BaseApplicationStack` now defaults `datadog.nodeLayerVersion` to 143 (dd-trace 6.x) instead of 132, and passes `enableMergeXrayTraces: false` to `DatadogLambda`. These reach every project on its next `npx projen`. With merging off, the `aws.apigateway` span Datadog infers starts the API trace; API Gateway stage X-Ray tracing stays on. A stack that set its own `nodeLayerVersion` keeps it. To merge X-Ray traces again, override `createDatadogExtension()` in your `ApplicationStack`:\n\n```ts\nprotected override createDatadogExtension() {\n super.createDatadogExtension();\n Object.assign(this.datadog.props, { enableMergeXrayTraces: true });\n}\n```\n\nNew projects' `src/constructs/Api.ts` installs `express` and `pg` into the Lambda artifact instead of bundling them, so dd-trace can trace router and `pg.query` calls. `Api.ts` is yours once generated, so existing projects add `express` and `pg` to `bundling.nodeModules` on the `NodejsFunction` in `createLambdaFunction()`, creating the block if it has none:\n\n```ts\nbundling: {\n nodeModules: ['express', 'pg'],\n},\n```\n\nCDK installs each package at the version spec in your root `package.json`, so `express` and `pg` must have plain version ranges there. A `catalog:` spec fails synth.\n\n### The base stack no longer creates a VPC (v1.30.0)\n\n`BaseApplicationStack` used to create a VPC with a NAT gateway and attach the API Lambda to it.\nIt now creates neither unless the stack props set `enableVpc: true`. A stack that upgrades\nwithout it deletes its VPC and NAT gateway on the next deploy.\n\nAdd `enableVpc: true` to every `ApplicationStack` in `src/main.ts` and `src/LocalDevApp.ts` (new projects: `additionalStackProps: { enableVpc: true }` on each environment) if any of these apply:\n\n- your `ApplicationStack` uses `this.vpc` or overrides `createVpc()`; the override is not called otherwise;\n- the Lambda reaches anything private, such as RDS or a VPC endpoint;\n- another stack imports this stack's VPC outputs; CloudFormation refuses to delete them.\n\n`this.vpc` is now typed `IVpc | undefined`, even with `enableVpc: true`, so code that passes it where an `IVpc` is required (such as `new SecurityGroup(this, 'Sg', { vpc: this.vpc })`) stops compiling. With `enableVpc: true` the VPC is created before your `ApplicationStack` constructor runs, so use `this.vpc!` there, or check it and throw if it's missing.\n\nOtherwise, make `vpc` optional in `src/constructs/Api.ts` (`readonly vpc?: IVpc;`) so the project compiles. Deleting the VPC can take a while as Lambda releases its network interfaces.\n\nWith `enableVpc: true`, the Lambda is attached only if your `Api.ts` still accepts a `vpc` prop and your stack doesn't override `createApi()` without passing it.\n\n### n8n support is removed (v1.30.0)\n\n`BatmanProject` and `BootcampProject` no longer generate any n8n wiring. The base stacks have no `n8nEndpoint` prop, `src/constructs/WorkflowProvider.ts` and a construct per `src/workflows/*.json` are no longer generated, and new projects get an `Api.ts`, `main.ts` and `LocalDevApp.ts` without n8n. The `n8nWorkflows` option, the `n8nEndpoint` environment config field and the exported `WorkflowAutoDiscover` class are gone, so every project removes `n8nWorkflows` and `n8nEndpoint` from its `.projenrc.ts`.\n\nA project that doesn't use n8n stops compiling until it also removes:\n\n- `n8nEndpoint` from every `ApplicationStack` in `src/main.ts` and `src/LocalDevApp.ts`;\n- the `n8nEndpoint` prop, the n8n JWT key secret and its `grantRead` from `src/constructs/Api.ts`;\n- any `n8nEndpoint: this.props.n8nEndpoint` in a `createApi()` override;\n- any generated `src/constructs/*Workflow.ts` files and `src/workflows/`, which import the now-deleted `WorkflowProvider`.\n\nA project that uses n8n takes ownership of it:\n\n1. Upgrading makes projen delete `src/constructs/WorkflowProvider.ts`. Restore it from the last commit that had it, which works whether or not the deletion is already committed:\n\n ```bash\n git checkout \"$(git log -n1 --format=%H --diff-filter=AM -- src/constructs/WorkflowProvider.ts)\" -- src/constructs/WorkflowProvider.ts\n ```\n\n Then delete the `~~ Generated by projen` header line from it and from your per-workflow constructs (such as `AlfredWorkflow.ts`). They're yours from now on, and a new workflow needs its construct written by hand.\n2. Move `n8nEndpoint` from `Api` to your `ApplicationStack`. Remove the `n8nEndpoint` prop and its `N8N_ENDPOINT` environment entry from `src/constructs/Api.ts`, add `readonly n8nEndpoint: string;` to `ApplicationStackProps` (your `main.ts` and `LocalDevApp.ts` already pass it), and set the variable after `super()`:\n\n ```typescript\n this.api.lambdaFunction.addEnvironment('N8N_ENDPOINT', props.n8nEndpoint);\n ```\n\n### `BaseService.ts` is no longer generated (v1.28.0)\n\n`ViteReactProject` no longer writes `web/src/services/BaseService.ts` or `web/src/services/RootService.ts`. `BaseService.ts` was managed, so upgrading makes projen delete it; `RootService.ts` was yours and stays. New projects get `web/src/services/ApiService.ts` and `web/src/helpers/` instead, and existing projects get them too wherever those files don't already exist.\n\nAnything that imports `BaseService.ts`, such as the old sample `App.tsx` or `RootService.ts`, stops compiling. Switch it to `useApiQuery` / `useApiMutation` from `ApiService.ts`, or keep your own copy of `BaseService.ts` by restoring it from the last commit that had it:\n\n```bash\ngit checkout \"$(git log -n1 --format=%H --diff-filter=AM -- web/src/services/BaseService.ts)\" -- web/src/services/BaseService.ts\n```\n\n## SoftwareFactoryFiles (standalone, non-Batman projects)\n\n`SoftwareFactoryFiles` is independently exported and can be attached to any\n`projen` `NodeProject` — it does not require `BatmanProject` or\n`BootcampProject`. It generates the `@swamp/software-factory` state machine,\nthe architecture rule registry, the pre-PR attestation gate, the OpenSpec\ntask-completion gate, and the swamp workflows that wire them together.\n\n```typescript\nimport { javascript } from 'projen';\nimport { SoftwareFactoryFiles } from '@macedon-technologies/batman';\n\nconst project = new javascript.NodeProject({\n name: 'my-other-project',\n defaultReleaseBranch: 'main',\n});\n\nnew SoftwareFactoryFiles(project, {\n repoName: 'my-other-project',\n githubOwner: 'my-github-org', // defaults to 'macedon-technologies' if omitted\n baseBranch: 'main', // defaults to 'main'\n});\n\nproject.synth();\n```\n\nAfter running `npx projen`, follow the printed `swamp:bootstrap` task to pull\nthe required swamp extensions and create the project's secrets vault.\n\n### Work items and `factory/work-item-sources.md`\n\nA factory run's `workItem` is the ticket's bare key in its own tracker, such as\n`108` for a GitHub issue or `AI-123`, with nothing naming the tracker. The run's\nrecords and scratch paths are named after it, so a run is always started with\nthe bare key, even when the request names the tracker.\n\nThe factory's intake stage resolves the work item by following the managed\n`factory/work-item-sources.md`: which sources' key formats fit it, which model\nand method fetch it, how its fields map into the `issue-context` artifact, and\nwhich link line `open-pr` writes in the PR body (`Closes #<key>` for GitHub).\nWhen more than one source finds the key, intake stops and asks which was meant. Batman regenerates this file on every\nsynth, so supporting another tracker never needs a factory definition edit. The\nfile is part of the PR attestation manifest. The first synth that adds it changes\n`attestation/manifest.ts`, so any factory PR that's already open needs\nre-attesting.\n\n#### Updating an already-scaffolded factory\n\nThe factory definition (`models/@swamp/software-factory/<repo>-factory.yaml`)\nis written once, so a repo scaffolded before the routing file existed\nregenerates it:\n\n1. Note the file's `id:` line and any changes the repo has made to it since it\n was scaffolded (`git log -p -- <file>`).\n2. Delete the file and run `npx projen`, which writes the current template.\n3. Put the old `id:` line back, so swamp still treats it as the same model, and\n re-apply the repo's changes.\n\nRuns that recorded the old `issue-context` (`number` instead of `source`/`key`)\nkeep working: the routing file tells later stages to treat them as GitHub issues."
|
|
101
101
|
},
|
|
102
102
|
"repository": {
|
|
103
103
|
"type": "git",
|
|
@@ -1393,6 +1393,6 @@
|
|
|
1393
1393
|
"symbolId": "src/WorkflowActionVersions:WorkflowActionVersions"
|
|
1394
1394
|
}
|
|
1395
1395
|
},
|
|
1396
|
-
"version": "1.
|
|
1397
|
-
"fingerprint": "
|
|
1396
|
+
"version": "1.33.0",
|
|
1397
|
+
"fingerprint": "cGijwamH3ea9tzt5nrOJYVxPV0QTXWy0gyYBQ2wuILk="
|
|
1398
1398
|
}
|
package/README.md
CHANGED
|
@@ -116,7 +116,9 @@ If the variable or the secret is missing from the environment, the run fails wit
|
|
|
116
116
|
|
|
117
117
|
## Upgrading
|
|
118
118
|
|
|
119
|
-
|
|
119
|
+
Each note names the Batman release that introduced it. Read every note newer than the version you're upgrading from. A note is removed once every known Batman project is on that release or later.
|
|
120
|
+
|
|
121
|
+
### Datadog tracing defaults changed (v1.32.0)
|
|
120
122
|
|
|
121
123
|
`BaseApplicationStack` now defaults `datadog.nodeLayerVersion` to 143 (dd-trace 6.x) instead of 132, and passes `enableMergeXrayTraces: false` to `DatadogLambda`. These reach every project on its next `npx projen`. With merging off, the `aws.apigateway` span Datadog infers starts the API trace; API Gateway stage X-Ray tracing stays on. A stack that set its own `nodeLayerVersion` keeps it. To merge X-Ray traces again, override `createDatadogExtension()` in your `ApplicationStack`:
|
|
122
124
|
|
|
@@ -137,7 +139,7 @@ bundling: {
|
|
|
137
139
|
|
|
138
140
|
CDK installs each package at the version spec in your root `package.json`, so `express` and `pg` must have plain version ranges there. A `catalog:` spec fails synth.
|
|
139
141
|
|
|
140
|
-
### The base stack no longer creates a VPC
|
|
142
|
+
### The base stack no longer creates a VPC (v1.30.0)
|
|
141
143
|
|
|
142
144
|
`BaseApplicationStack` used to create a VPC with a NAT gateway and attach the API Lambda to it.
|
|
143
145
|
It now creates neither unless the stack props set `enableVpc: true`. A stack that upgrades
|
|
@@ -155,7 +157,7 @@ Otherwise, make `vpc` optional in `src/constructs/Api.ts` (`readonly vpc?: IVpc;
|
|
|
155
157
|
|
|
156
158
|
With `enableVpc: true`, the Lambda is attached only if your `Api.ts` still accepts a `vpc` prop and your stack doesn't override `createApi()` without passing it.
|
|
157
159
|
|
|
158
|
-
### n8n support is removed
|
|
160
|
+
### n8n support is removed (v1.30.0)
|
|
159
161
|
|
|
160
162
|
`BatmanProject` and `BootcampProject` no longer generate any n8n wiring. The base stacks have no `n8nEndpoint` prop, `src/constructs/WorkflowProvider.ts` and a construct per `src/workflows/*.json` are no longer generated, and new projects get an `Api.ts`, `main.ts` and `LocalDevApp.ts` without n8n. The `n8nWorkflows` option, the `n8nEndpoint` environment config field and the exported `WorkflowAutoDiscover` class are gone, so every project removes `n8nWorkflows` and `n8nEndpoint` from its `.projenrc.ts`.
|
|
161
163
|
|
|
@@ -181,6 +183,16 @@ A project that uses n8n takes ownership of it:
|
|
|
181
183
|
this.api.lambdaFunction.addEnvironment('N8N_ENDPOINT', props.n8nEndpoint);
|
|
182
184
|
```
|
|
183
185
|
|
|
186
|
+
### `BaseService.ts` is no longer generated (v1.28.0)
|
|
187
|
+
|
|
188
|
+
`ViteReactProject` no longer writes `web/src/services/BaseService.ts` or `web/src/services/RootService.ts`. `BaseService.ts` was managed, so upgrading makes projen delete it; `RootService.ts` was yours and stays. New projects get `web/src/services/ApiService.ts` and `web/src/helpers/` instead, and existing projects get them too wherever those files don't already exist.
|
|
189
|
+
|
|
190
|
+
Anything that imports `BaseService.ts`, such as the old sample `App.tsx` or `RootService.ts`, stops compiling. Switch it to `useApiQuery` / `useApiMutation` from `ApiService.ts`, or keep your own copy of `BaseService.ts` by restoring it from the last commit that had it:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
git checkout "$(git log -n1 --format=%H --diff-filter=AM -- web/src/services/BaseService.ts)" -- web/src/services/BaseService.ts
|
|
194
|
+
```
|
|
195
|
+
|
|
184
196
|
## SoftwareFactoryFiles (standalone, non-Batman projects)
|
|
185
197
|
|
|
186
198
|
`SoftwareFactoryFiles` is independently exported and can be attached to any
|
package/lib/BatmanProject.js
CHANGED
|
@@ -12,7 +12,7 @@ const SoftwareFactoryFiles_1 = require("./SoftwareFactoryFiles");
|
|
|
12
12
|
const utils_1 = require("./utils");
|
|
13
13
|
const ViteReactProject_1 = require("./ViteReactProject");
|
|
14
14
|
class BatmanProject extends awscdk_1.AwsCdkTypeScriptApp {
|
|
15
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.BatmanProject", version: "1.
|
|
15
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.BatmanProject", version: "1.33.0" };
|
|
16
16
|
constructor(options) {
|
|
17
17
|
super({
|
|
18
18
|
...options,
|
package/lib/BootcampProject.js
CHANGED
|
@@ -12,7 +12,7 @@ const SoftwareFactoryFiles_1 = require("./SoftwareFactoryFiles");
|
|
|
12
12
|
const utils_1 = require("./utils");
|
|
13
13
|
const ViteReactProject_1 = require("./ViteReactProject");
|
|
14
14
|
class BootcampProject extends awscdk_1.AwsCdkTypeScriptApp {
|
|
15
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.BootcampProject", version: "1.
|
|
15
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.BootcampProject", version: "1.33.0" };
|
|
16
16
|
constructor(options) {
|
|
17
17
|
super({
|
|
18
18
|
...options,
|
package/lib/CodeOwnersFile.js
CHANGED
|
@@ -4,7 +4,7 @@ exports.CodeOwnersFile = void 0;
|
|
|
4
4
|
const JSII_RTTI_SYMBOL_1 = Symbol.for("jsii.rtti");
|
|
5
5
|
const projen_1 = require("projen");
|
|
6
6
|
class CodeOwnersFile extends projen_1.TextFile {
|
|
7
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.CodeOwnersFile", version: "1.
|
|
7
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.CodeOwnersFile", version: "1.33.0" };
|
|
8
8
|
constructor(project, options = {}) {
|
|
9
9
|
const defaultOwners = ['* @macedon-technologies/platform', '* @macedon-technologies/ai-development-team'];
|
|
10
10
|
const allOwners = [...defaultOwners, ...(options.additionalOwners || [])];
|
|
@@ -14,7 +14,7 @@ const PR_AUTO_MERGE_README_URL = 'https://github.com/macedon-technologies/platfo
|
|
|
14
14
|
* workflows from pull request branches can't read the key. The job never checks out pull request code.
|
|
15
15
|
*/
|
|
16
16
|
class PrAutoMergeWorkflow extends projen_1.YamlFile {
|
|
17
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.PrAutoMergeWorkflow", version: "1.
|
|
17
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.PrAutoMergeWorkflow", version: "1.33.0" };
|
|
18
18
|
constructor(project, options = {}) {
|
|
19
19
|
const actionVersions = (0, WorkflowActionVersions_1.resolveActionVersions)(options.actionVersions);
|
|
20
20
|
super(project, '.github/workflows/pr-auto-merge.yml', {
|
|
@@ -7,7 +7,7 @@ const javascript_1 = require("projen/lib/javascript");
|
|
|
7
7
|
const utils_1 = require("./utils");
|
|
8
8
|
const WorkflowActionVersions_1 = require("./WorkflowActionVersions");
|
|
9
9
|
class ProductionDeployWorkflow extends projen_1.YamlFile {
|
|
10
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.ProductionDeployWorkflow", version: "1.
|
|
10
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.ProductionDeployWorkflow", version: "1.33.0" };
|
|
11
11
|
constructor(project, options) {
|
|
12
12
|
const packageManager = project.package.packageManager;
|
|
13
13
|
const actionVersions = (0, WorkflowActionVersions_1.resolveActionVersions)(options.actionVersions);
|
|
@@ -35,7 +35,7 @@ const DEFAULT_GITHUB_OWNER = 'macedon-technologies';
|
|
|
35
35
|
* workflows that wire them together) is templated.
|
|
36
36
|
*/
|
|
37
37
|
class SoftwareFactoryFiles {
|
|
38
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.SoftwareFactoryFiles", version: "1.
|
|
38
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.SoftwareFactoryFiles", version: "1.33.0" };
|
|
39
39
|
constructor(project, options) {
|
|
40
40
|
const { repoName, actionVersions, attestationFiles } = options;
|
|
41
41
|
const githubOwner = options.githubOwner || DEFAULT_GITHUB_OWNER;
|
|
@@ -7,7 +7,7 @@ const javascript_1 = require("projen/lib/javascript");
|
|
|
7
7
|
const utils_1 = require("./utils");
|
|
8
8
|
const WorkflowActionVersions_1 = require("./WorkflowActionVersions");
|
|
9
9
|
class StagingDeployWorkflow extends projen_1.YamlFile {
|
|
10
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.StagingDeployWorkflow", version: "1.
|
|
10
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "@macedon-technologies/batman.StagingDeployWorkflow", version: "1.33.0" };
|
|
11
11
|
constructor(project, options) {
|
|
12
12
|
const packageManager = project.package.packageManager;
|
|
13
13
|
const actionVersions = (0, WorkflowActionVersions_1.resolveActionVersions)(options.actionVersions);
|
package/package.json
CHANGED
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"main": "lib/index.js",
|
|
50
50
|
"license": "Apache-2.0",
|
|
51
51
|
"stability": "stable",
|
|
52
|
-
"version": "1.
|
|
52
|
+
"version": "1.33.0",
|
|
53
53
|
"jest": {
|
|
54
54
|
"coverageProvider": "v8",
|
|
55
55
|
"testMatch": [
|
|
@@ -126,6 +126,7 @@
|
|
|
126
126
|
"release": "projen release",
|
|
127
127
|
"swamp:bootstrap": "projen swamp:bootstrap",
|
|
128
128
|
"test": "projen test",
|
|
129
|
+
"test:templates": "projen test:templates",
|
|
129
130
|
"test:watch": "projen test:watch",
|
|
130
131
|
"unbump": "projen unbump",
|
|
131
132
|
"upgrade": "projen upgrade",
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Architecture rules
|
|
2
|
+
|
|
3
|
+
A data-driven registry of architectural constraints, enforced by
|
|
4
|
+
`pnpm validate:architecture` and run as part of the pre-PR verification
|
|
5
|
+
workflow (`workflows/workflow-pre-pr-verify.yaml`) before the swamp factory
|
|
6
|
+
opens a PR. New rules are new entries in `rules.json`, not new code — the
|
|
7
|
+
engine (`check.ts`) only needs a new case in `evaluateRule()` when a rule
|
|
8
|
+
needs a genuinely new kind of check.
|
|
9
|
+
|
|
10
|
+
## Rule shape
|
|
11
|
+
|
|
12
|
+
Two `check.type`s are implemented: `forbidden-import` (whole-repo import-graph
|
|
13
|
+
check) and `required-companion` (diff-based co-change check).
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"id": "unique-id",
|
|
18
|
+
"description": "What this enforces and why.",
|
|
19
|
+
"enabled": true,
|
|
20
|
+
"severity": "low" | "medium" | "high" | "critical",
|
|
21
|
+
"check": {
|
|
22
|
+
"type": "forbidden-import",
|
|
23
|
+
"from": ["glob patterns selecting files this rule inspects"],
|
|
24
|
+
"forbid": ["glob patterns those files may not import from"]
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"id": "unique-id",
|
|
32
|
+
"description": "What this enforces and why.",
|
|
33
|
+
"enabled": true,
|
|
34
|
+
"severity": "low" | "medium" | "high" | "critical",
|
|
35
|
+
"check": {
|
|
36
|
+
"type": "required-companion",
|
|
37
|
+
"from": ["glob patterns selecting changed files that trigger the requirement"],
|
|
38
|
+
"requireOneOf": ["glob patterns -- at least one CHANGED file must match one of these"],
|
|
39
|
+
"exempt": ["optional -- from-files matching these globs don't trigger the requirement"]
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`required-companion` evaluates the set of files changed in the current diff
|
|
45
|
+
(`git diff --name-only --diff-filter=ACMR <baseRef>...HEAD`), not the whole
|
|
46
|
+
repo tree: if any changed file matches `from` (and doesn't match `exempt`) but
|
|
47
|
+
no changed file matches `requireOneOf`, that's a violation. The base ref
|
|
48
|
+
defaults to `origin/main` and can be overridden with the
|
|
49
|
+
`ARCHITECTURE_RULES_BASE_REF` environment variable. This means the checkout
|
|
50
|
+
running `pnpm validate:architecture` must have that base ref fetched and
|
|
51
|
+
resolvable (a shallow, single-branch checkout will make the check fail closed
|
|
52
|
+
with an error rather than silently reporting no violations) — make sure
|
|
53
|
+
whatever runs this task fetches enough history for `git diff <baseRef>...HEAD`
|
|
54
|
+
to succeed.
|
|
55
|
+
|
|
56
|
+
`from`/`requireOneOf`/`exempt` globs are matched against the paths `git
|
|
57
|
+
diff --name-only` reports, which are relative to the git repository's
|
|
58
|
+
top-level directory. This lines up with `from`'s own directory (the parent of
|
|
59
|
+
`architecture-rules/`) in the common case — a single project generated at the
|
|
60
|
+
repo root — but if `architecture-rules/` instead lives under a nested
|
|
61
|
+
subdirectory of a larger git repo, write globs relative to the git root, not
|
|
62
|
+
to that subdirectory.
|
|
63
|
+
|
|
64
|
+
**`required-companion` is a coverage check, not a correctness check.** It only
|
|
65
|
+
confirms that *some* changed file matches `requireOneOf` — it can't tell
|
|
66
|
+
whether that change is actually related to the triggering `from` change (a
|
|
67
|
+
trivial or unrelated edit to a file under `requireOneOf` satisfies the rule
|
|
68
|
+
just as well as a substantive one), and it can't tell whether a given `from`
|
|
69
|
+
change genuinely needed a companion at all (a pure refactor might not).
|
|
70
|
+
`exempt` covers *known, glob-expressible* exceptions, but not every false
|
|
71
|
+
positive is expressible as a glob — that judgment call still belongs to the
|
|
72
|
+
rule author (scoping `from`/`exempt`) and the reviewer (reading the companion
|
|
73
|
+
diff, not just trusting that the check passed). Also note that `main()`
|
|
74
|
+
fails the whole run on *any* violation regardless of `severity` — `severity`
|
|
75
|
+
is informational only, not a leniency lever — so start with a narrowly
|
|
76
|
+
scoped `from` (or `enabled: false`) and widen it as the convention proves
|
|
77
|
+
itself, the same guidance as for `forbidden-import`.
|
|
78
|
+
|
|
79
|
+
`enabled: false` rules are skipped (reported as "deferred") rather than
|
|
80
|
+
evaluated — use this for a rule you've named and described but don't yet
|
|
81
|
+
have a concrete convention to check.
|
|
82
|
+
|
|
83
|
+
## Current rules
|
|
84
|
+
|
|
85
|
+
None yet — `rules.json` ships empty. Add rules as your domain module
|
|
86
|
+
conventions solidify (e.g. an event-sourced/CQRS module layout under
|
|
87
|
+
`src/domains/<name>/{commands,events,aggregates,projections}/`).
|
|
88
|
+
|
|
89
|
+
## Adding a check type
|
|
90
|
+
|
|
91
|
+
`forbidden-import` (whole-repo import graph) and `required-companion`
|
|
92
|
+
(diff-based co-change) are the implemented `check.type`s. If a future rule
|
|
93
|
+
needs a data source neither provides (e.g. "every aggregate file must have a
|
|
94
|
+
matching events file", which is a repo-wide naming convention rather than
|
|
95
|
+
either an import-graph or a diff check), add a new `type` value, a matching
|
|
96
|
+
interface, and a case in `evaluateRule()` in `check.ts` — keep the engine
|
|
97
|
+
itself generic; rule-specific knowledge belongs in `rules.json`.
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic architecture-rule engine. Rules live entirely in rules.json — this
|
|
3
|
+
* file only knows how to evaluate the check "types" that rules can declare.
|
|
4
|
+
* Add a new rule by adding a rules.json entry; add a new check type by adding
|
|
5
|
+
* a case in evaluateRule().
|
|
6
|
+
*/
|
|
7
|
+
import * as fs from 'node:fs';
|
|
8
|
+
import * as path from 'node:path';
|
|
9
|
+
import { execFileSync } from 'node:child_process';
|
|
10
|
+
import rulesFile from './rules.json';
|
|
11
|
+
|
|
12
|
+
interface ForbiddenImportCheck {
|
|
13
|
+
type: 'forbidden-import';
|
|
14
|
+
// Glob patterns (relative to repo root) selecting the files this rule inspects.
|
|
15
|
+
from: string[];
|
|
16
|
+
// Glob patterns (relative to repo root) that "from" files may not import from.
|
|
17
|
+
forbid: string[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface RequiredCompanionCheck {
|
|
21
|
+
type: 'required-companion';
|
|
22
|
+
// Glob patterns selecting changed files that trigger the requirement.
|
|
23
|
+
from: string[];
|
|
24
|
+
// Glob patterns -- at least one CHANGED file must match one of these.
|
|
25
|
+
requireOneOf: string[];
|
|
26
|
+
// Optional -- 'from' files matching these globs don't trigger the requirement.
|
|
27
|
+
exempt?: string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Rule {
|
|
31
|
+
id: string;
|
|
32
|
+
description: string;
|
|
33
|
+
enabled: boolean;
|
|
34
|
+
severity: 'low' | 'medium' | 'high' | 'critical';
|
|
35
|
+
check: ForbiddenImportCheck | RequiredCompanionCheck;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface Violation {
|
|
39
|
+
ruleId: string;
|
|
40
|
+
severity: string;
|
|
41
|
+
message: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const REPO_ROOT = path.resolve(__dirname, '..');
|
|
45
|
+
const IGNORED_DIRS = new Set(['node_modules', '.git', '.swamp', 'cdk.out', 'lib', 'build', 'dist']);
|
|
46
|
+
const BASE_REF = process.env.ARCHITECTURE_RULES_BASE_REF || 'origin/main';
|
|
47
|
+
|
|
48
|
+
// Minimal glob -> RegExp: supports "*", "**", "**/" and literal path segments.
|
|
49
|
+
// No new dependency for this — the only pattern shapes rules.json ever needs
|
|
50
|
+
// are directory-prefix globs like "src/domains/*/commands/**".
|
|
51
|
+
function globToRegExp(glob: string): RegExp {
|
|
52
|
+
let out = '';
|
|
53
|
+
for (let i = 0; i < glob.length; i++) {
|
|
54
|
+
const c = glob[i];
|
|
55
|
+
if (c === '*' && glob[i + 1] === '*') {
|
|
56
|
+
i++;
|
|
57
|
+
if (glob[i + 1] === '/') {
|
|
58
|
+
out += '(?:.*/)?';
|
|
59
|
+
i++;
|
|
60
|
+
} else {
|
|
61
|
+
out += '.*';
|
|
62
|
+
}
|
|
63
|
+
} else if (c === '*') {
|
|
64
|
+
out += '[^/]*';
|
|
65
|
+
} else if (c === '?') {
|
|
66
|
+
out += '[^/]';
|
|
67
|
+
} else if ('.+^${}()|[]\\'.includes(c)) {
|
|
68
|
+
out += `\\${c}`;
|
|
69
|
+
} else {
|
|
70
|
+
out += c;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return new RegExp(`^${out}$`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function matchesAny(relFile: string, globs: string[]): boolean {
|
|
77
|
+
return globs.some((glob) => globToRegExp(glob).test(relFile));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function toRepoRelative(absPath: string): string {
|
|
81
|
+
return path.relative(REPO_ROOT, absPath).split(path.sep).join('/');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Files changed relative to baseRef, sourced from git rather than the whole-tree
|
|
85
|
+
// walk() below -- required-companion checks care about what a PR touched, not
|
|
86
|
+
// the full repo. Throws (rather than returning []) if baseRef cannot be resolved,
|
|
87
|
+
// so an unfetched base ref fails the check instead of silently reporting no violations.
|
|
88
|
+
function getChangedFiles(baseRef: string): string[] {
|
|
89
|
+
let output: string;
|
|
90
|
+
try {
|
|
91
|
+
output = execFileSync('git', ['diff', '--name-only', '--diff-filter=ACMR', `${baseRef}...HEAD`], {
|
|
92
|
+
cwd: REPO_ROOT,
|
|
93
|
+
encoding: 'utf8',
|
|
94
|
+
});
|
|
95
|
+
} catch (err) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
`architecture-rules: failed to compute the changed-file set against base ref "${baseRef}" -- ` +
|
|
98
|
+
`is it fetched and resolvable in this checkout? (${(err as Error).message})`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
return output.split('\n').map((line) => line.trim()).filter((line) => line.length > 0);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function walk(dir: string, acc: string[] = []): string[] {
|
|
105
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
106
|
+
if (IGNORED_DIRS.has(entry.name)) continue;
|
|
107
|
+
const full = path.join(dir, entry.name);
|
|
108
|
+
if (entry.isDirectory()) {
|
|
109
|
+
walk(full, acc);
|
|
110
|
+
} else if (entry.isFile() && (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx'))) {
|
|
111
|
+
acc.push(full);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return acc;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const RELATIVE_IMPORT_RE = /(?:import|export)\s+(?:[^'";]*?\bfrom\s+)?['"](\.[^'"]+)['"]/g;
|
|
118
|
+
|
|
119
|
+
function findRelativeImports(source: string): string[] {
|
|
120
|
+
const specs: string[] = [];
|
|
121
|
+
RELATIVE_IMPORT_RE.lastIndex = 0;
|
|
122
|
+
let match: RegExpExecArray | null;
|
|
123
|
+
while ((match = RELATIVE_IMPORT_RE.exec(source))) {
|
|
124
|
+
specs.push(match[1]);
|
|
125
|
+
}
|
|
126
|
+
return specs;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// An import spec resolves to a module, not a specific file extension, so a
|
|
130
|
+
// forbid glob is checked against the bare resolved path plus its .ts/index.ts
|
|
131
|
+
// variants.
|
|
132
|
+
function resolvedCandidates(fromFile: string, spec: string): string[] {
|
|
133
|
+
const resolved = toRepoRelative(path.normalize(path.join(path.dirname(fromFile), spec)));
|
|
134
|
+
return [resolved, `${resolved}.ts`, `${resolved}/index.ts`];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function evaluateForbiddenImport(rule: Rule): Violation[] {
|
|
138
|
+
const { from, forbid } = rule.check as ForbiddenImportCheck;
|
|
139
|
+
if (from.length === 0 || forbid.length === 0) return [];
|
|
140
|
+
|
|
141
|
+
const violations: Violation[] = [];
|
|
142
|
+
for (const file of walk(REPO_ROOT)) {
|
|
143
|
+
const relFile = toRepoRelative(file);
|
|
144
|
+
if (!matchesAny(relFile, from)) continue;
|
|
145
|
+
|
|
146
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
147
|
+
for (const spec of findRelativeImports(source)) {
|
|
148
|
+
const candidates = resolvedCandidates(file, spec);
|
|
149
|
+
if (candidates.some((candidate) => matchesAny(candidate, forbid))) {
|
|
150
|
+
violations.push({
|
|
151
|
+
ruleId: rule.id,
|
|
152
|
+
severity: rule.severity,
|
|
153
|
+
message: `${relFile} imports "${spec}", which resolves under a path forbidden by rule "${rule.id}"`,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return violations;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function evaluateRequiredCompanion(rule: Rule): Violation[] {
|
|
162
|
+
const { from, requireOneOf, exempt } = rule.check as RequiredCompanionCheck;
|
|
163
|
+
if (from.length === 0 || requireOneOf.length === 0) return [];
|
|
164
|
+
|
|
165
|
+
const changedFiles = getChangedFiles(BASE_REF);
|
|
166
|
+
const triggering = changedFiles.filter(
|
|
167
|
+
(file) => matchesAny(file, from) && !(exempt && matchesAny(file, exempt)),
|
|
168
|
+
);
|
|
169
|
+
if (triggering.length === 0) return [];
|
|
170
|
+
|
|
171
|
+
const satisfied = changedFiles.some((file) => matchesAny(file, requireOneOf));
|
|
172
|
+
if (satisfied) return [];
|
|
173
|
+
|
|
174
|
+
return [
|
|
175
|
+
{
|
|
176
|
+
ruleId: rule.id,
|
|
177
|
+
severity: rule.severity,
|
|
178
|
+
message: `changed file(s) ${triggering.join(', ')} match rule "${rule.id}"'s "from" patterns, but no changed file matches its "requireOneOf" patterns`,
|
|
179
|
+
},
|
|
180
|
+
];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function evaluateRule(rule: Rule): Violation[] {
|
|
184
|
+
switch (rule.check.type) {
|
|
185
|
+
case 'forbidden-import':
|
|
186
|
+
return evaluateForbiddenImport(rule);
|
|
187
|
+
case 'required-companion':
|
|
188
|
+
return evaluateRequiredCompanion(rule);
|
|
189
|
+
default:
|
|
190
|
+
throw new Error(`architecture-rules: unknown check.type "${(rule.check as { type: string }).type}" on rule "${rule.id}"`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function main(): number {
|
|
195
|
+
const rules = (rulesFile as { rules: Rule[] }).rules;
|
|
196
|
+
let evaluated = 0;
|
|
197
|
+
let deferred = 0;
|
|
198
|
+
const violations: Violation[] = [];
|
|
199
|
+
|
|
200
|
+
for (const rule of rules) {
|
|
201
|
+
if (!rule.enabled) {
|
|
202
|
+
deferred++;
|
|
203
|
+
console.log(`[deferred] ${rule.id}: ${rule.description}`);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
evaluated++;
|
|
207
|
+
violations.push(...evaluateRule(rule));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
console.log(`\narchitecture-rules: ${evaluated} rule(s) evaluated, ${deferred} deferred, ${violations.length} violation(s)`);
|
|
211
|
+
for (const violation of violations) {
|
|
212
|
+
console.error(` [${violation.severity}] ${violation.ruleId}: ${violation.message}`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return violations.length > 0 ? 1 : 0;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
process.exit(main());
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gate: fails unless every task in the named OpenSpec change's tasks.md is
|
|
3
|
+
* checked off. `openspec validate`/`openspec status` don't check this (an
|
|
4
|
+
* in-progress change is a normal, valid state) — this is the deterministic
|
|
5
|
+
* check the pre-pr pipeline needs before letting implementation proceed.
|
|
6
|
+
*/
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
|
|
9
|
+
interface OpenSpecChangeSummary {
|
|
10
|
+
name: string;
|
|
11
|
+
completedTasks: number;
|
|
12
|
+
totalTasks: number;
|
|
13
|
+
status: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function main(): number {
|
|
17
|
+
// pnpm's `-- <args>` forwarding (and projen's receiveArgs) can pass a
|
|
18
|
+
// literal "--" through as an argv token ahead of the real argument.
|
|
19
|
+
const slug = process.argv.slice(2).find((arg) => arg !== '--');
|
|
20
|
+
if (!slug) {
|
|
21
|
+
console.error('Usage: check-tasks-complete <change-slug>');
|
|
22
|
+
return 1;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const raw = execFileSync('openspec', ['list', '--json'], { encoding: 'utf8', shell: true });
|
|
26
|
+
const { changes } = JSON.parse(raw) as { changes: OpenSpecChangeSummary[] };
|
|
27
|
+
const change = changes.find((c) => c.name === slug);
|
|
28
|
+
|
|
29
|
+
if (!change) {
|
|
30
|
+
console.error(`OpenSpec change "${slug}" not found (openspec list --json)`);
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
if (change.status !== 'complete') {
|
|
34
|
+
console.error(
|
|
35
|
+
`OpenSpec change "${slug}" has incomplete tasks: ${change.completedTasks}/${change.totalTasks}`,
|
|
36
|
+
);
|
|
37
|
+
return 1;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
console.log(`OpenSpec change "${slug}": all ${change.totalTasks} tasks complete`);
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
process.exit(main());
|