agjan 0.0.20 → 0.0.22

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.
Files changed (59) hide show
  1. package/README.md +2 -1
  2. package/dist/adapters/claude-code.js +9 -3
  3. package/dist/auto.js +4 -0
  4. package/dist/baseline.js +11 -8
  5. package/dist/commands/check.js +65 -13
  6. package/dist/commands/gates.js +9 -1
  7. package/dist/commands/lint.js +16 -5
  8. package/dist/commands/new.js +4 -3
  9. package/dist/commands/setup.js +91 -81
  10. package/dist/config.js +24 -0
  11. package/dist/fix.js +13 -10
  12. package/dist/git.js +57 -9
  13. package/dist/launcher.js +9 -3
  14. package/dist/progress-view.js +35 -23
  15. package/dist/progress.js +103 -38
  16. package/dist/qa.js +18 -9
  17. package/dist/review-policy.js +12 -4
  18. package/dist/review.js +82 -35
  19. package/dist/schema.js +85 -0
  20. package/dist/scope.js +12 -4
  21. package/dist/tests-map.js +17 -11
  22. package/docs/guide.md +46 -7
  23. package/kit/domains/btp/domain.json +2 -2
  24. package/kit/hooks/guard.mjs +53 -9
  25. package/kit/skills/agjan-ask/SKILL.md +69 -0
  26. package/kit/skills/agjan-ask/references/sources.md +45 -0
  27. package/kit/skills/agjan-design/SKILL.md +13 -0
  28. package/kit/skills/agjan-fix/SKILL.md +1 -1
  29. package/kit/skills/agjan-spec/SKILL.md +7 -1
  30. package/kit/skills/agjan-spec/references/elicitation.md +135 -0
  31. package/kit/skills/btp-architect/SKILL.md +8 -3
  32. package/kit/skills/btp-architect/references/deployment.md +43 -0
  33. package/kit/skills/btp-architect/references/security.md +59 -4
  34. package/kit/skills/cap-developer/SKILL.md +20 -8
  35. package/kit/skills/cap-developer/references/agents.md +90 -0
  36. package/kit/skills/cap-developer/references/handlers.md +88 -9
  37. package/kit/skills/cap-developer/references/modeling.md +41 -0
  38. package/kit/skills/cap-developer/references/project-setup.md +57 -7
  39. package/kit/skills/cap-developer/references/services.md +172 -7
  40. package/kit/skills/cap-developer/references/testing.md +79 -6
  41. package/kit/skills/cap-developer/references/typescript.md +8 -7
  42. package/kit/skills/cap-developer/references/validation-security.md +74 -2
  43. package/kit/skills/fiori-developer/SKILL.md +22 -2
  44. package/kit/skills/fiori-developer/references/accessibility.md +65 -0
  45. package/kit/skills/fiori-developer/references/app-setup.md +10 -3
  46. package/kit/skills/fiori-developer/references/elements-cookbook.md +71 -0
  47. package/kit/skills/fiori-developer/references/elements.md +82 -9
  48. package/kit/skills/fiori-developer/references/freestyle-ts.md +27 -0
  49. package/kit/skills/fiori-developer/references/testing.md +5 -0
  50. package/kit/skills/fiori-developer/references/ui5-basics.md +34 -1
  51. package/kit/skills/qa-tester/SKILL.md +11 -4
  52. package/kit/skills/qa-tester/references/techniques.md +123 -0
  53. package/kit/skills/solution-reviewer/SKILL.md +10 -0
  54. package/kit/skills/solution-reviewer/references/defects.md +154 -0
  55. package/kit/templates/agents-block.md +3 -2
  56. package/kit/templates/agjan-ci.yml +3 -0
  57. package/package.json +1 -1
  58. package/schemas/config.schema.json +1 -1
  59. package/schemas/reviews.schema.json +1 -1
@@ -28,6 +28,29 @@ with `search_docs`.
28
28
  - 5xx errors reach the client as generic messages in production; never put internal
29
29
  details into them, and do not turn sanitizing off.
30
30
  - If an annotation can do the check, do not write it (see validation-security.md).
31
+ - CAP's own messages (`INVALID_FLOW_TRANSITION_SINGLE`, `ASSERT_*`) get the project's
32
+ texts in `_i18n/messages_en.properties` (and the other languages' files): the
33
+ framework's English file takes precedence over a project's `messages.properties`
34
+ (checked with `@sap/cds` 10.1).
35
+ - Messages take arguments: `req.reject(400, 'LIMIT_EXCEEDED', [max])` fills `{0}` of
36
+ `LIMIT_EXCEEDED=At most {0} days.` in `_i18n/messages.properties` (checked with `@sap/cds`
37
+ 10.1). Annotation messages (`@assert`) take none.
38
+
39
+ ## Messages that do not fail the request
40
+
41
+ A handler can tell the user something and still succeed; the messages travel in the
42
+ `sap-messages` response header. How Fiori elements shows them after an action (checked in
43
+ a browser with SAPUI5 1.145 on 2026-10-21):
44
+
45
+ | Call | Severity | Fiori elements shows |
46
+ |---|---|---|
47
+ | `req.notify('KEY')` | success | a toast that disappears by itself |
48
+ | `req.info('KEY')` | information | a dialog the user has to close |
49
+ | `req.warn('KEY')` | warning | a warning dialog the user has to close |
50
+
51
+ - A confirmation that something worked is `req.notify`; `info` and `warn` interrupt the
52
+ user and are for what they must read.
53
+ - Keys resolve like error codes, from `_i18n/messages.properties`, with arguments.
31
54
 
32
55
  ## Queries
33
56
 
@@ -38,6 +61,52 @@ with `search_docs`.
38
61
  - `INSERT.into`, `UPDATE(Entity, key).with(…)`, `DELETE.from` work the same way; on a
39
62
  service, `srv.run(query)` or the CRUD helpers `srv.read/create/update`.
40
63
 
64
+ ## Performance
65
+
66
+ - **No queries in a loop.** Read what the rows need in one query: `SELECT.from(Employees)
67
+ .where({ userId: { in: ids } })`, or with the parent in one go through a nested
68
+ projection: `SELECT.from(Employees, e => { e.name, e.team(t => { t.name }) })`
69
+ (checked with `@sap/cds` 10.1). Ten rows on a page must not mean ten round trips.
70
+ - **Read only the columns you use**, never `*` on wide entities.
71
+ - **OData reads are paged:** `cds.query.limit.max` (default 1000) caps every collection
72
+ read; the response then carries `@odata.nextLink`, and a larger `$top` is cut to the
73
+ maximum without an error (checked with `@sap/cds` 10.1). Code that reads a collection
74
+ over OData follows the next link; a page size per entity is `@cds.query.limit`.
75
+ - Database work in handlers is pushed down where it can be (`UPDATE … with` an expression,
76
+ a calculated element), not done row by row in JavaScript.
77
+
78
+ ## Work that runs later or elsewhere
79
+
80
+ - Calls to other systems that must happen when (and only when) the transaction commits,
81
+ and survive a crash (mails, events, a remote update), go through a queued service:
82
+ `const mail = cds.queued(await cds.connect.to('Mail')); await mail.send('send', data)`.
83
+ The message is stored in the same transaction (`cds.outbox.Messages`) and dispatched
84
+ after the commit, with retries (the persistent queue is the default; `cds.outboxed` is
85
+ the older name). Events to a message broker (`messaging.emit`) are queued that way too.
86
+ - **Events between apps:** declare the event in the service (`event Request.Decided { ID :
87
+ UUID; status : String; }`) and send it from a handler with `await this.emit(…)`; another
88
+ app connects to that service (`cds.requires` with its model) and subscribes,
89
+ `(await cds.connect.to('LeaveService')).on('Request.Decided', msg => …)`. With
90
+ `"messaging": true` in `cds.requires`, CAP uses file-based messaging in development
91
+ (`~/.cds-msg-box`, so two apps on one machine exchange events with no broker) and SAP
92
+ Event Mesh in production, queued in both (checked with cds-dk 10.2,
93
+ `cds env get requires.messaging`; the event declared, emitted and received in-process
94
+ with `@sap/cds` 10.1). The production broker is a btp decision.
95
+ - **Delayed or recurring work** (a nightly cleanup, a replication every 10 minutes):
96
+ `await srv.schedule('cleanup', { olderThan: '30d' }).every('1h')`, or `.after('10m')`, or
97
+ a cron string (`.every('0 2 * * *')`). It is queued like `cds.queued(srv).send()`, but as
98
+ **one** task per event name, stored and run once across all instances, so registering it
99
+ at every start is safe (in `server.js` at the project root,
100
+ `cds.on('served', async () => { … })`: CAP runs these listeners one after the other and
101
+ starts serving requests only after them; checked with `@sap/cds` 10.1); `.as('<name>')`
102
+ makes several tasks of one event,
103
+ `srv.unschedule('<name>')` removes one (CAP 10; a delayed task checked with `@sap/cds`
104
+ 10.1).
105
+ - `cds.spawn` runs a detached in-memory job: lost on a crash and run by every instance.
106
+ Only for work that is idempotent and may be dropped (a cache refresh).
107
+ - Choosing a broker (SAP Event Mesh, Kafka, Redis) or SAP's Job Scheduling service (jobs
108
+ managed outside the app) is a btp decision.
109
+
41
110
  ## Transactions
42
111
 
43
112
  - A request handler already runs in a transaction; do not wrap it in `cds.tx(req)`
@@ -48,10 +117,18 @@ with `search_docs`.
48
117
  you, and nested calls to other services do not join it.
49
118
  - Lock what you read before changing it in the same transaction:
50
119
  `SELECT(1).from(Orders, id).forUpdate()`.
51
- - For a status transition, make the update itself conditional on the expected state, in
52
- one round trip. It returns the number of changed rows (`@sap/cds` 10.1; projects that set
53
- `cds.features.legacy_db_results: false` get `{ affected }` instead); 0 means the state
54
- had changed. `.where()` and `.with()` may come in either order.
120
+ - Status transitions are a flow (services.md, Status-transition flows). Where two people
121
+ may decide the same record at the same moment, also make the update conditional on the
122
+ expected state, in one round trip, in the action's `on` handler:
123
+ `const n = await UPDATE(req.subject).where({ status_code: 'N' }).with({ status_code: 'A' })`,
124
+ then `if (!n) return req.reject(409, …)`. Awaited in a handler, it runs on the database
125
+ and returns the number of changed rows (`@sap/cds` 10.1; `cds.features.legacy_db_results:
126
+ false` gives `{ affected }` instead); 0 means the state had changed. `.where()` and
127
+ `.with()` may come in either order.
128
+ - Through a service (`srv.run`, `srv.update`), a write returns an array with `.affected`
129
+ (CAP 10): an array is always truthy, so test `.affected`, never the result itself. For a
130
+ draft-enabled entity, `.affected` was 1 whatever matched (`@sap/cds` 10.1.1, checked with
131
+ 0 and 2 rows): conditional updates go to the database as above.
55
132
 
56
133
  ## A handler file (TypeScript, checked with @sap/cds 10.1)
57
134
 
@@ -73,11 +150,9 @@ export class LeaveService extends cds.ApplicationService { override init() {
73
150
  if (overlap) return req.reject(400, 'ASSERT_OVERLAP', 'startDate') // target: the field
74
151
  })
75
152
 
76
- // A status transition: one conditional UPDATE, no SELECT before it.
77
- this.on(LeaveRequest.actions.approve, async req => {
78
- const [{ ID }] = req.params as { ID: string }[]
79
- const n = await UPDATE(LeaveRequests, ID).where({ status_code: 'N' }).with({ status_code: 'A' })
80
- if (!n) return req.reject(409, 'ONLY_NEW_REQUESTS') // key in _i18n/messages.properties
153
+ // The flow (leave-flows.cds) checks and sets the status; handlers add what it does not.
154
+ this.after(LeaveRequest.actions.approve, (_, req) => {
155
+ req.notify('REQUEST_APPROVED') // a success message: Fiori shows it as a toast
81
156
  })
82
157
 
83
158
  // A virtual field per row and user (for example to enable a Fiori button).
@@ -87,6 +162,10 @@ export class LeaveService extends cds.ApplicationService { override init() {
87
162
  }
88
163
  })
89
164
 
165
+ this.on(LeaveRequest.actions.decline, async req => {
166
+ await UPDATE(req.subject).with({ reason: req.data.reason }) // the action's parameter
167
+ })
168
+
90
169
  return super.init() // required: the generic handlers, auth, drafts
91
170
  }}
92
171
  ```
@@ -31,6 +31,11 @@ with `search_docs`.
31
31
  instead of plain strings; `temporal` for validity periods.
32
32
  - Combine aspects (`entity Orders : cuid, managed { … }`) rather than building a base
33
33
  entity hierarchy.
34
+ - A model that several projects share (types, aspects, code lists) is an npm package with
35
+ an `index.cds` at its root as its public entry: consumers write
36
+ `using { my.common.tagged } from '@my/common';` and CAP loads that file (checked with
37
+ cds-dk 10.2). Extend or annotate what it brings in your own files, never in the package.
38
+ Adding such a package is a design decision.
34
39
 
35
40
  ## Compositions or associations
36
41
 
@@ -76,6 +81,42 @@ entity LeaveTypes : CodeList { key code : String(10); }
76
81
  - `managed` only on the root of a composition tree; the children are covered by it.
77
82
  - Calculated elements (`= <expression>`) are computed on read and need no handler.
78
83
 
84
+ ## Types that hold their promise
85
+
86
+ Checked with `@sap/cds` 10.1 on 2026-10-21:
87
+
88
+ - The runtime checks input against the type: a value longer than `String(10)`, or with more
89
+ decimals than `Decimal(9,2)`, is rejected with 400 `ASSERT_DATA_TYPE` and the element as
90
+ target. Give strings a length that matches the business rule, and never re-check it in a
91
+ handler.
92
+ - Money and quantities are `Decimal(p, s)`, never `Double` (binary rounding), with the
93
+ currency or unit next to them (`currency : Currency`, annotated
94
+ `@Measures.ISOCurrency: currency_code`). OData returns decimals as strings (`"12.34"`):
95
+ clients and tests compare strings or parse them on purpose.
96
+ - `Date` has no time and no time zone (a leave day, a due date); `DateTime` is a UTC point
97
+ in time to the second, `Timestamp` finer (milliseconds or better). A business day that users enter is
98
+ a `Date`; converting it from a `DateTime` in another time zone shifts it by a day.
99
+ - Large texts are `LargeString`, files `LargeBinary` with `@Core.MediaType` (or the
100
+ attachments plugin, `cds add attachments`, a btp decision).
101
+
102
+ ## Changing a model that is already deployed
103
+
104
+ On SAP HANA (HDI) only some changes apply by themselves (CAP documentation, "HDI Schema
105
+ Evolution"; confirm details with `search_docs`):
106
+
107
+ | Change | Applied without data loss |
108
+ |---|---|
109
+ | Adding an element or entity, making a type parameter larger | yes |
110
+ | Renaming an element, association or entity | **no**: it becomes a DROP and an ADD |
111
+ | Deleting an element, changing its type, shortening a string, `null` to `not null` | **no**: needs manual migration |
112
+
113
+ - So in a project that is live, a rename or a delete of persisted data is a design
114
+ decision with a migration plan, named under Risks; prefer adding the new element and
115
+ migrating values, and keep old names that clients use.
116
+ - For entities whose schema keeps changing, `@cds.persistence.journal` makes `cds build`
117
+ write `.hdbmigrationtable` files (with a `last-dev/csn.json`), which must be committed;
118
+ incompatible steps arrive as commented statements to resolve by hand.
119
+
79
120
  ## Localized data
80
121
 
81
122
  - Mark translatable texts with `localized` (`title : localized String`); CAP generates
@@ -11,32 +11,70 @@ cds init <name> --nodejs # ESM ("type": "module"), db/, srv/, app/
11
11
  cd <name>
12
12
  cds add typescript # TypeScript is the default; then fix tsconfig.json (typescript.md)
13
13
  npm add -D @cap-js/cds-test # tests with cds.test
14
+ cds add lint # eslint.config.mjs with CAP's rules
15
+ npm add -D eslint @sap/eslint-plugin-cds
14
16
  cds watch # dev loop; reloads on every save
15
17
  ```
16
18
 
17
19
  - Initialize in a folder of its own or in the current one (`cds init` without a name).
18
20
  If the project already has a `package.json` (agjan set up first), run `cds init` in that
19
21
  folder and keep the existing dependencies.
22
+ - `cds lint` (ESLint with `@sap/eslint-plugin-cds`) checks the **model**: an empty
23
+ `@restrict` is an error, `grant: 'WRITEX'` a warning ("Did you mean 'WRITE'?"); its
24
+ other rules cover `to` and `where` of `@restrict`, CSV headers, reserved database words
25
+ and name casing (`auth-valid-restrict-to`, `valid-csv-header`, `no-db-keywords`, …). Checked with
26
+ cds-dk 10.2 and plugin 4.2: `cds add lint` writes only `eslint.config.mjs`, so add the
27
+ two dev dependencies yourself. Its recommended rules did not check handler files
28
+ (`.ts` or `.js`); `tsc` and the tests cover those. Where the project has
29
+ `eslint.config.mjs`, run `npx cds lint` after a model change.
20
30
  - **Never run `cds add sample`**: it scaffolds a whole demo app (bookshop) into the project.
21
31
  Use `cds add tiny-sample` only when the user asks for a minimal starter model.
22
32
  - Add features with `cds add <feature>` only when a task needs them: `hana`, `xsuaa`,
23
33
  `mta`, `approuter`, `data` (see below). Each is a design decision for the btp area.
24
34
  - Keep ESM: never remove `"type": "module"` or rewrite handlers as CommonJS to work around
25
- an import error.
35
+ an import error. CAP moves its samples and core packages to ESM too.
36
+ - Node.js: CAP 10 requires 22 and recommends 24 (`"engines"` in `package.json` and the
37
+ runtime of the deployment say the same).
38
+ - Upgrading CAP is a `kind: technical` feature of its own (below).
39
+
40
+ ## Upgrading CAP
41
+
42
+ `cds upgrade` of `@sap/cds-dk` (alpha in CAP 10) guides an upgrade between major versions.
43
+ How it behaved with cds-dk 10.2 (checked in a pseudo-terminal on a copy of the example;
44
+ CAP's own `cap-upgrade` agent skill describes other flags, so trust `cds help upgrade` of
45
+ the installed version):
46
+
47
+ - It is **interactive**: it proposes the dependency updates and asks, then asks to delete
48
+ the lock files and run `npm upgrade`, then analyzes the code. Without a terminal it stops
49
+ with exit code 2 and changes nothing: ask the user to run it in their terminal (Claude
50
+ Code: `! npx cds upgrade --report`).
51
+ - `--report` writes `.cds-upgrade/report.md` and `report.yaml`: findings in the code, and
52
+ rules it cannot detect by pattern ("Manual Review Recommended"), each with what to check
53
+ and how to fix it. Work through both; they are notes, not part of the commit.
54
+ - Accepting the dependency update rewrites the whole `package.json` (compact objects come
55
+ out expanded): review the diff, keep only the version changes if the project formats it
56
+ otherwise.
57
+ - `--fix` runs OpenRewrite for Java projects only.
58
+ - Then the project's tests, `typecheck`, `cds lint` and the UI tests, and the migration
59
+ guide of the major version for behavior no scan finds (handlers.md and services.md name
60
+ the CAP 10 changes these skills know).
26
61
 
27
62
  ## Layout
28
63
 
29
64
  | File | Content |
30
65
  |---|---|
31
66
  | `db/schema.cds` | the domain model, with a `namespace` |
32
- | `db/data/<namespace>-<Entity>.csv` | seed and test data |
67
+ | `db/data/<namespace>-<Entity>.csv` | code lists and configuration only: deployed to production |
68
+ | `test/data/<namespace>-<Entity>.csv` | demo and test rows: loaded in development and tests, never deployed |
33
69
  | `srv/<name>-service.cds` | one service per file: projections and actions |
34
70
  | `srv/<name>-service.ts` | its handlers; same base name, so CAP finds it (no `@impl`); `.js` in a JavaScript project |
35
71
  | `srv/<name>-constraints.cds` | input validation (`@mandatory`, `@assert…`) and helper `extend`s for it |
72
+ | `srv/<name>-flows.cds` | status-transition flows (`@flow.status`, `@from`, `@to`; services.md) |
36
73
  | `app/<app>/annotations.cds` | the Fiori annotations of one app (never in `srv/`) |
37
74
  | `app/services.cds` | `using from './<app>/annotations';` for every app |
38
- | `_i18n/i18n.properties` | labels used as `{i18n>Key}` in annotations |
39
- | `_i18n/messages.properties` | error messages, by the codes in `@assert` and `req.reject` |
75
+ | `_i18n/i18n.properties` | labels used as `{i18n>Key}` in annotations, each with its translator note (`#XFLD: …`) |
76
+ | `_i18n/messages_en.properties` | the project's texts for CAP's own messages (`INVALID_FLOW_TRANSITION_SINGLE`): the framework's English file wins over `messages.properties` (handlers.md, Errors) |
77
+ | `_i18n/messages.properties` | error messages, by the codes in `@assert` and `req.reject`; each text with its translator note (`#XMSG: …`, fiori-developer `ui5-basics.md`, Data and texts) |
40
78
  | `test/<topic>.test.ts` | tests with `cds.test` and `node --test` (`.test.js` in a JavaScript project) |
41
79
  | `tsconfig.json`, `tsconfig.cdsbuild.json` | TypeScript settings for the service and its build (typescript.md) |
42
80
  | `@cds-models/` | types generated by cds-typer; ignored by git, never edited |
@@ -78,9 +116,21 @@ cds watch # dev loop; reloads on every save
78
116
 
79
117
  ## Sample data
80
118
 
81
- - `cds add data --records <n> --keys-only` writes one CSV per entity with generated keys
82
- and empty other columns. It does **not** fill foreign keys (checked with cds-dk 10.1):
83
- fill them, and the content, yourself, and keep the generated keys and headers.
119
+ - **Where the CSV goes decides whether production gets it.** `db/data` is deployed with the
120
+ application, and on SAP HANA the deployer owns those tables' rows: every deployment
121
+ overwrites them, so a user's change to such a row is lost. Put only code lists and
122
+ configuration that users never change there. Demo and test rows (employees, orders,
123
+ requests) go into `test/data`, which `cds watch`, `cds serve` and `cds.test` load in the
124
+ development profile and no production build includes (checked with `@sap/cds` 10.1:
125
+ `cds env get requires.db.data` lists `db/data`, `db/csv`, `test/data` in development).
126
+ - A CSV once deployed to HANA stays owned even after the file is deleted; removing it needs
127
+ an entry in `db/undeploy.json` (`src/gen/**/*.hdbtabledata`), never one for tables.
128
+ - `cds add data --records <n> --keys-only --out test/data` writes one CSV per entity with
129
+ generated keys **and foreign keys** that point at the generated rows of the other files,
130
+ code-list codes from their enums, and empty other columns (checked with cds-dk 10.2;
131
+ 10.1 left the foreign keys empty). Fill the content; keep the headers, keys and foreign
132
+ keys as generated. `--filter <Entity>` limits it to some entities. Without `--out` the
133
+ files go to `db/data`, which production gets.
84
134
  - Small, readable data is often better written by hand: a few rows per entity, keys that
85
135
  tell a story (`employee`, `manager`, fixed UUIDs for rows that tests address).
86
136
  - Code lists (`Status`, types) are data too: their codes in a CSV, names and criticality.
@@ -32,7 +32,7 @@ service LeaveService {
32
32
  virtual null as canDecide : Boolean // per row and user, set in an after-READ handler
33
33
  } excluding { createdBy, modifiedBy } actions {
34
34
  action approve();
35
- action reject(reason : String(500) @mandatory);
35
+ action decline(reason : String(500) @mandatory); // not reject: every service has that method
36
36
  };
37
37
  @readonly entity LeaveTypes as projection on my.LeaveTypes; // code lists: read-only
38
38
  @readonly entity Status as projection on my.Status;
@@ -47,6 +47,36 @@ service LeaveService {
47
47
  redirected automatically (or mark one `@cds.redirection.target`).
48
48
  - UI annotations belong in `app/<app>/annotations.cds`, never in the service file.
49
49
 
50
+ ## What the client may not set (checked with @sap/cds 10.1)
51
+
52
+ - `@readonly` on an element: the client cannot set it at all. `@Core.Immutable`: the client
53
+ sets it on create, never after (a document number, a start date that must not move).
54
+ - Both are **dropped silently**: the request succeeds (201 or 200) and the stored value is
55
+ the server's. A status, an owner or a foreign key the server decides is `@readonly` and
56
+ filled in a handler; without it, any client can send `status_code: 'A'` with its create
57
+ (mass assignment). Test the stored value, not a 400 (testing.md).
58
+
59
+ ## Concurrent changes
60
+
61
+ - **Draft-enabled entities lock themselves:** while one user edits, the row is locked for
62
+ others until the draft is saved, cancelled or the lock times out (15 minutes by default,
63
+ `cds.fiori.draft_lock_timeout`). There is never more than one draft of a row.
64
+ - **Entities changed without a draft by several users** (an API, an action on a list) need
65
+ optimistic locking, or the last write silently wins: annotate the **element**,
66
+ `annotate Service.Orders with { modifiedAt @odata.etag; }`. Then an update without
67
+ `If-Match` gets 428 and one with an outdated ETag 412 (checked with `@sap/cds` 10.1). The
68
+ entity-level form `@odata.etag: modifiedAt` is accepted but does nothing.
69
+ - A status flow checks the state without a lock (below): where two people may decide the
70
+ same record at once, keep a conditional `UPDATE` in the action's handler (handlers.md).
71
+
72
+ ## Value help for code lists
73
+
74
+ An association to a `sap.common.CodeList` entity gets a value help in `$metadata` without
75
+ any annotation (CodeList carries `@cds.odata.valuelist`; checked with `@sap/cds` 10.1). Its
76
+ label is the entity's name and it shows only the code: give the code list a `@title`, and
77
+ annotate the field in the app for the name column and a dropdown (fiori-developer
78
+ `elements.md`).
79
+
50
80
  ## Actions and functions
51
81
 
52
82
  - Actions change data; functions only read. Unbound ones belong to the service; bound
@@ -54,9 +84,51 @@ service LeaveService {
54
84
  - Implement them like CRUD handlers: `this.on('approve', Orders, req => …)` for bound,
55
85
  `this.on('submitOrder', req => …)` for unbound. Keys of a bound instance are in
56
86
  `req.params`, the arguments in `req.data`.
87
+ - Do not name an action or function like a method of a CAP service (`reject`, `post`,
88
+ `emit`, `send`, `run`, `read`, `create`, `update`, `delete`, …): CAP cannot add its
89
+ typed method and warns on every start. The example's action is `decline`, labeled
90
+ "Reject" in the app.
57
91
  - Over OData, bound operations are called with the service prefix
58
92
  (`/Orders(ID)/OrdersService.approve`) and functions always with `()`.
59
93
  - Authorize them like entities: `@restrict` grants accept operation names.
94
+ - Parameters the user enters get labels and checks like elements:
95
+ `action decline(reason : String(500) @mandatory)`; the label for the Fiori dialog is an
96
+ annotation in the app (fiori-developer `elements.md`).
97
+
98
+ ## Status-transition flows (checked with @sap/cds 10.1)
99
+
100
+ A status that actions move along (new, approved, rejected) is modeled, not coded:
101
+
102
+ <!-- checked: srv/leave-flows.cds -->
103
+ ```cds
104
+ annotate LeaveService.LeaveRequests with @flow.status: status actions {
105
+ approve @from: #new @to: #approved;
106
+ decline @from: #new @to: #rejected;
107
+ }
108
+ ```
109
+
110
+ - `@flow.status` names the element: an enum, or an association to a code list whose key
111
+ `code` is an enum (as `Status` in the example); write the states as its enum symbols.
112
+ CAP makes it `@readonly`; give it a `default` for new rows.
113
+ - `@from` (one state or a list) and `@to` go on **bound actions**. Before the action CAP
114
+ checks the state: otherwise 409 with `INVALID_FLOW_TRANSITION_SINGLE` (`_MULTI` for a
115
+ list), whose text names the element and the symbols ("Action "approve" requires
116
+ "status_code" to be ["new"]"), so give it the project's text (handlers.md, Errors).
117
+ After the action's handlers CAP sets the `@to` state. `@to: $flow.previous` returns to
118
+ the state before (it records the transitions; see `search_docs`).
119
+ - Handlers add what the flow does not: an `after` handler for the message, an `on`
120
+ handler for the action's parameters (`reason`), checks of other conditions in `before`.
121
+ - For Fiori elements CAP adds `Core.OperationAvailable` (the `@from` states),
122
+ `Common.SideEffects` (the status) and the actions to `UI.Identification` **and**
123
+ `UI.LineItem` (hidden while a draft is edited), labeled with the action's `@title`, else
124
+ `{i18n><action>}`. A condition of your own (`canDecide`, the user's role too) must be
125
+ written as an expression, `@Core.OperationAvailable : ($self.canDecide)`: the
126
+ `$edmJson` form is replaced by the flow's (fiori-developer `elements.md`).
127
+ - Limits: only bound actions are flow-controlled, not create, update or delete; while a
128
+ draft is edited its actions are disabled.
129
+ - The check reads the row without a lock and the new state is written unconditionally
130
+ (the `@sap/cds` 10.1.1 source): two decisions at the same moment both succeed and the
131
+ last one wins. Where that can happen, add the conditional `UPDATE` (handlers.md).
60
132
 
61
133
  ## Drafts (Fiori editing)
62
134
 
@@ -79,13 +151,106 @@ service LeaveService {
79
151
  treat a `403` on a draft `PATCH` as likely.
80
152
  - `SELECT.from(Entity)` reads active data, `SELECT.from(Entity.drafts)` draft data. Do
81
153
  not filter on draft properties by hand.
154
+ - **Drafts can be bypassed (CAP 10 default):** a request without `IsActiveEntity` addresses
155
+ the active row, so a client with the `UPDATE` grant changes it directly, without a draft
156
+ (checked with `@sap/cds` 10.1: `PATCH /LeaveRequests(ID=…)` answered 200; `@assert`
157
+ still answered 400). Draft locks still apply. Rules that must hold for saved data
158
+ therefore belong in annotations or `before UPDATE` of the active entity, never only in
159
+ draft events, and an `UPDATE` grant is an API to the active rows, not only Edit in Fiori.
160
+ A plain `POST` still creates a draft unless `cds.fiori.draft_new_action` is set.
82
161
  - Introducing drafts changes how handlers run; it is a design decision.
83
162
 
84
163
  ## Remote services
85
164
 
86
- - Consume external APIs as CAP remote services: a `cds.requires` entry with the
87
- imported model and a BTP destination, then `cds.connect.to(…)`. Prefer this over
88
- calling the Cloud SDK directly; CAP handles connections, authentication and user
89
- propagation.
90
- - Query remote and local services with `cds.ql` and `srv.run(…)`: protocol-independent.
91
- `srv.send` with OData query options ties the code to one protocol.
165
+ Checked with `@sap/cds` 10.1 and cds-dk 10.2 in a lab: a consumer app importing the
166
+ example's `LeaveService` as `LeaveAPI`, once mocked and once running in its own process.
167
+
168
+ - **Import** the API: `cds import <file>.edmx --as cds` writes `srv/external/<API>.cds`
169
+ (and the `.edmx`), adds `cds.requires.<API>` with `kind` and `model`, and adds the SAP
170
+ Cloud SDK packages that production needs for destinations. A CAP package of the API
171
+ (`npm add …`) brings its model and mock data the same way.
172
+ - **A CAP app that provides an API** publishes it as such a package:
173
+ `cds export srv/<service>.cds --to apis/<name> --plugin` writes `index.cds`, the CSN, a
174
+ `cds-plugin.js` and a `package.json` that registers `cds.requires.<Service>` in every
175
+ app that installs it (CAP 10, checked with cds-dk 10.2). `--data` adds mock rows **from
176
+ the project's own data**: on the example it copied employees' names from `test/data`.
177
+ An API package carries invented rows only; check `data/` before it is published.
178
+ - **A consumption view** maps what the app needs into its own names, and the rest of the
179
+ model uses only that view, never the imported definitions:
180
+
181
+ ```cds
182
+ using { LeaveAPI as remote } from '../srv/external/LeaveAPI';
183
+
184
+ entity Types as projection on remote.LeaveTypes { code, name }; // only what is used
185
+
186
+ entity Notes : cuid {
187
+ text : String;
188
+ type : Association to Types;
189
+ }
190
+ ```
191
+
192
+ - `cds.connect.to('<API>')` with the exact name of `cds.requires` (or of the package's
193
+ service); query with `cds.ql` and `remote.run(…)`, protocol-independent. **Delegate**
194
+ reads of the view to the remote service: `this.on('READ', Types, req => remote.run(req.query))`;
195
+ expose the view `@readonly` in the service.
196
+ - **What crosses the boundary and what does not:** a read of the view works. But a local
197
+ entity's `$expand` to the remote entity answered **200 without the remote part**, and a
198
+ `$filter` on a remote field answered **500 "no such table"**: the database cannot join
199
+ what lives in another system. Where the UI lists local rows with remote fields (a column,
200
+ a filter, a sort), the data must be **federated**, close to the app. Tag the
201
+ consumption view with CAP's intent annotation, `@federated entity Types as projection on …`,
202
+ and decide per environment how (CAP documentation, "CAP-level Data Federation"):
203
+ service-level **replication** into a local table, or, on SAP HANA, synonyms to the
204
+ provider's tables (the plugin `cds-federation-synonyms`, installed from GitHub in SAP's
205
+ reCAP 2026 hands-on, so early). CAP's sample replicates with generic code that it enables
206
+ outside production only. Replication by hand: `annotate Types with @cds.persistence.table;` and
207
+ `UPSERT` the remote rows into it, `await UPSERT(await remote.run(SELECT.from(Types))).into(Types)`
208
+ (then the expand and the filter answered 200 with data), on a schedule
209
+ (`srv.schedule(…).every(…)`, handlers.md), reading only what changed where the remote
210
+ entity has a change timestamp (`where modifiedAt > <last>`). Delegate for value
211
+ helps and single reads where freshness matters; replicate for joins and when the app must
212
+ work while the remote system is down. Which one is a design decision per entity.
213
+ - **The in-process mock hides this:** `cds watch` (and `cds.test` started with
214
+ `cds.test('serve', 'all', '--with-mocks', '--in-memory?')`) puts the remote entities into
215
+ the local database, so the expand and the filter above both "worked" there. Without
216
+ `--with-mocks`, `cds.test` fails with "No credentials configured". Test the integration
217
+ at least once against the API in a process of its own: `cds mock <API>` in one terminal
218
+ and the app in another (CAP documentation, "Consuming Services"), or credentials with a
219
+ `url` in a development profile. The mock's rows come from
220
+ `srv/external/data/<API>-<Entity>.csv`; project only columns it fills.
221
+ - Locally, CAP 10 called the remote with URL credentials through Node's `fetch` without the
222
+ Cloud SDK packages; in BTP, destinations need them (btp-architect).
223
+ - Writes to the remote system that need no answer go through `cds.queued(remote)`
224
+ (handlers.md), so they are sent after the commit, with retries.
225
+ - Extend a remote entity only with unmanaged associations and virtual or calculated
226
+ elements; it has no columns of its own here.
227
+
228
+ ## Other protocols
229
+
230
+ - `@odata` is the default; `@rest` and `@hcql` serve the same service in other protocols
231
+ (`annotate CatalogService with @odata @rest;`).
232
+ - **`@mcp`** with the plugin `@cap-js/mcp` (beta in the CAP release of June 2026) serves a
233
+ service to AI agents. Only when the spec asks for it; it is a design decision. Checked
234
+ with `@cap-js/mcp` 1.5.0 on a copy of the example:
235
+ - **`annotate LeaveService with @mcp;` alone replaces OData**: the service was served at
236
+ `/mcp/leave` only and `/odata/v4/leave` answered 404, so the Fiori app broke. Name every
237
+ protocol: `annotate LeaveService with @odata @mcp;`.
238
+ - Tools: `describe` (the model) and `query`, which takes a CQL `SELECT` (an `UPDATE` or
239
+ `DELETE` was refused by its parser). The bound actions (`approve`, `decline`) were not
240
+ offered, also not with `cds.mcp.per_action_tool`; the `call` tool is for the service's
241
+ unbound actions and functions.
242
+ - Authorization holds: the service's `@requires` answers `initialize` with 401
243
+ (anonymous) or 403 (no role), and `@restrict` filters the rows of `query` as over
244
+ OData (the employee saw one request, the team's manager two, another manager none).
245
+ Draft entities and entities outside the service were rejected. But `query` follows
246
+ associations like `$filter` does: see validation-security.md, "What paths can reach".
247
+ - **In development `cds watch` writes the service into the user's Claude Code
248
+ configuration** (`~/.claude.json`, `mcpServers` entry `cds:<Service>`, with a Basic
249
+ authorization header of the mocked user `alice` unless `cds.mcp.autowire` names
250
+ another) and OpenCode's, and removes it on exit (the plugin's source). In an agjan
251
+ project set `"cds": { "mcp": { "autowire": false } }`: the agents' MCP servers are
252
+ agjan's (`agjan sync`), and an agent must not read the app's data through it unasked.
253
+ - Prefer a **service of its own for agents**, as CAP's guide does (`@mcp service
254
+ BooksService { … }`): `@readonly` projections with only the entities and fields the
255
+ use case needs, its own `@requires`, small projections for association targets.
256
+ - Doc comments (`/** … */`) and `@mcp.instructions` give the agent its context.
@@ -17,7 +17,7 @@ import assert from 'node:assert/strict'
17
17
  const { GET, POST, axios } = cds.test(import.meta.dirname + '/..')
18
18
  axios.defaults.validateStatus = () => true // assert on status codes, not exceptions
19
19
  const as = (user: string) => ({ auth: { username: user, password: user } })
20
- const ID = '7a1e0c1a-0001-4c2b-9a5f-000000000001' // a row from db/data, status New
20
+ const ID = '7a1e0c1a-0001-4c2b-9a5f-000000000001' // a row from test/data, status New
21
21
  const requests = '/odata/v4/leave/LeaveRequests'
22
22
 
23
23
  // Draft-enabled: a new request is a draft first; the checks run when it is activated.
@@ -46,13 +46,17 @@ describe('LeaveService', () => {
46
46
  it('TLR-AC6: only a manager approves, and only once', async () => {
47
47
  const url = `${requests}(ID=${ID},IsActiveEntity=true)/LeaveService.approve`
48
48
  assert.equal((await POST(url, {}, as('employee'))).status, 403)
49
- assert.equal((await POST(url, {}, as('manager'))).status, 204)
50
- assert.equal((await POST(url, {}, as('manager'))).status, 409)
49
+ const approved = await POST(url, {}, as('manager'))
50
+ assert.equal(approved.status, 204)
51
+ assert.deepEqual(JSON.parse(approved.headers['sap-messages']).map((m: { message: string }) => m.message), ['The request is approved.'])
52
+ const again = await POST(url, {}, as('manager')) // the flow: approve only from New
53
+ assert.equal(again.status, 409)
54
+ assert.equal(again.data.error.message, 'Only new requests can be approved or rejected.')
51
55
  })
52
56
  it('TLR-AC7: a manager of another team can neither approve nor reject', async () => {
53
57
  const other = `${requests}(ID=7a1e0c1a-0001-4c2b-9a5f-000000000002,IsActiveEntity=true)/LeaveService`
54
58
  assert.equal((await POST(`${other}.approve`, {}, as('manager2'))).status, 403)
55
- assert.equal((await POST(`${other}.reject`, { reason: 'no' }, as('manager2'))).status, 403)
59
+ assert.equal((await POST(`${other}.decline`, { reason: 'no' }, as('manager2'))).status, 403)
56
60
  })
57
61
  })
58
62
  ```
@@ -75,6 +79,72 @@ describe('LeaveService', () => {
75
79
  the whole draft choreography, including editing an active row).
76
80
  - `cds.test` keeps the console quiet during tests; write diagnostics to a file if needed.
77
81
 
82
+ ## Choosing the runner
83
+
84
+ CAP announced in its June 2026 release that it moves its own test suites to Node's runner
85
+ and Vitest, moves its samples and core packages to ESM, and will remove Jest support from
86
+ `cds.test` (`@cap-js/cds-test` 1.0 supports Vitest and Chai 6). `cds init` creates ESM
87
+ projects, which Jest handles badly.
88
+
89
+ - **New projects:** Node's runner (`node --test`, or `cds test`, a thin wrapper around it),
90
+ as in the example: no extra dependency. Vitest where the team wants its watch mode or
91
+ coverage report. **Never Jest.**
92
+ - **A project on Jest** keeps it until the team decides: porting the suite to Vitest is
93
+ technical work of its own (`/agjan-spec`, `kind: technical`), not part of a feature.
94
+ Under Jest, `cds.test`'s `expect` is only a lookalike of Chai's that lacks some APIs;
95
+ use Jest's own `expect` there.
96
+ - **Vitest** (checked with Vitest 5.0 and the example's tests): the file stays the same
97
+ except that `describe` and `it` come from `vitest`; `node:assert` works there too. Keep
98
+ the Playwright specs out and switch TypeScript mode on in `vitest.config.ts`, run with
99
+ `npx vitest run`:
100
+
101
+ ```ts
102
+ import { defineConfig } from 'vitest/config'
103
+
104
+ export default defineConfig({
105
+ test: {
106
+ include: ['test/**/*.test.ts'], // test/ui holds the Playwright specs
107
+ env: { CDS_TYPESCRIPT: 'true' }, // CAP loads .ts handlers only in TypeScript mode
108
+ },
109
+ })
110
+ ```
111
+
112
+ - **Without TypeScript mode, CAP serves the service without its `.ts` handlers and says
113
+ nothing:** the tests of annotations pass and those of handler rules fail (checked under
114
+ both runners: 5 of the example's 8 tests passed). A failing handler test in a TypeScript
115
+ project is checked with the project's test command, never with a bare `node --test` or
116
+ `vitest` on the file.
117
+ - In JavaScript, `cds.test` also provides `describe`, `it`, `beforeAll` and `expect` as
118
+ globals for every runner, so a file runs under each unchanged. TypeScript has no types
119
+ for those globals: import them from the runner, as above.
120
+
121
+ ## Tests an expert adds
122
+
123
+ Beyond the happy path of each AC (each checked with `@sap/cds` 10.1):
124
+
125
+ - **Read-only input**: send what the client must not set and assert the stored value; CAP
126
+ drops it without an error:
127
+
128
+ <!-- checked: test/leaves.test.ts -->
129
+ ```ts
130
+ it('TLR-AC10: an employee cannot set the status of a request; it starts as New', async () => {
131
+ const { status, data } = await create({ startDate: '2026-12-01', endDate: '2026-12-02', type_code: 'vacation', status_code: 'A' }, 'employee')
132
+ assert.equal(status, 201) // read-only input is dropped, not rejected
133
+ assert.equal(data.status_code, 'N')
134
+ })
135
+ ```
136
+
137
+ - **Messages**: a success message arrives in the `sap-messages` header:
138
+ `JSON.parse(res.headers['sap-messages'])[0].message`.
139
+ - **Boundaries**: one character over a `String(n)`, one decimal too many, the first and the
140
+ last allowed date, an empty string where `@mandatory` applies; each gets 400 with the
141
+ element as `target`.
142
+ - **Concurrency**: an action twice (the second answers 409, above); with `@odata.etag`, an
143
+ update without `If-Match` (428) and with an old ETag (412); in a draft app, a second user
144
+ opening a row another user edits.
145
+ - **Paging**: a collection larger than `cds.query.limit.max` comes back with
146
+ `@odata.nextLink`; code that reads all rows follows it.
147
+
78
148
  ## Rules
79
149
 
80
150
  - Call `cds.test(…)` **first** in the file, before touching `cds.env` or other `cds`
@@ -88,8 +158,11 @@ describe('LeaveService', () => {
88
158
  and an anonymous request (401).
89
159
  - Mock as little as possible; the more is mocked, the less is tested. Mocking module
90
160
  caches or timers can break the CAP server.
91
- - Use the project's runner (`node:test`, jest, mocha, vitest); `cds.test` works with all
92
- of them.
161
+ - Use the project's runner (section "Choosing the runner"); a new project gets Node's
162
+ runner or Vitest, never Jest.
163
+ - Compare what matters, not whole responses (ids and timestamps change): the error `code`
164
+ and `target`, the fields the AC names. Where a status may differ from the expected one,
165
+ let the assertion show why: `assert.equal(status, 400, JSON.stringify(data))`.
93
166
  - agjan: every AC of a task gets at least one test whose name starts with its id, and
94
167
  every validation gets a test of its failure case.
95
168
  - If the project configures test results (`verify.cap.results`), the test command must