agjan 0.0.6 → 0.0.7

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/docs/guide.md CHANGED
@@ -114,7 +114,11 @@ records (step, review, approval, amendment, fix record):
114
114
  Both are local (`.agjan/` is not committed).
115
115
 
116
116
  `npx agjan progress` regenerates the pages and prints the overview; `--open` opens the
117
- HTML page in your browser. Units already on the base branch appear in the overview but
117
+ HTML page in your browser. A unit shows **your turn** when it waits for you: a gate to
118
+ approve, an amendment, or the next skill to start (`/agjan-design`, `/agjan-build`,
119
+ `/agjan-verify`; a skill counts as running once it logged its start). A verified feature
120
+ is **done**: trying it locally, manual checks and the pull request are optional next
121
+ steps. `npx agjan status --done` prints just that block. Units already on the base branch appear in the overview but
118
122
  get no new page on another branch.
119
123
 
120
124
  ## Small changes and existing applications
@@ -226,15 +230,24 @@ settings remove the routine prompts without giving up control:
226
230
  "agent": { "allow": ["npx agjan", "npm test", "git status", "git diff", "git log", "git add", "git commit"] }
227
231
  ```
228
232
 
229
- agjan's guard hook approves a command without a prompt when it is a **single simple
230
- command** starting with a listed entry: `npm test` and `git commit -m "…"` run, but
231
- `npm test && git push`, pipes, redirections and `$(…)` still ask. `agjan approve`,
233
+ agjan's guard hook approves a command, or a chain (`&&`, `||`, `;`, `|`), without a
234
+ prompt when **every part** starts with a listed entry, is a read-only command (`ls`,
235
+ `cat`, `head`, `tail`, `grep`, `wc`, `sort`, `uniq`, `pwd`, `echo`, `sed -n`) or a `cd`
236
+ inside the project, and at least one part is listed. So
237
+ `git add … && git commit -m "…" && npx agjan log … 2>&1 | tail -5` runs, but
238
+ `npm test && git push`, `$(…)`, backticks, background jobs and redirects into files still
239
+ ask (only `2>&1`, `2>/dev/null` and `>/dev/null` are accepted). `agjan approve`,
232
240
  `accept` and `reject` are always denied, listed or not. Works in Claude Code and the
233
241
  Copilot CLI (both run the hook). Edit the list like any configuration: a change is a
234
242
  policy change that `check` reports and the PR shows.
235
- - **File changes (Copilot):** start with `copilot --allow-tool write`, or answer the first
236
- edit prompt with "don't ask again for file operations in this repo". agjan's scope
237
- check, the pre-commit hook and the reviewer cover what the agent changes.
243
+ - **File changes: `agent.allow_edits`** (`init` asks; `--agent-allow-edits`). With `true`,
244
+ the guard approves the hosts' file edit tools for files inside the project without a
245
+ prompt. Policy files (`agjan.config.json`, `.github/hooks/`, `.github/agents/`,
246
+ `.github/workflows/`, `.claude/settings.json`, the MCP configuration) still ask. agjan's
247
+ scope check, the pre-commit hook and the reviewer cover what the agent changes.
248
+ - **agjan's records are never edited by hand:** the guard always denies the edit tools on
249
+ `approvals.json`, `reviews.json`, `review.md`, `log.jsonl`, `progress.md`, the fix
250
+ records and `baseline.json`; agjan writes them.
238
251
 
239
252
  **Script edits are denied.** Agents sometimes edit files with small scripts
240
253
  (`python3 - <<EOF … open(p, 'w')`, `sed -i`, `cat > file <<EOF`) instead of their edit
@@ -10,20 +10,28 @@
10
10
  * `agent.script_edits` to "allow" (design decision 63).
11
11
  *
12
12
  * It also approves, without a prompt, shell commands the project lists in `agent.allow`
13
- * of agjan.config.json (opt-in, design decision 61): a single simple command that starts
14
- * with a listed command. Anything with `;`, `&&`, `|`, `$(…)`, backticks or redirections is
15
- * left to the host's own prompt. Denying always comes first.
13
+ * of agjan.config.json (opt-in, design decisions 61 and 68): a command, or a chain of
14
+ * commands (`&&`, `||`, `;`, `|`), in which every part starts with a listed command or is a
15
+ * built-in read-only command (ls, cat, head, …) or a `cd` inside the project. Only the
16
+ * redirects 2>&1, 2>/dev/null and >/dev/null are accepted; `$(…)`, backticks, other
17
+ * redirects and unknown commands are left to the host's own prompt.
18
+ *
19
+ * File edit tools (Copilot `edit`/`create`, Claude Code `Edit`/`Write`/`MultiEdit`): hand
20
+ * edits of agjan's records (approvals.json, reviews.json, review.md, log.jsonl, …) are always
21
+ * denied. With `agent.allow_edits: true` other files inside the project are approved,
22
+ * except the policy files (configuration, hooks, agents, workflows), which stay with the
23
+ * host's prompt. Denying always comes first.
16
24
  *
17
25
  * Reads the host's payload on stdin and answers in the host's format:
18
- * - GitHub Copilot: { toolName, toolArgs: { command } } -> { permissionDecision, permissionDecisionReason }
19
- * - Claude Code: { tool_name, tool_input: { command } } -> { hookSpecificOutput: { … } }
26
+ * - GitHub Copilot: { toolName, toolArgs: { command | path } } -> { permissionDecision, permissionDecisionReason }
27
+ * - Claude Code: { tool_name, tool_input: { command | file_path } } -> { hookSpecificOutput: { … } }
20
28
  * Prints nothing (default behavior) for any other command or unreadable input.
21
29
  *
22
30
  * Deliberately self-contained and dependency-free: it runs before every tool call.
23
31
  */
24
32
 
25
33
  import { readFileSync, realpathSync } from 'node:fs';
26
- import { join } from 'node:path';
34
+ import { isAbsolute, join, relative, resolve } from 'node:path';
27
35
  import { fileURLToPath } from 'node:url';
28
36
 
29
37
  const REASON =
@@ -75,20 +83,120 @@ function unquoted(command) {
75
83
  return command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, 'Q');
76
84
  }
77
85
 
78
- /** Characters that chain, substitute or redirect: such commands are never auto-approved. */
79
- const COMPOUND = /[;&|`$<>(){}\n\r]/;
86
+ /** Read-only commands a chain may contain besides the allow list (design decision 68). */
87
+ const READ_ONLY = new Set(['ls', 'cat', 'head', 'tail', 'grep', 'wc', 'sort', 'uniq', 'pwd', 'echo', 'true', 'date']);
88
+ const SAFE_REDIRECT = /(?:^|\s)(?:2>&1|[12&]?>\s*\/dev\/null)(?=\s|$)/g;
89
+
90
+ /**
91
+ * Splits a command line into its simple commands at &&, ||, ; and | outside quotes.
92
+ * Null when it contains what the guard never approves: $(…), backticks, parentheses,
93
+ * braces, input redirects or heredocs, background jobs, or a redirect into a file.
94
+ */
95
+ export function splitChain(command) {
96
+ const parts = [];
97
+ let current = '';
98
+ let quote = null;
99
+ for (let i = 0; i < command.length; i++) {
100
+ const c = command[i];
101
+ if (quote) {
102
+ // Inside double quotes the shell still runs $(…) and backticks.
103
+ if (quote === '"' && (c === '`' || (c === '$' && command[i + 1] === '('))) return null;
104
+ if (c === '\\' && quote === '"') {
105
+ current += c + (command[i + 1] ?? '');
106
+ i++;
107
+ continue;
108
+ }
109
+ if (c === quote) quote = null;
110
+ current += c;
111
+ continue;
112
+ }
113
+ if (c === "'" || c === '"') {
114
+ quote = c;
115
+ current += c;
116
+ continue;
117
+ }
118
+ if ('`(){}<'.includes(c) || (c === '$' && command[i + 1] === '(')) return null;
119
+ const two = command.slice(i, i + 2);
120
+ if (two === '&&' || two === '||') {
121
+ parts.push(current);
122
+ current = '';
123
+ i++;
124
+ continue;
125
+ }
126
+ if (c === ';' || c === '|' || c === '\n') {
127
+ parts.push(current);
128
+ current = '';
129
+ continue;
130
+ }
131
+ if (c === '&' && command[i - 1] !== '>' && command[i + 1] !== '>') return null; // background job
132
+ current += c;
133
+ }
134
+ if (quote) return null;
135
+ parts.push(current);
136
+ const cleaned = [];
137
+ for (const part of parts) {
138
+ const text = part.replace(SAFE_REDIRECT, ' ').trim();
139
+ if (!text) continue;
140
+ if (/>/.test(unquoted(text))) return null; // a redirect into a file
141
+ cleaned.push(text.replace(/\s+/g, ' '));
142
+ }
143
+ return cleaned.length ? cleaned : null;
144
+ }
80
145
 
81
- /** Whether `command` is one simple command starting with an entry of the allow list. */
82
- export function allowed(command, allow) {
83
- if (!Array.isArray(allow) || COMPOUND.test(command)) return false;
84
- const normalized = command.trim().replace(/\s+/g, ' ');
146
+ function listed(part, allow) {
85
147
  return allow.some((entry) => {
86
148
  if (typeof entry !== 'string' || entry.trim() === '') return false;
87
149
  const prefix = entry.trim().replace(/\s+/g, ' ');
88
- return normalized === prefix || normalized.startsWith(`${prefix} `);
150
+ return part === prefix || part.startsWith(`${prefix} `);
89
151
  });
90
152
  }
91
153
 
154
+ function readOnly(part, root) {
155
+ const [word, ...rest] = part.split(' ');
156
+ if (word === 'cd') {
157
+ const target = rest.join(' ').replace(/^["']|["']$/g, '');
158
+ if (!target || rest.length > 1) return false;
159
+ const where = isAbsolute(target) ? relative(root, target) : target;
160
+ return !where.split(/[\\/]/).includes('..') && !isAbsolute(where);
161
+ }
162
+ if (word === 'sed') return /(?:^|\s)-n\b/.test(part) && !/(?:^|\s)-[a-zA-Z]*i\b|--in-place/.test(part);
163
+ return READ_ONLY.has(word);
164
+ }
165
+
166
+ /** Whether `command` (one command or a chain) is approved by the allow list (decision 68). */
167
+ export function allowed(command, allow, root = process.cwd()) {
168
+ if (!Array.isArray(allow) || allow.length === 0) return false;
169
+ const parts = splitChain(command);
170
+ if (!parts) return false;
171
+ // At least one part must be on the list: a chain of read-only commands alone is left to the host.
172
+ return parts.every((part) => listed(part, allow) || readOnly(part, root)) && parts.some((part) => listed(part, allow));
173
+ }
174
+
175
+ const RECORD_REASON =
176
+ 'agjan writes this file itself (approvals, reviews, logs, progress, fix records, baseline). Never edit it by hand; use the agjan commands.';
177
+
178
+ /** agjan's records inside docs/agjan/: never edited by an agent's edit tool. */
179
+ const RECORD = /^docs\/agjan\/(?:.+\/)?(?:approvals\.json|reviews\.json|review\.md|log\.jsonl|progress\.md|report\.md|fix\.json|fix\.md)$|^docs\/agjan\/baseline\.json$/;
180
+
181
+ /** Files that define the rules: edits stay with the host's own prompt even with allow_edits. */
182
+ const POLICY = /^(?:agjan\.config\.json|agjan\.lock\.json|\.mcp\.json|\.vscode\/mcp\.json|\.claude\/settings(?:\.local)?\.json|\.claude\/agents\/.*|\.github\/(?:hooks|agents|workflows)\/.*|\.github\/CODEOWNERS)$/;
183
+
184
+ const EDIT_TOOLS = new Set(['edit', 'create', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
185
+
186
+ /** The guard's answer for a file edit tool call, or null. */
187
+ function decideEdit(payload, config, root) {
188
+ const args = payload.toolArgs ?? payload.tool_input ?? {};
189
+ const target = args.path ?? args.file_path ?? args.notebook_path;
190
+ if (typeof target !== 'string' || target === '') return null;
191
+ const rel = relative(root, resolve(root, target)).split('\\').join('/');
192
+ const inside = rel !== '' && !rel.startsWith('../') && rel !== '..' && !isAbsolute(rel);
193
+ if (inside && RECORD.test(rel)) return answer(payload, 'deny', RECORD_REASON);
194
+ if (config?.agent?.allow_edits === true && inside && !POLICY.test(rel)) {
195
+ return answer(payload, 'allow', 'agent.allow_edits in agjan.config.json');
196
+ }
197
+ return null;
198
+ }
199
+
92
200
  function answer(payload, decision, reason) {
93
201
  if (payload.tool_input !== undefined) {
94
202
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision, permissionDecisionReason: reason } };
@@ -100,7 +208,8 @@ function answer(payload, decision, reason) {
100
208
  * The guard's answer for a payload: deny, allow (listed in `config.agent.allow`), or null
101
209
  * (the host decides). `config` is the project's agjan.config.json.
102
210
  */
103
- export function decide(payload, config = {}) {
211
+ export function decide(payload, config = {}, root = process.env.CLAUDE_PROJECT_DIR || process.cwd()) {
212
+ if (EDIT_TOOLS.has(payload?.toolName ?? payload?.tool_name)) return decideEdit(payload, config, root);
104
213
  const command = payload?.toolArgs?.command ?? payload?.tool_input?.command;
105
214
  if (typeof command !== 'string') return null;
106
215
  if (HUMAN_ONLY.test(command)) return answer(payload, 'deny', REASON);
@@ -108,7 +217,7 @@ export function decide(payload, config = {}) {
108
217
  if (config?.agent?.script_edits !== 'allow' && SCRIPT_EDITS.some((matches) => matches(command))) return answer(payload, 'deny', EDIT_REASON);
109
218
  const allow = config?.agent?.allow ?? [];
110
219
  const shell = /^(bash|powershell|shell)$/i.test(payload.toolName ?? payload.tool_name ?? '');
111
- if (shell && allowed(command, allow)) return answer(payload, 'allow', 'listed in agent.allow of agjan.config.json');
220
+ if (shell && allowed(command, allow, root)) return answer(payload, 'allow', 'listed in agent.allow of agjan.config.json');
112
221
  return null;
113
222
  }
114
223
 
@@ -25,7 +25,9 @@ review due again: `npx agjan status` lists it; do it before the final review.
25
25
  ## 3. Baseline
26
26
 
27
27
  If the feature added a CDS service, a Fiori application or a BTP service, update
28
- `docs/agjan/project.md` (short, with pointers to the real files). Then run
28
+ `docs/agjan/project.md` (short, with pointers to the real files). Keep its section
29
+ "Run locally" current: the start command, the URLs of the apps and the test users with
30
+ their roles, so the user can try the result. Then run
29
31
  `npx agjan baseline refresh` whenever `npx agjan check` warns that watched files changed
30
32
  since the baseline, and commit both.
31
33
 
@@ -44,11 +46,12 @@ Any change after the final review makes it stale; review again after the last ch
44
46
  changed.
45
47
  - `npx agjan report` writes `report.md` (durations, gate waits, models, tokens); commit
46
48
  it.
47
- - Finish with `npx agjan status`. When the feature is verified it ends with a block
48
- that starts `✔ <KEY> is verified`. Your final message is that block, unchanged, followed
49
- by anything the user must know that it does not say (for example what you could not
50
- check yourself). Then offer to open the PR; the PR description is the output of
51
- `npx agjan pr-summary`.
49
+ - Finish with `npx agjan status --done`. Your final message starts with its output,
50
+ **verbatim, in a code block**: it says that development is done, what was met, and the
51
+ optional next steps. After it, add only what the user must know that it does not say
52
+ (for example what you could not check yourself). Do not end with a question: opening a
53
+ pull request is one of the optional next steps, done only when the user asks (its
54
+ description is the output of `npx agjan pr-summary`).
52
55
 
53
56
  ## 6. Pull request, only when the user asks
54
57
 
@@ -23,6 +23,7 @@ Rules for designing and building CAP Node.js backends in agjan. Project conventi
23
23
 
24
24
  | The task touches | Read |
25
25
  |---|---|
26
+ | a new project, the layout, configuration, development users, sample data, running it | `references/project-setup.md` |
26
27
  | entities, types, associations, compositions, localized texts | `references/modeling.md` |
27
28
  | services, projections, actions, functions, drafts, remote services | `references/services.md` |
28
29
  | input validation, `@mandatory`, `@assert…`, authorization, error messages | `references/validation-security.md` |
@@ -31,6 +32,9 @@ Rules for designing and building CAP Node.js backends in agjan. Project conventi
31
32
 
32
33
  ## Decide in this order
33
34
 
35
+ 0. **A new project** starts as `references/project-setup.md` says (`cds init <name>
36
+ --nodejs`, never `cds add sample`).
37
+
34
38
  1. **Declarative before code.** What an annotation can express (validation, read-only,
35
39
  authorization, defaults) is never written as handler code.
36
40
  2. **Extend before adding.** A new service, entity or BTP-relevant dependency is a
@@ -1,7 +1,10 @@
1
1
  # Handlers, queries, errors, transactions (Node.js)
2
2
 
3
3
  Distilled from the CAP documentation (capire, Apache-2.0), retrieved through the CAP
4
- MCP server on 2026-10-17. Rules restated; check details with `search_docs`.
4
+ MCP server on 2026-10-17, with patterns from the CAP team's agent skills (`capire/skills`)
5
+ and the reference apps `capire/bookshop` and `capire/incidents-app` (Apache-2.0); the
6
+ examples were checked with `@sap/cds` 10.1 on 2026-10-18. Rules restated; check details
7
+ with `search_docs`.
5
8
 
6
9
  ## Where handlers go
7
10
 
@@ -45,6 +48,60 @@ MCP server on 2026-10-17. Rules restated; check details with `search_docs`.
45
48
  you, and nested calls to other services do not join it.
46
49
  - Lock what you read before changing it in the same transaction:
47
50
  `SELECT(1).from(Orders, id).forUpdate()`.
48
- - For a status transition, make the update itself conditional on the expected state:
49
- `UPDATE(Orders).set({ status: 'Shipped' }).where({ ID: id, status: 'Approved' })`
50
- returns the number of changed rows; 0 means the state changed in between.
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.
55
+
56
+ ## A handler file (ESM, checked with @sap/cds 10.1)
57
+
58
+ <!-- checked: srv/leave-service.js -->
59
+ ```js
60
+ import cds from '@sap/cds'
61
+
62
+ export class LeaveService extends cds.ApplicationService { init() {
63
+ const { LeaveRequests } = this.entities
64
+
65
+ // Fill what the client must not set; check a rule across rows.
66
+ this.before('CREATE', LeaveRequests, async req => {
67
+ const { startDate, endDate } = req.data
68
+ req.data.employee_userId = req.user.id
69
+ const overlap = await SELECT.one.from(LeaveRequests).columns('ID').where({
70
+ employee_userId: req.user.id, status_code: { '!=': 'R' },
71
+ startDate: { '<=': endDate }, endDate: { '>=': startDate }
72
+ })
73
+ if (overlap) return req.reject(400, 'ASSERT_OVERLAP', 'startDate') // target: the field
74
+ })
75
+
76
+ // A status transition: one conditional UPDATE, no SELECT before it.
77
+ this.on('approve', LeaveRequests, async req => {
78
+ const [{ ID }] = req.params
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
81
+ })
82
+
83
+ // A virtual field per row and user (for example to enable a Fiori button).
84
+ this.after('READ', LeaveRequests, (rows, req) => {
85
+ for (const r of Array.isArray(rows) ? rows : [rows]) {
86
+ if (r) r.canDecide = req.user.is('manager') && r.status_code === 'N'
87
+ }
88
+ })
89
+
90
+ return super.init() // required: the generic handlers, auth, drafts
91
+ }}
92
+ ```
93
+
94
+ - An after-`READ` handler sees only the columns the client selected (Fiori selects what
95
+ the page shows). Compute from columns that are on the page, or read the missing ones.
96
+ - `req.reject(status, code)` ends the request; `req.error(…)` collects several errors.
97
+ Never `throw new Error(…)`: it becomes a 500.
98
+ - A rule across rows (no overlaps, a limit per user) belongs in a `before` handler, as
99
+ above; rules within one row are `@assert` annotations (validation-security.md). A query
100
+ awaited in a handler goes to the database without the service's `@restrict`: filter by
101
+ the user yourself.
102
+ - Never add a helper association (for example `on 1 = 1`, to reach other rows) to an
103
+ entity a service exposes: clients can follow it with `$expand` and read rows the
104
+ `where` of `@restrict` hides (checked with `@sap/cds` 10.1).
105
+ - Select explicit columns (`SELECT.one.from(E, id).columns('status_code')`), never `*`.
106
+ - Events to other parts of the application: `await this.emit('Approved', { ID })` in an
107
+ `after` handler.
@@ -1,7 +1,10 @@
1
1
  # Domain modeling (CDS)
2
2
 
3
3
  Distilled from the CAP documentation (capire, Apache-2.0), retrieved through the CAP
4
- MCP server on 2026-10-17. Rules restated; check details with `search_docs`.
4
+ MCP server on 2026-10-17, with patterns from the CAP team's agent skills (`capire/skills`)
5
+ and the reference apps `capire/bookshop` and `capire/incidents-app` (Apache-2.0); the
6
+ examples were checked with `@sap/cds` 10.1 on 2026-10-18. Rules restated; check details
7
+ with `search_docs`.
5
8
 
6
9
  ## Keep it simple
7
10
 
@@ -44,6 +47,35 @@ composed to your body; your phone is associated with you.")
44
47
  - A child of a composition has a back association to its parent
45
48
  (`Items : Composition of many OrderItems on Items.parent = $self`).
46
49
 
50
+ ## Code lists, enums and calculated elements (checked with @sap/cds 10.1)
51
+
52
+ <!-- checked: db/schema.cds -->
53
+ ```cds
54
+ using { cuid, managed, sap.common.CodeList } from '@sap/cds/common';
55
+ namespace sap.capire.leaves;
56
+
57
+ entity LeaveRequests : cuid, managed {
58
+ employee : Association to Employees;
59
+ startDate : Date @mandatory;
60
+ endDate : Date @mandatory;
61
+ type : Association to LeaveTypes @mandatory;
62
+ status : Association to Status default 'N';
63
+ days : Integer = days_between(startDate, endDate) + 1; // calculated, not stored
64
+ }
65
+
66
+ entity Status : CodeList { // name, descr (localized) from CodeList
67
+ key code : String(1) enum { new = 'N'; approved = 'A'; rejected = 'R'; };
68
+ criticality : Integer; // 1 red, 2 yellow, 3 green: Fiori colors the status
69
+ }
70
+ entity LeaveTypes : CodeList { key code : String(10); }
71
+ ```
72
+
73
+ - A status or a type with a fixed set of values is a **code list** entity (`CodeList`)
74
+ with an association to it, not a plain string: Fiori shows its name, offers it as a
75
+ value help, and colors it by `criticality`.
76
+ - `managed` only on the root of a composition tree; the children are covered by it.
77
+ - Calculated elements (`= <expression>`) are computed on read and need no handler.
78
+
47
79
  ## Localized data
48
80
 
49
81
  - Mark translatable texts with `localized` (`title : localized String`); CAP generates
@@ -0,0 +1,87 @@
1
+ # Project setup and layout (CAP Node.js)
2
+
3
+ Distilled from the CAP documentation (capire), the CAP team's agent skills
4
+ (`capire/skills`) and the reference apps `capire/bookshop` and `capire/incidents-app`
5
+ (all Apache-2.0), checked with `@sap/cds` 10.1 on 2026-10-18. Rules restated.
6
+
7
+ ## A new project
8
+
9
+ ```sh
10
+ cds init <name> --nodejs # ESM ("type": "module"), db/, srv/, app/
11
+ cd <name>
12
+ npm add -D @cap-js/cds-test # tests with cds.test
13
+ cds watch # dev loop; reloads on every save
14
+ ```
15
+
16
+ - Initialize in a folder of its own or in the current one (`cds init` without a name).
17
+ If the project already has a `package.json` (agjan set up first), run `cds init` in that
18
+ folder and keep the existing dependencies.
19
+ - **Never run `cds add sample`**: it scaffolds a whole demo app (bookshop) into the project.
20
+ Use `cds add tiny-sample` only when the user asks for a minimal starter model.
21
+ - Add features with `cds add <feature>` only when a task needs them: `hana`, `xsuaa`,
22
+ `mta`, `approuter`, `data` (see below). Each is a design decision for the btp area.
23
+ - Keep ESM: never remove `"type": "module"` or rewrite handlers as CommonJS to work around
24
+ an import error.
25
+
26
+ ## Layout
27
+
28
+ | File | Content |
29
+ |---|---|
30
+ | `db/schema.cds` | the domain model, with a `namespace` |
31
+ | `db/data/<namespace>-<Entity>.csv` | seed and test data |
32
+ | `srv/<name>-service.cds` | one service per file: projections and actions |
33
+ | `srv/<name>-service.js` | its handlers; same base name, so CAP finds it (no `@impl`) |
34
+ | `srv/<name>-constraints.cds` | input validation (`@mandatory`, `@assert…`) and helper `extend`s for it |
35
+ | `app/<app>/annotations.cds` | the Fiori annotations of one app (never in `srv/`) |
36
+ | `app/services.cds` | `using from './<app>/annotations';` for every app |
37
+ | `_i18n/i18n.properties` | labels used as `{i18n>Key}` in annotations |
38
+ | `_i18n/messages.properties` | error messages, by the codes in `@assert` and `req.reject` |
39
+ | `test/<topic>.test.js` | tests with `cds.test` and `node --test` |
40
+
41
+ ## Configuration
42
+
43
+ - Project configuration goes into the `cds` section of `package.json`, where `cds init`
44
+ and `cds add` put it. Use `.cdsrc.json` only if the project already uses it.
45
+ Personal, local settings belong in `.cdsrc-private.json` (not committed).
46
+ - Development users go into the `[development]` profile, named after their role with the
47
+ name as password, plus one without a role. `cds.test` and `cds watch` use them; in
48
+ production (`NODE_ENV=production`) the real authentication applies:
49
+
50
+ <!-- checked: package.json -->
51
+ ```json
52
+ "cds": {
53
+ "requires": {
54
+ "[development]": {
55
+ "auth": {
56
+ "kind": "mocked",
57
+ "users": {
58
+ "employee": { "password": "employee", "roles": ["employee"] },
59
+ "employee2": { "password": "employee2", "roles": ["employee"] },
60
+ "manager": { "password": "manager", "roles": ["manager"] },
61
+ "nobody": { "password": "nobody", "roles": [] }
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ ```
68
+
69
+ - Check: `NODE_ENV=production npx cds env get requires.auth.kind` must not print `mocked`.
70
+ - Scripts: `"watch": "cds watch"`, `"test": "node --test"` (add the JUnit reporter when
71
+ `verify.<area>.results` in `agjan.config.json` names a results file).
72
+
73
+ ## Sample data
74
+
75
+ - `cds add data --records <n> --keys-only` writes one CSV per entity with generated keys
76
+ and empty other columns. It does **not** fill foreign keys (checked with cds-dk 10.1):
77
+ fill them, and the content, yourself, and keep the generated keys and headers.
78
+ - Small, readable data is often better written by hand: a few rows per entity, keys that
79
+ tell a story (`employee`, `manager`, fixed UUIDs for rows that tests address).
80
+ - Code lists (`Status`, types) are data too: their codes in a CSV, names and criticality.
81
+
82
+ ## Run locally
83
+
84
+ Keep the section "Run locally" of `docs/agjan/project.md` current: the start command
85
+ (`npx cds watch`), the URLs of the apps (`http://localhost:4004/<app>/webapp/index.html`),
86
+ and the development users with their roles. A browser keeps a login: another user needs a
87
+ private window.
@@ -1,7 +1,10 @@
1
1
  # Services, operations, drafts
2
2
 
3
3
  Distilled from the CAP documentation (capire, Apache-2.0), retrieved through the CAP
4
- MCP server on 2026-10-17. Rules restated; check details with `search_docs`.
4
+ MCP server on 2026-10-17, with patterns from the CAP team's agent skills (`capire/skills`)
5
+ and the reference apps `capire/bookshop` and `capire/incidents-app` (Apache-2.0); the
6
+ examples were checked with `@sap/cds` 10.1 on 2026-10-18. Rules restated; check details
7
+ with `search_docs`.
5
8
 
6
9
  ## Services as facades
7
10
 
@@ -16,6 +19,34 @@ MCP server on 2026-10-17. Rules restated; check details with `search_docs`.
16
19
  - Prefer `@readonly`, `@mandatory` and similar CDS annotations over the equivalent OData
17
20
  `@Capabilities` annotations: shorter, and they mean the same.
18
21
 
22
+ ## Projections (checked with @sap/cds 10.1)
23
+
24
+ <!-- checked: srv/leave-service.cds -->
25
+ ```cds
26
+ using { sap.capire.leaves as my } from '../db/schema';
27
+
28
+ service LeaveService {
29
+ entity LeaveRequests as projection on my.LeaveRequests {
30
+ *,
31
+ employee.name as employeeName, // flatten what the UI shows
32
+ virtual null as canDecide : Boolean // per row and user, set in an after-READ handler
33
+ } excluding { createdBy, modifiedBy } actions {
34
+ action approve();
35
+ action reject(reason : String(500) @mandatory);
36
+ };
37
+ @readonly entity LeaveTypes as projection on my.LeaveTypes; // code lists: read-only
38
+ @readonly entity Status as projection on my.Status;
39
+ }
40
+ ```
41
+
42
+ - `excluding` only works after the wildcard `*`.
43
+ - A virtual field goes into the projection's select list (`virtual null as x : Type`); an
44
+ `extend` of a projection needs `extend … with columns { … }`, not `with { … }`.
45
+ - One service per `.cds` file; the handler file has the same base name.
46
+ - Do not expose two projections of the same entity in one service: associations cannot be
47
+ redirected automatically (or mark one `@cds.redirection.target`).
48
+ - UI annotations belong in `app/<app>/annotations.cds`, never in the service file.
49
+
19
50
  ## Actions and functions
20
51
 
21
52
  - Actions change data; functions only read. Unbound ones belong to the service; bound
@@ -1,24 +1,54 @@
1
1
  # Testing with cds.test (Node.js)
2
2
 
3
3
  Distilled from the CAP documentation (capire, Apache-2.0), retrieved through the CAP
4
- MCP server on 2026-10-17. Rules restated; check details with `search_docs`.
4
+ MCP server on 2026-10-17, with patterns from the CAP team's agent skills (`capire/skills`)
5
+ and the reference apps `capire/bookshop` and `capire/incidents-app` (Apache-2.0); the
6
+ examples were checked with `@sap/cds` 10.1 on 2026-10-18. Rules restated; check details
7
+ with `search_docs`.
5
8
 
6
- ## Shape of a test file
9
+ ## Shape of a test file (ESM, `node --test`, checked with @sap/cds 10.1)
7
10
 
11
+ <!-- checked: test/leaves.test.js -->
8
12
  ```js
9
- const cds = require('@sap/cds');
10
- const { GET, POST, expect, defaults } = cds.test(__dirname + '/..');
11
- defaults.path = '/odata/v4/orders';
12
- defaults.auth = { username: 'alice' };
13
-
14
- describe('OrdersService', () => {
15
- it('ORDF-AC1: lists only orders of the chosen status', async () => {
16
- const { data } = await GET`Orders?$filter=status eq 'New'`;
17
- expect(data.value.every((o) => o.status === 'New')).to.be.true;
18
- });
19
- });
13
+ import cds from '@sap/cds'
14
+ import { describe, it } from 'node:test'
15
+ import assert from 'node:assert/strict'
16
+
17
+ const { GET, POST, axios } = cds.test(import.meta.dirname + '/..')
18
+ axios.defaults.validateStatus = () => true // assert on status codes, not exceptions
19
+ const as = (user) => ({ auth: { username: user, password: user } })
20
+ const ID = '7a1e0c1a-0001-4c2b-9a5f-000000000001' // a row from db/data, status New
21
+
22
+ describe('LeaveService', () => {
23
+ it('TLR-AC1: employees see only their own requests', async () => {
24
+ const { status, data } = await GET('/odata/v4/leave/LeaveRequests', as('employee'))
25
+ assert.equal(status, 200)
26
+ assert.deepEqual(data.value.map((r) => r.employee_userId), ['employee'])
27
+ })
28
+ it('TLR-AC9: a user without a role gets 403, an anonymous request 401', async () => {
29
+ assert.equal((await GET('/odata/v4/leave/LeaveRequests', as('nobody'))).status, 403)
30
+ assert.equal((await GET('/odata/v4/leave/LeaveRequests')).status, 401)
31
+ })
32
+ it('TLR-AC3: the end date may not be before the start date', async () => {
33
+ const { status, data } = await POST('/odata/v4/leave/LeaveRequests',
34
+ { startDate: '2026-11-10', endDate: '2026-11-01', type_code: 'vacation' }, as('employee'))
35
+ assert.equal(status, 400)
36
+ assert.equal(data.error.code, 'ASSERT_END_BEFORE_START')
37
+ })
38
+ it('TLR-AC6: only a manager approves, and only once', async () => {
39
+ const url = `/odata/v4/leave/LeaveRequests(${ID})/LeaveService.approve`
40
+ assert.equal((await POST(url, {}, as('employee'))).status, 403)
41
+ assert.equal((await POST(url, {}, as('manager'))).status, 204)
42
+ assert.equal((await POST(url, {}, as('manager'))).status, 409)
43
+ })
44
+ })
20
45
  ```
21
46
 
47
+ - Bound actions: `/<Entity>(<key>)/<Service>.<action>`; a draft-enabled entity's key is
48
+ `(ID=…,IsActiveEntity=true)`, and saving a draft is `POST …/<Service>.draftActivate`
49
+ (the incidents app's tests show the whole draft choreography).
50
+ - `cds.test` keeps the console quiet during tests; write diagnostics to a file if needed.
51
+
22
52
  ## Rules
23
53
 
24
54
  - Call `cds.test(…)` **first** in the file, before touching `cds.env` or other `cds`
@@ -27,7 +57,9 @@ describe('OrdersService', () => {
27
57
  - Point it at the project folder (`cds.test(folder)` or `.in(folder)`); never use
28
58
  `process.chdir()`.
29
59
  - Test through the service's HTTP API (`GET`, `POST`, `PATCH`, `DELETE`), with the users
30
- and roles the spec names (`auth`), so authorization is tested too.
60
+ and roles the spec names (`auth`), so authorization is tested too: for every rule of
61
+ the spec's Authorization section, a test with the right role, one without a role (403)
62
+ and an anonymous request (401).
31
63
  - Mock as little as possible; the more is mocked, the less is tested. Mocking module
32
64
  caches or timers can break the CAP server.
33
65
  - Use the project's runner (`node:test`, jest, mocha, vitest); `cds.test` works with all