From 709a072538354953fb14e3e80c10a11380887b0d Mon Sep 17 00:00:00 2001 From: samhere06 Date: Fri, 14 Aug 2026 16:47:15 +0530 Subject: [PATCH 1/2] T-40568: Spec Kit set up and instruction files created --- .github/instructions/bridge.instructions.md | 89 +++ .../build-scripts.instructions.md | 70 ++ .../instructions/components.instructions.md | 308 ++++++++ .github/instructions/testing.instructions.md | 101 +++ .github/skills/speckit-analyze/SKILL.md | 259 +++++++ .github/skills/speckit-checklist/SKILL.md | 373 ++++++++++ .github/skills/speckit-clarify/SKILL.md | 291 ++++++++ .github/skills/speckit-constitution/SKILL.md | 168 +++++ .github/skills/speckit-converge/SKILL.md | 277 +++++++ .github/skills/speckit-implement/SKILL.md | 223 ++++++ .github/skills/speckit-plan/SKILL.md | 166 +++++ .github/skills/speckit-specify/SKILL.md | 345 +++++++++ .github/skills/speckit-tasks/SKILL.md | 214 ++++++ .github/skills/speckit-taskstoissues/SKILL.md | 109 +++ .specify/init-options.json | 9 + .specify/integration.json | 15 + .specify/integrations/copilot.manifest.json | 17 + .specify/integrations/speckit.manifest.json | 17 + .specify/memory/.constitution-template.json | 4 + .specify/memory/constitution.md | 151 ++++ .specify/scripts/bash/check-prerequisites.sh | 195 +++++ .specify/scripts/bash/common.sh | 704 ++++++++++++++++++ .specify/scripts/bash/create-new-feature.sh | 392 ++++++++++ .specify/scripts/bash/setup-plan.sh | 83 +++ .specify/scripts/bash/setup-tasks.sh | 91 +++ .specify/templates/checklist-template.md | 40 + .specify/templates/constitution-template.md | 50 ++ .specify/templates/plan-template.md | 113 +++ .specify/templates/spec-template.md | 131 ++++ .specify/templates/tasks-template.md | 252 +++++++ .specify/workflows/speckit/workflow.yml | 78 ++ .specify/workflows/workflow-registry.json | 13 + AGENTS.md | 114 +++ docs/architecture.md | 168 +++++ 34 files changed, 5630 insertions(+) create mode 100644 .github/instructions/bridge.instructions.md create mode 100644 .github/instructions/build-scripts.instructions.md create mode 100644 .github/instructions/components.instructions.md create mode 100644 .github/instructions/testing.instructions.md create mode 100644 .github/skills/speckit-analyze/SKILL.md create mode 100644 .github/skills/speckit-checklist/SKILL.md create mode 100644 .github/skills/speckit-clarify/SKILL.md create mode 100644 .github/skills/speckit-constitution/SKILL.md create mode 100644 .github/skills/speckit-converge/SKILL.md create mode 100644 .github/skills/speckit-implement/SKILL.md create mode 100644 .github/skills/speckit-plan/SKILL.md create mode 100644 .github/skills/speckit-specify/SKILL.md create mode 100644 .github/skills/speckit-tasks/SKILL.md create mode 100644 .github/skills/speckit-taskstoissues/SKILL.md create mode 100644 .specify/init-options.json create mode 100644 .specify/integration.json create mode 100644 .specify/integrations/copilot.manifest.json create mode 100644 .specify/integrations/speckit.manifest.json create mode 100644 .specify/memory/.constitution-template.json create mode 100644 .specify/memory/constitution.md create mode 100755 .specify/scripts/bash/check-prerequisites.sh create mode 100755 .specify/scripts/bash/common.sh create mode 100755 .specify/scripts/bash/create-new-feature.sh create mode 100755 .specify/scripts/bash/setup-plan.sh create mode 100755 .specify/scripts/bash/setup-tasks.sh create mode 100644 .specify/templates/checklist-template.md create mode 100644 .specify/templates/constitution-template.md create mode 100644 .specify/templates/plan-template.md create mode 100644 .specify/templates/spec-template.md create mode 100644 .specify/templates/tasks-template.md create mode 100644 .specify/workflows/speckit/workflow.yml create mode 100644 .specify/workflows/workflow-registry.json create mode 100644 AGENTS.md create mode 100644 docs/architecture.md diff --git a/.github/instructions/bridge.instructions.md b/.github/instructions/bridge.instructions.md new file mode 100644 index 00000000..5cd2ce60 --- /dev/null +++ b/.github/instructions/bridge.instructions.md @@ -0,0 +1,89 @@ +--- +applyTo: "packages/react-sdk-components/src/bridge/**" +description: "Use when modifying the PConnect bridge layer. Covers react_pconnect.jsx flow, SdkComponentMap, StoreContext, visibility HOC, and Redux connect patterns." +--- +# PConnect Bridge Architecture + +This directory is the SDK's integration layer that maps the PConnect component tree (provided by `@pega/constellationjs`) to SDK React components. The engine decides **what** to render; this bridge decides **how** to render it. + +`@pega/constellationjs` provides: `PCore` (global API), `PConnect` (per-component API), and the Redux store (`PCore.getStore()`). The bridge consumes these to wire SDK components into the engine's component tree. + +## Files + +| File | Responsibility | +|------|---------------| +| `react_pconnect.jsx` | Redux-connected HOC that resolves PConnect nodes to React components | +| `Context/StoreContext.ts` | React context wrapping `PCore.getStore()` (Redux store from engine) | +| `helpers/sdk_component_map.ts` | Singleton component registry — maps names to React components | + +## How react_pconnect.jsx Works + +1. **Redux `connect()`**: Maps PCore Redux state to component props via `connectRedux()` with custom `areStatePropsEqual` for performance +2. **Component resolution**: `getComponent()` resolves in 3 steps: `LazyComponentMap` (currently unused) → `SdkComponentMap.getLocalComponentMap()` → `SdkComponentMap.getPegaProvidedComponentMap()` → `ErrorBoundary` fallback +3. **Visibility HOC**: `withVisibility()` wraps components that have conditions — if `visibility === false`, renders nothing +4. **ErrorBoundary**: Wraps rendered components to catch rendering failures gracefully +5. **UID generation**: `createUID()` assigns unique IDs to each component instance for React key stability +6. **Action wiring**: `processActions()` sets up `onChange`/`onBlur` on the PConnect node via `actionsApi` +7. **Recursive children**: `createChildren()` wraps each child PConnect node in a new `PConnect` class instance + +``` +PConnect metadata (from engine) + → getComponent(c11nEnv) resolves React class from 3-layer map + → if c11nEnv.isConditionExist(): connectRedux(withVisibility(component)) + → else: connectRedux(component) + → PConnect class renders {children} + → On error: +``` + +### Key exports from react_pconnect.jsx +- `createPConnectComponent()` — factory that returns the `PConnect` class. Used at the root (in `FullPortal`/`Embedded`) AND recursively by template components (e.g., `DefaultForm` calls `createElement(createPConnectComponent(), childProps)` to render each child) +- `setVisibilityForList(c11nEnv, visibility)` — handles visibility for list/multi-select components + +### PConnect class lifecycle +- **constructor**: resolves the SDK component via `getComponent()`, gets `actionsApi`, calls `processActions()` which sets up `onChange`/`onBlur` handlers +- **componentDidMount**: calls `c11nEnv.addFormField()` (registers in form) and `setVisibilityForList(c11nEnv, true)` +- **componentWillUnmount**: calls `removeFormField()`, `setVisibilityForList(c11nEnv, false)`, and `c11nEnv.removeNode()` — this last call is critical: without it, field references from previous steps persist in the context tree and cause 400 errors on submission +- **render**: merges config props + actions + additional props into `finalProps`, renders `{this.createChildren()}` + +## SdkComponentMap (helpers/sdk_component_map.ts) + +Singleton pattern with two component maps: + +| Map | Source | Priority | +|-----|--------|----------| +| `localComponentMap` | `sdk-local-component-map.js` | **Checked first** — consumer-side overrides | +| `pegaProvidedComponentMap` | `sdk-pega-component-map.js` | Fallback — SDK's master component registry (maintained in this repo) | + +### Initialization +```typescript +// Called once during app startup (in FullPortal/Embedded initialRender) +const theMap = await getSdkComponentMap(localSdkComponentMap); +``` + +### Component Lookup +```typescript +// Used by react_pconnect.jsx to resolve each PConnect node +const Component = SdkComponentMap.getComponentFromMap('TextInput'); +``` + +## StoreContext (Context/StoreContext.ts) + +Provides access to PCore's Redux store via React context: + +```typescript +// In FullPortal — wraps root component with store context +const contextValue = { store: PCore.getStore() }; +{thePConnObj} +``` + +Components below this provider can access the store via `useConstellationContext()`. + +## Rules for Modifying Bridge Code + +- **Do NOT create a separate Redux store** — `PCore.getStore()` IS the store +- **Do NOT bypass `react_pconnect.jsx`** for rendering PConnect nodes +- **Component map priority is intentional** — local always overrides Pega-provided +- **The bridge does NOT contain business logic** — it's purely a mapping/wiring layer +- **`SdkComponentMap` is a singleton** — only one instance exists per app lifecycle +- **Visibility is engine-controlled** — do not override visibility logic in components +- The `classID` comparison logic in Redux `connect()` is intentional for performance — do not simplify without understanding the shallowEqual optimization diff --git a/.github/instructions/build-scripts.instructions.md b/.github/instructions/build-scripts.instructions.md new file mode 100644 index 00000000..ad38b8aa --- /dev/null +++ b/.github/instructions/build-scripts.instructions.md @@ -0,0 +1,70 @@ +--- +applyTo: "scripts/**,webpack.config.js,tsconfig*.json" +description: "Use when modifying build scripts, webpack config, or TypeScript config. Covers build pipeline flow, script purposes, and packaging." +--- +# Build Scripts + +Node.js automation scripts for building and packaging the SDK. + +## Scripts Overview + +| Script | When Called | Purpose | +|--------|------------|---------| +| `build-exports.js` | `prebuild-sdk` → `prepare-code-for-compilation` | Scans component `index.ts` files, generates export statements for the package entry point | +| `build-overrides.js` | `build-overrides` | Generates the `@pega/react-sdk-overrides` package from source components | +| `copy-static-to-lib.js` | `postbuild-sdk` → `copy-static-files-to-lib` | Copies non-TypeScript files (CSS, JSON, HTML) to `lib/` after TS compilation | +| `edit-pega-components-map-in-lib.js` | `postbuild-sdk` → `edit-pega-components-map` | Transforms the component map in `lib/` for package consumption | +| `copy-npm-assets-to-components.js` | `postbuild-sdk` | Copies `package.json`, README, LICENSE to `packages/react-sdk-components/lib/` | +| `copy-npm-assets-to-overrides.js` | `postbuild-overrides` | Copies `package.json`, README, LICENSE to `packages/react-sdk-overrides/lib/` | +| `update-dependencies.js` | `create_and_install_sdk_packages` | Updates internal package versions in dependency trees | +| `copy-file.js` | — | Generic file copy utility used by other scripts | +| `override-constants.js` | — | Constants (paths, patterns) used by override build | +| `playwright-message.js` | `pretest` | Displays informational message before E2E tests | + +## Build Pipeline Flow + +### `npm run build-sdk` (TypeScript package build) +``` +prebuild-sdk: + 1. delete-tsbuildinfo → remove stale incremental build info + 2. clear-lib → rm -rf lib/ and packages/react-sdk-components/lib/ + 3. prepare-code-for-compilation → run build-exports.js (generates exports) + +build-sdk: + 4. compile-ts → tsc -b tsconfig.build.json (TypeScript project build) + +postbuild-sdk: + 5. copy-static-files-to-lib → copy CSS, JSON, HTML to lib/ + 6. edit-pega-components-map → transform component map for package use + 7. copy-doc-files-to-lib → copy doc/ to lib/doc/ + 8. copy-local-component-map-to-lib → copy sdk-local-component-map.js + 9. copy-types-to-lib → copy src/types/ to lib/types/ + 10. copy-npm-assets-to-components.js → package.json, README, LICENSE +``` + +### `npm run build:dev` (Webpack dev bundle) +``` +parallel: + - lint (eslint + prettier) + - build-dev-only: + 1. webpack --mode=development → dist/app.bundle.js + 2. _internal-copy-index → copies index.html to portal.html, embedded.html, etc. +``` + +## build-exports.js Details + +This script auto-generates the package's public API exports: +1. Scans `packages/react-sdk-components/src/components/` directories +2. Reads each component's `index.ts` to determine what it exports (default, named, or both) +3. Writes export statements to the package root entry file + +This runs during `prebuild-sdk` to ensure the compiled `lib/` package exposes all components. + +## Key Points + +- Scripts are Node.js (CommonJS, `require`) — not TypeScript +- They use `fs.promises` for async file operations +- Paths are relative to the script location (`__dirname`) +- `shx` is used in npm scripts for cross-platform shell commands (cp, rm, mkdir) +- The override build (`build-overrides.js`) mirrors the source component tree into the overrides package +- Do NOT edit files in `lib/` manually — they are regenerated by these scripts diff --git a/.github/instructions/components.instructions.md b/.github/instructions/components.instructions.md new file mode 100644 index 00000000..e204aa5c --- /dev/null +++ b/.github/instructions/components.instructions.md @@ -0,0 +1,308 @@ +--- +applyTo: "packages/react-sdk-components/src/components/**" +description: "Use when creating, modifying, or reviewing SDK components. Covers component structure per subtype (field, template, widget, infra, designSystemExtension), PConnProps interface, MUI design system, hooks, and rendering rules." +--- +# Components + +React SDK component reference implementation using Material UI v6. Components are organized into five subtypes, each with distinct patterns. + +## Subtypes at a Glance + +| Subtype | Has `config-ext.json` | Uses `getPConnect` | Pattern | +|---------|----------------------|--------------------|--------| +| `field/` | Yes (most) | Always | Input controls — extend `PConnFieldProps`, use `actionsApi` for value propagation | +| `template/` | Yes (most) | Always | Layout shells — receive children from PConnect tree, render via `createPConnectComponent()` | +| `widget/` | Yes (most) | Always | Self-contained data views — fetch their own data via `PCore` APIs | +| `infra/` | No | Most (except Region, ActionButtons, VerticalTabs) | Container/orchestration plumbing — manage case flow, routing, assignment lifecycle | +| `designSystemExtension/` | No | None | Pure presentational — receive data as props, no PConnect dependency | + +--- + +## Field Components (`field/`) + +Form input controls. Every field follows the same data-flow pattern. + +### Structure +``` +TextInput/ +├── TextInput.tsx # Component +├── index.tsx # Re-export +└── config-ext.json # { "type": "Field", "subtype": "Text" } +``` +Some fields have additional files (e.g., `currency-utils.ts` in Currency/, CSS files). + +### Pattern + +All field components: +1. **Extend `PConnFieldProps`** (or `Omit` for non-string values like Checkbox) +2. **Get `actionsApi`** via `getPConnect().getActionsApi()` and `propName` via `getPConnect().getStateProps().value` +3. **Propagate values** via `handleEvent(actions, 'changeNblur', propName, value)` from `helpers/event-utils` — trigger point depends on field type (see below) +4. **Handle display modes**: `DISPLAY_ONLY` and `STACKED_LARGE_VAL` — delegate to `getComponentFromMap('FieldValueList')` +5. **Validate with `useStatus()`** — takes `{ showFieldMessage, messageVisibility, validatemessage, readOnly }` object +6. **Use MUI components** for rendering (TextField, Select, Checkbox, etc.) + +### Value propagation — two patterns + +**Text-input fields** (TextInput, TextArea, Email, URL, Integer) — buffer with `useState`, propagate on blur: +``` +User types → handleChange() updates local useState + → User blurs → handleBlur() calls handleEvent(actions, 'changeNblur', propName, value) +``` + +**Selection fields** (Checkbox, Dropdown, RadioButtons, Date, Time, AutoComplete, Phone, Currency, Decimal, Percentage) — propagate immediately on change: +``` +User selects → handleChange() calls handleEvent(actions, 'changeNblur', propName, value) directly +``` + +Both patterns use `handleEvent` with `'changeNblur'` which calls both `updateFieldValue` and `triggerFieldChange`. The difference is the trigger point: blur for free-text input (to avoid re-rendering on every keystroke), immediate for selection (where the value is final on selection). + +### Display mode rendering +Fields never render raw `` for read-only. They delegate to FieldValueList: +```typescript +const FieldValueList = getComponentFromMap('FieldValueList'); +if (displayMode === 'DISPLAY_ONLY') { + return ; +} +if (displayMode === 'STACKED_LARGE_VAL') { + return ; +} +``` + +### Exceptions +- **CancelAlert** — no `config-ext.json` (modal dialog, not a standalone field) +- **Group, EmbeddedDataMulti, ScalarList** — field containers that manage child fields rather than single values +- **Checkbox** — uses `Omit` since its value is boolean, not string + +--- + +## Template Components (`template/`) + +Page and form layouts that render child components from the PConnect tree. + +### Structure — two patterns + +**Flat** — single component: +``` +CaseView/ +├── CaseView.tsx +├── index.tsx +└── config-ext.json # { "type": "Template", "subtype": "CASEVIEW" } +``` + +**Nested variants** — parent directory with sub-variants for different contexts (Page, Form, Details, Tab): +``` +NarrowWide/ +├── NarrowWide/NarrowWide.tsx # Base layout (pure, receives children as props) +├── NarrowWidePage/NarrowWidePage.tsx # Page context variant (has config-ext.json) +├── NarrowWideForm/NarrowWideForm.tsx # Form context variant (has config-ext.json) +└── NarrowWideDetails/ # Read-only context variant (has config-ext.json) +``` +Nested: OneColumn, TwoColumn, NarrowWide, WideNarrow, Details, SimpleTable, AdvancedSearch. + +### Rendering patterns + +Templates extend `PConnProps` (not `PConnFieldProps`). Three sub-patterns: + +**Form/Page templates** (DefaultForm, OneColumnPage, TwoColumnForm) — render children via `createPConnectComponent()`: +```typescript +import { createElement } from 'react'; +import createPConnectComponent from '../../../bridge/react_pconnect'; + +// Children accessed via: getPConnect().getChildren()[0].getPConnect().getChildren() +const arChildren = getPConnect().getChildren()[0].getPConnect().getChildren(); +const renderedChildren = arChildren?.map((kid, index) => + createElement(createPConnectComponent(), { ...kid, key: index.toString() }) +); +``` +Note: `DefaultForm` additionally wraps children with `connectToState(mapStateToProps)` for visibility tracking — this is specific to `DefaultForm`, not a general template pattern. + +**Layout templates** (OneColumn, TwoColumn, NarrowWide base) — pure layout, receive `children` as React props: +```typescript +export default function OneColumn(props: PropsWithChildren) { + const { children } = props; + return {(children as ReactElement[]).map(child => child)}; +} +``` + +**Data-driven templates** (CaseView, ListView, Details) — use `getPConnect()` heavily for metadata, named regions, and dynamic component creation: +```typescript +// CaseView accesses named regions from children +const theSummaryRegion = getChildRegionByName('summary'); + +// Details sets inherited props and creates components dynamically +getPConnect().setInheritedProp('displayMode', 'DISPLAY_ONLY'); +const children = getPConnect().getChildren().map(c => createElement(createPConnectComponent(), c)); +``` + +### Key PConnect APIs for templates +- `getPConnect().getChildren()` — access child PConnect nodes +- `getPConnect().getInheritedProps()` — get label/display settings from parent +- `getPConnect().setInheritedProp(key, value)` — propagate settings to children +- `getPConnect().getRawMetadata()` — access raw component metadata +- `getPConnect().createComponent(field)` — dynamically create a component from metadata + +--- + +## Widget Components (`widget/`) + +Self-contained functional widgets that fetch and display their own data. + +### Structure +``` +CaseHistory/ +├── CaseHistory.tsx +├── index.tsx +└── config-ext.json # { "type": "Widget", "subtype": "CASE" } +``` + +### Pattern + +Widgets extend `PConnProps`. Unlike fields (values via props) or templates (render children), widgets: +1. **Fetch their own data** using `PCore.getDataApiUtils().getData()` or `getPConnect().getValue()` +2. **Manage their own state** with `useState`/`useEffect` for loading/data +3. **Render tables, lists, or cards** using MUI Table, Card, List components +4. **Don't propagate values** — they display information, not capture input + +### Exceptions +- **Followers** — stub/unsupported (renders placeholder) +- **Attachment, FileUtility** — handle file upload/download flows + +--- + +## Infrastructure Components (`infra/`) + +Container and orchestration components managing case flow, routing, and layout plumbing. + +### Structure +``` +infra/ +├── ActionButtons/ # Submit/cancel buttons (NO getPConnect) +├── Assignment/ # Assignment lifecycle wrapper +├── Containers/ # Sub-directory with 4 container types: +│ ├── FlowContainer/ # Case flow orchestration +│ ├── ModalViewContainer/ # Modal rendering +│ ├── SimpleView/ # Basic view wrapper +│ ├── ViewContainer/ # Routed view container +│ └── container-helpers.ts +├── NavBar/ # Top navigation bar +├── Region/ # Passthrough wrapper (NO getPConnect) +├── View/ # View renderer with template resolution +├── VerticalTabs/ # Tab layout (NO getPConnect) +└── ... # ErrorBoundary, Stages, MultiStep, etc. +``` + +**No `config-ext.json` files** — infra components are wired by the engine directly, not registered in the SDK component registry. + +### Pattern + +Infra has **no single pattern** — each is specialized plumbing: +- **Region** — simplest: pure passthrough `<>{children}`, no PConnect +- **ActionButtons** — receives button arrays and `onButtonPress` callback, no PConnect +- **View** — critical orchestrator: resolves template names, sets page titles, handles form/page/modal contexts +- **FlowContainer** — manages case assignment lifecycle, renders assignment cards, shows banners +- **Containers** can be modified but require extra vigilance: changes must be backward compatible, well-tested, and include clear comments explaining the reasoning. These are rarely changed and affect the entire rendering pipeline + +Infra manages **lifecycle and routing** rather than rendering user-facing content. + +--- + +## Design System Extension Components (`designSystemExtension/`) + +Presentational UI components that are **not PConnect-aware**. + +### Structure +``` +Banner/ +├── Banner.tsx +├── Banner.css +└── index.tsx +``` +**No `config-ext.json` files** — DSE components are resolved via `getComponentFromMap()` by other components. + +### Pattern + +Almost all DSE components (10 of 11): +1. **Do NOT extend `PConnProps`** — custom prop interfaces +2. **Do NOT call `getPConnect()`** — no PConnect tree awareness +3. **Are pure presentational** — receive data, render UI +4. **Are consumed by other components** — fields and templates resolve them via `getComponentFromMap()` + +Key DSE components and their consumers: +- **FieldValueList** — renders field values in display mode (used by ALL field components for `DISPLAY_ONLY`) +- **FieldGroup** — renders labeled, collapsible group of fields (used by Details template) +- **AlertBanner** — renders alert messages with severity variants +- **Banner** — renders hero banner with background image +- **RichTextEditor** — TinyMCE wrapper with custom props (not PConnProps) + +--- + +## Creating a New Component + +1. Create directory: `//` +2. Create `ComponentName.tsx` — implement following the subtype pattern above +3. Create `index.tsx` — re-export: `export { default } from './ComponentName';` +4. If field, template, or widget: create `config-ext.json`: + ```json + { + "name": "ComponentName", + "label": "Human readable label", + "description": "Short description", + "type": "Field|Template|Widget", + "subtype": "SubtypeIdentifier", + "properties": [] + } + ``` +5. Register in `sdk-pega-component-map.js` — import the component and add it to the default export object + +Note: infra and designSystemExtension also need to be registered in `sdk-pega-component-map.js`. `sdk-local-component-map.js` is for consumer-side overrides only. + +--- + +## MUI Design System + +All components use **MUI v6** with **Emotion** as the styling engine. + +| Package | Use for | +|---------|---------| +| `@mui/material` | Core components (TextField, Button, Select, Grid2, Typography, Card, Table) | +| `@mui/lab` | Experimental/beta components | +| `@mui/x-date-pickers` | Date and time pickers (Date, DateTime, Time fields) | +| `@mui/icons-material` | Material Design icons | +| `@mui/styles` | Legacy `makeStyles`/`withStyles` (many existing components use it — prefer `sx` or `styled` for new code) | +| `@emotion/react` | CSS-in-JS runtime (used by MUI internally) | +| `@emotion/styled` | `styled()` API for creating styled components | + +### Theme (`theme.ts`) +- Light/dark modes (controlled by `sdk-config.json` → `theme`) +- Primary: `#007bff`, Secondary: `#FFC400` +- Custom extensions: `card`, `modal`, `headerNav`, `embedded`, `actionButtons` +- Access via `useTheme()` or `` + +### Styling +- Many existing components use `makeStyles`/`withStyles` — legacy but functional +- For new code prefer MUI `sx` prop or `@emotion/styled` +- Some components use CSS files alongside MUI (e.g., `Banner.css`, `ListView.css`) + +--- + +## Helpers (`helpers/`) + +| File | Use for | +|------|---------| +| `event-utils.ts` | `handleEvent(actions, 'changeNblur', propName, value)` — field value propagation. `changeNblur` calls both `updateFieldValue` and `triggerFieldChange` | +| `state-utils.tsx` | `connectToState` HOC — used by DefaultForm for child visibility tracking | +| `field-utils.ts` | Field value formatting, `getFieldSx()` for status-based styling | +| `case-utils.tsx` | Case-level operations, status, actions | +| `template-utils.ts` | `getInstructions()`, `getAllFields()` for template rendering | +| `date-format-utils.ts` | Date/time formatting across locales | +| `common-utils.ts` | Generic utilities (string manipulation, type checks) | +| `attachmentShared.ts` | File upload/download shared logic | +| `utils.ts` | Miscellaneous utilities, `Utils.generateDateTime()` | +| `data_page.ts` | `getDataPage()` — data page API access for dropdowns/lookups | +| `field-group-utils.ts` | Field group layout and validation | +| `instructions-utils.ts` | Case/assignment instructions rendering | +| `object-utils.ts` | Object reference helpers | +| `reactContextHelpers.ts` | React context utility wrappers | +| `simpleTableHelpers.ts` | `filterData()` — simple table data and column helpers | +| `versionHelpers.ts` | `compareSdkPCoreVersions()` — SDK/PCore version comparison | +| `formatters/` | Value formatters (`format()`) for display mode — currency, date, etc. | diff --git a/.github/instructions/testing.instructions.md b/.github/instructions/testing.instructions.md new file mode 100644 index 00000000..774fb2d3 --- /dev/null +++ b/.github/instructions/testing.instructions.md @@ -0,0 +1,101 @@ +--- +applyTo: "packages/react-sdk-components/tests/**,**/*.spec.*,**/*.test.*" +description: "Use when writing or modifying tests. Covers Jest unit tests, Playwright E2E setup, test credentials, helpers, and configuration." +--- +# Testing + +This directory contains both unit tests (Jest) and end-to-end tests (Playwright). + +## Structure + +``` +tests/ +├── unit/ # Jest unit tests +│ └── components/ # Component-level unit tests +├── e2e/ # Playwright E2E tests +│ ├── MediaCo/ # MediaCo sample app tests +│ │ ├── portal.spec.js # Full portal workflow +│ │ └── embedded.spec.js # Embedded/mashup workflow +│ └── Digv2/ # DigV2 application tests (various field/template scenarios) +├── common.js # Shared Playwright helpers (launchPortal, login, date utils) +├── config.js # Test environment config (URLs, credentials, viewport settings) +└── setUpTests.js # Jest setup (test environment bootstrapping) +``` + +## Unit Tests (Jest) + +### Running +```bash +npm run test-jest # Watch mode +npm run test-jest-coverage # With coverage report +``` + +### Configuration +- Config: `jest.config.js` at project root +- Environment: `jsdom` +- Preset: `ts-jest` (TypeScript support) +- Setup file: `tests/setUpTests.js` +- Coverage output: `tests/coverage/` + +### Writing Unit Tests +- Place tests in `tests/unit/components//` +- Use `@testing-library/react` for rendering and assertions +- Use `@testing-library/jest-dom` for DOM matchers +- Mock `getPConnect()` — components always expect this prop + +## E2E Tests (Playwright) + +### Prerequisites +1. App must be running: `npm run start-prod` (serves at http://localhost:3502) +2. Pega Infinity server must be accessible at the URL in `sdk-config.json` +3. Test users must exist on the Infinity server + +### Running +```bash +npm test # Chromium, MediaCo portal + embedded +npm run test:headed # Same but with visible browser +npx playwright test --debug # Debug mode (step through) +npm run test-report # View last test report +``` + +### Test Credentials (config.js) + +| App | Role | Username | Password | +|-----|------|----------|----------| +| MediaCo | Representative | `rep@mediaco` | `pega` | +| MediaCo | Manager | `manager@mediaco` | `pega` | +| MediaCo | Technician | `tech@mediaco` | `pega` | +| DigV2 | User | `user.digv2` | `pega` | + +### Configuration (config.js) +- `baseUrl`: `http://localhost:3502` +- Viewport: 1920x1080 (config.js default), overridden to 1720x1080 in common.js helpers +- Default timeout: 60s +- Headless by default +- SlowMo: 120ms (config.js), 200ms (playwright.config.js `launchOptions`) + +### Shared Helpers (common.js) + +| Function | Purpose | +|----------|---------| +| `launchPortal({ page })` | Navigate to portal URL, set viewport | +| `launchEmbedded({ page })` | Navigate to embedded URL, set viewport | +| `launchSelfServicePortal({ page })` | Navigate to self-service portal | +| `login(username, password, page)` | Fill login form and submit | +| `getFormattedDate(date)` | Format date as MMDDYYYY | +| `getFutureDate()` | Get date 2 days from now (formatted) | + +### Playwright Config (playwright.config.js) +- Test directory: `packages/react-sdk-components/tests/e2e` +- Test timeout: 120 seconds +- Assertion timeout: 50 seconds +- Trace: on first retry +- Retries: 2 on CI, 0 locally +- Ignored tests: ManyToMany.spec.js, Localization.spec.js + +### Writing E2E Tests +- Use `@playwright/test` for test/expect +- Import helpers from `../common.js` and config from `../config.js` +- Tests follow login → navigate → interact → assert pattern +- Always wait for `networkidle` after navigation +- Use `data-testid` attributes for element selection where possible diff --git a/.github/skills/speckit-analyze/SKILL.md b/.github/skills/speckit-analyze/SKILL.md new file mode 100644 index 00000000..8b2016db --- /dev/null +++ b/.github/skills/speckit-analyze/SKILL.md @@ -0,0 +1,259 @@ +--- +name: "speckit-analyze" +description: "Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation." +compatibility: "Requires spec-kit project structure with .specify/ directory" +metadata: + author: "github-spec-kit" + source: "templates/commands/analyze.md" +--- + + +## User Input + +```text +$ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). + +## Pre-Execution Checks + +**Check for extension hooks (before analysis)**: +- Check if `.specify/extensions.yml` exists in the project root. +- If it exists, read it and look for entries under the `hooks.before_analyze` key +- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- When constructing command invocations from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- For each executable hook, output the following based on its `optional` flag: + - **Optional hook** (`optional: true`): + ``` + ## Extension Hooks + + **Optional Pre-Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + - **Mandatory hook** (`optional: false`): + ``` + ## Extension Hooks + + **Automatic Pre-Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + + Wait for the result of the hook command before proceeding to the Goal. + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently + +## Goal + +Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/speckit-tasks` has successfully produced a complete `tasks.md`. + +## Operating Constraints + +**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually). + +**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/speckit-analyze`. + +## Execution Steps + +### 1. Initialize Analysis Context + +Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths: + +- SPEC = FEATURE_DIR/spec.md +- PLAN = FEATURE_DIR/plan.md +- TASKS = FEATURE_DIR/tasks.md + +Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command). +For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). + +### 2. Load Artifacts (Progressive Disclosure) + +Load only the minimal necessary context from each artifact: + +**From spec.md:** + +- Overview/Context +- Functional Requirements +- Success Criteria (measurable outcomes — e.g., performance, security, availability, user success, business impact) +- User Stories +- Edge Cases (if present) + +**From plan.md:** + +- Architecture/stack choices +- Data Model references +- Phases +- Technical constraints + +**From tasks.md:** + +- Task IDs +- Descriptions +- Phase grouping +- Parallel markers [P] +- Referenced file paths + +**From constitution:** + +- Load `.specify/memory/constitution.md` for principle validation + +### 3. Build Semantic Models + +Create internal representations (do not include raw artifacts in output): + +- **Requirements inventory**: For each Functional Requirement (FR-###) and Success Criterion (SC-###), record a stable key. Use the explicit FR-/SC- identifier as the primary key when present, and optionally also derive an imperative-phrase slug for readability (e.g., "User can upload file" → `user-can-upload-file`). Include only Success Criteria items that require buildable work (e.g., load-testing infrastructure, security audit tooling), and exclude post-launch outcome metrics and business KPIs (e.g., "Reduce support tickets by 50%"). +- **User story/action inventory**: Discrete user actions with acceptance criteria +- **Task coverage mapping**: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases) +- **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements + +### 4. Detection Passes (Token-Efficient Analysis) + +Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary. + +#### A. Duplication Detection + +- Identify near-duplicate requirements +- Mark lower-quality phrasing for consolidation + +#### B. Ambiguity Detection + +- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria +- Flag unresolved placeholders (TODO, TKTK, ???, ``, etc.) + +#### C. Underspecification + +- Requirements with verbs but missing object or measurable outcome +- User stories missing acceptance criteria alignment +- Tasks referencing files or components not defined in spec/plan + +#### D. Constitution Alignment + +- Any requirement or plan element conflicting with a MUST principle +- Missing mandated sections or quality gates from constitution + +#### E. Coverage Gaps + +- Requirements with zero associated tasks +- Tasks with no mapped requirement/story +- Success Criteria requiring buildable work (performance, security, availability) not reflected in tasks + +#### F. Inconsistency + +- Terminology drift (same concept named differently across files) +- Data entities referenced in plan but absent in spec (or vice versa) +- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note) +- Conflicting requirements (e.g., one requires Next.js while other specifies Vue) + +### 5. Severity Assignment + +Use this heuristic to prioritize findings: + +- **CRITICAL**: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality +- **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion +- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case +- **LOW**: Style/wording improvements, minor redundancy not affecting execution order + +### 6. Produce Compact Analysis Report + +Output a Markdown report (no file writes) with the following structure: + +## Specification Analysis Report + +| ID | Category | Severity | Location(s) | Summary | Recommendation | +|----|----------|----------|-------------|---------|----------------| +| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version | + +(Add one row per finding; generate stable IDs prefixed by category initial.) + +**Coverage Summary Table:** + +| Requirement Key | Has Task? | Task IDs | Notes | +|-----------------|-----------|----------|-------| + +**Constitution Alignment Issues:** (if any) + +**Unmapped Tasks:** (if any) + +**Metrics:** + +- Total Requirements +- Total Tasks +- Coverage % (requirements with >=1 task) +- Ambiguity Count +- Duplication Count +- Critical Issues Count + +### 7. Provide Next Actions + +At end of report, output a concise Next Actions block: + +- If CRITICAL issues exist: Recommend resolving before `/speckit-implement` +- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions +- Provide explicit command suggestions: e.g., "Run /speckit-specify with refinement", "Run /speckit-plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'" + +### 8. Offer Remediation + +Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.) + +### 9. Check for extension hooks + +After reporting, check if `.specify/extensions.yml` exists in the project root. +- If it exists, read it and look for entries under the `hooks.after_analyze` key +- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- When constructing command invocations from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- For each executable hook, output the following based on its `optional` flag: + - **Optional hook** (`optional: true`): + ``` + ## Extension Hooks + + **Optional Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + - **Mandatory hook** (`optional: false`): + ``` + ## Extension Hooks + + **Automatic Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently + +## Operating Principles + +### Context Efficiency + +- **Minimal high-signal tokens**: Focus on actionable findings, not exhaustive documentation +- **Progressive disclosure**: Load artifacts incrementally; don't dump all content into analysis +- **Token-efficient output**: Limit findings table to 50 rows; summarize overflow +- **Deterministic results**: Rerunning without changes should produce consistent IDs and counts + +### Analysis Guidelines + +- **NEVER modify files** (this is read-only analysis) +- **NEVER hallucinate missing sections** (if absent, report them accurately) +- **Prioritize constitution violations** (these are always CRITICAL) +- **Use examples over exhaustive rules** (cite specific instances, not generic patterns) +- **Report zero issues gracefully** (emit success report with coverage statistics) + +## Context + +$ARGUMENTS diff --git a/.github/skills/speckit-checklist/SKILL.md b/.github/skills/speckit-checklist/SKILL.md new file mode 100644 index 00000000..5d28650f --- /dev/null +++ b/.github/skills/speckit-checklist/SKILL.md @@ -0,0 +1,373 @@ +--- +name: "speckit-checklist" +description: "Generate a custom checklist for the current feature based on user requirements." +compatibility: "Requires spec-kit project structure with .specify/ directory" +metadata: + author: "github-spec-kit" + source: "templates/commands/checklist.md" +--- + + +## Checklist Purpose: "Unit Tests for English" + +**CRITICAL CONCEPT**: Checklists are **UNIT TESTS FOR REQUIREMENTS WRITING** - they validate the quality, clarity, and completeness of requirements in a given domain. + +**NOT for verification/testing**: + +- ❌ NOT "Verify the button clicks correctly" +- ❌ NOT "Test error handling works" +- ❌ NOT "Confirm the API returns 200" +- ❌ NOT checking if code/implementation matches the spec + +**FOR requirements quality validation**: + +- ✅ "Are visual hierarchy requirements defined for all card types?" (completeness) +- ✅ "Is 'prominent display' quantified with specific sizing/positioning?" (clarity) +- ✅ "Are hover state requirements consistent across all interactive elements?" (consistency) +- ✅ "Are accessibility requirements defined for keyboard navigation?" (coverage) +- ✅ "Does the spec define what happens when logo image fails to load?" (edge cases) + +**Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works. + +## User Input + +```text +$ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). + +## Pre-Execution Checks + +**Check for extension hooks (before checklist generation)**: +- Check if `.specify/extensions.yml` exists in the project root. +- If it exists, read it and look for entries under the `hooks.before_checklist` key +- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- When constructing command invocations from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- For each executable hook, output the following based on its `optional` flag: + - **Optional hook** (`optional: true`): + ``` + ## Extension Hooks + + **Optional Pre-Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + - **Mandatory hook** (`optional: false`): + ``` + ## Extension Hooks + + **Automatic Pre-Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + + Wait for the result of the hook command before proceeding to the Execution Steps. + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently + +## Execution Steps + +1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list. + - All file paths must be absolute. + - For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). + +2. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints. + +3. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST: + - Be generated from the user's phrasing + extracted signals from spec/plan/tasks + - Only ask about information that materially changes checklist content + - Be skipped individually if already unambiguous in `$ARGUMENTS` + - Prefer precision over breadth + + Generation algorithm: + 1. Extract signals: feature domain keywords (e.g., auth, latency, UX, API), risk indicators ("critical", "must", "compliance"), stakeholder hints ("QA", "review", "security team"), and explicit deliverables ("a11y", "rollback", "contracts"). + 2. Cluster signals into candidate focus areas (max 4) ranked by relevance. + 3. Identify probable audience & timing (author, reviewer, QA, release) if not explicit. + 4. Detect missing dimensions: scope breadth, depth/rigor, risk emphasis, exclusion boundaries, measurable acceptance criteria. + 5. Formulate questions chosen from these archetypes: + - Scope refinement (e.g., "Should this include integration touchpoints with X and Y or stay limited to local module correctness?") + - Risk prioritization (e.g., "Which of these potential risk areas should receive mandatory gating checks?") + - Depth calibration (e.g., "Is this a lightweight pre-commit sanity list or a formal release gate?") + - Audience framing (e.g., "Will this be used by the author only or peers during PR review?") + - Boundary exclusion (e.g., "Should we explicitly exclude performance tuning items this round?") + - Scenario class gap (e.g., "No recovery flows detected—are rollback / partial failure paths in scope?") + + Question formatting rules: + - If presenting options, generate a compact table with columns: Option | Candidate | Why It Matters + - Limit to A–E options maximum; omit table if a free-form answer is clearer + - Never ask the user to restate what they already said + - Avoid speculative categories (no hallucination). If uncertain, ask explicitly: "Confirm whether X belongs in scope." + + Defaults when interaction impossible: + - Depth: Standard + - Audience: Reviewer (PR) if code-related; Author otherwise + - Focus: Top 2 relevance clusters + + Output the questions (label Q1/Q2/Q3). After answers: if ≥2 scenario classes (Alternate / Exception / Recovery / Non-Functional domain) remain unclear, you MAY ask up to TWO more targeted follow‑ups (Q4/Q5) with a one-line justification each (e.g., "Unresolved recovery path risk"). Do not exceed five total questions. Skip escalation if user explicitly declines more. + +4. **Understand user request**: Combine `$ARGUMENTS` + clarifying answers: + - Derive checklist theme (e.g., security, review, deploy, ux) + - Consolidate explicit must-have items mentioned by user + - Map focus selections to category scaffolding + - Infer any missing context from spec/plan/tasks (do NOT hallucinate) + +5. **Load feature context**: Read from FEATURE_DIR: + - spec.md: Feature requirements and scope + - plan.md (if exists): Technical details, dependencies + - tasks.md (if exists): Implementation tasks + + **Context Loading Strategy**: + - Load only necessary portions relevant to active focus areas (avoid full-file dumping) + - Prefer summarizing long sections into concise scenario/requirement bullets + - Use progressive disclosure: add follow-on retrieval only if gaps detected + - If source docs are large, generate interim summary items instead of embedding raw text + +6. **Generate checklist** - Create "Unit Tests for Requirements": + - Create `FEATURE_DIR/checklists/` directory if it doesn't exist + - Generate unique checklist filename: + - Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`) + - Format: `[domain].md` + - File handling behavior: + - If file does NOT exist: Create new file and number items starting from CHK001 + - If file exists: Append new items to existing file, continuing from the last CHK ID (e.g., if last item is CHK015, start new items at CHK016) + - Never delete or replace existing checklist content - always preserve and append + + **CORE PRINCIPLE - Test the Requirements, Not the Implementation**: + Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for: + - **Completeness**: Are all necessary requirements present? + - **Clarity**: Are requirements unambiguous and specific? + - **Consistency**: Do requirements align with each other? + - **Measurability**: Can requirements be objectively verified? + - **Coverage**: Are all scenarios/edge cases addressed? + + **Category Structure** - Group items by requirement quality dimensions: + - **Requirement Completeness** (Are all necessary requirements documented?) + - **Requirement Clarity** (Are requirements specific and unambiguous?) + - **Requirement Consistency** (Do requirements align without conflicts?) + - **Acceptance Criteria Quality** (Are success criteria measurable?) + - **Scenario Coverage** (Are all flows/cases addressed?) + - **Edge Case Coverage** (Are boundary conditions defined?) + - **Non-Functional Requirements** (Performance, Security, Accessibility, etc. - are they specified?) + - **Dependencies & Assumptions** (Are they documented and validated?) + - **Ambiguities & Conflicts** (What needs clarification?) + + **HOW TO WRITE CHECKLIST ITEMS - "Unit Tests for English"**: + + ❌ **WRONG** (Testing implementation): + - "Verify landing page displays 3 episode cards" + - "Test hover states work on desktop" + - "Confirm logo click navigates home" + + ✅ **CORRECT** (Testing requirements quality): + - "Are the exact number and layout of featured episodes specified?" [Completeness] + - "Is 'prominent display' quantified with specific sizing/positioning?" [Clarity] + - "Are hover state requirements consistent across all interactive elements?" [Consistency] + - "Are keyboard navigation requirements defined for all interactive UI?" [Coverage] + - "Is the fallback behavior specified when logo image fails to load?" [Edge Cases] + - "Are loading states defined for asynchronous episode data?" [Completeness] + - "Does the spec define visual hierarchy for competing UI elements?" [Clarity] + + **ITEM STRUCTURE**: + Each item should follow this pattern: + - Question format asking about requirement quality + - Focus on what's WRITTEN (or not written) in the spec/plan + - Include quality dimension in brackets [Completeness/Clarity/Consistency/etc.] + - Reference spec section `[Spec §X.Y]` when checking existing requirements + - Use `[Gap]` marker when checking for missing requirements + + **EXAMPLES BY QUALITY DIMENSION**: + + Completeness: + - "Are error handling requirements defined for all API failure modes? [Gap]" + - "Are accessibility requirements specified for all interactive elements? [Completeness]" + - "Are mobile breakpoint requirements defined for responsive layouts? [Gap]" + + Clarity: + - "Is 'fast loading' quantified with specific timing thresholds? [Clarity, Spec §NFR-2]" + - "Are 'related episodes' selection criteria explicitly defined? [Clarity, Spec §FR-5]" + - "Is 'prominent' defined with measurable visual properties? [Ambiguity, Spec §FR-4]" + + Consistency: + - "Do navigation requirements align across all pages? [Consistency, Spec §FR-10]" + - "Are card component requirements consistent between landing and detail pages? [Consistency]" + + Coverage: + - "Are requirements defined for zero-state scenarios (no episodes)? [Coverage, Edge Case]" + - "Are concurrent user interaction scenarios addressed? [Coverage, Gap]" + - "Are requirements specified for partial data loading failures? [Coverage, Exception Flow]" + + Measurability: + - "Are visual hierarchy requirements measurable/testable? [Acceptance Criteria, Spec §FR-1]" + - "Can 'balanced visual weight' be objectively verified? [Measurability, Spec §FR-2]" + + **Scenario Classification & Coverage** (Requirements Quality Focus): + - Check if requirements exist for: Primary, Alternate, Exception/Error, Recovery, Non-Functional scenarios + - For each scenario class, ask: "Are [scenario type] requirements complete, clear, and consistent?" + - If scenario class missing: "Are [scenario type] requirements intentionally excluded or missing? [Gap]" + - Include resilience/rollback when state mutation occurs: "Are rollback requirements defined for migration failures? [Gap]" + + **Traceability Requirements**: + - MINIMUM: ≥80% of items MUST include at least one traceability reference + - Each item should reference: spec section `[Spec §X.Y]`, or use markers: `[Gap]`, `[Ambiguity]`, `[Conflict]`, `[Assumption]` + - If no ID system exists: "Is a requirement & acceptance criteria ID scheme established? [Traceability]" + + **Surface & Resolve Issues** (Requirements Quality Problems): + Ask questions about the requirements themselves: + - Ambiguities: "Is the term 'fast' quantified with specific metrics? [Ambiguity, Spec §NFR-1]" + - Conflicts: "Do navigation requirements conflict between §FR-10 and §FR-10a? [Conflict]" + - Assumptions: "Is the assumption of 'always available podcast API' validated? [Assumption]" + - Dependencies: "Are external podcast API requirements documented? [Dependency, Gap]" + - Missing definitions: "Is 'visual hierarchy' defined with measurable criteria? [Gap]" + + **Content Consolidation**: + - Soft cap: If raw candidate items > 40, prioritize by risk/impact + - Merge near-duplicates checking the same requirement aspect + - If >5 low-impact edge cases, create one item: "Are edge cases X, Y, Z addressed in requirements? [Coverage]" + + **🚫 ABSOLUTELY PROHIBITED** - These make it an implementation test, not a requirements test: + - ❌ Any item starting with "Verify", "Test", "Confirm", "Check" + implementation behavior + - ❌ References to code execution, user actions, system behavior + - ❌ "Displays correctly", "works properly", "functions as expected" + - ❌ "Click", "navigate", "render", "load", "execute" + - ❌ Test cases, test plans, QA procedures + - ❌ Implementation details (frameworks, APIs, algorithms) + + **✅ REQUIRED PATTERNS** - These test requirements quality: + - ✅ "Are [requirement type] defined/specified/documented for [scenario]?" + - ✅ "Is [vague term] quantified/clarified with specific criteria?" + - ✅ "Are requirements consistent between [section A] and [section B]?" + - ✅ "Can [requirement] be objectively measured/verified?" + - ✅ "Are [edge cases/scenarios] addressed in requirements?" + - ✅ "Does the spec define [missing aspect]?" + +7. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, `##` category sections containing `- [ ] CHK### ` lines with globally incrementing IDs starting at CHK001. + +8. **Report**: Output full path to checklist file, item count, and summarize whether the run created a new file or appended to an existing one. Summarize: + - Focus areas selected + - Depth level + - Actor/timing + - Any explicit user-specified must-have items incorporated + +**Important**: Each `/speckit-checklist` command invocation uses a short, descriptive checklist filename and either creates a new file or appends to an existing one. This allows: + +- Multiple checklists of different types (e.g., `ux.md`, `test.md`, `security.md`) +- Simple, memorable filenames that indicate checklist purpose +- Easy identification and navigation in the `checklists/` folder + +To avoid clutter, use descriptive types and clean up obsolete checklists when done. + +## Example Checklist Types & Sample Items + +**UX Requirements Quality:** `ux.md` + +Sample items (testing the requirements, NOT the implementation): + +- "Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1]" +- "Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1]" +- "Are interaction state requirements (hover, focus, active) consistently defined? [Consistency]" +- "Are accessibility requirements specified for all interactive elements? [Coverage, Gap]" +- "Is fallback behavior defined when images fail to load? [Edge Case, Gap]" +- "Can 'prominent display' be objectively measured? [Measurability, Spec §FR-4]" + +**API Requirements Quality:** `api.md` + +Sample items: + +- "Are error response formats specified for all failure scenarios? [Completeness]" +- "Are rate limiting requirements quantified with specific thresholds? [Clarity]" +- "Are authentication requirements consistent across all endpoints? [Consistency]" +- "Are retry/timeout requirements defined for external dependencies? [Coverage, Gap]" +- "Is versioning strategy documented in requirements? [Gap]" + +**Performance Requirements Quality:** `performance.md` + +Sample items: + +- "Are performance requirements quantified with specific metrics? [Clarity]" +- "Are performance targets defined for all critical user journeys? [Coverage]" +- "Are performance requirements under different load conditions specified? [Completeness]" +- "Can performance requirements be objectively measured? [Measurability]" +- "Are degradation requirements defined for high-load scenarios? [Edge Case, Gap]" + +**Security Requirements Quality:** `security.md` + +Sample items: + +- "Are authentication requirements specified for all protected resources? [Coverage]" +- "Are data protection requirements defined for sensitive information? [Completeness]" +- "Is the threat model documented and requirements aligned to it? [Traceability]" +- "Are security requirements consistent with compliance obligations? [Consistency]" +- "Are security failure/breach response requirements defined? [Gap, Exception Flow]" + +## Anti-Examples: What NOT To Do + +**❌ WRONG - These test implementation, not requirements:** + +```markdown +- [ ] CHK001 - Verify landing page displays 3 episode cards [Spec §FR-001] +- [ ] CHK002 - Test hover states work correctly on desktop [Spec §FR-003] +- [ ] CHK003 - Confirm logo click navigates to home page [Spec §FR-010] +- [ ] CHK004 - Check that related episodes section shows 3-5 items [Spec §FR-005] +``` + +**✅ CORRECT - These test requirements quality:** + +```markdown +- [ ] CHK001 - Are the number and layout of featured episodes explicitly specified? [Completeness, Spec §FR-001] +- [ ] CHK002 - Are hover state requirements consistently defined for all interactive elements? [Consistency, Spec §FR-003] +- [ ] CHK003 - Are navigation requirements clear for all clickable brand elements? [Clarity, Spec §FR-010] +- [ ] CHK004 - Is the selection criteria for related episodes documented? [Gap, Spec §FR-005] +- [ ] CHK005 - Are loading state requirements defined for asynchronous episode data? [Gap] +- [ ] CHK006 - Can "visual hierarchy" requirements be objectively measured? [Measurability, Spec §FR-001] +``` + +**Key Differences:** + +- Wrong: Tests if the system works correctly +- Correct: Tests if the requirements are written correctly +- Wrong: Verification of behavior +- Correct: Validation of requirement quality +- Wrong: "Does it do X?" +- Correct: "Is X clearly specified?" + +## Post-Execution Checks + +**Check for extension hooks (after checklist generation)**: +Check if `.specify/extensions.yml` exists in the project root. +- If it exists, read it and look for entries under the `hooks.after_checklist` key +- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- When constructing command invocations from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- For each executable hook, output the following based on its `optional` flag: + - **Optional hook** (`optional: true`): + ``` + ## Extension Hooks + + **Optional Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + - **Mandatory hook** (`optional: false`): + ``` + ## Extension Hooks + + **Automatic Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently diff --git a/.github/skills/speckit-clarify/SKILL.md b/.github/skills/speckit-clarify/SKILL.md new file mode 100644 index 00000000..b445bda4 --- /dev/null +++ b/.github/skills/speckit-clarify/SKILL.md @@ -0,0 +1,291 @@ +--- +name: "speckit-clarify" +description: "Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec." +compatibility: "Requires spec-kit project structure with .specify/ directory" +metadata: + author: "github-spec-kit" + source: "templates/commands/clarify.md" +--- + + +## User Input + +```text +$ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). + +## Pre-Execution Checks + +**Check for extension hooks (before clarification)**: +- Check if `.specify/extensions.yml` exists in the project root. +- If it exists, read it and look for entries under the `hooks.before_clarify` key +- If the YAML cannot be parsed or is invalid, skip hook checking silently and continue normally +- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default. +- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions: + - If the hook has no `condition` field, or it is null/empty, treat the hook as executable + - If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation +- When constructing command invocations from hook command names, replace dots (`.`) with hyphens (`-`). For example, `speckit.git.commit` → `/speckit-git-commit`. +- For each executable hook, output the following based on its `optional` flag: + - **Optional hook** (`optional: true`): + ``` + ## Extension Hooks + + **Optional Pre-Hook**: {extension} + Command: `/{command}` + Description: {description} + + Prompt: {prompt} + To execute: `/{command}` + ``` + - **Mandatory hook** (`optional: false`): + ``` + ## Extension Hooks + + **Automatic Pre-Hook**: {extension} + Executing: `/{command}` + EXECUTE_COMMAND: {command} + + Wait for the result of the hook command before proceeding to the Outline. + ``` + After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook. +- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently + +## Outline + +Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file. + +Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit-plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases. + +Execution steps: + +1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields: + - `FEATURE_DIR` + - `FEATURE_SPEC` + - (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.) + - If JSON parsing fails, abort and instruct user to re-run `/speckit-specify` or verify feature branch environment. + - For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). + +2. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints. + +3. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked). + + Functional Scope & Behavior: + - Core user goals & success criteria + - Explicit out-of-scope declarations + - User roles / personas differentiation + + Domain & Data Model: + - Entities, attributes, relationships + - Identity & uniqueness rules + - Lifecycle/state transitions + - Data volume / scale assumptions + + Interaction & UX Flow: + - Critical user journeys / sequences + - Error/empty/loading states + - Accessibility or localization notes + + Non-Functional Quality Attributes: + - Performance (latency, throughput targets) + - Scalability (horizontal/vertical, limits) + - Reliability & availability (uptime, recovery expectations) + - Observability (logging, metrics, tracing signals) + - Security & privacy (authN/Z, data protection, threat assumptions) + - Compliance / regulatory constraints (if any) + + Integration & External Dependencies: + - External services/APIs and failure modes + - Data import/export formats + - Protocol/versioning assumptions + + Edge Cases & Failure Handling: + - Negative scenarios + - Rate limiting / throttling + - Conflict resolution (e.g., concurrent edits) + + Constraints & Tradeoffs: + - Technical constraints (language, storage, hosting) + - Explicit tradeoffs or rejected alternatives + + Terminology & Consistency: + - Canonical glossary terms + - Avoided synonyms / deprecated terms + + Completion Signals: + - Acceptance criteria testability + - Measurable Definition of Done style indicators + + Misc / Placeholders: + - TODO markers / unresolved decisions + - Ambiguous adjectives ("robust", "intuitive") lacking quantification + + For each category with Partial or Missing status, add a candidate question opportunity unless: + - Clarification would not materially change implementation or validation strategy + - Information is better deferred to planning phase (note internally) + +4. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints: + - Maximum of 5 total questions across the whole session. + - Each question must be answerable with EITHER: + - A short multiple‑choice selection (2–5 distinct, mutually exclusive options), OR + - A one-word / short‑phrase answer (explicitly constrain: "Answer in <=5 words"). + - Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation. + - Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved. + - Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness). + - Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests. + - If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic. + +5. Sequential questioning loop (interactive): + - Present EXACTLY ONE question at a time. + - **Question writing quality (applies to every question, MC or short-answer):** + - Lead with `**Question:**` followed by a full interrogative that ends with `?`. The question text before the `?` must make sense on its own. + - NEVER use a topic label, section heading, or requirement id as the question itself. For example, `Acceptance device/runtime matrix (FR-023)` is INVALID — it is a label, not a question. + - After the `?`, the only permitted suffix is an optional parenthesized requirement/question id. Exact format: `**Question:** ?` or `**Question:** ? (FR-023)`. Never put the id before the `?`, and never use the id (alone or with a topic label) as the whole prompt. + - Immediately after the question line, add one plain-language "Why it matters" sentence (the stake for acceptance or shipping) before the recommendation/options. + - Use everyday wording; introduce jargon only if defined in the same sentence. Self-check: a reader who does not know Spec Kit must be able to answer from the Question line alone. Terse is fine; cryptic labels are not. + - For multiple‑choice questions: + - **Analyze all options** and determine the **most suitable option** based on: + - Best practices for the project type + - Common patterns in similar implementations + - Risk reduction (security, performance, maintainability) + - Alignment with any explicit project goals or constraints visible in the spec + - Present your **recommended option prominently** at the top with clear reasoning (1-2 sentences explaining why this is the best choice). + - Format as: `**Recommended:** Option [X] - ` + - Then render all options as a Markdown table: + + | Option | Description | + |--------|-------------| + | A |