@jahia/agentic 0.1.0 → 0.2.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/claude/.claude/rules/jahia.md +3 -1
  3. package/dist/claude/.claude/skills/jahia-dev-build-component/SKILL.md +7 -22
  4. package/dist/claude/.claude/skills/jahia-dev-create-view/SKILL.md +58 -0
  5. package/dist/claude/.claude/skills/jahia-dev-java/SKILL.md +7 -2
  6. package/dist/claude/.claude/skills/jahia-java-concurrency/SKILL.md +308 -0
  7. package/dist/claude/.claude/skills/jahia-java-jcr/SKILL.md +153 -0
  8. package/dist/claude/.claude/skills/jahia-java-osgi/SKILL.md +134 -0
  9. package/dist/claude/.claude/skills/jahia-java-persistence/SKILL.md +177 -0
  10. package/dist/claude/.claude/skills/jahia-java-security/SKILL.md +84 -0
  11. package/dist/claude/.claude/skills/jahia-review-java/SKILL.md +131 -0
  12. package/dist/claude/.claude/skills/jahia-review-java/references/code-review-output.md +121 -0
  13. package/dist/claude/CLAUDE.md +4 -2
  14. package/dist/codex/.agents/skills/jahia-dev-build-component/SKILL.md +7 -22
  15. package/dist/codex/.agents/skills/jahia-dev-create-view/SKILL.md +58 -0
  16. package/dist/codex/.agents/skills/jahia-dev-java/SKILL.md +7 -2
  17. package/dist/codex/.agents/skills/jahia-java-concurrency/SKILL.md +308 -0
  18. package/dist/codex/.agents/skills/jahia-java-jcr/SKILL.md +153 -0
  19. package/dist/codex/.agents/skills/jahia-java-osgi/SKILL.md +134 -0
  20. package/dist/codex/.agents/skills/jahia-java-persistence/SKILL.md +177 -0
  21. package/dist/codex/.agents/skills/jahia-java-security/SKILL.md +84 -0
  22. package/dist/codex/.agents/skills/jahia-review-java/SKILL.md +131 -0
  23. package/dist/codex/.agents/skills/jahia-review-java/references/code-review-output.md +121 -0
  24. package/dist/codex/AGENTS.md +4 -2
  25. package/dist/copilot/.agents/skills/jahia-dev-build-component/SKILL.md +7 -22
  26. package/dist/copilot/.agents/skills/jahia-dev-create-view/SKILL.md +58 -0
  27. package/dist/copilot/.agents/skills/jahia-dev-java/SKILL.md +7 -2
  28. package/dist/copilot/.agents/skills/jahia-java-concurrency/SKILL.md +308 -0
  29. package/dist/copilot/.agents/skills/jahia-java-jcr/SKILL.md +153 -0
  30. package/dist/copilot/.agents/skills/jahia-java-osgi/SKILL.md +134 -0
  31. package/dist/copilot/.agents/skills/jahia-java-persistence/SKILL.md +177 -0
  32. package/dist/copilot/.agents/skills/jahia-java-security/SKILL.md +84 -0
  33. package/dist/copilot/.agents/skills/jahia-review-java/SKILL.md +131 -0
  34. package/dist/copilot/.agents/skills/jahia-review-java/references/code-review-output.md +121 -0
  35. package/dist/copilot/AGENTS.md +4 -2
  36. package/dist/cursor/.agents/skills/jahia-dev-build-component/SKILL.md +7 -22
  37. package/dist/cursor/.agents/skills/jahia-dev-create-view/SKILL.md +58 -0
  38. package/dist/cursor/.agents/skills/jahia-dev-java/SKILL.md +7 -2
  39. package/dist/cursor/.agents/skills/jahia-java-concurrency/SKILL.md +308 -0
  40. package/dist/cursor/.agents/skills/jahia-java-jcr/SKILL.md +153 -0
  41. package/dist/cursor/.agents/skills/jahia-java-osgi/SKILL.md +134 -0
  42. package/dist/cursor/.agents/skills/jahia-java-persistence/SKILL.md +177 -0
  43. package/dist/cursor/.agents/skills/jahia-java-security/SKILL.md +84 -0
  44. package/dist/cursor/.agents/skills/jahia-review-java/SKILL.md +131 -0
  45. package/dist/cursor/.agents/skills/jahia-review-java/references/code-review-output.md +121 -0
  46. package/dist/cursor/.cursor/rules/jahia.mdc +3 -1
  47. package/dist/gemini/.agents/skills/jahia-dev-build-component/SKILL.md +7 -22
  48. package/dist/gemini/.agents/skills/jahia-dev-create-view/SKILL.md +58 -0
  49. package/dist/gemini/.agents/skills/jahia-dev-java/SKILL.md +7 -2
  50. package/dist/gemini/.agents/skills/jahia-java-concurrency/SKILL.md +308 -0
  51. package/dist/gemini/.agents/skills/jahia-java-jcr/SKILL.md +153 -0
  52. package/dist/gemini/.agents/skills/jahia-java-osgi/SKILL.md +134 -0
  53. package/dist/gemini/.agents/skills/jahia-java-persistence/SKILL.md +177 -0
  54. package/dist/gemini/.agents/skills/jahia-java-security/SKILL.md +84 -0
  55. package/dist/gemini/.agents/skills/jahia-review-java/SKILL.md +131 -0
  56. package/dist/gemini/.agents/skills/jahia-review-java/references/code-review-output.md +121 -0
  57. package/dist/gemini/AGENTS.md +4 -2
  58. package/dist/index.js +1 -0
  59. package/dist/opencode/.agents/skills/jahia-dev-build-component/SKILL.md +7 -22
  60. package/dist/opencode/.agents/skills/jahia-dev-create-view/SKILL.md +58 -0
  61. package/dist/opencode/.agents/skills/jahia-dev-java/SKILL.md +7 -2
  62. package/dist/opencode/.agents/skills/jahia-java-concurrency/SKILL.md +308 -0
  63. package/dist/opencode/.agents/skills/jahia-java-jcr/SKILL.md +153 -0
  64. package/dist/opencode/.agents/skills/jahia-java-osgi/SKILL.md +134 -0
  65. package/dist/opencode/.agents/skills/jahia-java-persistence/SKILL.md +177 -0
  66. package/dist/opencode/.agents/skills/jahia-java-security/SKILL.md +84 -0
  67. package/dist/opencode/.agents/skills/jahia-review-java/SKILL.md +131 -0
  68. package/dist/opencode/.agents/skills/jahia-review-java/references/code-review-output.md +121 -0
  69. package/dist/opencode/AGENTS.md +4 -2
  70. package/dist/windsurf/.windsurf/rules/jahia.md +3 -1
  71. package/dist/windsurf/.windsurf/skills/jahia-dev-build-component/SKILL.md +7 -22
  72. package/dist/windsurf/.windsurf/skills/jahia-dev-create-view/SKILL.md +58 -0
  73. package/dist/windsurf/.windsurf/skills/jahia-dev-java/SKILL.md +7 -2
  74. package/dist/windsurf/.windsurf/skills/jahia-java-concurrency/SKILL.md +308 -0
  75. package/dist/windsurf/.windsurf/skills/jahia-java-jcr/SKILL.md +153 -0
  76. package/dist/windsurf/.windsurf/skills/jahia-java-osgi/SKILL.md +134 -0
  77. package/dist/windsurf/.windsurf/skills/jahia-java-persistence/SKILL.md +177 -0
  78. package/dist/windsurf/.windsurf/skills/jahia-java-security/SKILL.md +84 -0
  79. package/dist/windsurf/.windsurf/skills/jahia-review-java/SKILL.md +131 -0
  80. package/dist/windsurf/.windsurf/skills/jahia-review-java/references/code-review-output.md +121 -0
  81. package/dist/windsurf/AGENTS.md +4 -2
  82. package/package.json +9 -1
@@ -16,17 +16,17 @@ Run these steps in order. Do not skip to the view before the content type is def
16
16
 
17
17
  ---
18
18
 
19
- ## Step 0 — Optional: capture reference screenshot
19
+ ## Step 0 — Optional: capture reference screenshot (interactive sessions only)
20
20
 
21
21
  If the user provides a reference URL (or mentions a site to model after), invoke `/jahia-dev-screenshot` **before writing any code** to capture the visual spec.
22
22
 
23
- The screenshot gives the view implementation visual context: layout, colors, typography, and component anatomy. Reference it throughout Steps 2–3.
23
+ > Skip this step in automated / autopilot contexts screenshot comparison requires human review and adds significant time.
24
24
 
25
25
  ---
26
26
 
27
- ## Step 1 — Write and confirm the content spec
27
+ ## Step 1 — Write the content spec
28
28
 
29
- Before writing any code, fill out this template and confirm with the user:
29
+ Before writing any code, draft this spec internally. In an interactive session, confirm with the user; in autopilot mode, proceed with your best judgement and document what you chose:
30
30
 
31
31
  ```
32
32
  Name: <ComponentName>
@@ -41,8 +41,6 @@ Used where: <Area on page / nested in <Parent> / listing item>
41
41
  Has children: <yes: ChildType / no>
42
42
  ```
43
43
 
44
- Only proceed once the spec is confirmed.
45
-
46
44
  ---
47
45
 
48
46
  ## Step 2 — Invoke `jahia-dev-define-content-type`
@@ -69,25 +67,12 @@ Use the instructions from the `jahia-dev-create-view` skill to:
69
67
 
70
68
  ---
71
69
 
72
- ## Step 4 — Validate and compare
70
+ ## Step 4 — Validate
73
71
 
74
72
  1. In Jahia Page Builder, click **New content** and select the new type
75
73
  2. Fill in the content form and click **Save**
76
74
  3. Verify the component renders correctly on the page
77
75
  4. Check for the error `No rendering set for node: <type>` — if seen, re-run `yarn build && yarn jahia-deploy`
78
- 5. **If a reference screenshot was taken in Step 0**, invoke `/jahia-dev-screenshot` again to capture the Jahia render and compare against the reference.
79
-
80
- ---
81
-
82
- ## Step 5 — Accessibility check
83
-
84
- After the component is live, invoke `/jahia-dev-accessibility` to audit it:
85
-
86
- 1. Run the axe-core audit against the page(s) containing the new component
87
- 2. Fix any `critical` or `serious` violations before considering the component done
88
- 3. Report remaining violations to the user
89
-
90
- A component is not complete until it has no critical or serious accessibility violations.
91
76
 
92
77
  ---
93
78
 
@@ -128,13 +113,13 @@ If the component has child nodes (e.g. a hero with CTA buttons), repeat Steps 2
128
113
  ---
129
114
 
130
115
  ## Validation checklist
131
- - [ ] Spec confirmed before writing any code
116
+ - [ ] Spec written before any code
132
117
  - [ ] Component count within scale of thumbs (1–4 templates, 5–10 types, 2–5 mixins, 1–4 views/type)
133
118
  - [ ] `definition.cnd` created with correct namespace and mixins
134
119
  - [ ] `types.ts` reflects all CND properties
135
120
  - [ ] `default.server.tsx` renders without errors
136
121
  - [ ] Views handle null/missing fields gracefully (mandatory does not guarantee a value at runtime)
137
122
  - [ ] `component.module.css` applied and visible
123
+ - [ ] Semantic HTML used: correct heading level, `alt` text on images, sufficient colour contrast
138
124
  - [ ] Component appears in Page Builder content picker
139
125
  - [ ] Content can be created and renders on the page
140
- - [ ] No critical or serious accessibility violations (`/jahia-dev-accessibility`)
@@ -78,6 +78,64 @@ When you have a source HTML fragment to translate (e.g. from `/jahia-dev-import-
78
78
 
79
79
  ---
80
80
 
81
+ ## Step 1b — Accessibility and SEO rules (apply to every view)
82
+
83
+ Build these requirements in from the start — retrofitting them later is more expensive.
84
+
85
+ ### Semantic HTML structure
86
+
87
+ | Element | Rule |
88
+ |---|---|
89
+ | `<section>`, `<article>` | Wrap every self-contained block of content |
90
+ | `<header>` / `<footer>` | Use for the page header and footer in page templates |
91
+ | `<nav>` | Wrap navigation menus; add `aria-label` when there are multiple navs |
92
+ | `<main>` | Exactly one per page, wrapping all page body content (already enforced by the Layout component for page templates) |
93
+ | Headings | Each page must have exactly one `<h1>`; section headings use `<h2>`; sub-section headings use `<h3>`. Never skip levels. |
94
+
95
+ ### Images
96
+
97
+ Every `<img>` must have an `alt` attribute. Decorative images use `alt=""`. Informational images use a descriptive string from a CND property:
98
+
99
+ ```tsx
100
+ // ❌ Missing alt
101
+ <img src={buildNodeUrl(props.image)} />
102
+
103
+ // ✅ Descriptive alt from content
104
+ <img src={buildNodeUrl(props.image)} alt={props.imageAlt ?? ""} />
105
+ ```
106
+
107
+ Add `- imageAlt (string) i18n` to the CND and `imageAlt?: string` to `types.ts` for any type with an image field.
108
+
109
+ ### Colour contrast
110
+
111
+ Use colours with a contrast ratio ≥ 4.5:1 for body text and ≥ 3:1 for large text (18px+ or bold 14px+) against the background. Avoid light grey on white. When in doubt, use near-black (`#333333` or `#1a1a1a`) for body text.
112
+
113
+ ### Link and button names
114
+
115
+ Every `<a>` and `<button>` must have an accessible name — either visible text or `aria-label`. Icon-only buttons must have `aria-label`:
116
+
117
+ ```tsx
118
+ // ❌ No accessible name
119
+ <button><svg>…</svg></button>
120
+
121
+ // ✅ Accessible name via aria-label
122
+ <button aria-label="Close menu"><svg aria-hidden="true">…</svg></button>
123
+ ```
124
+
125
+ ### Focus styles
126
+
127
+ Never suppress focus indicators globally. Use `:focus-visible` to style keyboard focus:
128
+
129
+ ```css
130
+ /* ❌ Never do this */
131
+ * { outline: none; }
132
+
133
+ /* ✅ Style keyboard focus without affecting mouse users */
134
+ :focus-visible { outline: 2px solid #0969da; outline-offset: 2px; }
135
+ ```
136
+
137
+ ---
138
+
81
139
  ## Step 2 — Import Props from types.ts
82
140
 
83
141
  Always import `Props` from `./types.js` (not `./types.ts` — use `.js` extension at import time):
@@ -15,14 +15,19 @@ allowed-tools: Read
15
15
 
16
16
  ## When to load which reference
17
17
 
18
- | Task | Reference file |
19
- |------|---------------|
18
+ | Task | Reference |
19
+ |------|-----------|
20
20
  | Creating a new module, Maven pom.xml, deployment, Java 11/17, static assets, deploy-free coding, troubleshooting bundle errors | `references/modules.md` |
21
21
  | Writing CND definitions, content type hierarchy, property types, choicelist initializers, modifying existing definitions | `references/content-types.md` |
22
22
  | JSP views, view selection, `@cache` tag, caching configuration, navigation menus, rendering filters, AMP | `references/rendering.md` |
23
23
  | Drools rules (DRL), JCR event listeners, JCR SQL2 queries, external data provider, permissions and roles | `references/backend.md` |
24
24
  | OSGi bundle lifecycle, Declarative Services, Blueprint XML, package Import/Export, service registry, Karaf tooling | `references/osgi.md` |
25
25
  | Content Editor JSON overrides, jContent UI extension points, component registry, custom selectors, settings pages, CKEditor | `references/ui-extensions.md` |
26
+ | JCR session lifecycle, workspace, node names, SNS, mixins, locks, versioning — **correct patterns and pitfalls** | `/jahia-java-jcr` skill |
27
+ | OSGi `@Component` state, `@Reference`, lifecycle side effects, Export-Package — **correct patterns and pitfalls** | `/jahia-java-osgi` skill |
28
+ | Securing HTTP-reachable surfaces (servlets, GraphQL, filters) — Security Filter, CSRF Guard, ACLs | `/jahia-java-security` skill |
29
+ | Relational persistence alongside JCR — N+1, timestamp consistency, entity model, transactional asymmetry | `/jahia-java-persistence` skill |
30
+ | Thread safety in a multi-threaded webapp — `volatile`, locking, atomic variables, thread-safe collections, JCR session threading | `/jahia-java-concurrency` skill |
26
31
 
27
32
  ## Key Concepts Glossary
28
33
 
@@ -0,0 +1,308 @@
1
+ ---
2
+ name: jahia-java-concurrency
3
+ description: Thread safety patterns for Jahia Java backend development in a multi-threaded web application. Covers volatile, locking, atomic variables, thread-safe collections, immutability, and common pitfalls that cause data races, stale reads, and silent corruption. Load when implementing or reviewing any class that holds mutable state accessible from multiple threads — OSGi services, caches, static fields, background workers, event listeners.
4
+ allowed-tools: Read
5
+ ---
6
+
7
+ # Concurrency and Thread Safety for Jahia Java Backend
8
+
9
+ In a Jahia webapp, every OSGi service is a singleton — its instance fields are shared across every concurrent request, publication job, event listener, and background thread. A field that looks fine in a single-threaded test can silently corrupt data or read stale values under real load.
10
+
11
+ This skill covers the correct patterns and the pitfalls. Both developers and reviewers use it.
12
+
13
+ > OSGi-specific concurrency (`@Modified` config reload, `@Reference` dynamic rebinding) is covered in `/jahia-java-osgi`. This skill covers the general Java concurrency model applicable to all backend code.
14
+
15
+ ---
16
+
17
+ ## The three questions to ask about any mutable field
18
+
19
+ Before writing or reviewing any instance or static field in a service:
20
+
21
+ 1. **Can it be written by more than one thread?** If yes → needs synchronization or an atomic type.
22
+ 2. **Can it be read while another thread is writing it?** If yes → at minimum needs `volatile`.
23
+ 3. **Are read + write part of a compound action** (check-then-act, read-modify-write)? If yes → `volatile` alone is not enough, needs a lock or an atomic with CAS.
24
+
25
+ ---
26
+
27
+ ## Immutability — the first line of defence
28
+
29
+ ### Correct approach
30
+
31
+ Prefer immutable objects. An immutable object needs no synchronization — it is inherently thread-safe.
32
+
33
+ - Make fields `final` wherever possible.
34
+ - Use `record` types for config/value objects (all fields are final by definition).
35
+ - Use `List.of()`, `Map.of()`, `Set.of()` for collections that do not change after construction.
36
+ - Return copies or unmodifiable views of mutable internal collections rather than the live reference.
37
+
38
+ ### Pitfall
39
+
40
+ ```java
41
+ // dangerous — caller can mutate the internal list
42
+ public List<String> getAllowedRoles() {
43
+ return allowedRoles; // returns live mutable reference
44
+ }
45
+ ```
46
+
47
+ Return `Collections.unmodifiableList(allowedRoles)` or `List.copyOf(allowedRoles)` instead.
48
+
49
+ ---
50
+
51
+ ## `volatile` — correct use and limits
52
+
53
+ ### Correct use
54
+
55
+ `volatile` guarantees **visibility**: a write to a `volatile` field is immediately visible to all subsequent reads in other threads. Use it when:
56
+
57
+ - One thread writes, many threads read (no compound action needed).
58
+ - The written value is a single reference or primitive (not two fields that must be updated atomically together).
59
+
60
+ ```java
61
+ // correct — single writer (SCR @Modified), many readers
62
+ private volatile Config config;
63
+
64
+ @Activate @Modified
65
+ void activate(Cfg cfg) {
66
+ this.config = new Config(cfg); // atomic reference swap
67
+ }
68
+ ```
69
+
70
+ ### Limits — volatile is NOT enough for compound actions
71
+
72
+ ```java
73
+ // WRONG — read-modify-write is not atomic even with volatile
74
+ private volatile int counter = 0;
75
+ public void increment() {
76
+ counter++; // read, increment, write — three steps, not one
77
+ }
78
+ ```
79
+
80
+ Two threads can both read `counter = 5`, both compute `6`, and both write `6` — losing one increment. Use `AtomicInteger.incrementAndGet()` instead.
81
+
82
+ Similarly, volatile does not protect **two fields that must be consistent with each other**:
83
+
84
+ ```java
85
+ // WRONG — reader can see updated 'host' with old 'port'
86
+ private volatile String host;
87
+ private volatile int port;
88
+ ```
89
+
90
+ Bundle related fields into a single immutable record and swap the reference atomically (as shown in `/jahia-java-osgi`).
91
+
92
+ ---
93
+
94
+ ## Atomic variables
95
+
96
+ Use `java.util.concurrent.atomic` for lock-free, thread-safe single-value updates:
97
+
98
+ | Need | Type |
99
+ |---|---|
100
+ | Thread-safe counter | `AtomicInteger` / `AtomicLong` |
101
+ | Thread-safe reference swap | `AtomicReference<T>` |
102
+ | Conditional update (compare-and-swap) | `AtomicReference.compareAndSet()` |
103
+ | Accumulator under high contention | `LongAdder` (more scalable than `AtomicLong` for pure counting) |
104
+
105
+ ### Check-then-act with `compareAndSet`
106
+
107
+ ```java
108
+ // correct — atomic conditional update
109
+ AtomicReference<State> stateRef = new AtomicReference<>(State.IDLE);
110
+
111
+ public boolean tryStart() {
112
+ return stateRef.compareAndSet(State.IDLE, State.RUNNING);
113
+ }
114
+ ```
115
+
116
+ Two threads calling `tryStart()` concurrently: only one gets `true`. No lock needed.
117
+
118
+ ---
119
+
120
+ ## Synchronized blocks and `ReentrantLock`
121
+
122
+ ### When to use
123
+
124
+ Use explicit locking when:
125
+ - The critical section spans multiple statements that must execute atomically.
126
+ - You need read/write distinction (`ReadWriteLock`).
127
+ - You need a timed or interruptible lock attempt (`ReentrantLock.tryLock(timeout)`).
128
+
129
+ ### Correct approach
130
+
131
+ ```java
132
+ // small, focused critical section
133
+ private final Object lock = new Object();
134
+ private List<String> items = new ArrayList<>();
135
+
136
+ public void addItem(String item) {
137
+ synchronized (lock) {
138
+ items.add(item);
139
+ }
140
+ }
141
+
142
+ public List<String> snapshot() {
143
+ synchronized (lock) {
144
+ return List.copyOf(items); // return a copy, not the live list
145
+ }
146
+ }
147
+ ```
148
+
149
+ ### Pitfalls
150
+
151
+ - **Locking on `this`.** Callers can also `synchronized(service)` from outside, causing unexpected contention or deadlock. Prefer a private `final Object lock`.
152
+ - **Holding a lock during I/O or JCR calls.** A lock held while doing a JCR query or an HTTP call blocks all other threads waiting for it. Move I/O outside the critical section; only protect the state mutation.
153
+ - **Inconsistent lock object.** Two methods protecting the same state must use the same lock.
154
+ - **Deadlock.** Two threads each holding lock A and waiting for lock B. Always acquire multiple locks in the same fixed order. Prefer `tryLock(timeout)` and fail gracefully rather than block indefinitely.
155
+
156
+ ### `ReadWriteLock` for read-heavy state
157
+
158
+ ```java
159
+ private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
160
+ private Map<String, String> cache = new HashMap<>();
161
+
162
+ public String get(String key) {
163
+ rwLock.readLock().lock();
164
+ try { return cache.get(key); }
165
+ finally { rwLock.readLock().unlock(); }
166
+ }
167
+
168
+ public void put(String key, String value) {
169
+ rwLock.writeLock().lock();
170
+ try { cache.put(key, value); }
171
+ finally { rwLock.writeLock().unlock(); }
172
+ }
173
+ ```
174
+
175
+ Multiple readers proceed concurrently; a writer gets exclusive access. Worth the complexity only when reads heavily outnumber writes.
176
+
177
+ ---
178
+
179
+ ## Thread-safe collections
180
+
181
+ | Use case | Correct type | What NOT to use |
182
+ |---|---|---|
183
+ | Concurrent map (read-heavy or write-heavy) | `ConcurrentHashMap` | `HashMap` (not thread-safe), `Collections.synchronizedMap` (full lock on every op) |
184
+ | Concurrent list, infrequent writes | `CopyOnWriteArrayList` | `ArrayList`, `Collections.synchronizedList` |
185
+ | Concurrent queue / work queue | `LinkedBlockingQueue`, `ArrayBlockingQueue` | `LinkedList` |
186
+ | Set | `ConcurrentHashMap.newKeySet()` | `HashSet` |
187
+ | Cache with eviction | `Caffeine` or `Guava Cache` | `HashMap` with manual cleanup |
188
+
189
+ ### Pitfall — compound actions on `ConcurrentHashMap`
190
+
191
+ ```java
192
+ // WRONG — check-then-put is not atomic
193
+ if (!map.containsKey(key)) {
194
+ map.put(key, value);
195
+ }
196
+ // CORRECT
197
+ map.putIfAbsent(key, value);
198
+ // or for a more complex compute:
199
+ map.computeIfAbsent(key, k -> expensiveCreate(k));
200
+ ```
201
+
202
+ Even `ConcurrentHashMap` does not make compound actions atomic unless you use the atomic methods (`putIfAbsent`, `computeIfAbsent`, `merge`, `compute`).
203
+
204
+ ---
205
+
206
+ ## Static fields
207
+
208
+ ### Pitfall
209
+
210
+ Static fields are shared across all class loader instances — effectively global state in a webapp. A static mutable field is the most dangerous form of shared state: it is not scoped to a component lifecycle, so it outlives bundle reactivations and can carry stale state.
211
+
212
+ ```java
213
+ // dangerous — static mutable state in a webapp
214
+ private static Map<String, Object> cache = new HashMap<>();
215
+ ```
216
+
217
+ **Rule:** static fields in a Jahia module must be either:
218
+ - `final` and truly immutable (constants, loggers), or
219
+ - `volatile` / concurrent-typed with documented thread-safety, or
220
+ - `ThreadLocal` (thread-scoped, not shared).
221
+
222
+ If you need a cache or shared service state, use an OSGi `@Component` instance field — the OSGi lifecycle manages it correctly.
223
+
224
+ ---
225
+
226
+ ## `ThreadLocal`
227
+
228
+ `ThreadLocal` gives each thread its own isolated copy of a variable. Correct for per-request state (locale, user context, transaction context).
229
+
230
+ ### Pitfall — thread pool reuse
231
+
232
+ Jahia uses thread pools. A `ThreadLocal` set during request A and not cleared will be visible during a later request B handled by the same thread:
233
+
234
+ ```java
235
+ // always clean up in a finally block
236
+ threadLocal.set(value);
237
+ try {
238
+ doWork();
239
+ } finally {
240
+ threadLocal.remove(); // mandatory
241
+ }
242
+ ```
243
+
244
+ Failing to call `remove()` is a P1 finding — stale user context or locale leaked to subsequent requests.
245
+
246
+ ---
247
+
248
+ ## JCR sessions are NOT thread-safe
249
+
250
+ A `JCRSessionWrapper` must never be shared across threads. Do not store a session as an instance field of an OSGi service and reuse it across requests.
251
+
252
+ ```java
253
+ // WRONG — shared session across threads
254
+ @Component
255
+ public class MyService {
256
+ private JCRSessionWrapper session; // one session, all threads — crash under concurrency
257
+ }
258
+ ```
259
+
260
+ Always obtain a fresh session per-thread (and per-locale where i18n matters) and close it in a `finally` block or via `JCRTemplate`.
261
+
262
+ ---
263
+
264
+ ## Lazy initialization
265
+
266
+ ### Correct approach — `volatile` + double-checked locking
267
+
268
+ ```java
269
+ private volatile ExpensiveObject instance;
270
+
271
+ public ExpensiveObject get() {
272
+ if (instance == null) { // first check (no lock)
273
+ synchronized (this) {
274
+ if (instance == null) { // second check (with lock)
275
+ instance = new ExpensiveObject();
276
+ }
277
+ }
278
+ }
279
+ return instance;
280
+ }
281
+ ```
282
+
283
+ Without `volatile`, the JVM may publish a partially-constructed object due to instruction reordering. **`volatile` on the field is mandatory for double-checked locking to be correct.**
284
+
285
+ ### Simpler alternative — holder idiom
286
+
287
+ ```java
288
+ // no synchronization needed — class loading is inherently thread-safe
289
+ private static class Holder {
290
+ static final ExpensiveObject INSTANCE = new ExpensiveObject();
291
+ }
292
+ public static ExpensiveObject get() { return Holder.INSTANCE; }
293
+ ```
294
+
295
+ ---
296
+
297
+ ## Review checklist
298
+
299
+ When reviewing any class in a Jahia module, check:
300
+
301
+ 1. **Instance fields of `@Component` services** — are mutable ones `volatile`, atomic, or synchronized?
302
+ 2. **Static mutable fields** — flag immediately; require justification and correct synchronization.
303
+ 3. **Compound actions** — every check-then-act or read-modify-write on a shared field needs a lock or atomic CAS.
304
+ 4. **Collections returned from getters** — are they copies or unmodifiable views?
305
+ 5. **JCR sessions** — never stored as instance fields; always obtained and closed per-thread.
306
+ 6. **`ThreadLocal`** — always cleaned up in a `finally` block.
307
+ 7. **Locks** — held for the minimum possible time; no I/O inside a critical section.
308
+ 8. **Undocumented thread-safety contract** — if the class is not internally thread-safe, its Javadoc must say so and name the required external synchronization.
@@ -0,0 +1,153 @@
1
+ ---
2
+ name: jahia-java-jcr
3
+ description: JCR patterns for Jahia Java development — correct usage of sessions, workspaces, node operations, mixins, locks, and versioning. Covers both the right approach and the pitfalls that cause data loss, security gaps, or concurrency bugs. Load when implementing or reviewing any class that reads or writes the JCR.
4
+ allowed-tools: Read
5
+ ---
6
+
7
+ # JCR Patterns for Jahia Java
8
+
9
+ This skill covers how to use the JCR correctly in a Jahia Java module. Each section states the correct approach first, then the pitfall to avoid. Both developers and reviewers use this skill: developers to implement correctly from the start, reviewers to identify violations.
10
+
11
+ ---
12
+
13
+ ## Session lifecycle and workspace
14
+
15
+ ### Correct approach
16
+
17
+ - **User session** (`JCRSessionWrapper` obtained from `JCRSessionFactory.getCurrentUserSession(workspace, locale)`) enforces ACLs. Use this for any operation that should respect the user's permissions.
18
+ - **System session** (`JCRTemplate.doExecuteWithSystemSession` or `JCRSessionFactory.getCurrentSystemSession`) bypasses ACLs. Use only when a permission check was performed earlier in the call chain and documented explicitly.
19
+ - **Workspace boundary.** `default` (edit workspace, where authors work) vs `live` (published, visitor-facing). Public-facing reads must use `live`. Admin UIs use `default`. Writes that must appear publicly go through `PublicationService` — never write to `live` directly unless you have a specific operational reason.
20
+ - **Locale.** `getCurrentUserSession(workspace, locale)` resolves i18n properties. Omitting the locale falls back to default — correct only if the caller truly does not need a specific locale.
21
+
22
+ ### Pitfalls
23
+
24
+ - **System session without prior permission check.** When a system session performs an operation, trace back to where the target node ID came from. If it came from a user-session lookup with no further authorization check, the user-session lookup is the entire security boundary. Document this explicitly. If it is absent, it is a security finding.
25
+ - **Workspace mismatch.** Reading from `default` when rendering public pages, or writing to `live` when the intended target is `default`. Both produce silent wrong behavior.
26
+ - **Locale omission.** Calling without locale and reading `jcr:title` or any i18n property — the result is locale-nondeterministic.
27
+
28
+ ---
29
+
30
+ ## Node names — JSR-283 conformance
31
+
32
+ ### Correct approach
33
+
34
+ Forbidden characters in a local name: `/ : [ ] | *`, plus whitespace-only names. Use `JCRContentUtils.escapeLocalNodeName` to sanitize any externally-supplied string before using it as a node name.
35
+
36
+ ### Pitfall
37
+
38
+ Hand-rolled filename sanitization (regex replacements, `String.replace`) is almost always incomplete. The JSR-283 character set is non-obvious. Use the platform helper.
39
+
40
+ ---
41
+
42
+ ## Same-name siblings (SNS)
43
+
44
+ ### Correct approach
45
+
46
+ Two children with the same name under the same parent are indexed `node[1]`, `node[2]`. If you need to find-or-create by name under concurrent load, either:
47
+ - Lock the parent node before the check-then-create sequence.
48
+ - Use a unique-by-construction name (UUID, slug+timestamp) and store the display name as a property.
49
+
50
+ ### Pitfall
51
+
52
+ Unguarded find-or-create patterns under any concurrent caller (publication pipeline, event listener, HTTP endpoint) hit `ItemExistsException` or silently create a duplicate SNS node. Under guest endpoints this is a P1 finding.
53
+
54
+ ---
55
+
56
+ ## Mixin handling
57
+
58
+ ### Correct approach
59
+
60
+ - Before setting properties specific to a mixin, call `node.addMixin("ns:myMixin")` if the node does not already have it.
61
+ - Use `node.isNodeType("ns:myMixin")` to classify behavior rather than switching on concrete node type strings from another module. This keeps the engine decoupled from specific UI modules.
62
+ - **Definition-level vs instance-level mixins.** Mixins applied in the CND definition are always present on every node of that type. Mixins added at runtime via `addMixin()` are instance-level — they must be captured and restored explicitly in any serialization/versioning path.
63
+
64
+ ### Pitfalls
65
+
66
+ - Assuming a mixin is present because the content type "should" have it — this breaks when the content was created before the mixin was added to the definition.
67
+ - Hardcoded concrete node-type strings from another module (`fmdb:inputText`, `fmdb:textarea`). The correct pattern is classifying mixins in the engine's own CND.
68
+ - Serialization paths (export, versioning, diff) that capture `properties` but ignore `mixinNodeTypesNames` — instance-level mixin changes are silently lost on restore.
69
+
70
+ ---
71
+
72
+ ## Versioning and checkout
73
+
74
+ ### Correct approach
75
+
76
+ Writing to a `mix:versionable` node requires a `checkout()` call first. After saving, call `checkin()` if the workflow requires it. Jahia's publication service handles this for standard publication flows — only write direct checkout/checkin in custom write paths.
77
+
78
+ ### Pitfall
79
+
80
+ Writing to a versioned node without `checkout()` throws `VersionException`. Code that assumes the node is always in a checked-out state breaks whenever the publication service last left it checked in.
81
+
82
+ ---
83
+
84
+ ## Locking
85
+
86
+ ### Correct approach
87
+
88
+ Respect existing locks before performing write operations. Before clearing a lock:
89
+ 1. Check whether the lock is owned by the current operation or by an external caller (another user, a publication job, a workflow).
90
+ 2. If the lock is external, **fail the operation** with a clear error — do not clear it silently and continue.
91
+ 3. Document the thread-safety contract of any write path that involves locking.
92
+
93
+ ### Pitfall
94
+
95
+ ```java
96
+ // dangerous — clears locks unconditionally, continues even if clearing fails
97
+ JCRContentUtils.clearAllLocks(node);
98
+ restoreContent(node, version);
99
+ ```
100
+
101
+ A node locked by an active publication job, a concurrent editor, or a workflow step is locked for a reason. Clearing it unconditionally can corrupt in-progress work. This is a P0 finding if the code ships to production; P1 if guarded by a feature flag that is off by default.
102
+
103
+ ---
104
+
105
+ ## JCR event listeners
106
+
107
+ ### Correct approach
108
+
109
+ Register listeners in `@Activate` and unregister in `@Deactivate`. Use `JCRObservationManager` or Jahia's `DefaultEventListener` base class. Keep listeners short — heavy work should be dispatched to a separate thread or scheduled task.
110
+
111
+ Event listener disabling via `JCRObservationManager.setAllEventListenersDisabled(true)` is **thread-local** in Jahia, not global. It is safe to use inside a request thread or a background thread without affecting other concurrent threads.
112
+
113
+ ### Pitfalls
114
+
115
+ - Listeners registered but never unregistered — accumulate across reactivations, causing duplicate event processing.
116
+ - Blocking I/O or JCR writes inside a synchronous event listener — holds the observation thread and causes lag across the entire event queue.
117
+
118
+ ---
119
+
120
+ ## `RepositoryException` handling
121
+
122
+ ### Correct approach
123
+
124
+ - On a **security gate** (checking node type, checking permission): if the check throws, fail closed. Do not let the operation continue.
125
+ - On a **data read**: if partial results would be misleading downstream, fail or return an empty result with a logged warning.
126
+
127
+ ### Pitfall
128
+
129
+ ```java
130
+ try {
131
+ requiresAuth = node.isNodeType("...");
132
+ } catch (RepositoryException e) {
133
+ log.warn(...);
134
+ return; // operation continues — fails open
135
+ }
136
+ ```
137
+
138
+ Fail-open on a security gate is a P0 finding. Fail-open on a data read producing misleading partial state is P0 or P1 depending on downstream impact.
139
+
140
+ ---
141
+
142
+ ## JCR SQL2 queries
143
+
144
+ ### Correct approach
145
+
146
+ - Scope queries with `ISDESCENDANTNODE(alias, '/sites/...')` — never query the entire repository.
147
+ - Use specific node types, not `nt:base`. Use `jmix:searchable` for broad content queries.
148
+ - Parameterize with bind variables, not string concatenation.
149
+ - Set a `LIMIT` on unbounded queries.
150
+
151
+ ### Pitfall
152
+
153
+ `SELECT * FROM [nt:base]` against the full repository is a full-scan and blocks the query index. String-concatenated queries are a JCR injection vector (less critical than SQL injection but still wrong).