diff --git a/.deploy/mta.yaml b/.deploy/mta.yaml index e6ef2319d..f3ee3c7af 100644 --- a/.deploy/mta.yaml +++ b/.deploy/mta.yaml @@ -10,7 +10,7 @@ ID: tutorials-ims # Bump this on each release you deploy — it's the version shown by `cf mtas` # and in the mtar filename (tutorials-ims_.mtar). Deploy is manual: # `cd .deploy && mbt build && cf deploy mta_archives/tutorials-ims_.mtar -e ../deploy/.mtaext -f`. -version: 1.44.4 +version: 1.45.0 # Top-level parameters (overridable per-env via deploy/.mtaext). parameters: @@ -259,7 +259,7 @@ modules: # Wipe each static dir BEFORE cp'ing fresh content. Hugo public, qa, admin-ui, # analytics-ui, scanner-ui all need this; everything not under static/ here # (e.g. node_modules, package.json) is preserved. - - rm -rf static/admin-ui static/analytics-ui static/scanner-ui static/explore-ui static/channel-atlas-ui static/data-inspector-ui static/qa + - rm -rf static/admin-ui static/analytics-ui static/scanner-ui static/explore-ui static/channel-atlas-ui static/data-inspector-ui static/qa static/prerelease # CAP-sourced Hugo sections (concepts, developer-advocates, browse) are # generated at build time from /build/* endpoints. Because `cp -r` is # union (see comment above), a build against a backend with FEWER rows @@ -274,6 +274,9 @@ modules: - mkdir -p static/qa - cp -r ../hugo/public-qa/. static/qa/ - rm -rf static/qa/tutorials + - mkdir -p static/prerelease + - cp -r ../hugo/public-prerelease/. static/prerelease/ + - rm -rf static/prerelease/tutorials - npm --prefix ../app/admin-shell install - npm --prefix ../app/admin-shell run build - mkdir -p static/admin-ui diff --git a/.deploy/xs-security.json b/.deploy/xs-security.json index b24d0a304..c40725dad 100644 --- a/.deploy/xs-security.json +++ b/.deploy/xs-security.json @@ -35,6 +35,10 @@ "name": "$XSAPPNAME.Tutorial.Author", "description": "QA channel author preview (unpublished tutorials at /tutorials-qa/*)" }, + { + "name": "$XSAPPNAME.Tutorial.PreRelease", + "description": "Pre-release channel access (unreleased-feature tutorials at /tutorials-prerelease/*)" + }, { "name": "$XSAPPNAME.KnowledgeGraph.Admin", "description": "Knowledge graph admin: merge/veto concepts, run raw SPARQL" @@ -125,6 +129,14 @@ "$XSAPPNAME.Everyone" ] }, + { + "name": "TutorialPreRelease", + "description": "Pre-release channel access (preview unreleased-feature tutorials)", + "scope-references": [ + "$XSAPPNAME.Tutorial.PreRelease", + "$XSAPPNAME.Everyone" + ] + }, { "name": "Everyone", "description": "Baseline", @@ -195,6 +207,14 @@ "$XSAPPNAME.Everyone" ] }, + { + "name": "Tutorials PreRelease", + "description": "Pre-release channel access (gates /tutorials-prerelease/*; unreleased-feature tutorials)", + "role-template-references": [ + "$XSAPPNAME.TutorialPreRelease", + "$XSAPPNAME.Everyone" + ] + }, { "name": "Tutorials Scanner", "description": "Mobile scanner UI access for event staff (gates /scanner-ui/*, /scanner-vue/*, /scanner/*)", diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 224121ef3..926783d43 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -136,7 +136,7 @@ jobs: # Cache .tutorial-cache/ across runs so fetch-tutorials does not re-pull # ~1400 tutorials from GitHub on every CI run. Without this, mbt's 10-min # per-command timeout fires during the QA-channel fetch (the second of - # two fetches in the build sequence). Mirrors rebuild-content.yml's + # three fetches in the build sequence). Mirrors rebuild-content.yml's # caching pattern. # Cache key is keyed to the fetcher implementation (scripts/fetch-tutorials.ts # + scripts/parsers/), NOT to deploy.yml. Workflow file edits don't change @@ -180,13 +180,13 @@ jobs: # Prefetch tutorials OUTSIDE the mbt before-all phase. mbt enforces a # 10-minute timeout for the entire before-all sequence; cold-cache CI - # runs do TWO ~6-min full fetches (prod + QA) which blow past 10 min. + # runs do THREE ~6-min full fetches (prod + QA + prerelease) which blow past 10 min. # Doing the fetches as separate workflow steps removes them from mbt's # cap, AND populates the actions/cache@v4 directories for any future # mbt invocation in the same job (mbt's own fetch step then hits a # warm cache and finishes in seconds). # - # Both fetches run sequentially since they share the GitHub API rate + # All fetches run sequentially since they share the GitHub API rate # limit budget; in parallel they'd compete for tokens. Each is gated # by `if: failure()` is NOT used — we WANT a hard failure if discovery # breaks (otherwise mbt would re-fetch anyway and surface the same @@ -209,6 +209,13 @@ jobs: CAP_BASE_URL: ${{ steps.cap-url.outputs.url }} SNIPPETS_ENABLED_REPOS: meta-tutorials + - name: Prefetch prerelease tutorials (warms .tutorial-cache-prerelease) + run: npm run fetch-tutorials -- --target hugo --channel prerelease + env: + GITHUB_TOKEN: ${{ secrets.TUTORIALS_GITHUB_TOKEN || github.token }} + CAP_BASE_URL: ${{ steps.cap-url.outputs.url }} + SNIPPETS_ENABLED_REPOS: meta-tutorials + # [#797] Hugo safeHTML XSS-guard. Sweeps hugo/layouts/**/*.{html,xml,xsl} # for unmarked `| safeHTML` / `| safeHTMLAttr` / `printf "<...%s"` usages # and fails CI if any occurrence lacks a `` diff --git a/app/admin-annotations.cds b/app/admin-annotations.cds index 6e72f572b..0acfbf3c0 100644 --- a/app/admin-annotations.cds +++ b/app/admin-annotations.cds @@ -644,6 +644,9 @@ annotate AdminService.Tutorials with { ] }; ownerEmail @Common.Label: 'Owner Email' @Common.FieldControl: #ReadOnly; + // #3099 — tutorial visibility (LISTED / UNLISTED / ROLE_GATED). Enum dropdown + // from @Common.ValueListWithFixedValues; writable by admins to gate access. + visibility @Common.Label: 'Visibility' @Common.ValueListWithFixedValues; }; annotate AdminService.TutorialMeta with { @@ -704,6 +707,7 @@ annotate AdminService.Tutorials with @UI: { ]}, FieldGroup#Lifecycle: { Data: [ { Value: status }, + { Value: visibility }, { Value: deletionReason }, { Value: redirectTo_ID, Label: 'Redirect To' }, { Value: redirectUrl, Label: 'Redirect URL (external)' } diff --git a/approuter/xs-app.json b/approuter/xs-app.json index 70151a52a..89579084e 100644 --- a/approuter/xs-app.json +++ b/approuter/xs-app.json @@ -567,6 +567,13 @@ "destination": "srv-api", "authenticationType": "xsuaa" }, + { + "source": "^/content/tutorials-prerelease/(.*)$", + "target": "/content/tutorials-prerelease/$1", + "destination": "srv-api", + "authenticationType": "xsuaa", + "scope": "$XSAPPNAME.Tutorial.PreRelease" + }, { "source": "^/content/(.*)$", "target": "/content/$1", @@ -672,6 +679,34 @@ "authenticationType": "xsuaa", "scope": "$XSAPPNAME.Tutorial.Author" }, + { + "source": "^/tutorials-prerelease/_nav\\.json$", + "target": "/content/tutorials-prerelease/_nav", + "destination": "srv-api", + "authenticationType": "xsuaa", + "scope": "$XSAPPNAME.Tutorial.PreRelease" + }, + { + "source": "^/tutorials-prerelease/?$", + "target": "/prerelease/index.html", + "localDir": "static", + "authenticationType": "xsuaa", + "scope": "$XSAPPNAME.Tutorial.PreRelease" + }, + { + "source": "^/tutorials-prerelease/((?:css|js|img|fonts|vendor)/.*)$", + "target": "/$1", + "localDir": "static", + "authenticationType": "xsuaa", + "scope": "$XSAPPNAME.Tutorial.PreRelease" + }, + { + "source": "^/tutorials-prerelease/(.*)$", + "target": "/content/tutorials-prerelease/$1", + "destination": "srv-api", + "authenticationType": "xsuaa", + "scope": "$XSAPPNAME.Tutorial.PreRelease" + }, { "source": "^/tutorials/_nav\\.json$", "target": "/content/nav", diff --git a/db-qa/schema.cds b/db-qa/schema.cds index 583e30d59..75806390d 100644 --- a/db-qa/schema.cds +++ b/db-qa/schema.cds @@ -38,14 +38,18 @@ entity BranchSpecs : shared.BranchSpecsAspect {} entity RepoCatalog : shared.RepoCatalogAspect {} // Minimal Tutorials entity required by the content-store serve handler -// for status-aware lookup (soft-delete / redirect). QA only needs status -// and redirectTo so we don't replicate the full prod schema here. +// for status-aware lookup (soft-delete / redirect) and the visibility gate. +// QA only needs status, redirectTo, and visibility so we don't replicate the +// full prod schema here. `visibility` must exist because the shared serve +// handler's status SELECT reads it unconditionally (#3099); QA has no +// pre-release channel, so QA tutorials are always LISTED (the default). @cds.autoexpose: false entity Tutorials : managed { key ID : UUID; slug : String(255); title : String(500); status : String(20) default 'ACTIVE'; + visibility : String(50) default 'LISTED'; redirectTo : Association to Tutorials; redirectUrl : String(1000); } diff --git a/db/last-dev/csn.json b/db/last-dev/csn.json index f00464bf7..a273d725c 100644 --- a/db/last-dev/csn.json +++ b/db/last-dev/csn.json @@ -830,6 +830,14 @@ "length": 36, "@odata.foreignKey4": "author", "@cds.persistence.name": "AUTHOR_ID" + }, + "visibility": { + "type": "cds.String", + "length": 50, + "default": { + "val": "LISTED" + }, + "@cds.persistence.name": "VISIBILITY" } }, "$tableConstraints": { diff --git a/db/schema.cds b/db/schema.cds index 7008159c5..4b42258b4 100644 --- a/db/schema.cds +++ b/db/schema.cds @@ -21,6 +21,7 @@ type TaskType : String(20) enum { TUTORIAL; GROUP; CHECKPOINT; PUZZLE; P type EventType : String(20) enum { DEVTOBERFEST; TECHED; CODEJAM; CHALLENGE; OTHER; } type AttendanceMode : String(20) enum { VIRTUAL; IN_PERSON; HYBRID; } // #2370 +type Visibility : String(50) enum { LISTED; UNLISTED; ROLE_GATED; } type LinkHealthStatus : String(8) enum { UNKNOWN; OK; SLOW; BROKEN; }; // Per-row URL reachability, written by the url-health-check job (#2787). @@ -70,6 +71,7 @@ entity Tutorials : TaskBase, LinkHealth { categories : Composition of many TutorialCategories on categories.tutorial = $self; variables : Composition of many TutorialVariables on variables.tutorial = $self; author : Association to Users; + visibility : Visibility default 'LISTED'; } @assert.unique.slug: [slug] diff --git a/db/src/com.sap.developers.ims.Tutorials.hdbmigrationtable b/db/src/com.sap.developers.ims.Tutorials.hdbmigrationtable index 585c21587..0b8fc83b1 100644 --- a/db/src/com.sap.developers.ims.Tutorials.hdbmigrationtable +++ b/db/src/com.sap.developers.ims.Tutorials.hdbmigrationtable @@ -1,4 +1,4 @@ -== version=7 +== version=8 COLUMN TABLE com_sap_developers_ims_Tutorials ( ID NVARCHAR(36) NOT NULL, createdAt TIMESTAMP, @@ -25,9 +25,14 @@ COLUMN TABLE com_sap_developers_ims_Tutorials ( redirectTo_ID NVARCHAR(36), redirectUrl NVARCHAR(1000), author_ID NVARCHAR(36), + visibility NVARCHAR(50) DEFAULT 'LISTED', PRIMARY KEY(ID) ) +== migration=8 +-- generated by cds-compiler version 7.2.1 +ALTER TABLE com_sap_developers_ims_Tutorials ADD (visibility NVARCHAR(50) DEFAULT 'LISTED'); + == migration=7 -- generated by cds-compiler version 7.0.1 ALTER TABLE com_sap_developers_ims_Tutorials ADD (optionalSteps NVARCHAR(1000)); diff --git a/db/views.cds b/db/views.cds index 6d957769e..79882335b 100644 --- a/db/views.cds +++ b/db/views.cds @@ -93,7 +93,8 @@ view NavigatorCatalog as item.taskType } where item.taskType = 'TUTORIAL' and tut.slug is not null - and mission.published = true; + and mission.published = true + and (tut.visibility = 'LISTED' or tut.visibility is null); view SearchableItems as SELECT from ims.Tutorials as t @@ -109,7 +110,8 @@ view SearchableItems as inner join ims.Tags as tg on tg.ID = tt.tag.ID where tt.tutorial.ID = t.ID ) as tagBag : String(5000) - } where t.status is null or t.status = 'ACTIVE' + } where (t.status is null or t.status = 'ACTIVE') + and (t.visibility = 'LISTED' or t.visibility is null) UNION ALL SELECT from ims.Missions as m { m.ID, m.legacyId, m.title, m.description, m.slug, diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 59604c4d5..f061adde2 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -265,6 +265,7 @@ export default defineConfig({ { text: 'Iframe allowlist', link: '/developers/reference/iframe-allowlist' }, { text: 'MCP server tool reference', link: '/developers/reference/mcp-server' }, { text: 'On-read fetch caching', link: '/developers/reference/on-read-fetch-caching' }, + { text: 'Private tutorials research', link: '/developers/reference/private-tutorials-research' }, { text: 'Publish performance spike (#2802)', link: '/developers/reference/publish-performance-spike-2802' }, { text: 'Sage extension migration', link: '/developers/reference/sage-extension-migration' }, { text: 'TechEd sessions', link: '/developers/reference/teched' }, diff --git a/docs/developers/operations/scheduler-troubleshooting.md b/docs/developers/operations/scheduler-troubleshooting.md index 55a934e13..1b5455fe1 100644 --- a/docs/developers/operations/scheduler-troubleshooting.md +++ b/docs/developers/operations/scheduler-troubleshooting.md @@ -2,10 +2,11 @@ When a CAP 10 scheduled job stops firing without any error surfacing, it's almost always an outbox wedge: a `cds.outbox.Messages` row stuck at `status='processing'` blocks the framework from firing subsequent ticks for that jobName. -> **Three distinct "stuck job" failure modes.** Diagnose which before acting — they live in different tables and have different fixes. +> **Four distinct "stuck job" failure modes.** Diagnose which before acting — they live in different tables/columns and have different fixes. > 1. **Outbox wedge** (blocks future ticks for ONE job) — a `cds.outbox.Messages` row stuck at `status='processing'`. Fix: Force-unwedge (deletes the one row). > 2. **Orphaned `PipelineLog` row** — a job shows **RUNNING forever** on the health board while still rescheduling normally; left by a process death mid-run (deploy/crash). See [Orphaned RUNNING PipelineLog rows](#orphaned-running-pipelinelog-rows-1293). Fix: boot reconciler / Force-close. > 3. **Queue-processor stall** (**ALL** jobs overdue at once) — the shared CronService queue stops draining and high-frequency job rows drop out of the outbox entirely. A plain unwedge/delete does **NOT** fix this. See [All jobs overdue — queue-processor stall](#all-jobs-overdue--queue-processor-stall). Fix: **rolling `cf restart` of `tutorials-srv`**. +> 4. **Dead-lettered rows** (#3171) — a job's `cds.outbox.Messages` row burned all retries and sits at **`attempts = maxAttempts` (10) with `status = NULL`**. CAP never retries a dead-lettered row, and a plain **rolling restart does NOT clear it** (`CronService.init()`'s `.every().as()` UPSERT advances the next-fire `timestamp` but **preserves `attempts`**). Typical cause: the durable outbox processor ran on an instance before `CronService` was wired (boot-crash window). See [All jobs overdue — dead-letter reset](#automatic-recovery--dead-letter-reset-3171). Fix (auto since #3171): the self-heal resets `attempts=0, lastError=NULL`; manual: the SQL in that section. ## When to use this @@ -212,7 +213,43 @@ timeout: 180 -If the `SchedulerStallDetected` alert fires but the board **still** shows all jobs overdue after a couple of self-heal ticks (reaper + re-seed + `cds.flush()` all ran and none cleared it), fall back to the manual rolling restart below. +### Automatic recovery — dead-letter reset (#3171) + +The reaper (#2782/#2814), re-seeder (#2827), and `cds.flush()` (#2975) all assume the row, once present and non-`processing`, is **retryable**. There is a fourth mode where the row is present, `status=NULL` (so it looks like a healthy pending tick), and yet CAP will **never** fire it: a row **dead-lettered at `attempts = maxAttempts`** (CAP's `cds.requires.queue.maxAttempts` default is **10**, not overridden here). + +- **How it happens.** CAP's durable HANA outbox processor can pick up a `cron.` tick on an instance whose `CronService` is **not yet in the in-process registry** — e.g. a boot-crash window / not-yet-wired instance. Each tick then throws `No service 'com.sap.developers.ims.CronService' found` (`@sap/cds` queue processing). That is a **failed attempt**, not a crash: CAP increments `attempts` and writes `lastError`, no process exit. After `maxAttempts` failures the row is **dead-lettered** — left at `attempts=10, status=NULL`, with **no further retry ever**. The job silently stops firing. + - **Observed on PROD 2026-11-22:** the 2026-11-21 1.44.4 deploy had a boot-crash window; during it **12 job rows** (`metrics-rollup`, `kg-ondemand-drain`, `publish-stuck-manifest-watchdog`, `community-blogs-fetch`, `concept-embedding-backfill`, `embedding-reconciliation`, `fetch-learning-journeys`, `freshness-corpus-embedding`, `metrics-snapshots-retention`, `pipeline-log-gc`, `reconcile-completions`, `url-health-check`) burned all 10 retries (clustered `LASTATTEMPTTIMESTAMP` at 02:17/03:17/04:17 UTC) and ended at `attempts=10, status=NULL`. Both canaries were among them → `SchedulerStallDetected` fired from both instances every ~10 min (the 20+ alerts). +- **Why the other three passes miss it.** The reaper only deletes `status='processing'` rows (a dead-lettered row is `status=NULL` → skipped). The re-seeder only re-seeds jobs with **zero** `target='queue'` rows (the dead-lettered job still has its poisoned row → counts as present → no-op). `cds.flush()` drains *ready* rows but will not re-run one already at `attempts=maxAttempts`. +- **Why a rolling restart is INSUFFICIENT.** `CronService.init()`'s `schedule().every().as()` is a deterministic-ID UPSERT that advances the row's `timestamp` (next fire) but **preserves `attempts`**. Verified live in the incident: after restarting instance #0, the 12 rows' fire times advanced but `attempts` stayed 10 and the canaries still did not execute. +- **What it does.** Since #3171, the same ~10-min self-heal tick (and a boot sweep in `CronService.init()`, parity with the reaper) runs `resetDeadLetteredScheduledJobRows()` (`srv/lib/scheduler-reaper.js`): for every `target='queue'` row whose `task` is a **registered** job and whose `attempts >= maxAttempts` and `status !== 'processing'`, it `UPDATE`s `attempts=0, lastError=null` — leaving `status` (already NULL → eligible) and `timestamp` (the next-fire) untouched. This is exactly CAP's documented dead-letter recovery. The reset runs **before** the tick's `cds.flush()`, so a freshly-reset row drains on the same tick. Recovery lands within ≤ one self-heal interval (~10 min), no restart. +- **Conservative — registered jobs only.** The `task ∈ jobSchedules` guard is what never touches the `TASK=null` `SecurityEvent` audit rows (they also sit in this table) and leaves any retired/unknown job's poisoned row alone. A `status='processing'` row is skipped too — that is the reaper's territory (an in-flight claim CAP still owns); never double-handle it. +- **Fail-open throughout.** A missing outbox entity, a faulting SELECT, or a single row's UPDATE throwing never aborts the pass, never kills the timer, and never fails a scheduled tick. Overridable via `SCHEDULER_MAX_ATTEMPTS` if the queue config ever changes. + +**Recognise it** — the tell is a **bimodal `attempts`** distribution (most rows at 0, a cluster at exactly 10) with those rows at `status=NULL`: + +```sql +-- bimodal 0 / 10 → dead-letter mode. A healthy fleet is all 0. +SELECT ATTEMPTS, COUNT(*) FROM CDS_OUTBOX_MESSAGES + WHERE TARGET='queue' GROUP BY ATTEMPTS ORDER BY ATTEMPTS; + +-- the dead-lettered rows themselves +SELECT TASK, ATTEMPTS, STATUS, TO_VARCHAR(LASTATTEMPTTIMESTAMP), LASTERROR + FROM CDS_OUTBOX_MESSAGES + WHERE TARGET='queue' AND ATTEMPTS>=10 ORDER BY TASK; +``` + +**Manual reset** (the auto-recovery does this; use only if you need to force it before the next tick). **A plain rolling restart does NOT clear this mode** (it preserves `attempts`): + +```sql +UPDATE CDS_OUTBOX_MESSAGES SET ATTEMPTS=0, LASTERROR=NULL + WHERE TARGET='queue' AND ATTEMPTS>=10; -- the dead-lettered rows +``` + +Then a `cds.flush()` (or wait one self-heal tick) drains them. `status` is already NULL (eligible), so it does not need touching. + +> **Investigation note — the boot-crash window itself (#3171 item 3, open).** The `/health/ready` gate + MTA `health-check-type: http` keys (#2975) ARE in the deployed 1.44.4 build, yet instances still crash-looped `/health/ready` on 11-21 (CF events 12:51/22:54/23:35 EST). Working hypothesis: cold-HANA init exceeded `health-check-invocation-timeout: 10` / `timeout: 180` during a rough deploy, so green never reached `markSchedulerReady()` while the durable outbox kept dead-lettering on the not-yet-wired instance. **Before changing the timeouts**, capture next time: the `tutorials-srv` boot log timing from process start → `CronService wired …` → `markSchedulerReady()`, the HANA connection-pool warm-up duration, and whether `/health/ready` returned 503 vs. timed out. Only raise `invocation-timeout`/`timeout` with a reproduction showing init legitimately needs longer — otherwise the dead-letter auto-reset above already bounds the blast radius. + +If the `SchedulerStallDetected` alert fires but the board **still** shows all jobs overdue after a couple of self-heal ticks (reaper + re-seed + dead-letter reset + `cds.flush()` all ran and none cleared it), fall back to the manual rolling restart below. The alert body names this tick's self-heal actions (reset / reaped / re-seeded counts) — **if it reports dead-lettered rows reset, recheck the next tick before restarting** (the reset needs one `cds.flush()`/tick to drain, and a restart would not have helped anyway). ### Self-heal liveness — do NOT read it off a `JobLastRun` row (#2983) @@ -272,6 +309,7 @@ The earlier candidate hardening ("have `forceClose` also re-arm the affected out - Issue: [#2762](https://github.com/sap-tutorials/tutorials-ims/issues/2762) — post-boot scheduler-stall self-check + auto rolling-restart (blue-green stall); **superseded by #2782** (the self-restart didn't durably recover) - Issue: [#2782](https://github.com/sap-tutorials/tutorials-ims/issues/2782) — outbox tombstone reaper: durable fix for the NULL-`lastAttemptTimestamp` `processing` row CAP's lease can't reclaim - Issue: [#2814](https://github.com/sap-tutorials/tutorials-ims/issues/2814) — reaper PipelineLog cross-check: fast-recovers HANA-HA-failover tombstones (no app restart) via the RUNNING-row signal, bypassing the 60-min floor for jobs that aren't actually in-flight +- Issue: [#3171](https://github.com/sap-tutorials/tutorials-ims/issues/3171) — dead-letter reset: auto-recovers `attempts=maxAttempts, status=NULL` scheduled-job rows CAP will never retry (PROD stall 2026-11-22); a plain rolling restart preserves `attempts` and does not clear it - Code: `srv/jobs/scheduler.js:runWithLock` — belt-and-suspenders - Code: `srv/lib/scheduler-wedge.js` — helpers (`deleteStuckOutboxRow`, `loadStuckOutboxTargets`) - Code: `srv/lib/pipeline-log-reconciler.js` — orphaned-row reconciler (`reconcileOrphanedRunningJobs`, `forceCloseRunningPipelineLog`) diff --git a/docs/developers/reference/private-tutorials-research.md b/docs/developers/reference/private-tutorials-research.md new file mode 100644 index 000000000..74d50fed3 --- /dev/null +++ b/docs/developers/reference/private-tutorials-research.md @@ -0,0 +1,112 @@ +# Private Tutorials — Research + +**Issue:** [sap-tutorials/tutorials-ims#3099](https://github.com/sap-tutorials/tutorials-ims/issues/3099) · Research spike, 2026-11-21. + +Evaluates how to add **Private Tutorials** to developers.sap.com: tutorials authored and rendered through the existing pipeline but **served to a restricted audience** — gated to specific logged-in accounts, or geo/IP-fenced — so they can safely carry sensitive material (credentials, login details) or unreleased features shown only in a controlled setting (CodeJams, App Space, TechEd labs). This is a scoping doc; it does **not** commit an implementation to the roadmap. + +--- + +## TL;DR + +- **Reuse is high.** Authoring and rendering are unchanged — the gap is entirely at the **serve/access** layer. We already ship two working templates for "same pipeline, restricted audience": the **QA channel** (`srv-qa`) and the **SAGE preview backend** (`srv-sage`). +- **Nothing gates tutorial content today.** `/tutorials/*` is `authenticationType: "none"` at the approuter and a bare, unauthenticated Express handler in CAP. The only serve-time decision is lifecycle `status` (ACTIVE vs INACTIVE). There is **no** per-tutorial visibility flag, **no** account allowlist, and **no** geo/IP fencing anywhere in the codebase — all three are net-new. +- **Two viable gating models**, matching the two precedents: + 1. **Channel gate (coarse, QA-style):** a separate app/namespace + approuter XSUAA-scope gate. All-or-nothing per channel, edge-enforced. Cheapest; proven. + 2. **Per-identity gate (fine, SAGE-style):** IAS/XSUAA-authenticated backend with in-handler identity checks (allowlist / event-membership). Needed for "gate to specific accounts." +- **Geo/IP fencing is greenfield** — we have a reusable client-IP extractor but no country resolution or allow/deny evaluation. Best placed as an approuter extension (defense at the edge) rather than deep in CAP. +- **Sensitive content raises the bar.** Every existing channel gates only at the approuter; the CAP serve handler trusts whoever reaches it. For credentials-in-tutorials, a design should add **defense-in-depth** (handler also enforces), and treat secrets as rotate-after-event, never long-lived. +- **Recommendation:** pursue as a feature-flagged spike in house style (DB flags, fail-closed for *private* content, DEV-first). Start from the **SAGE auth model** for account-gating; layer the **QA channel pattern** for a whole-channel event lane; treat geo/IP as an optional, separate approuter layer. + +--- + +## What "private" must change — and what it must not + +The authoring and rendering pipeline is **unchanged**. A private tutorial is still markdown in a `sap-tutorials` repo → parsers → Hugo → HTML BLOB in HANA. What changes is only **who can retrieve the rendered HTML**, and **where the sensitive source lives**. + +| Layer | Public tutorials today | Private tutorials need | +| --- | --- | --- | +| Authoring | markdown in public `sap-tutorials/*` repos | **private** source repo (credentials must not sit in a public repo) | +| Parse / render | `scripts/parsers/*` → Hugo | unchanged | +| Storage | `ContentCurrent` BLOB, flat `slug` namespace | prefixed slug or separate namespace/container | +| **Serve** | `/tutorials/*` → `none` auth → bare Express handler | **authenticated + authorized** serve path | +| Access decision | `status !== 'INACTIVE'` | identity allowlist / event-membership / geo-IP | + +--- + +## Existing building blocks (verified in-repo) + +### 1. Serving is 100% anonymous today + +- AppRouter `approuter/xs-app.json` routes `^/tutorials/(.*)$` → `/content/tutorials/$1`, destination `srv-api`, **`authenticationType: "none"`** (same for `_nav.json`/`.model.json`). +- CAP mounts a bare Express route in `srv/server.js:849` — `app.get('/content/tutorials/*slug', serveHandler)` — **no auth middleware**. +- `serveHandler` (`packages/content/content-store.js:1116`; `srv/lib/content-store.js` is a re-export facade) does a status lookup (`content-store.js:1295-1326`): the **only** access decision is `status === 'INACTIVE'` → 404. Everything else is served. +- **Implication:** account-gating `/tutorials/*` requires flipping the route to `xsuaa`/`ias` *and* adding enforcement in the handler. Doing it for a *subset* (only private slugs) means either a distinct route prefix or a separate destination/app. + +### 2. QA channel — the coarse "channel gate" template + +- Separate deployed app `tutorials-srv-qa` + separate HDI container `tutorials-hana-qa`, same codebase, CDS namespace `com.sap.developers.ims.qa`, separate publish key `CONTENT_API_KEY_QA`. Handlers instantiated per-namespace via `createContentHandlers({ namespace, apiKeyEnv })` (`content-store.js:2319`). +- Gate is **entirely at the approuter**: `xs-app.json` `/tutorials-qa/*` routes are `authenticationType: "xsuaa"` + `"scope": "$XSAPPNAME.Tutorial.Author"`, destination `srv-qa-api`. Access = assign the **"Tutorials Author"** role collection (`xs-security.json`). +- **Fit:** proves "same render pipeline, different channel, XSUAA-scope-gated at the edge." A private *event lane* could clone it: new prefix (`/tutorials-private/*`) → new scope (`Tutorial.Private`) → new namespace/app. **Coarse** — one scope = the whole channel, not per-tutorial or per-account. + +### 3. SAGE preview backend — the fine "per-identity gate" template (closest precedent) + +- New (2026-11) isolated CF app `tutorials-srv-sage` (MTA `mta-sage.yaml`, `path: gen/srv-sage`) over the **shared** `tutorials-hana` container (adopted `existing-service`). Mirrors the `srv-mcp`/`srv-qa` isolation pattern. +- **Auth:** `srv-sage/package.json` sets `cds.requires.auth = { kind: ias, xsuaa: true }` — IAS primary (public PKCE client `tutorials-sage-identity`), XSUAA fallback. Service is `@path:'/author' @requires:'authenticated-user'`. +- **Authorization is in-handler by caller identity** (`assertOwnership` / `provisionDbUser`) — a user sees only their *own* tutorials, because IAS tokens carry no XSUAA scopes. **This per-user in-handler check is exactly the mechanism "gate to specific accounts" extends.** +- **Rendering:** `POST /preview/render` (`srv-sage/preview-renderer.js`) shells out to a bundled Hugo against a `preview-site/` scaffold, rendering on the fly from author-pushed markdown — **content never persisted to the public store.** This "render a tutorial for a restricted viewer without publishing it publicly" is architecturally the core of private tutorials. +- **Fit:** start here for account-gated private tutorials. It already does isolated + authenticated + per-identity-scoped rendering; it does **not** yet do account-allowlist or geo/IP (gating today is "owner only"). + +### 4. Content keying — flat `slug` namespace, prefix convention + +- `ContentCurrent` (key `slug`, the live serve table), `ContentHistory` (`version,slug`), `ContentManifest` (`version`) — `db/schema.cds:704-725`, aspects in `db/_content-shape.cds`. **No "kind" discriminator.** +- Kinds coexist by **slug prefix**: top-level pages are `page-` (`page-browse`, `page-teched`), tutorials use bare slugs. Serve/publish select `.where({slug})` with no kind filter. +- **Fit:** a `private-<...>` prefix (or a per-event/per-account prefix), or a discriminator/visibility column on `ContentCurrentAspect`, both slot in cleanly. But `ContentCurrent` is the **public** serve table with no read gate — any private namespace needs its gate at serve/approuter, as in §2/§3. + +### 5. Event ↔ tutorial relationship already exists (for the event use cases) + +- **App Space** (`/app-space/?eventId=NNN`) is a per-event progress overlay, not a content namespace. The event→tutorial link is the `Events` → `Missions` → `CompletionPaths` → `CompletionPathItems` graph, keyed by `eventId` (`Events.legacyId`); backend `getAppSpaceProgress` (`srv/developer-service.js:640`). **Fully public** — personalizes via the caller's JWT but gates nothing. +- **`EventRegistrations`** (`db/devtoberfest.cds:71`, `{user, event, joinedAt, termsVersion}`) is the only **per-user event-membership** entity — closest existing "this user belongs to this event," though today it gates registration/terms, not content. +- **TechEd sessions** (`db/external/teched.cds`) are a public read-only RainFocus directory; no gating; not a reuse candidate. +- **Fit:** for "unlock these tutorials for attendees of event X," `EventRegistrations`-style membership is the natural authorization input to a SAGE-style in-handler check. + +### 6. Enum / restriction precedents to copy + +- Audience tier: `db/schema.cds:682` `audience : String(20) enum { ALL; AUTHENTICATED; ADMIN; }` (on alerts) — closest "audience tier" shape for a new `Tutorials.audience`/`visibility`. +- Private-vs-shared: `db/analytics-builder.cds:35` `visibility default 'private' enum { private; shared-admins }`. +- Row-level restriction: `@restrict` in `analytics-service.cds:146-152` (user-scoped SavedQueries) — the one existing per-user row filter; a model for per-account tutorial filtering. +- XSUAA machinery: add a `Tutorial.Private` scope + role collection shaped exactly like `Tutorial.Author` (`xs-security.json`). + +### 7. Geo/IP — greenfield + +- No geo/country/CIDR logic anywhere. IP is read only for rate-limiting/spam dedup, via `x-forwarded-for`: reusable extractor `clientIpFrom(req)` at `srv/lib/rate-limit/shared-limiter.js:70`. +- No `cf-ipcountry`/geoip/CIDR evaluation exists — country resolution and allow/deny is new work, best as an approuter extension (edge) or alongside the serve-time status check. + +--- + +## Gating options (ranked) + +| Option | Granularity | Reuse | Build cost | Best for | +| --- | --- | --- | --- | --- | +| **A. SAGE-style per-identity backend** | per-account / per-event-membership | High (clone `srv-sage` auth + preview-render) | Medium | **Gate to specific accounts.** CodeJams, invite-only labs. | +| **B. QA-style channel gate** | whole channel (one scope) | High (clone `srv-qa` + approuter scope) | Low | A coarse "private event lane" where everyone with the role sees everything in it. | +| **C. Approuter geo/IP fence** | by source IP/country | Low (only IP extractor exists) | Medium–High | On-site-only content; layer *on top of* A or B, never alone. | +| **D. Visibility flag on public serve path** | per-tutorial | Medium | Medium | Not recommended for sensitive content — keeps secrets in the public store/table and flips `/tutorials/*` to auth for everyone. | + +**Recommended composition:** **A** as the core (isolated authenticated backend, in-handler allowlist keyed off an `EventRegistrations`-style membership), optionally fronted by **C** for on-site-only events. Use **B** when a whole invite-only channel is simpler than per-account logic. Avoid **D** for anything truly sensitive. + +--- + +## Risks & design constraints + +- **Edge-only gating is insufficient for secrets.** Every current channel trusts the serve handler. Private content with credentials needs **defense-in-depth**: the handler itself must re-check identity/authorization, not just the approuter route. (Platform posture today is edge-only — this is the one place private tutorials must diverge.) +- **Private source must not live in a public repo.** The authoring reuse story breaks if credentials sit in `sap-tutorials/*` public markdown — private tutorials need a private source repo (fetch-tutorials already supports private repos via token; the SAGE "push markdown, render on the fly, don't persist publicly" model avoids a public BLOB entirely). +- **Secrets are rotate-after-event.** Treat any credential shown in a tutorial as burned when the event ends; design for per-event ephemeral accounts, not durable secrets baked into content. +- **IAS tokens carry no XSUAA scopes** (per SAGE) — account-gating via IAS must be in-handler identity, not scope-based; scope-based gating (QA-style) uses XSUAA. +- **Geo/IP is advisory, not a security boundary** — XFF terminates at our own approuter and is spoofable before it; treat it as convenience fencing, always paired with real auth. +- House style: **DB feature flags, DEV-first, fail-open for public, fail-CLOSED for private** (a bug must not leak private content). + +--- + +## Suggested next step (if pursued) + +A time-boxed POC extending `srv-sage`: add an **allowlist/event-membership authorization check** (keyed off an `EventRegistrations`-style table) to the existing per-identity preview-render path, serving a non-persisted private tutorial to an invited account — proving account-gating end-to-end on the closest existing backend before deciding on channel (B) or geo (C) layers. diff --git a/docs/superpowers/plans/2026-11-21-navigator-search-count-guard-fix.md b/docs/superpowers/plans/2026-11-21-navigator-search-count-guard-fix.md new file mode 100644 index 000000000..c0b3cd340 --- /dev/null +++ b/docs/superpowers/plans/2026-11-21-navigator-search-count-guard-fix.md @@ -0,0 +1,153 @@ +# Navigator Search Count-Guard Fix + Pinned Filters — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make a matched mission/group actually render in navigator search results (fix #3112, which PR #3123 failed to fix), and pin selected filters above each facet list. + +**Architecture:** One root cause — the `before('READ', SearchableItems)` hook bails on `$count=true` (`srv/search-service.js:283`), which the navigator always sends, so the word-boundary filter + rank never run on the live cards query. Fix: apply the filter on all reads; gate only the `_searchRank` column+orderBy behind `!sel.count`. Plus a client-side per-column pinned selected-chips block in the navigator Vue island. + +**Tech Stack:** CAP Node.js (`@sap/cds` 10.2.2), Vitest + in-memory SQLite (unit), CAP OData over SQLite, Vue 3 island (`hugo-apps/`), Playwright (e2e). + +**Spec:** `docs/superpowers/specs/2026-11-21-navigator-search-count-guard-fix-design.md` + +## Global Constraints + +- Branch from fresh `origin/DEV`; PR targets `DEV` (not `main` — no main-hotfix path). Already on branch `worktree-3112-navigator-search-count-guard` off `origin/DEV`. +- Never change match semantics (word-boundary tokenization, stopwords, KG/community rerank). The fix is about *when* the filter/rank run, not *what* matches. +- Anti-goal: never push `_searchRank` onto a `COUNT(*)` projection (the guard's original real concern). +- CDS/API work: verify against cds-mcp before changing CDS; no raw SQL outside the existing `applyWordBoundarySearch`/`attachSearchRank` string-built clauses (which are pre-existing and out of scope to rewrite). +- Fresh worktree: `srv/lib/_shared/mcp.bundle.mjs` must exist before unit tests run — generate with `node scripts/bundle-shared.cjs` (already run this session; re-run after a clean). +- Full unit suite is hook-blocked locally; run scoped: `npm test -- ` / `npx vitest run `. + +## Review Focus + +- **Count path with no `$search`** (`$count=true` alone): must still short-circuit via the phrase guard and return the full-corpus count unchanged — pinned by Task 1 test "plain $count unaffected". +- **Internal `srv.run(SELECT…search…)` callers with no `sel.columns`** (MCP `search_tutorials`, semantic search): `attachSearchRank` self-bails at `:232`; the guard change must not break them — pinned by Task 1 test "internal search-without-columns still filters". +- **getFacets vs pager count agreement** after the fix (both should be the word-boundary set): a residual off-by-set would show a lozenge the grid can't fill — pinned by Task 1 test "count agrees with getFacets totalCount". +- **e2e self-skip masking the bug**: the existing G2 test uses `SAP` and skips if the lozenge is 0, so it can stay green before and after — Task 3 switches it to `Device` and asserts the pre→post flip. +- **Pinned-chip removal wiring**: clicking a pinned chip must clear exactly that selection (not toggle a neighbor) — pinned by Task 2 test "removing a pinned chip clears only that filter". + +--- + +## Task 1: Server — split the count guard so search filter + rank apply on the cards query + +**Files:** +- Modify: `srv/search-service.js:279-323` (the `before('READ', SearchableItems)` hook) +- Test: `test/search-service.test.js` (add cases to the existing `describe('SearchableItems'…)` block) + +**Interfaces:** +- Consumes: existing `applyWordBoundarySearch(query, term) -> string[]` (`:137`), `attachSearchRank(query, tokens, kgFragment?, communityFragment?)` (`:191`, self-bails when `!sel.columns`). +- Produces: nothing new; behavior change only. After this task, a `$search`+`$count=true` read returns the word-boundary-filtered count and (on the data read) rank-ordered rows with `searchScore` populated. + +- [ ] **Step 1: Write the failing tests** in `test/search-service.test.js` (SearchableItems block). Use the existing fixtures (`search-t2` cap-getting-started, `search-m1` full-stack-mission both match `CAP`; `search-mprobe` mission matches `missionprobe`): + +```js +it('$search + $count=true returns the word-boundary-filtered count (not 0, not whole corpus)', async () => { + const { data } = await project.get('/search/SearchableItems?$search=CAP&$count=true&$top=48'); + const slugs = data.value.map(i => i.slug); + expect(data['@odata.count']).toBeGreaterThan(0); + expect(slugs).toContain('cap-getting-started'); + expect(slugs).toContain('full-stack-mission'); + expect(slugs).not.toContain('hana-cloud-setup'); // no CAP word → filter really applied +}); + +it('$search + $count=true ranks a matching MISSION ahead of tutorial body-only matches', async () => { + // missionprobe: mission body-match (2+2 type-boost=4) must out-rank tutorial body-only (2). + const { data } = await project.get('/search/SearchableItems?$search=missionprobe&$count=true&$top=48'); + const idx = data.value.findIndex(i => i.slug === 'missionprobe-mission'); + expect(idx).toBe(0); + expect(data.value[0].searchScore).toBeGreaterThanOrEqual(4); +}); + +it('plain $count=true with no $search is unaffected (full corpus count)', async () => { + const { data } = await project.get('/search/SearchableItems?$count=true'); + expect(data['@odata.count']).toBeGreaterThanOrEqual(5); +}); +``` + +- [ ] **Step 2: Run tests to verify they FAIL** — Run: `npx vitest run test/search-service.test.js -t "count"`. Expected: the first two FAIL on current code (count=0 / mission not at idx 0, because the guard bails); the third PASSES already. + +- [ ] **Step 3: Implement the guard split** in `srv/search-service.js:279-323`. Change `if (!sel || sel.count) return;` (`:283`) to `if (!sel) return;`. Leave the phrase guard (`:284-287`) and `applyWordBoundarySearch` call (`:288-289`) unconditional. Wrap the KG/community fragment block (`:291-320`) **and** the `attachSearchRank(...)` call (`:322`) in a single `if (!sel.count) { … }` so the rank column/orderBy and the KG work run only on the data read, never the count projection. Update the `:281-282` comment to describe the split (filter always; rank only when not a count projection). + +- [ ] **Step 4: Run tests to verify they PASS** — Run: `npx vitest run test/search-service.test.js -t "count"`. Expected: all three PASS. + +- [ ] **Step 5: Run the full search-service suite for regressions** — Run: `npx vitest run test/search-service.test.js`. Expected: all green (existing `$search`, pagination, bodyText, word-boundary cases still pass). + +- [ ] **Step 6: Commit** + +```bash +git add srv/search-service.js test/search-service.test.js +git commit -m "fix(search): apply word-boundary filter+rank on \$count reads so missions surface (#3112)" +``` + +--- + +## Task 2: Client — per-column pinned selected-filter chips above each facet list + +**Files:** +- Modify: `hugo-apps/src/navigator/TutorialNavigator.vue` (filter section `:391-476`) +- Modify: `hugo/assets/css/home.css` (add `.filter-selected-pins`) +- Test: `hugo-apps/src/navigator/__tests__/TutorialNavigator.*` if present, else add a focused Vitest component test alongside the island (check for existing test dir first). + +**Interfaces:** +- Consumes: existing reactive `filters.topics/products/levels/types` arrays and the toggles `toggleFilter(dimension, value)` / `toggleProduct(value)` / `isProductSelected(value)` from `useNavigatorFilters.ts` (`:630-646`); the `ordered*` computeds (`:208-227`) and `partitionSelected` stay as-is (keep the in-list float). +- Produces: a `.filter-selected-pins` block per column; no new composable API. + +- [ ] **Step 1: Write the failing component test** asserting that when a topic/product/level/type is selected, a chip with its label renders in the `.filter-selected-pins` block for that column, and clicking the chip's remove control calls the matching toggle so the selection clears. (If no island component-test harness exists, add a minimal Vitest + `@vue/test-utils` mount test; name it `renders and removes pinned selected filter chips`.) + +- [ ] **Step 2: Run test to verify it FAILS** — Run: `npm --prefix hugo-apps run test -- TutorialNavigator` (or the discovered test command). Expected: FAIL (no `.filter-selected-pins` element). + +- [ ] **Step 3: Implement the pinned block.** In `TutorialNavigator.vue`, above each `.filter-list` in the four facet columns (`:394-460`), add a `.filter-selected-pins` block that `v-for`s over the selected values for that dimension (derive from `filters.*`), rendering a removable chip per selection whose click invokes the existing toggle for that dimension. Keep the existing in-list `ordered*`/`partitionSelected` float untouched. Add `.filter-selected-pins` + chip styles in `home.css` using existing Horizon token variables; do not change the `.filter-list` `max-height`. + +- [ ] **Step 4: Run test to verify it PASSES** — Run the same command. Expected: PASS. + +- [ ] **Step 5: Typecheck/lint the island** — Run: `npm --prefix hugo-apps run build` (or `lint`/`typecheck` if faster). Expected: no errors. + +- [ ] **Step 6: Commit** + +```bash +git add hugo-apps/src/navigator/TutorialNavigator.vue hugo/assets/css/home.css hugo-apps/src/navigator/__tests__/ +git commit -m "feat(navigator): pin selected filters above each facet list (#3112)" +``` + +--- + +## Task 3: e2e — make the G2 mission-search test actually exercise the dropped-mission path + +**Files:** +- Modify: `test/e2e/navigator-search-filter.spec.ts:106-173` (G2 test) + +**Interfaces:** +- Consumes: deployed navigator (post-fix on DEV). No code interface. + +- [ ] **Step 1: Change the search term and tighten the assertion.** Replace the `searchInput.fill('SAP')` (`:140`) with `'Device'` — the proven repro term that matches a mission buried past `$top=48` pre-fix and ranked onto page 1 post-fix. Keep the "lozenge ≥ 1 ⇒ mission card MUST be visible" invariant. Add a comment citing #3112 and the design doc. Do **not** widen the graceful-skip; if `Device` yields a 0 lozenge on the target env the test should still skip (content varies) — but on DEV/PROD with the Devtoberfest mission present it will assert. + +- [ ] **Step 2: Verify the test flips.** Against the current PROD (pre-fix) the assertion fails; against a post-fix DEV deploy it passes. Document the manual check: `SMOKE_BASE_URL= npx playwright test test/e2e/navigator-search-filter.spec.ts -g "G2"`. (This runs post-deploy, not in CI PRs — note it in the PR description.) + +- [ ] **Step 3: Commit** + +```bash +git add test/e2e/navigator-search-filter.spec.ts +git commit -m "test(e2e): search 'Device' so G2 exercises the buried-mission path (#3112)" +``` + +--- + +## Task 4: Hybrid confirmation + PR + +**Files:** none (verification + PR). + +- [ ] **Step 1: Hybrid assertion (real HANA)** — if a hybrid search test exists (`test/*hybrid*`/`npm run test:hybrid`), add/confirm an assertion that `$search=Device&$top=48&$count=true` returns `@odata.count` 56 (or current PROD value) with a MISSION at `searchScore` 7 on page 1, and that `getFacets(search='Device')` totalCount equals that `@odata.count`. Requires `cf login`. If no hybrid harness fits cheaply, record the two-row curl proof from the design doc against the DEV deploy in the PR instead. + +- [ ] **Step 2: Full scoped verification** — Run: `npx vitest run test/search-service.test.js` and the island test. Expected: green. Re-generate the shared bundle first if the worktree was cleaned (`node scripts/bundle-shared.cjs`). + +- [ ] **Step 3: Open the PR to DEV** — `gh pr create --base DEV` with a body covering: the real root cause (guard shadowing #3123's boost), the proof table, what #3123 got wrong, the pinned-filters default, and the post-deploy e2e/hybrid steps. Link #3112. + +--- + +## Notes carried from the design (decided, not open) + +- One PR for both server fix and pinned filters (Tom, 2026-11-21). +- Keep the in-list `partitionSelected` float (dropping it breaks the existing G1 e2e). +- getFacets product-mirroring already works — no re-fix, locked by Task 1's count-agreement test. +- Q1 spike **already run this session**: the bug is unit-reproducible on SQLite (`$search=CAP&$count=true` → count 0 on buggy code), so the count assertion lives in the unit test (Task 1), with hybrid as confirmation (Task 4). diff --git a/docs/superpowers/plans/2026-11-21-prerelease-navigator.md b/docs/superpowers/plans/2026-11-21-prerelease-navigator.md new file mode 100644 index 000000000..3038c5b10 --- /dev/null +++ b/docs/superpowers/plans/2026-11-21-prerelease-navigator.md @@ -0,0 +1,306 @@ +# Pre-release Navigator Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give `Tutorial.PreRelease` role-holders a scope-gated navigator to browse/filter/search ROLE_GATED tutorials, instead of needing a direct link per tutorial. + +**Architecture:** A live gated nav feed on `srv-api` (ROLE_GATED-filtered, served behind the existing `{gated:true}` seam), a QA-style build-time `prerelease` Hugo channel for the navigator shell (client-side search, reusing the existing island), and a prerequisite fix to the pre-existing public `semantic_search` ROLE_GATED leak. No schema change, no new XSUAA scope, no new CAP app. + +**Tech Stack:** CAP Node.js (`@sap/cds`), Express handlers in `packages/content/`, Hugo + Vue 3 islands, SAP approuter (`xs-app.json`), XSUAA, SQLite (unit tests) / HANA (hybrid/prod). + +**Spec:** `docs/superpowers/specs/2026-11-21-prerelease-navigator-design.md` + +## Global Constraints + +- **Base + target branch: `origin/DEV`** (never `main`). PRs target DEV. +- **No schema change** — `visibility` enum + `Tutorials.visibility` already exist on DEV. +- **No `xs-security.json` change** — scope `$XSAPPNAME.Tutorial.PreRelease`, role-template `TutorialPreRelease`, role-collection `"Tutorials PreRelease"` already exist (#3099). No `cf update-service` needed. +- **Gated trust = server-side mount**, never a client-settable header (matches #3099 `{gated:true}` at `srv/server.js:850`). +- **Gated responses must not enter a public/shared cache** — `Cache-Control: private, no-store`, never written to the slug-keyed in-process cache. +- **Channel selection is build-time** (`site.Params.`), mirroring QA — not a runtime switch. +- **CQN `.where({slug:{in:[...]}})` over large slug sets blows HANA's packet cap** — reuse the unbounded-fetch + Node-filter pattern already in `navHandlerFallback`. +- Unit tests run on in-memory SQLite (`npm test -- `); full suite is hook-blocked locally (CI runs it). + +## Review Focus + +- **Standalone (mission-less) ROLE_GATED tutorial** must appear in the gated navigator — the feed must NOT derive from the mission-scoped `NavigatorCatalog`. (Task 2 test.) +- **A LISTED tutorial must NEVER appear in the gated feed**, and a ROLE_GATED tutorial must never appear in the public `__nav__`/fallback. (Task 2 test.) +- **Public anonymous `semantic_search` must not return any ROLE_GATED slug** — on both HANA and SQLite branches. (Task 1 test.) +- **Gated nav feed response is `private, no-store`** and absent from the shared cache (no public-hit leak). (Task 2 test.) +- **An unauthenticated request to `/tutorials-prerelease/` and `/tutorials-prerelease/_nav.json` is refused by the approuter scope** (403), not served. (Task 5 — integration/e2e; approuter scope not unit-testable.) + +--- + +### Task 1: Fix public `semantic_search` ROLE_GATED leak + +Independent, must land (prerequisite). The public anonymous semantic tutorial corpus filters only on `status` + ContentCurrent presence; ROLE_GATED tutorials leak to anyone. + +**Files:** +- Modify: `srv/lib/semantic-search.js` (tutorial corpus query, ~lines 168-196 — both the HANA raw-SQL branch and the SQLite CQL branch) +- Test: `srv/__tests__/lib/semantic-search-visibility.test.js` (create) + +**Interfaces:** +- Produces: no new export; the existing semantic tutorial-search entrypoint now excludes ROLE_GATED on the public path. + +- [ ] **Step 1: Write the failing test** + +Seed two tutorials with embeddings: one `visibility='LISTED'`, one `visibility='ROLE_GATED'`, both `status='ACTIVE'` and both present in `ContentCurrent`. Call the semantic tutorial search path (the function invoked by the `semantic_search` action; import it directly from `semantic-search.js`). Assert the LISTED slug may be returned and the ROLE_GATED slug is **never** in the result set. + +```js +test('public semantic search excludes ROLE_GATED tutorials', async () => { + // seed LISTED + ROLE_GATED tutorials, both ACTIVE + in ContentCurrent, with embeddings + const results = await searchTutorials(db, queryVecForBoth, { topK: 10 }); + const slugs = results.map(r => r.slug); + expect(slugs).not.toContain('pre-release-secret'); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `npm test -- srv/__tests__/lib/semantic-search-visibility.test.js` +Expected: FAIL — ROLE_GATED slug present in results. + +- [ ] **Step 3: Add the visibility predicate to both branches in `srv/lib/semantic-search.js`** + +HANA branch: add to the SQL `WHERE` alongside the existing status gate — `AND (t."VISIBILITY" IS NULL OR t."VISIBILITY" <> 'ROLE_GATED')`. SQLite branch: add to the `.where(...)` on the `Tutorials` index fetch — `status (null/ACTIVE) and (visibility is null or visibility <> 'ROLE_GATED')`. Keep the existing `filterServableSlugs` call unchanged. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `npm test -- srv/__tests__/lib/semantic-search-visibility.test.js` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add srv/lib/semantic-search.js srv/__tests__/lib/semantic-search-visibility.test.js +git commit -m "fix(search): exclude ROLE_GATED from public semantic_search (#3168, #3099 leak)" +``` + +--- + +### Task 2: Live gated nav feed handler + +**Files:** +- Modify: `packages/content/content-store.js` (add `preReleaseNavHandler`; extract the slug-set→tutorial-nav assembly from `navHandlerFallback` ~lines 1765-1900 into a shared helper; export the new handler via `_defaults` + the module export block ~line 2327/2355) +- Modify: `srv/server.js` (mount near line 850, beside the existing `/content/tutorials-prerelease/*slug` gated serve mount) +- Test: `srv/__tests__/lib/prerelease-nav.test.js` (create) + +**Interfaces:** +- Consumes: Task 1 unaffected. +- Produces: `preReleaseNavHandler(req, res)` — Express handler returning `{ version, count, tutorials }` where each tutorial is `{ slug, title, time, level, stepCount, displayTags, ... }` (identical shape to `navHandlerFallback`). Mounted at CAP `GET /content/tutorials-prerelease/_nav`. + +- [ ] **Step 1: Write the failing test** + +Seed three tutorials in `ContentCurrent` + `Tutorials`: `listed-a` (LISTED), `gated-standalone` (ROLE_GATED, **not** in any published mission), `gated-b` (ROLE_GATED). Invoke `preReleaseNavHandler` with a mock req/res. Assert: +- `tutorials` contains `gated-standalone` and `gated-b` (standalone ROLE_GATED IS listed — Review Focus); +- `tutorials` does NOT contain `listed-a`; +- the response `Cache-Control` header is `private, no-store`; +- each returned item has `slug`, `title`, `time`, `level`, `stepCount`, `displayTags`. + +Also assert the inverse on the public path: call the existing `navHandler`/fallback over the same seed and confirm neither ROLE_GATED slug appears. + +```js +test('gated nav feed returns only ROLE_GATED incl. standalone, no-store', async () => { + const res = mockRes(); + await preReleaseNavHandler(mockReq(), res); + const slugs = res.body.tutorials.map(t => t.slug); + expect(slugs).toEqual(expect.arrayContaining(['gated-standalone', 'gated-b'])); + expect(slugs).not.toContain('listed-a'); + expect(res.headers['Cache-Control']).toBe('private, no-store'); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `npm test -- srv/__tests__/lib/prerelease-nav.test.js` +Expected: FAIL — `preReleaseNavHandler` not defined. + +- [ ] **Step 3: Extract the assembly helper and implement `preReleaseNavHandler`** + +Refactor `navHandlerFallback` so the slug-set→tutorial-nav-object assembly (the `allTutRows` fetch, step counts, display tags, and the final `{ slug, title, time, level, stepCount, displayTags }` mapping) is a shared helper `buildNavTutorials(slugSet, { visibilityFilter })` that filters `allTutRows` by `status !== 'INACTIVE'` and, when `visibilityFilter === 'ROLE_GATED'`, keeps only `t.visibility === 'ROLE_GATED'` (else keeps `visibility` LISTED-or-null and excludes ROLE_GATED — this **hardens** the cold-start fallback path, which has no visibility filter today; the normal public path serves the pre-baked `__nav__` blob that already excludes ROLE_GATED at build time, so this is defense-in-depth, not a change to the hot path). `preReleaseNavHandler` enumerates `ContentCurrent` slugs (reusing the fallback's ContentCurrent read), calls `buildNavTutorials(slugSet, { visibilityFilter: 'ROLE_GATED' })`, sets `Cache-Control: private, no-store`, and returns `{ version, count, tutorials }`. Do NOT read or write the shared slug-keyed `cache`. Export `preReleaseNavHandler`. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `npm test -- srv/__tests__/lib/prerelease-nav.test.js` +Expected: PASS. + +- [ ] **Step 5: Mount the handler in `srv/server.js`** + +Near line 850 (the existing gated serve mount), add: `app.get('/content/tutorials-prerelease/_nav', (req, res) => preReleaseNavHandler(req, res));` and add `preReleaseNavHandler` to the import from `./lib/content-store.js`. + +- [ ] **Step 6: Run the broader content-store nav tests to confirm no public regression** + +Run: `npm test -- srv/__tests__/lib/` (nav/content-store scope) +Expected: PASS — public `navHandler` still LISTED-only. + +- [ ] **Step 7: Commit** + +```bash +git add packages/content/content-store.js srv/server.js srv/__tests__/lib/prerelease-nav.test.js +git commit -m "feat(prerelease): live gated nav feed for ROLE_GATED tutorials (#3168)" +``` + +--- + +### Task 3: `prerelease` build channel (fetch + config + scripts) + +Mirror the QA channel plumbing. Build-time, no runtime switch. + +**Files:** +- Modify: `scripts/fetch-tutorials.ts` (extend `Channel` union + `--channel` validation line ~79-96; add `prerelease` cache/content/nav/static dir cases; filter the cataloged set to `visibility='ROLE_GATED'` for the `prerelease` channel, reading visibility off `/build/catalog`) +- Create: `hugo.prerelease.toml` (copy `hugo.qa.toml`; `dataDir = "data-prerelease"`, `params.prerelease = true`, prefix/baseURL for `/tutorials-prerelease/`) +- Create: `scripts/sync-island-manifest-prerelease.cjs` (copy `scripts/sync-island-manifest-qa.cjs`, retargeted to the prerelease data/public dirs) — or parameterize the QA one if trivial +- Modify: `package.json` scripts: add `fetch-tutorials:prerelease`, `build:prerelease`, `prerelease:full` (mirror `fetch-tutorials:qa`/`build:qa`/`qa:full`); wire `build:prerelease` into `build:all` +- Modify: `scripts/verify-qa-build.ts` → generalize or add `verify-prerelease-build` target for `hugo/public-prerelease` +- Test: `scripts/__tests__/fetch-tutorials-channel.test.ts` (create or extend existing channel test) + +**Interfaces:** +- Consumes: `/build/catalog` payload (already carries `visibility` per tutorial). +- Produces: `hugo/data-prerelease/` (nav/browse data, ROLE_GATED only), `hugo/public-prerelease/` (built site incl. `index.html`), and the channel accepted by `--channel prerelease`. + +- [ ] **Step 1: Write the failing test** + +Assert `parseChannel(['--channel','prerelease'])` returns `'prerelease'` (currently throws `Unknown channel`), and that the prerelease dir helpers (`getQaCacheDir`/`getHugoContentDir`/`getNavJsonDir` or their generalized forms) return `*-prerelease`/`static-prerelease` paths for the prerelease channel. + +```ts +test('prerelease channel parses and maps to prerelease dirs', () => { + expect(parseChannel(['--channel','prerelease'])).toBe('prerelease') + expect(getHugoContentDir('prerelease')).toMatch(/prerelease/) +}) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `npm test -- scripts/__tests__/fetch-tutorials-channel.test.ts` +Expected: FAIL — `Unknown channel: prerelease`. + +- [ ] **Step 3: Extend the channel union + dir helpers + visibility filter** + +`Channel = 'prod' | 'qa' | 'prerelease'`; accept it in `parseChannel`; add `prerelease` cases to the cache/content/nav/static dir helpers (`data-prerelease`, `static-prerelease`, `public-prerelease`). In the catalog→content step, when `channel === 'prerelease'` keep only tutorials whose catalog `visibility === 'ROLE_GATED'` (prod keeps LISTED, qa keeps its contribution set). Reuse the QA degraded-cache guard pattern if it applies. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `npm test -- scripts/__tests__/fetch-tutorials-channel.test.ts` +Expected: PASS. + +- [ ] **Step 5: Create `hugo.prerelease.toml`, the manifest-sync script, and the `package.json` scripts** + +Copy `hugo.qa.toml` → `hugo.prerelease.toml` (set `dataDir`, `params.prerelease`, baseURL/prefix). Add scripts mirroring QA. Wire `build:prerelease` into `build:all` beside `build:qa`. + +- [ ] **Step 6: Build the channel end-to-end (smoke)** + +Run: `scripts/quiet-run.sh npm run fetch-tutorials:prerelease && scripts/quiet-run.sh npm run build:prerelease` +Expected: exit 0; `hugo/public-prerelease/tutorials-prerelease/index.html` (or the configured shell path) exists. (Requires `CAP_BASE_URL` pointing at a backend with a seeded ROLE_GATED tutorial, or an empty-but-valid build.) + +- [ ] **Step 7: Commit** + +```bash +git add scripts/fetch-tutorials.ts hugo.prerelease.toml scripts/sync-island-manifest-prerelease.cjs package.json scripts/verify-*.ts scripts/__tests__/fetch-tutorials-channel.test.ts +git commit -m "feat(prerelease): QA-style prerelease build channel (#3168)" +``` + +--- + +### Task 4: Navigator template `prerelease` branch + +**Files:** +- Modify: `hugo/layouts/tutorial-navigator/list.html` (add `prerelease` to the channel conditions: the `{{ if not site.Params.qa }}` discovery-section gate at line 30/179, and the island data-attr line at line 41) +- Test: manual/visual via the Task 3 build output (template logic has no unit harness; covered by the Task 6 e2e). + +**Interfaces:** +- Consumes: `site.Params.prerelease` (set by `hugo.prerelease.toml`), Task 2's `_nav.json` at `/tutorials-prerelease/_nav.json`. +- Produces: a navigator shell that mounts the island with `data-nav-base="/tutorials-prerelease"`, `data-href-base="/tutorials-prerelease"`, `data-client-search="true"`, and no `data-search-base` (client search). + +- [ ] **Step 1: Extend the discovery-section gate** + +Change `{{ if not site.Params.qa }}` (lines ~30, ~179) to also suppress the homepage/discovery sections for prerelease: `{{ if and (not site.Params.qa) (not site.Params.prerelease) }}`. + +- [ ] **Step 2: Extend the island data-attr line (line ~41)** + +Add a prerelease branch mirroring the QA one: when `site.Params.prerelease`, emit `data-nav-base="/tutorials-prerelease" data-href-base="/tutorials-prerelease" data-client-search="true"` and a "Pre-release" heading/badge. (No `data-search-base` — client search, confirmed: `TutorialNavigator.vue:27` + `useSearch.ts:18-21`.) Also update the `$hrefBase` SSR assignment (line ~198) to set `/tutorials-prerelease` when prerelease. + +- [ ] **Step 3: Rebuild and eyeball the shell** + +Run: `scripts/quiet-run.sh npm run build:prerelease` +Expected: the built `index.html` contains the island mount node with the prerelease data-attrs and omits the discovery sections. + +- [ ] **Step 4: Commit** + +```bash +git add hugo/layouts/tutorial-navigator/list.html +git commit -m "feat(prerelease): navigator template prerelease channel branch (#3168)" +``` + +--- + +### Task 5: Approuter routes (scope-gated surface) + +**Files:** +- Modify: `approuter/xs-app.json` (add the prerelease route block BEFORE the existing `^/tutorials-prerelease/(.*)$` slug catch-all; mirror the QA static/index/asset/nav routes but `scope: "$XSAPPNAME.Tutorial.PreRelease"`) +- Modify: `.deploy/xs-app.json` if a synced copy exists (follow the #3099 `.deploy` sync convention — verify) + +**Interfaces:** +- Consumes: static shell from Task 3/4 (built into the prerelease static dir), live nav feed from Task 2 (`/content/tutorials-prerelease/_nav`). +- Produces: scope-gated routes: `/tutorials-prerelease/` (index shell), `/tutorials-prerelease/`, `/tutorials-prerelease/_nav.json`; existing slug route unchanged and LAST. + +- [ ] **Step 1: Add the route block (specific-before-catch-all ordering)** + +Insert, before the slug route (and matching how QA maps `/qa/*` in the static dir — confirm the static path for prerelease, e.g. `/prerelease/index.html`): +```jsonc +{ "source": "^/tutorials-prerelease/?$", "target": "/prerelease/index.html", + "localDir": "static", "authenticationType": "xsuaa", "scope": "$XSAPPNAME.Tutorial.PreRelease" }, +{ "source": "^/tutorials-prerelease/((?:css|js|img|fonts|vendor)/.*)$", "target": "/$1", + "localDir": "static", "authenticationType": "xsuaa", "scope": "$XSAPPNAME.Tutorial.PreRelease" }, +{ "source": "^/tutorials-prerelease/_nav\\.json$", "target": "/content/tutorials-prerelease/_nav", + "destination": "srv-api", "authenticationType": "xsuaa", "scope": "$XSAPPNAME.Tutorial.PreRelease" } +``` +Leave the existing `^/tutorials-prerelease/(.*)$` → `/content/tutorials-prerelease/$1` slug route as the LAST of the group. + +- [ ] **Step 2: Validate JSON** + +Run: `jq . approuter/xs-app.json > /dev/null && echo OK` +Expected: `OK` (no parse error). + +- [ ] **Step 3: Sync `.deploy` copy if the convention requires it** + +Verify whether `.deploy/xs-app.json` is a tracked synced copy (as `.deploy/xs-security.json` was in #3099, commit `e44fe7176`). If so, apply the same edit there. + +- [ ] **Step 4: Commit** + +```bash +git add approuter/xs-app.json .deploy/xs-app.json +git commit -m "feat(prerelease): scope-gated navigator approuter routes (#3168)" +``` + +--- + +### Task 6: e2e + deploy-path wiring + +**Files:** +- Create: `test/e2e/prerelease-navigator.spec.ts` (Playwright; self-skips without `SMOKE_BASE_URL` + `SMOKE_TECH_USER`/`PASSWORD`, per the repo e2e convention) +- Modify: deploy/rebuild wiring if `build:prerelease` isn't already carried by `build:all` + the MTA packaging of the static shell (verify Task 3 Step 5 covered `build:all`; confirm the MTA ships `public-prerelease`/the static shell) + +**Interfaces:** +- Consumes: the deployed gated surface. + +- [ ] **Step 1: Write the e2e spec** + +With an authenticated `Tutorial.PreRelease` role-holder session: load `/tutorials-prerelease/`, assert the navigator island renders with ≥1 card for a seeded ROLE_GATED tutorial, filter/search client-side narrows the list, and clicking a card navigates to `/tutorials-prerelease/:slug` and renders `
`+`

` (served tutorials render those, NOT `
` — per repo e2e note). Self-skip when the smoke env vars are absent. + +- [ ] **Step 2: Confirm deploy packaging** + +Verify `build:all` runs `build:prerelease` and the MTA approuter builder ships the prerelease static shell + assets (same mechanism as QA's `static-qa`). Document the baked-artifact wipe caution (rebuild-tarball / local-deploy-skip) in the PR description and, if a runbook touches QA channels, add a prerelease line. + +- [ ] **Step 3: Commit** + +```bash +git add test/e2e/prerelease-navigator.spec.ts +git commit -m "test(prerelease): e2e navigator smoke + deploy-path note (#3168)" +``` + +--- + +## Notes for the executor + +- **Known DEV bug to avoid reintroducing:** server-side `$search` KG-rerank 500s on HANA (broken simple-CASE). This plan uses **client-side** search (no server `$search` for prerelease), so it's avoided — do not add a server search service. +- After all tasks: run the scoped unit suites that were touched (`npm test -- srv/__tests__/lib/ scripts/__tests__/`) and open a PR to **DEV** (`gh pr create --base DEV`). Do not merge to `main`. diff --git a/docs/superpowers/plans/2026-11-21-private-tutorials.md b/docs/superpowers/plans/2026-11-21-private-tutorials.md new file mode 100644 index 000000000..5d85db60d --- /dev/null +++ b/docs/superpowers/plans/2026-11-21-private-tutorials.md @@ -0,0 +1,181 @@ +# Private Tutorials Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add a per-tutorial `visibility` field (`LISTED`/`UNLISTED`/`ROLE_GATED`) that hides event-hidden tutorials from discovery and hard-gates pre-release tutorials behind an XSUAA scope, reusing the existing render/serve pipeline. + +**Architecture:** One enum column on `Tutorials`, defaulting to `LISTED` (no data migration). Discovery surfaces (navigator view, search view, catalog feed, sitemap) suppress non-`LISTED`. Pre-release tutorials are served only via a new scope-gated approuter prefix `/tutorials-prerelease/*` → a distinct CAP mount `/content/tutorials-prerelease/*` (same serve handler, `gated: true` flag); the public route 404s ROLE_GATED slugs and never caches them (fail-closed). + +**Tech Stack:** CAP (Node.js, CDS), SAP HANA, @sap/approuter, XSUAA, Hugo. Tests: Vitest/Jest unit (in-memory SQLite), existing `npm test -- ` scoped run. + +**Spec:** `docs/superpowers/specs/2026-11-21-private-tutorials-design.md` + +## Global Constraints + +- PRs target **DEV**; never direct-merge to `main`. (per project memory) +- Never write raw SQL via CDS QL — but the serve handler already uses raw `db.run()` for BLOB/LOB reasons; follow the existing pattern in `packages/content/content-store.js` only there. +- Never SELECT a HANA BLOB alongside metadata in one CDS QL query (LOB locators expire) — the status/visibility lookup is metadata-only, keep it separate from BLOB reads. +- Enum values are exactly `LISTED`, `UNLISTED`, `ROLE_GATED` (strings). Default `LISTED`. Treat `null` as `LISTED` for the pre-activation window. +- XSUAA scope name exactly `$XSAPPNAME.Tutorial.PreRelease`; role-template `TutorialPreRelease`; role-collection `"Tutorials PreRelease"` — mirroring the existing `Tutorial.Author` trio. +- Gated approuter prefix exactly `/tutorials-prerelease/`; gated CAP mount exactly `/content/tutorials-prerelease/`. +- Scope changes require manual `cf update-service tutorials-xsuaa -c xs-security.json` after deploy, verified live before the gated route serves. + +## Review Focus + +- **Null visibility on existing rows** — before the column default activates on HANA, rows read `null`; every discovery filter and the serve gate must treat `null` as `LISTED` (don't hide existing tutorials, don't gate them). → covered in Tasks 2, 3, 6. +- **Cache leak across routes** — a ROLE_GATED body fetched via the gated route must never be served to a later public-route hit from the shared in-process cache or the edge CDN. → covered in Task 6 (no-store + no shared-cache entry + check-before-cache-hit). +- **Public route hitting a ROLE_GATED slug** — must 404 (not 403, not serve). → covered in Task 6. +- **UNLISTED still servable** — hide-only means a direct URL still works; the serve gate must NOT 404 UNLISTED on the public route. → covered in Task 6. +- **Scope referenced before it's live** — approuter route references `Tutorial.PreRelease` before the XSUAA re-push; rollout must sequence scope-live before gated serving. → covered in Task 5 + Rollout. + +--- + +## Task 1: Add the `visibility` field and `Visibility` enum + +**Files:** +- Modify: `db/schema.cds` (enum near `TaskStatus` line ~18; element on `Tutorials` body lines 46-73) +- Test: `srv/__tests__/` (new file `visibility-model.test.js`) + +**Interfaces:** +- Produces: `com.sap.developers.ims.Tutorials.visibility` — enum string, default `'LISTED'`, values `LISTED|UNLISTED|ROLE_GATED`. + +- [ ] **Step 1: Write the failing test** — `visibility-model.test.js`: insert a `Tutorials` row without `visibility`, read it back, assert `visibility === 'LISTED'` (default applies); insert one with `'ROLE_GATED'`, assert it round-trips. +- [ ] **Step 2: Run, verify it fails** — `npm test -- visibility-model` → FAIL (field unknown). +- [ ] **Step 3: Add to `db/schema.cds`** — `type Visibility : String(50) enum { LISTED; UNLISTED; ROLE_GATED; }` near line 18; add `visibility : Visibility default 'LISTED';` to the `Tutorials` entity body. Do **not** add to `TaskBase` (keep it per-tutorial). +- [ ] **Step 4: Run, verify it passes** — `npm test -- visibility-model` → PASS. +- [ ] **Step 5: Commit** — `feat(db): add Tutorials.visibility enum (#3099)` + +## Task 2: Filter the navigator view + +**Files:** +- Modify: `db/views.cds:95-96` (`NavigatorCatalog` view WHERE) +- Test: `srv/__tests__/` (`navigator-visibility.test.js`) + +**Interfaces:** +- Consumes: `Tutorials.visibility` (Task 1). + +- [ ] **Step 1: Write the failing test** — seed three tutorials (LISTED, UNLISTED, ROLE_GATED) wired into a published mission/path; read `NavigatorCatalog`; assert only the LISTED slug appears. Add a fourth with `visibility = null`; assert it DOES appear (null = listed). +- [ ] **Step 2: Run, verify it fails** — `npm test -- navigator-visibility` → FAIL (UNLISTED/ROLE_GATED present). +- [ ] **Step 3: Edit the view WHERE** — add `and (tut.visibility = 'LISTED' or tut.visibility is null)` to the `NavigatorCatalog` WHERE at `db/views.cds:95-96`. +- [ ] **Step 4: Run, verify it passes** — → PASS. +- [ ] **Step 5: Commit** — `feat(nav): hide non-listed tutorials from navigator (#3099)` + +## Task 3: Filter the search index view + +**Files:** +- Modify: `db/views.cds:112` (`SearchableItems` Tutorials-branch WHERE) +- Test: `srv/__tests__/` (`search-visibility.test.js`) + +**Interfaces:** +- Consumes: `Tutorials.visibility` (Task 1). + +- [ ] **Step 1: Write the failing test** — seed LISTED + UNLISTED + ROLE_GATED + null tutorials; read `SearchableItems` filtered to `taskType='TUTORIAL'`; assert only LISTED and null appear. +- [ ] **Step 2: Run, verify it fails** — `npm test -- search-visibility` → FAIL. +- [ ] **Step 3: Edit the view WHERE** — add `and (t.visibility = 'LISTED' or t.visibility is null)` to the Tutorials branch at `db/views.cds:112`. +- [ ] **Step 4: Run, verify it passes** — → PASS. +- [ ] **Step 5: Commit** — `feat(search): exclude non-listed tutorials from search index (#3099)` + +## Task 4: Carry `visibility` on the catalog feed (do NOT filter it) + +**Files:** +- Modify: `srv/lib/build-catalog.js:24-26` (add column, no predicate change) +- Test: `srv/__tests__/` (`build-catalog-visibility.test.js`) + +**Interfaces:** +- Consumes: `Tutorials.visibility` (Task 1). +- Produces: each tutorial entry in the `/build/catalog` payload carries a `visibility` property. Consumed by Task 7 (sitemap front-matter). + +- [ ] **Step 1: Write the failing test** — call `buildCatalogHandler` (or the function it delegates to) with a seeded UNLISTED tutorial; assert the tutorial entry is **present** in the payload AND has `visibility: 'UNLISTED'`. (Guards against accidentally filtering the feed.) +- [ ] **Step 2: Run, verify it fails** — `npm test -- build-catalog-visibility` → FAIL (`visibility` undefined). +- [ ] **Step 3: Edit the SELECT** — add `'visibility'` to the `.columns(...)` list at `srv/lib/build-catalog.js:24-26`. Do **not** change the `status` WHERE. Ensure the field is passed through into the emitted payload object. +- [ ] **Step 4: Run, verify it passes** — → PASS. +- [ ] **Step 5: Commit** — `feat(catalog): expose visibility on build-catalog feed (#3099)` + +## Task 5: Add the `Tutorial.PreRelease` XSUAA scope + role, and the gated approuter route + +**Files:** +- Modify: `xs-security.json` (scope after line ~37; role-template after the `TutorialAuthor` block ~127; role-collection after `"Tutorials Author"` ~197) +- Modify: `approuter/xs-app.json` (new route block mirroring the `Tutorial.Author` QA routes ~629-674) +- Test: none automated (config); verified in Task 8 smoke. + +**Interfaces:** +- Produces: scope `$XSAPPNAME.Tutorial.PreRelease`; approuter route `^/tutorials-prerelease/(.*)$` → target `/content/tutorials-prerelease/$1`, `authenticationType: xsuaa`, `scope: $XSAPPNAME.Tutorial.PreRelease`, destination `srv-api`. Consumed by Task 6 (CAP mount) + Task 8 (smoke). + +- [ ] **Step 1: Add XSUAA entries** — mirror the three `Tutorial.Author` entries in `xs-security.json` for `Tutorial.PreRelease` / `TutorialPreRelease` / `"Tutorials PreRelease"` (scope-references include `$XSAPPNAME.Everyone`, same as the Author trio). +- [ ] **Step 2: Add the approuter route** — insert the gated route block (exact shape in the design §3) into `approuter/xs-app.json`, placed with the other authenticated routes. +- [ ] **Step 3: Validate JSON** — `jq . xs-security.json >/dev/null && jq . approuter/xs-app.json >/dev/null` → no parse errors. +- [ ] **Step 4: Commit** — `feat(auth): add Tutorial.PreRelease scope + gated approuter route (#3099)` + +## Task 6: Serve-gate ROLE_GATED tutorials (distinct mount + handler check + cache fail-closed) + +**Files:** +- Modify: `packages/content/content-store.js` — status SELECT ~1295-1298 (add `visibility` column), `serveHandler` ~1116 and `serveStoredSlug` ~984 (gated flag, pre-cache check, no-store cache rules) +- Modify: `srv/server.js:849` area — add `app.get('/content/tutorials-prerelease/*slug', ...)` calling the shared handler with `{ gated: true }` +- Test: `srv/__tests__/` (`serve-gate-visibility.test.js`) + +**Interfaces:** +- Consumes: `Tutorials.visibility` (Task 1); gated route from Task 5. +- Produces: public `/content/tutorials/*` mount (`gated: false`) + gated `/content/tutorials-prerelease/*` mount (`gated: true`), both → `serveHandler`. + +- [ ] **Step 1: Write the failing tests** — four cases against the serve handler: + (a) public route + ROLE_GATED slug → 404 (`serveNotFound`); + (b) gated mount + ROLE_GATED slug → 200, served; + (c) public route + UNLISTED slug → 200, served (hide-only, NOT gated); + (d) gated-route response sets `Cache-Control: private, no-store` and the slug is NOT retrievable from the shared cache on a subsequent public hit (assert public hit after a gated hit still 404s — proves no cross-route cache leak). +- [ ] **Step 2: Run, verify they fail** — `npm test -- serve-gate-visibility` → FAIL. +- [ ] **Step 3: Implement** — + - Add `visibility` to the status SELECT columns (`content-store.js:1295-1298`), metadata-only (no BLOB). + - Thread a `gated` boolean into `serveHandler`/`serveStoredSlug` (bound per mount). + - **Before `cache.get(slug)`** (line ~989): resolve visibility; if `visibility === 'ROLE_GATED'` and `!gated` → `serveNotFound` and return (runs on every request, including would-be cache hits). + - When `gated && visibility === 'ROLE_GATED'`: set `Cache-Control: private, no-store` instead of `public, max-age=60`, and do **not** `cache.set(...)` for it (or key the cache by `gated`+slug so a gated entry can't satisfy a public lookup). + - Treat `null`/`undefined`/`LISTED`/`UNLISTED` visibility as servable on the public route. +- [ ] **Step 4: Add the gated CAP mount** — in `srv/server.js` near line 849, mount `/content/tutorials-prerelease/*slug` to the shared handler with `{ gated: true }`; leave the public mount `{ gated: false }`. +- [ ] **Step 5: Run, verify they pass** — `npm test -- serve-gate-visibility` → PASS. +- [ ] **Step 6: Commit** — `feat(serve): hard-gate ROLE_GATED tutorials, fail-closed cache (#3099)` + +## Task 7: Sitemap suppression via `private` front-matter + +**Files:** +- Modify: `scripts/fetch-tutorials.ts` (page front-matter generation; reads catalog `visibility` from Task 4) +- Test: `scripts/__tests__/` or the repo's TS test location (`fetch-tutorials-private.test.ts`) — if fetch-tutorials has no unit harness, a focused test around the front-matter emit function; otherwise document a manual check. + +**Interfaces:** +- Consumes: catalog `visibility` property (Task 4). + +- [ ] **Step 1: Write the failing test** — given a catalog entry with `visibility: 'UNLISTED'` (and one `ROLE_GATED`, one `LISTED`), the generated tutorial front-matter has `private: true` for UNLISTED and ROLE_GATED, and no `private` (or `false`) for LISTED. +- [ ] **Step 2: Run, verify it fails** — scoped test → FAIL. +- [ ] **Step 3: Implement** — in the front-matter emit path, set `private: true` when the catalog `visibility` for that slug is not `LISTED` (and not null). The Hugo template `hugo/layouts/_default/sitemap.xml` already excludes `.Params.private` — no template change needed. +- [ ] **Step 4: Run, verify it passes** — → PASS. +- [ ] **Step 5: Commit** — `feat(sitemap): exclude non-listed tutorials via private front-matter (#3099)` + +## Task 8: Admin-UI affordance + smoke verification + +**Files:** +- Modify: the tutorial admin Fiori form (field annotation enabling `visibility` edit — builder locates the admin entity projection for `Tutorials`) +- Test: `test/smoke/` or `test/e2e/` as fits the repo — a smoke assertion that the gated route 403s without the scope. + +**Interfaces:** +- Consumes: scope + route (Task 5); gated mount (Task 6). + +- [ ] **Step 1: Expose `visibility` on the admin projection** — add the field to the admin service projection of `Tutorials` so it's editable; a dropdown falls out of the enum type. (Follow existing admin-field patterns.) +- [ ] **Step 2: Smoke test (post-deploy, documented)** — against a deployed DEV env with a ROLE_GATED tutorial: `GET /tutorials-prerelease/` without the role → 403 at approuter; with the role → 200. `GET /tutorials/` (public) for the same slug → 404. Record as a smoke/e2e step (self-skips without `SMOKE_BASE_URL`, per repo convention). +- [ ] **Step 3: Commit** — `feat(admin): edit tutorial visibility; smoke-gate pre-release (#3099)` + +--- + +## Rollout + +DEV-first. Default `LISTED` keeps the change inert until a tutorial is marked otherwise. + +**Ship order (each step independently safe):** +1. Tasks 1–4, 7 — data model + discovery suppression + sitemap. Makes UNLISTED fully work and hides ROLE_GATED from discovery. +2. Tasks 5–6 — XSUAA scope/role + approuter gated route + handler gate. **Before this serves:** run `cf update-service tutorials-xsuaa -c xs-security.json` and verify `Tutorial.PreRelease` is live (MTA deploys skip the re-push). Admin edit (Task 8) can land with either step. + +Fail-closed everywhere: if `visibility` can't be read, a ROLE_GATED-marked row is never served on the public route; discovery filters treat unknown as LISTED (don't accidentally hide everything). + +## Self-review notes + +- **Spec coverage:** field (T1), three discovery seams (T2 nav, T3 search, T4+T7 sitemap), serve gate (T6), XSUAA+route (T5), admin (T8) — all design sections mapped. +- **Type consistency:** `visibility` string enum used identically across T1–T7; `gated` boolean defined T6 and used only there; catalog `visibility` property produced T4 / consumed T7. +- **Review Focus:** all five pinned to tasks (null→T2/T3/T6, cache leak→T6, public-404→T6, UNLISTED-servable→T6, scope-sequencing→T5/Rollout). +- **Proportion:** plan is signatures + test names + exact values; no function bodies transcribed. In proportion to the design. diff --git a/docs/superpowers/specs/2026-11-21-navigator-search-count-guard-fix-design.md b/docs/superpowers/specs/2026-11-21-navigator-search-count-guard-fix-design.md new file mode 100644 index 000000000..a8cb9e57c --- /dev/null +++ b/docs/superpowers/specs/2026-11-21-navigator-search-count-guard-fix-design.md @@ -0,0 +1,186 @@ +# Navigator search: count-guard fix + pinned selected filters (#3112 follow-up) + +**Date:** 2026-11-21 +**Issue:** sap-tutorials/tutorials-ims#3112 (follow-up comment 2026-11-18 by `thecodester`) +**Supersedes the search half of:** `2026-11-12-navigator-search-filter-improvements-design.md` (PR #3123, merged + promoted to `main` 2026-11-12) — whose G2 fix did not work in PROD. + +## Intent and why + +Issue #3112's follow-up (2026-11-18) reports that search **still** drops missions in +production, five days after PR #3123 ("fully delivered in production and live") merged and +promoted. Tom's repro: on `/tutorial-navigator/?...&q=Device` the mission lozenge shows a +count but no mission card renders. He also restated the filter ask: selected filters should +be visible **outside** the scrolling facet box, not merely floated to the top inside it. He +confirmed the completed-tutorials filter is good and de-prioritized the filter-visibility ask +("not really that important"), but it is cheap and worth doing. + +The point of this work: make a matched mission actually render in the search grid, and keep +the selected filters in view. + +## Root cause (proven, not theorized) + +The #3123 design attributed the dropped mission to three things — low mission rank, missing +search-mode pagination, and `getFacets` ignoring `$filter` — and fixed all three. **None was +the cause.** The real cause is a single guard: + +``` +srv/search-service.js:283 if (!sel || sel.count) return; // before('READ', SearchableItems) +``` + +The island's cards query **always** sends `$count=true` (`hugo-apps/src/navigator/useSearch.ts:201-212`; +no `$select`, no `$orderby`). In CAP 10.2.2 the OData adapter dispatches `$count=true` as a +**single** `READ` with `SELECT.count` truthy on the same query object (`@sap/cds` `libx/odata/middleware/read.js:262`, +grammar `:906`); the db-service derives the count by cloning that **already-processed** query +(`@cap-js/db-service` `SQLService.js:170-172, 336-361`). So the guard makes the `before('READ')` +hook bail on **every** island search, which means: + +- `applyWordBoundarySearch` never runs → `sel.search` survives → CAP's default `$search` + translation fires (broad, wrong match-set: **count 91**, not the word-boundary **56**). +- `attachSearchRank` never runs → no `_searchRank` column, no `_searchRank DESC` orderBy → + **raw UNION-ALL view order**; `searchScore` is `null` on every row. +- The mission that would rank **#0 (score 7 = 3 title + 2 desc + 2 type-boost)** is buried + behind ~80 concepts, past the `$top=48` page → "counted but never shown." + +The #3123 rank boost (`search-service.js:214`) is correct but **dead code** on the live path, +because this guard shadows it. + +### Proof (PROD, developers.sap.com, 2026-11-21) + +| Request | Count | Order | Mission | +|---|---|---|---| +| `$search=Device&$top=48&$count=true` (island shape) | 91 | raw (searchScore null ×48) | absent | +| `$search=Device&$top=48` (no `$count` → hook runs) | 56 | ranked | **#0, score 7** | + +### What is NOT broken (verified, so do not "re-fix") + +- **getFacets product-mirroring already works.** `getFacets(search='Device', products=['software-product>sap-build-apps'])` + returns totalCount 1 / TUTORIAL:1 / **no mission** — agrees with the items query under the + same filter (count 1, TUTORIAL only). #3123 wired `products`/`isNew` into `getFacets` + (`search-service.js:559-564`) and it functions. Bug "B" (lozenge ≠ grid under a product + filter) does **not** reproduce today; Tom's 2026-11-18 screenshot predates that wiring + reaching PROD or shows a stale lozenge. We lock it with a regression test, not a new fix. + +## Goals / non-goals / anti-goals + +**Goals** +- G1 — A mission/group that matches a free-text query **renders in the grid**, at its ranked + position, on the island's real request shape (`$search=…&$top=48&$skip=0&$count=true`). +- G2 — The `@odata.count` returned for that request reflects the **word-boundary** match-set + (the 56-set), not CAP's default-`$search` 91-set, so the pager total is honest. +- G3 — Selected facets are visible **outside** the capped scroll box, in all applicable + columns, removed by clicking the pinned chip. + +**Non-goals** +- Changing what counts as a match (the word-boundary tokenization, stopwords, KG/community + rerank). Match semantics stay identical. +- Re-touching `getFacets` filtering (already correct). +- The homepage `/` flip or `/browse/` (shares the composable but not this bug). + +**Anti-goals** +- Do **not** add `_searchRank` to a `COUNT(*)` projection — the guard's original concern + (comment `search-service.js:281-282`) is real: a count-clone keeps `columns`, so a pushed + rank column could break the count SQL. +- Do not make the count honest in the wrong direction (render a non-matching mission, or + double-count). + +## Constraints + +- CAP `@sap/cds` 10.2.2; UNION-ALL view `SearchableItems` (`db/views.cds:98-166`). +- `searchScore` is a virtual (`srv/search-service.cds:61`) populated only by the after-hook + from `_searchRank`. +- Must not regress `getFacets`, the MCP `search_tutorials`/semantic-search paths, or internal + `srv.run(SELECT…search…)` callers (which arrive with no `sel.columns` → `attachSearchRank` + already self-bails at `:232`). +- Full suite is hook-blocked locally; scope tests with `npm test -- `. e2e is post-deploy + only (`test/e2e/navigator-search-filter.spec.ts`). + +## Approaches considered + +1. **Surgical guard split (CHOSEN).** Apply `applyWordBoundarySearch` (the *filter*) on all + reads, including when `sel.count` is truthy; gate only `attachSearchRank` (the *column + + orderBy*) behind `!sel.count`. The count-clone keeps the `.where` from the filter (so count + = 56, honest) and drops `orderBy`/`limit`; the data read gets both filter and rank. Smallest + change, preserves the guard's real intent (no rank column on a count projection), fixes G1+G2 + together. + - *Trade-off:* relies on CAP keeping `where` (not `orderBy`) in the count-clone — verified in + SQLService.js and reproducible via the no-`$count` repro. A future CAP change to count-clone + behavior would need a re-check; pinned by a hybrid test. + +2. **Remove the guard outright.** Let rewrite + rank run on every read. Simpler diff, but pushes + `_searchRank` into `sel.columns` on the count path — exactly what the "MANDATORY" comment + warns against; risks a `COUNT(*)`-projection SQL error on HANA. Rejected. + +3. **Client-side: stop sending `$count`, derive total from a separate count call.** Moves the + fix to `useSearch.ts`. Larger blast radius (pager math, two round-trips), and leaves the + server hook wrong for any other `$count` caller. Rejected. + +**Chosen: Approach 1.** + +## The how (decided) + +### Server — `srv/search-service.js`, `before('READ', SearchableItems)` (~:279-323) + +- Replace `if (!sel || sel.count) return;` with `if (!sel) return;`. The existing phrase guard + (`:285-287`) already short-circuits any read with no usable `$search` phrase, so a plain + `$count` with no search term stays untouched. +- Keep `applyWordBoundarySearch(req.query, phrase)` unconditional (runs for count + data). +- Wrap the KG/community fragment computation (`:291-320`) and the `attachSearchRank(…)` call + (`:322`) in `if (!sel.count) { … }`, so the rank column + orderBy are added **only** on the + data read, never the count projection. Skipping KG/community on the count path is also a free + latency win. +- `after('READ')` (`:251-268`) is unchanged — on the count path it early-returns on the numeric + result (`:253`). + +### Server — no change to `getFacets` (already correct). Add a regression test only. + +### Client — `hugo-apps/src/navigator/*` + `hugo/assets/css/home.css` + +- G3 pinned selected filters: render a **per-column** selected-chips block **above** each + `.filter-list` (inside `