From 22ae630e380e4733e19575d200619fb8e9eb6961 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Fri, 21 Aug 2026 21:36:07 -0400
Subject: [PATCH 01/10] docs: design organization deep linking
---
...-08-21-organization-deep-linking-design.md | 229 ++++++++++++++++++
1 file changed, 229 insertions(+)
create mode 100644 docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
diff --git a/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
new file mode 100644
index 0000000..08b9556
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
@@ -0,0 +1,229 @@
+# Organization Deep Linking and Recovery Design
+
+**Date:** 2026-08-21
+**Status:** Approved in conversation; awaiting written-spec review
+
+## Purpose
+
+RoleImpact currently keeps the active page and workspace in React component state. A browser refresh therefore returns the user to the homepage, and the homepage does not provide a direct way to reopen an existing organization. This design gives every editable organization a stable public code and nested URL routes, while keeping impact previews temporary.
+
+The same change removes Harborline cloning from the product and backend. Users will either explore Harborline as a read-only example, open an organization they already know, or create a blank organization.
+
+## Goals
+
+- Give every editable organization a stable, human-friendly public code.
+- Allow an organization to be opened by entering its code on the homepage or by using its URL.
+- Preserve the current organization screen across refreshes and direct navigation.
+- Keep organization links editable for the portfolio MVP without introducing accounts or authentication.
+- Keep impact and mitigation preview results temporary and deterministic.
+- Remove the Harborline cloning flow, API, persistence logic, and template-specific UI branches.
+- Preserve all existing organization records and catalog data.
+
+## Non-goals
+
+- User accounts, authentication, invitations, or organization membership.
+- Separate view-only and edit links.
+- Persisted impact-run history or shareable impact-result URLs.
+- Restoring an in-progress impact result after refresh.
+- Renaming the backend `workspace` package and API vocabulary to `organization` in this change.
+- Deleting organizations that were previously created by cloning.
+
+## Product Flow
+
+### Homepage
+
+The homepage presents three actions:
+
+1. **Explore Harborline** opens the existing read-only example.
+2. **Open your organization** accepts a public organization code and navigates to its map.
+3. **Create a new organization** creates an empty draft and navigates to its map.
+
+The existing **Clone Harborline** card is removed and its space is used by **Open your organization**.
+
+The organization-code form:
+
+- trims surrounding whitespace;
+- normalizes letters to uppercase;
+- accepts the displayed form with or without its hyphen;
+- does not navigate when the code is malformed;
+- displays an inline not-found message when no organization matches;
+- never lists all organizations from the server.
+
+### Organization creation
+
+Creating a blank organization generates both its internal UUID and public code. The frontend redirects to `/organizations/{code}/map` and displays a persistent onboarding notice containing:
+
+- the organization code;
+- a **Copy ID** action;
+- a **Copy organization link** action; and
+- a reminder that anyone with the link or code can edit the organization in the portfolio MVP.
+
+The organization header continues to expose Copy ID and Copy Link after the onboarding notice is dismissed. Copy Link copies the stable map URL rather than a temporary impact state.
+
+In user-facing language, **Organization ID** means the public organization code. The internal UUID remains an implementation detail and is not shown as the recovery credential.
+
+### Organization navigation
+
+The organization map, inventory, and impact tabs are real nested routes:
+
+- `/organizations/{code}/map`
+- `/organizations/{code}/inventory`
+- `/organizations/{code}/impact`
+
+`/organizations/{code}` redirects to `/organizations/{code}/map`.
+
+Changing tabs changes the URL. Refreshing or directly opening any valid nested route loads the organization from PostgreSQL and returns to that screen.
+
+Impact selections, results, and mitigation previews remain screen state. Refreshing `/impact` keeps the user on the Test Impact screen but clears the previous result and initializes a valid default workflow, responsibility, and role-holder selection from the current organization.
+
+The Harborline example receives a stable `/example` route so it also survives refresh, but it does not receive an editable organization code.
+
+## Public Organization Code
+
+The database continues using UUID primary keys and foreign keys. A separate `public_code` column is used only for entry and routing.
+
+Code properties:
+
+- generated once when an organization is created;
+- never changes when the organization is renamed;
+- globally unique;
+- case-insensitive;
+- random rather than sequential;
+- short enough to type accurately;
+- excludes visually ambiguous characters such as `0`, `O`, `1`, and `I`.
+
+Displayed codes use a three-letter name-derived prefix followed by six random Base32-style characters, for example `NSM-7K4P9D`. The name prefix is cosmetic and is not recalculated after rename. Uniqueness is enforced by the database, and the service retries generation on the unlikely event of a collision.
+
+The code is an unguessable locator, not authentication. The UI must state that real or sensitive company information should not be entered until authentication is added.
+
+## Database Migration
+
+A new Flyway migration will:
+
+1. add nullable `public_code` to `organizations`;
+2. backfill a unique generated code for every existing organization;
+3. make the column non-null;
+4. add a case-insensitive unique index;
+5. remove the clone-source index and foreign key; and
+6. drop `source_template_organization_id`.
+
+Dropping the clone-source metadata does not remove or alter cloned catalog records because cloned organizations already own independent copies of their data.
+
+The Harborline published example also receives an internal code during migration to satisfy the non-null constraint, but that code is not exposed as an editable organization route. Requests that resolve to a published example through the editable organization endpoint are rejected.
+
+## Backend API
+
+Existing catalog and impact endpoints continue to use internal workspace UUIDs after the organization is resolved. This limits the scope of the change and avoids rewriting every established API boundary.
+
+### Retained and changed endpoints
+
+- `POST /api/v1/workspaces`
+ - Creates an empty draft.
+ - Generates the public code.
+ - Returns the public code in `WorkspaceResource`.
+
+- `GET /api/v1/workspaces/by-code/{publicCode}`
+ - Normalizes and resolves the code.
+ - Returns only editable draft organizations.
+ - Returns `404` for unknown, malformed, or published-example codes.
+
+- `GET /api/v1/workspaces/{workspaceId}`
+ - Remains available for internal UUID-based consumers and tests.
+
+- Existing `/catalog`, `/impact-previews`, and `/impact-previews/mitigations` endpoints remain UUID-based.
+
+### Removed endpoints
+
+- `POST /api/v1/workspaces/{sourceWorkspaceId}/clones`
+- The public all-workspaces listing endpoint, `GET /api/v1/workspaces`, because an unauthenticated list would defeat code-based discovery boundaries.
+
+Harborline homepage counts and example navigation use the existing example/dashboard API rather than finding Harborline through the workspace list.
+
+## Backend Module Changes
+
+- `WorkspaceResource` replaces `sourceTemplateOrganizationId` with `publicCode`.
+- `WorkspaceService` generates codes and resolves editable workspaces by code.
+- `WorkspaceRepository` adds code lookup and collision-safe insertion.
+- `WorkspaceRepository.cloneCatalog` and all temporary clone-ID mapping SQL are removed.
+- `WorkspaceService.clonePublished` is removed.
+- `WorkspaceController.clone` and `WorkspaceController.list` are removed.
+- Template-specific validation messages are rewritten to direct users toward creating a new organization.
+- Existing clone tests are deleted or replaced with public-code creation and lookup tests.
+
+## Frontend Routing and State
+
+React Router will become the source of truth for the active top-level screen. `App` will no longer hold a manual `AppView` union in component state.
+
+Route responsibilities:
+
+- `/` renders the homepage.
+- `/example` renders the Harborline example.
+- `/organizations/:publicCode` redirects to the map.
+- `/organizations/:publicCode/:view` resolves the organization and renders the requested organization view.
+- unknown routes render a lightweight not-found screen.
+
+The organization route loader/query resolves the code once, obtains the internal UUID, and supplies the `Workspace` to `DraftWorkspace`. `DraftEditor` derives its active view from the route segment rather than local state. Inventory stage selection may remain local state because refreshing the inventory screen, rather than a particular inventory subsection, satisfies the approved requirement.
+
+The frontend workspace API removes cloning and listing functions and adds code lookup. Template-clone props, copy-specific wording, and clone-only branches are removed.
+
+Both the local development server and production host must use an SPA history fallback: any non-API path that does not match a static asset serves `index.html`. This ensures that directly opening or refreshing a nested organization URL reaches React Router instead of returning a host-level 404.
+
+## Error Handling
+
+- A malformed code is rejected on the homepage before a request is made.
+- An unknown or published-example code returns a consistent organization-not-found response.
+- A direct invalid organization route renders a recovery screen with:
+ - **Try another organization ID**;
+ - **Return home**; and
+ - **Create a new organization**.
+- API unavailability renders the existing connection-retry treatment without redirecting home.
+- A valid organization with an invalid nested view redirects to its map.
+- Clipboard failures display a non-blocking message and leave the code visible for manual copying.
+
+## Compatibility and Recovery
+
+- Existing draft organizations survive the migration and receive generated codes.
+- Existing cloned organizations become ordinary drafts after clone metadata is removed.
+- Existing catalog UUID relationships, canvas positions, and impact behavior remain unchanged.
+- During development handoff, the generated codes for important existing test organizations can be retrieved once from the database so they are not effectively hidden after the all-workspaces list is removed.
+- Previously bookmarked root URLs continue to open the homepage; there are no existing organization URLs to redirect.
+
+## Test Strategy
+
+### Backend
+
+- Migration integration test proves every existing organization receives a unique non-null code and clone metadata is removed without catalog loss.
+- Service tests cover code generation, normalization, collision retry, draft-only lookup, and not-found behavior.
+- Controller integration tests cover create-and-return-code, lookup-by-code, malformed code, unknown code, and published-example rejection.
+- Existing catalog and impact tests continue proving that UUID-based downstream endpoints work after code resolution.
+- Clone endpoint and clone-catalog tests are removed.
+
+### Frontend
+
+- Homepage tests cover code normalization, successful navigation, malformed code, unknown code, blank creation, and absence of clone controls.
+- Routing tests directly load and refresh map, inventory, impact, example, and invalid-code routes.
+- Impact-route tests prove refresh keeps the user on Test Impact while prior result panels are absent.
+- Header tests cover Copy ID and Copy Link content.
+- Existing organization-building, graph, and mitigation tests run through routed organization screens.
+
+### Browser verification
+
+- Create an organization and capture its code.
+- Refresh map, inventory, and impact routes independently.
+- Open the code in a fresh tab and verify the same organization loads.
+- Enter the code on the homepage and verify redirection to the map.
+- Confirm the impact result clears on refresh without leaving the impact route.
+- Confirm Harborline remains explorable and no clone action remains.
+
+## Acceptance Criteria
+
+- A newly created organization receives a stable public code and map URL.
+- Entering that code on the homepage opens the correct editable organization.
+- Anyone with the code or link can edit the organization in the portfolio MVP.
+- Refreshing map, inventory, impact, or example stays on the same screen.
+- Impact previews are not persisted and disappear after impact-route refresh.
+- Existing organizations and catalog data remain intact after migration.
+- Harborline remains a read-only example.
+- No clone card, clone API, cloning service, clone SQL, clone metadata field, or template-specific branch remains.
+- Invalid codes and routes provide clear recovery actions.
+- Backend tests, frontend tests, lint, production build, and browser verification pass.
From eb9a9b63de4da7c60a7b59de8fe675b116f3d8cf Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Fri, 21 Aug 2026 21:49:17 -0400
Subject: [PATCH 02/10] docs: plan organization deep linking
---
...zation-deep-linking-implementation-plan.md | 918 ++++++++++++++++++
1 file changed, 918 insertions(+)
create mode 100644 docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md
diff --git a/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md b/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md
new file mode 100644
index 0000000..66c38b8
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md
@@ -0,0 +1,918 @@
+# Organization Deep Linking and Recovery 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 every editable organization a stable public code and refresh-safe nested URL while removing Harborline cloning from the product and backend.
+
+**Architecture:** PostgreSQL keeps UUIDs as internal entity identifiers and gains a unique `public_code` locator on `organizations`. Spring resolves a public code once and continues serving catalog and impact APIs by UUID; React Router becomes the source of truth for home, example, map, inventory, and impact screens.
+
+**Tech Stack:** Java 21, Spring Boot 3.5, Spring JDBC, Flyway, PostgreSQL 17, React 19, TypeScript 6, React Router 7, TanStack Query 5, Vitest, Testing Library, Maven, Vite.
+
+**Spec:** `docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md`
+
+## Global Constraints
+
+- UUID primary and foreign keys remain the internal data model.
+- Public organization codes are stable, case-insensitive, random locators in the displayed form `ABC-XXXXXX`.
+- The random alphabet excludes `0`, `O`, `1`, and `I`.
+- Organization codes do not change when an organization is renamed.
+- Anyone with an editable organization link or code can edit it in this portfolio MVP; the UI must warn against entering sensitive data.
+- Impact and mitigation results remain temporary and are cleared by an impact-route refresh.
+- Harborline remains read-only at `/example` and cannot be opened through the editable code endpoint.
+- Previously cloned organizations remain ordinary editable drafts; no organization or catalog record is deleted.
+- The all-workspaces endpoint, clone endpoint, clone SQL, clone metadata, and clone-specific UI are removed.
+- Existing uncommitted graph and recommendation-transparency changes must be preserved and committed independently from this feature.
+- Production code follows test-first red-green-refactor cycles.
+
+---
+
+### Task 1: Add the public-code database contract and remove clone metadata
+
+**Files:**
+- Create: `backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql`
+- Modify: `backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java`
+
+**Interfaces:**
+- Consumes: the `organizations` table produced by migrations V1 through V6.
+- Produces: non-null `organizations.public_code VARCHAR(10)`, unique index `uq_organizations_public_code_ci`, and a schema without `source_template_organization_id` or `idx_organizations_source_template`.
+
+- [ ] **Step 1: Add a failing migration-contract test**
+
+Add this test to `CatalogMigrationIntegrationTest`:
+
+```java
+@Test
+void assignsPublicCodesAndRemovesCloneMetadata() {
+ var publicCodes = jdbcClient.sql("SELECT public_code FROM organizations ORDER BY id")
+ .query(String.class)
+ .list();
+ var cloneColumnCount = jdbcClient.sql("""
+ SELECT COUNT(*)
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'organizations'
+ AND column_name = 'source_template_organization_id'
+ """).query(Integer.class).single();
+
+ assertThat(publicCodes).isNotEmpty()
+ .allSatisfy(code -> assertThat(code).matches("[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}"));
+ assertThat(publicCodes.stream().map(String::toUpperCase).distinct().count())
+ .isEqualTo(publicCodes.size());
+ assertThat(cloneColumnCount).isZero();
+}
+```
+
+- [ ] **Step 2: Run the migration test and verify the expected failure**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml -Dtest=CatalogMigrationIntegrationTest#assignsPublicCodesAndRemovesCloneMetadata test
+```
+
+Expected: FAIL because `organizations.public_code` does not exist.
+
+- [ ] **Step 3: Add migration V7**
+
+Create the migration with these operations:
+
+```sql
+ALTER TABLE organizations ADD COLUMN public_code VARCHAR(10);
+
+CREATE FUNCTION pg_temp.encode_workspace_number(value BIGINT)
+RETURNS TEXT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ alphabet CONSTANT TEXT := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
+ encoded TEXT := '';
+ remainder INTEGER;
+BEGIN
+ FOR position IN 1..6 LOOP
+ remainder := MOD(value, 32);
+ encoded := SUBSTRING(alphabet FROM remainder + 1 FOR 1) || encoded;
+ value := value / 32;
+ END LOOP;
+ RETURN encoded;
+END;
+$$;
+
+WITH ranked_organizations AS (
+ SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS code_number
+ FROM organizations
+)
+UPDATE organizations organization
+SET public_code = RPAD(
+ SUBSTRING(
+ TRANSLATE(
+ COALESCE(NULLIF(UPPER(REGEXP_REPLACE(organization.name, '[^A-Za-z0-9]', '', 'g')), ''), 'ORG'),
+ 'OI01',
+ 'QJ23'
+ )
+ FROM 1 FOR 3
+ ),
+ 3,
+ 'X'
+ ) || '-' || pg_temp.encode_workspace_number(ranked.code_number)
+FROM ranked_organizations ranked
+WHERE ranked.id = organization.id;
+
+ALTER TABLE organizations
+ ALTER COLUMN public_code SET NOT NULL,
+ ADD CONSTRAINT ck_organizations_public_code_format
+ CHECK (public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$');
+
+CREATE UNIQUE INDEX uq_organizations_public_code_ci
+ ON organizations (UPPER(public_code));
+
+DROP INDEX IF EXISTS idx_organizations_source_template;
+
+ALTER TABLE organizations
+ DROP CONSTRAINT IF EXISTS ck_organizations_not_own_template,
+ DROP COLUMN source_template_organization_id;
+```
+
+The ranked Base32-style suffix makes every backfilled code unique without relying on a truncated UUID collision probability. V7 never updates organization IDs or dependent catalog rows.
+
+- [ ] **Step 4: Run the migration test and the full migration suite**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml -Dtest=CatalogMigrationIntegrationTest test
+```
+
+Expected: PASS, including the public-code schema assertions and all seed-data assertions.
+
+- [ ] **Step 5: Commit the migration contract**
+
+```powershell
+git add backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
+git commit -m "feat: add stable organization public codes"
+```
+
+---
+
+### Task 2: Implement public-code generation, lookup, and clone removal in Spring
+
+**Files:**
+- Create: `backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java`
+- Create: `backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java`
+- Create: `backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java`
+- Modify: `backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java`
+- Modify: `backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java`
+
+**Interfaces:**
+- Consumes: `organizations.public_code` from Task 1.
+- Produces: `WorkspaceCode.generate(String)`, `WorkspaceCode.normalize(String)`, `WorkspaceService.getEditableByCode(String)`, `WorkspaceRepository.findDraftByPublicCode(String)`, and `GET /api/v1/workspaces/by-code/{publicCode}`.
+- Produces: `WorkspaceResource.publicCode()` and removes `sourceTemplateOrganizationId()`.
+
+- [ ] **Step 1: Write failing unit tests for the code value object**
+
+Create `WorkspaceCodeTest` with concrete cases:
+
+```java
+class WorkspaceCodeTest {
+ @Test
+ void normalizesTypedCodesWithOrWithoutTheHyphen() {
+ assertThat(WorkspaceCode.normalize(" nsm-7k4p9d ")).isEqualTo("NSM-7K4P9D");
+ assertThat(WorkspaceCode.normalize("nsm7k4p9d")).isEqualTo("NSM-7K4P9D");
+ }
+
+ @Test
+ void rejectsMalformedOrAmbiguousCodes() {
+ assertThat(WorkspaceCode.normalize("NSM-7K4P0D")).isNull();
+ assertThat(WorkspaceCode.normalize("not-a-code")).isNull();
+ }
+
+ @Test
+ void generatesANamePrefixAndAllowedRandomSuffix() {
+ var code = new WorkspaceCode(new java.security.SecureRandom()).generate("Northstar Medical Supplies");
+ assertThat(code).matches("NMS-[A-HJ-NP-Z2-9]{6}");
+ }
+}
+```
+
+- [ ] **Step 2: Run the unit test and verify the expected failure**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceCodeTest test
+```
+
+Expected: FAIL because `WorkspaceCode` does not exist.
+
+- [ ] **Step 3: Implement the code value object**
+
+Implement `WorkspaceCode` as a Spring component with:
+
+```java
+@Component
+public class WorkspaceCode {
+ private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
+ private static final Pattern DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$");
+ private final SecureRandom random;
+
+ public WorkspaceCode() {
+ this(new SecureRandom());
+ }
+
+ WorkspaceCode(SecureRandom random) {
+ this.random = random;
+ }
+
+ public String generate(String organizationName) {
+ String asciiName = Normalizer.normalize(organizationName, Normalizer.Form.NFD)
+ .replaceAll("\\p{M}", "")
+ .toUpperCase(Locale.ROOT);
+ String initials = Arrays.stream(asciiName.split("[^A-Z0-9]+"))
+ .filter(token -> !token.isBlank())
+ .map(token -> token.substring(0, 1))
+ .collect(Collectors.joining());
+ String compact = asciiName.replaceAll("[^A-Z0-9]", "");
+ String prefixSeed = sanitize(initials + compact + "ORG");
+ StringBuilder suffix = new StringBuilder(6);
+ for (int index = 0; index < 6; index++) {
+ suffix.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
+ }
+ return prefixSeed.substring(0, 3) + "-" + suffix;
+ }
+
+ public static String normalize(String rawCode) {
+ if (rawCode == null) return null;
+ String candidate = rawCode.trim().toUpperCase(Locale.ROOT);
+ if (candidate.matches("^[A-HJ-NP-Z2-9]{9}$")) {
+ candidate = candidate.substring(0, 3) + "-" + candidate.substring(3);
+ }
+ return DISPLAYED.matcher(candidate).matches() ? candidate : null;
+ }
+
+ private static String sanitize(String value) {
+ return value.replace('O', 'Q').replace('I', 'J').replace('0', '2').replace('1', '3')
+ .replaceAll("[^A-HJ-NP-Z2-9]", "");
+ }
+}
+```
+
+Import `Normalizer`, `SecureRandom`, `Arrays`, `Locale`, `Pattern`, and `Collectors`. Appending the compact name and `ORG` guarantees a three-character prefix; `sanitize` removes ambiguous characters from the complete code.
+
+- [ ] **Step 4: Run `WorkspaceCodeTest` and verify it passes**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceCodeTest test
+```
+
+Expected: PASS.
+
+- [ ] **Step 5: Add a failing service test for public-code collision retry**
+
+Use Mockito to make the first generated code collide and the second succeed:
+
+```java
+@ExtendWith(MockitoExtension.class)
+class WorkspaceServiceTest {
+ @Mock WorkspaceRepository repository;
+ @Mock WorkspaceCode workspaceCode;
+
+ @Test
+ void retriesAPublicCodeCollisionWithoutChangingTheSlug() {
+ when(repository.existsBySlug("northstar-medical-supplies")).thenReturn(false);
+ when(workspaceCode.generate("Northstar Medical Supplies"))
+ .thenReturn("NMS-AAAAAA", "NMS-AAAAAB");
+ doThrow(new DataIntegrityViolationException("public code collision"))
+ .doNothing()
+ .when(repository).insertDraft(any(UUID.class), eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"), anyString());
+ when(repository.existsByPublicCode("NMS-AAAAAA")).thenReturn(true);
+ when(repository.findById(any(UUID.class))).thenAnswer(invocation -> Optional.of(
+ workspace(invocation.getArgument(0), "NMS-AAAAAB")));
+
+ var service = new WorkspaceService(repository, workspaceCode);
+ var created = service.createBlank(new WorkspaceRequest("Northstar Medical Supplies", null));
+
+ assertThat(created.publicCode()).isEqualTo("NMS-AAAAAB");
+ verify(repository).insertDraft(any(UUID.class), eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"), eq("NMS-AAAAAA"));
+ verify(repository).insertDraft(any(UUID.class), eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"), eq("NMS-AAAAAB"));
+ }
+}
+```
+
+Define the fixture in the same test class:
+
+```java
+private WorkspaceResource workspace(UUID id, String publicCode) {
+ var timestamp = Instant.parse("2026-08-21T12:00:00Z");
+ return new WorkspaceResource(
+ id,
+ "northstar-medical-supplies",
+ "Northstar Medical Supplies",
+ "DRAFT",
+ 0,
+ publicCode,
+ timestamp,
+ timestamp,
+ new WorkspaceResource.WorkspaceCounts(0, 0, 0, 0, 0, 0));
+}
+```
+
+- [ ] **Step 6: Run the collision test and verify the expected failure**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceServiceTest test
+```
+
+Expected: FAIL because `WorkspaceService` does not yet accept `WorkspaceCode` or retry a collision.
+
+- [ ] **Step 7: Replace the clone integration test with failing creation and lookup tests**
+
+In `WorkspaceIntegrationTest`, replace `createsBlankAndClonedDraftsWithoutChangingThePublishedTemplate` with tests that assert:
+
+```java
+@Test
+void createsAndResolvesAnEditableDraftByPublicCode() throws Exception {
+ var created = mockMvc.perform(post("/api/v1/workspaces")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(workspaceRequest("Northstar Medical Supplies", null)))
+ .andExpect(status().isCreated())
+ .andExpect(jsonPath("$.publicCode").value(org.hamcrest.Matchers.matchesPattern("NMS-[A-HJ-NP-Z2-9]{6}")))
+ .andReturn();
+ var resource = objectMapper.readTree(created.getResponse().getContentAsString());
+ var publicCode = resource.path("publicCode").asText();
+
+ mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", publicCode.toLowerCase()))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.id").value(resource.path("id").asText()))
+ .andExpect(jsonPath("$.status").value("DRAFT"));
+}
+```
+
+Also add tests proving:
+
+```java
+mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", "bad-code"))
+ .andExpect(status().isNotFound());
+mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", harborlinePublicCode))
+ .andExpect(status().isNotFound());
+mockMvc.perform(get("/api/v1/workspaces"))
+ .andExpect(status().isMethodNotAllowed());
+mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", HARBORLINE_ID)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(workspaceRequest("Removed Clone", null)))
+ .andExpect(status().isNotFound());
+```
+
+- [ ] **Step 8: Run the Spring integration test and verify the expected failures**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceIntegrationTest test
+```
+
+Expected: FAIL because the resource has no public code, lookup is absent, and list/clone endpoints still exist.
+
+- [ ] **Step 9: Implement repository and service behavior**
+
+Change the workspace select and mapper to read `o.public_code`. Add:
+
+```java
+public Optional findDraftByPublicCode(String publicCode) {
+ return jdbcClient.sql(WORKSPACE_SELECT + " WHERE UPPER(o.public_code) = :publicCode AND o.workspace_status = 'DRAFT'")
+ .param("publicCode", publicCode)
+ .query(this::mapWorkspace)
+ .optional();
+}
+
+public boolean existsByPublicCode(String publicCode) {
+ return jdbcClient.sql("SELECT EXISTS (SELECT 1 FROM organizations WHERE UPPER(public_code) = :publicCode)")
+ .param("publicCode", publicCode)
+ .query(Boolean.class)
+ .single();
+}
+
+public void insertDraft(UUID id, String slug, String name, String publicCode) {
+ jdbcClient.sql("""
+ INSERT INTO organizations (
+ id, slug, name, current_version, workspace_status, public_code, created_at, updated_at
+ ) VALUES (
+ :id, :slug, :name, 0, 'DRAFT', :publicCode, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
+ )
+ """)
+ .param("id", id)
+ .param("slug", slug)
+ .param("name", name)
+ .param("publicCode", publicCode)
+ .update();
+}
+```
+
+Inject `WorkspaceCode` beside `WorkspaceRepository`. Change `WorkspaceService.createBlank` to generate a code and retry a public-code collision up to five times:
+
+```java
+@Transactional
+public WorkspaceResource createBlank(WorkspaceRequest request) {
+ String name = request.name().trim();
+ String slug = resolveSlug(request, name);
+ if (workspaceRepository.existsBySlug(slug)) {
+ throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
+ }
+
+ for (int attempt = 0; attempt < 5; attempt++) {
+ UUID workspaceId = UUID.randomUUID();
+ String publicCode = workspaceCode.generate(name);
+ try {
+ workspaceRepository.insertDraft(workspaceId, slug, name, publicCode);
+ return get(workspaceId);
+ }
+ catch (DataIntegrityViolationException exception) {
+ if (workspaceRepository.existsBySlug(slug)) {
+ throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
+ }
+ if (!workspaceRepository.existsByPublicCode(publicCode)) {
+ throw exception;
+ }
+ }
+ }
+ throw new WorkspaceConflictException("A unique organization ID could not be generated; try again");
+}
+```
+
+Add code lookup:
+
+```java
+@Transactional(readOnly = true)
+public WorkspaceResource getEditableByCode(String rawCode) {
+ String code = WorkspaceCode.normalize(rawCode);
+ if (code == null) throw new WorkspaceNotFoundException(rawCode);
+ return workspaceRepository.findDraftByPublicCode(code)
+ .orElseThrow(() -> new WorkspaceNotFoundException(rawCode));
+}
+```
+
+Remove `list`, `clonePublished`, `findAll`, `findStatus`, `cloneCatalog`, and the clone-ID mapping helpers.
+
+- [ ] **Step 10: Update the REST resource and controller**
+
+Replace `sourceTemplateOrganizationId` with `String publicCode` in `WorkspaceResource`. Add:
+
+```java
+@GetMapping("/by-code/{publicCode}")
+public WorkspaceResource getByCode(@PathVariable String publicCode) {
+ return workspaceService.getEditableByCode(publicCode);
+}
+```
+
+Remove the list and clone mappings. Set the create response Location header to `/api/v1/workspaces/by-code/{publicCode}`.
+
+- [ ] **Step 11: Remove clone-specific messages**
+
+Change published mutation guidance to “Published examples are read-only; create a new organization to make changes.” Change the example workflow guidance to instruct users to create a custom workflow without mentioning cloning.
+
+- [ ] **Step 12: Run backend tests**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml test
+```
+
+Expected: PASS with no references to the removed clone endpoint or metadata.
+
+- [ ] **Step 13: Commit the backend API boundary**
+
+```powershell
+git add backend/src
+git commit -m "feat: resolve editable organizations by public code"
+```
+
+---
+
+### Task 3: Replace homepage cloning with organization-code access
+
+**Files:**
+- Modify: `frontend/src/api/workspaces.ts`
+- Modify: `frontend/src/components/workspaces/WorkspaceWelcome.tsx`
+- Modify: `frontend/src/App.css`
+- Modify: `frontend/src/App.test.tsx`
+
+**Interfaces:**
+- Consumes: `GET /api/v1/workspaces/by-code/{publicCode}` and `POST /api/v1/workspaces` from Task 2.
+- Produces: `normalizeWorkspaceCode(rawCode): string | null`, `fetchWorkspaceByCode(rawCode, signal?)`, and a homepage with Explore, Open, and Create choices.
+
+- [ ] **Step 1: Add failing homepage tests**
+
+Update the test renderer to include `MemoryRouter` and accept `initialEntries`. Add tests that:
+
+```tsx
+const linkedWorkspaceFixture: Workspace = {
+ id: '10000000-0000-0000-0000-000000000001',
+ slug: 'northstar-medical-supplies',
+ name: 'Northstar Medical Supplies',
+ status: 'DRAFT',
+ currentVersion: 0,
+ publicCode: 'NMS-7K4P9D',
+ createdAt: '2026-08-21T12:00:00Z',
+ updatedAt: '2026-08-21T12:00:00Z',
+ counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 },
+}
+```
+
+```tsx
+it('opens an existing organization by a normalized code', async () => {
+ const user = userEvent.setup()
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = input.toString()
+ if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture)
+ if (url.endsWith('/api/v1/workspaces/by-code/NMS-7K4P9D')) {
+ return jsonResponse(linkedWorkspaceFixture)
+ }
+ if (url.endsWith('/catalog')) return jsonResponse(blankCatalogFixture)
+ if (url.endsWith('/impact-previews/continuity')) return jsonResponse([])
+ return new Response(null, { status: 404 })
+ })
+ renderApp(['/'])
+ await user.type(screen.getByLabelText('Organization ID'), ' nms7k4p9d ')
+ await user.click(screen.getByRole('button', { name: 'Open organization' }))
+ expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument()
+ expect(screen.getByText('NMS-7K4P9D')).toBeInTheDocument()
+})
+```
+
+Add assertions that the homepage has no “Clone Harborline” or “Clone and customize”, malformed codes show an inline message without a fetch, unknown codes show “Organization not found”, and a successful blank creation navigates to the new organization.
+
+- [ ] **Step 2: Run the homepage tests and verify the expected failures**
+
+Run:
+
+```powershell
+npm --prefix frontend test -- --run src/App.test.tsx
+```
+
+Expected: FAIL because the homepage still lists workspaces and clones Harborline.
+
+- [ ] **Step 3: Replace the workspace API client**
+
+Change `Workspace` to include `publicCode: string` and remove `sourceTemplateOrganizationId`. Remove `fetchWorkspaces` and `cloneWorkspace`. Add:
+
+```ts
+export function normalizeWorkspaceCode(rawCode: string): string | null {
+ const compact = rawCode.trim().toUpperCase().replace('-', '')
+ if (!/^[A-HJ-NP-Z2-9]{9}$/.test(compact)) return null
+ return `${compact.slice(0, 3)}-${compact.slice(3)}`
+}
+
+export async function fetchWorkspaceByCode(rawCode: string, signal?: AbortSignal): Promise {
+ const code = normalizeWorkspaceCode(rawCode)
+ if (!code) throw new Error('Enter an organization ID such as NMS-7K4P9D')
+ const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/by-code/${code}`, { signal })
+ return readResponse(response, 'Organization not found')
+}
+```
+
+- [ ] **Step 4: Rebuild `WorkspaceWelcome` around the three approved choices**
+
+Use `fetchDashboard` for Harborline counts. Use `useNavigate` for navigation. On open success navigate to `/organizations/${workspace.publicCode}/map`; on create success navigate to the same path with `{ state: { newlyCreated: true } }`.
+
+The organization code form must use:
+
+```tsx
+Organization ID
+ setOrganizationCode(event.target.value)}
+ placeholder="NMS-7K4P9D"
+/>
+
+ {openMutation.isPending ? 'Opening…' : 'Open organization'}
+
+```
+
+Keep Harborline exploration independent of dashboard-count failure: show em dashes for unavailable counts while leaving the Explore action available.
+
+- [ ] **Step 5: Update homepage styles**
+
+Reuse `.workspace-choice` structure. Add an inline organization-code hint and error treatment without introducing a new page layout. Keep the three cards usable at existing responsive breakpoints.
+
+- [ ] **Step 6: Run the homepage tests**
+
+Run:
+
+```powershell
+npm --prefix frontend test -- --run src/App.test.tsx
+```
+
+Expected: homepage access and creation tests PASS; route-shell tests may still fail until Task 4.
+
+- [ ] **Step 7: Commit the homepage access flow**
+
+```powershell
+git add frontend/src/api/workspaces.ts frontend/src/components/workspaces/WorkspaceWelcome.tsx frontend/src/App.css frontend/src/App.test.tsx
+git commit -m "feat: open organizations from the homepage"
+```
+
+---
+
+### Task 4: Make nested routes the source of truth for organization screens
+
+**Files:**
+- Create: `frontend/src/components/workspaces/OrganizationRoute.tsx`
+- Modify: `frontend/src/App.tsx`
+- Modify: `frontend/src/components/workspaces/DraftWorkspace.tsx`
+- Modify: `frontend/src/components/workspaces/editor/DraftEditor.tsx`
+- Modify: `frontend/src/App.test.tsx`
+
+**Interfaces:**
+- Consumes: `fetchWorkspaceByCode` from Task 3.
+- Produces: `/`, `/example`, `/organizations/:publicCode`, and `/organizations/:publicCode/:view` where `view` is `map | inventory | impact`.
+- Produces: `DraftEditor({ workspaceId, view, onViewChange })` with no internal top-level view state.
+
+- [ ] **Step 1: Add failing direct-navigation and refresh tests**
+
+Add one test per approved route:
+
+```tsx
+function mockOrganizationRoute() {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = input.toString()
+ if (url.endsWith('/api/v1/workspaces/by-code/NMS-7K4P9D')) {
+ return jsonResponse(linkedWorkspaceFixture)
+ }
+ if (url.endsWith('/catalog')) return jsonResponse(blankCatalogFixture)
+ if (url.endsWith('/impact-previews/continuity')) return jsonResponse([])
+ if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture)
+ return new Response(null, { status: 404 })
+ })
+}
+
+it.each([
+ ['/organizations/NMS-7K4P9D/map', 'Map how your organization works'],
+ ['/organizations/NMS-7K4P9D/inventory', 'Detailed inventory'],
+ ['/organizations/NMS-7K4P9D/impact', 'Test a change before it happens'],
+])('loads %s directly', async (entry, expectedText) => {
+ mockOrganizationRoute()
+ renderApp([entry])
+ expect(await screen.findByText(expectedText)).toBeInTheDocument()
+})
+```
+
+Add tests for `/organizations/NMS-7K4P9D` redirecting to `/map`, an invalid nested view redirecting to `/map`, `/example` surviving direct load, and an unknown code rendering recovery actions without redirecting home.
+
+For impact refresh semantics, render directly at `/impact` and assert the Test Impact screen is present while no prior result or mitigation verdict is present.
+
+- [ ] **Step 2: Run the route tests and verify the expected failures**
+
+Run:
+
+```powershell
+npm --prefix frontend test -- --run src/App.test.tsx
+```
+
+Expected: FAIL because `App` still uses local `AppView` state.
+
+- [ ] **Step 3: Implement route declarations in `App`**
+
+Replace local view state with:
+
+```tsx
+
+ } />
+ } />
+ } />
+ } />
+ } />
+
+```
+
+Use `useNavigate` for Harborline’s back action. `OrganizationIndexRedirect` reads `publicCode` and returns ` `.
+
+- [ ] **Step 4: Implement `OrganizationRoute`**
+
+`OrganizationRoute` must:
+
+```tsx
+const validViews = ['map', 'inventory', 'impact'] as const
+type OrganizationView = typeof validViews[number]
+```
+
+Normalize the route code, fetch the workspace with TanStack Query key `['workspace', normalizedCode]`, redirect an invalid view to the organization map, and render a recovery screen for invalid/unknown codes. Keep connection errors on the route with a Retry action.
+
+Pass `newlyCreated` from `location.state` to `DraftWorkspace`; do not store it in the URL or database.
+
+- [ ] **Step 5: Make `DraftWorkspace` route-aware**
+
+Replace `onBack` with:
+
+```ts
+type DraftWorkspaceProps = {
+ workspace: Workspace
+ view: OrganizationView
+ newlyCreated: boolean
+ onViewChange: (view: OrganizationView) => void
+}
+```
+
+Use navigation to return home and pass route view props to `DraftEditor`.
+
+- [ ] **Step 6: Remove top-level view state from `DraftEditor`**
+
+Change the signature to:
+
+```ts
+export default function DraftEditor({ workspaceId, view, onViewChange }: {
+ workspaceId: string
+ view: 'map' | 'impact' | 'inventory'
+ onViewChange: (view: 'map' | 'impact' | 'inventory') => void
+})
+```
+
+Replace `setView('map')`, `setView('impact')`, and `setView('inventory')` with the matching `onViewChange` calls. Retain inventory `stage` as local state. Pass `initialFocus={false}` to `OrganizationCanvas` and remove `isTemplateClone`.
+
+- [ ] **Step 7: Run direct-route tests and the full frontend suite**
+
+Run:
+
+```powershell
+npm --prefix frontend test
+```
+
+Expected: PASS, including direct map, inventory, impact, example, redirect, and recovery tests.
+
+- [ ] **Step 8: Commit nested routing**
+
+```powershell
+git add frontend/src/App.tsx frontend/src/App.test.tsx frontend/src/components/workspaces/OrganizationRoute.tsx frontend/src/components/workspaces/DraftWorkspace.tsx frontend/src/components/workspaces/editor/DraftEditor.tsx
+git commit -m "feat: add refresh-safe organization routes"
+```
+
+---
+
+### Task 5: Add persistent organization recovery controls and creation onboarding
+
+**Files:**
+- Modify: `frontend/src/components/workspaces/DraftWorkspace.tsx`
+- Modify: `frontend/src/App.css`
+- Modify: `frontend/src/App.test.tsx`
+
+**Interfaces:**
+- Consumes: `Workspace.publicCode`, routed organization view, and `newlyCreated` from Task 4.
+- Produces: persistent Copy ID and Copy organization link actions plus a dismissible first-creation notice.
+
+- [ ] **Step 1: Add failing copy and onboarding tests**
+
+Mock `navigator.clipboard.writeText`. Add tests asserting:
+
+```tsx
+expect(screen.getByText('NMS-7K4P9D')).toBeInTheDocument()
+await user.click(screen.getByRole('button', { name: 'Copy organization ID' }))
+expect(navigator.clipboard.writeText).toHaveBeenCalledWith('NMS-7K4P9D')
+await user.click(screen.getByRole('button', { name: 'Copy organization link' }))
+expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ `${window.location.origin}/organizations/NMS-7K4P9D/map`,
+)
+```
+
+Creation navigation must show “Save this organization ID” and the warning “Anyone with this link or ID can edit this organization.” Directly reopening the same URL must keep header controls but not show the creation notice.
+
+- [ ] **Step 2: Run the focused tests and verify the expected failures**
+
+Run:
+
+```powershell
+npm --prefix frontend test -- --run src/App.test.tsx
+```
+
+Expected: FAIL because recovery controls and onboarding do not exist.
+
+- [ ] **Step 3: Implement copy controls and creation notice**
+
+In `DraftWorkspace`, derive the canonical map link from `window.location.origin` and `workspace.publicCode`. Keep copy feedback local and non-blocking:
+
+```ts
+async function copy(value: string, successMessage: string) {
+ try {
+ await navigator.clipboard.writeText(value)
+ setCopyMessage(successMessage)
+ } catch {
+ setCopyMessage('Copy failed. Select the visible organization ID instead.')
+ }
+}
+```
+
+The persistent header displays the public code and both copy buttons. The dismissible onboarding notice appears only when `newlyCreated` is true and includes the no-sensitive-data warning.
+
+- [ ] **Step 4: Style recovery controls for desktop and mobile**
+
+Add `.organization-recovery`, `.organization-code`, and `.organization-onboarding` styles that use existing colors, border radii, focus treatments, and mobile wrapping behavior.
+
+- [ ] **Step 5: Run the full frontend quality gate**
+
+Run:
+
+```powershell
+npm --prefix frontend test
+npm --prefix frontend run lint
+npm --prefix frontend run build
+```
+
+Expected: all commands PASS without warnings introduced by this feature.
+
+- [ ] **Step 6: Commit recovery controls**
+
+```powershell
+git add frontend/src/components/workspaces/DraftWorkspace.tsx frontend/src/App.css frontend/src/App.test.tsx
+git commit -m "feat: expose organization recovery controls"
+```
+
+---
+
+### Task 6: Verify direct-link hosting behavior and complete clone cleanup
+
+**Files:**
+- Modify: `README.md`
+- Modify: any test fixture still containing `sourceTemplateOrganizationId` or clone actions.
+
+**Interfaces:**
+- Consumes: the complete backend and frontend feature.
+- Produces: documented organization URL behavior, deployment fallback requirement, and a repository with no active cloning implementation.
+
+- [ ] **Step 1: Scan for forbidden clone implementation references**
+
+Run:
+
+```powershell
+rg -n -i "sourceTemplateOrganizationId|source_template_organization_id|cloneWorkspace|clonePublished|cloneCatalog|/clones|Clone Harborline|Clone and customize" backend/src frontend/src README.md
+```
+
+Expected: no matches outside historical migration V4 and the V7 statement that drops the old column. Remove stale test fixtures and product copy if the scan reports them.
+
+- [ ] **Step 2: Update README routes and local verification**
+
+Document:
+
+```markdown
+- `GET /api/v1/workspaces/by-code/{publicCode}` resolves an editable organization.
+- `/organizations/{publicCode}/map` opens its organization map.
+- `/organizations/{publicCode}/inventory` opens its detailed inventory.
+- `/organizations/{publicCode}/impact` opens a fresh impact-testing screen.
+```
+
+State that production hosting must rewrite non-asset, non-API paths to `frontend/index.html`. Document that Vite dev and preview already provide the SPA history fallback used for local verification.
+
+- [ ] **Step 3: Run all automated checks**
+
+Run:
+
+```powershell
+.\backend\mvnw.cmd -f backend\pom.xml test
+npm --prefix frontend test
+npm --prefix frontend run lint
+npm --prefix frontend run build
+```
+
+Expected: every command PASS.
+
+- [ ] **Step 4: Perform browser acceptance verification**
+
+With PostgreSQL, API, and frontend running:
+
+1. Create a blank organization and record its displayed ID.
+2. Refresh its map route and confirm the same organization loads.
+3. Navigate to inventory, refresh, and confirm inventory remains selected.
+4. Navigate to impact, run a test, refresh, and confirm the impact screen remains while the previous result is cleared.
+5. Paste the organization map URL into a fresh tab and confirm it loads.
+6. Enter the ID without its hyphen on the homepage and confirm it opens the organization.
+7. Open `/example`, refresh, and confirm Harborline remains read-only.
+8. Enter an unknown valid-format code and confirm the recovery screen offers Try another ID, Return home, and Create a new organization.
+
+- [ ] **Step 5: Commit documentation and cleanup**
+
+```powershell
+git add README.md backend/src frontend/src
+git commit -m "docs: document organization deep links"
+```
+
+- [ ] **Step 6: Review the final diff**
+
+Run:
+
+```powershell
+git status --short
+git diff --stat HEAD~5..HEAD
+git log --oneline -6
+```
+
+Expected: no unintended files, no uncommitted feature changes, and separate commits for schema, backend API, homepage, routing, recovery controls, and documentation.
From 98e23b04183c94cffc43e6375cd2798be4c5d2d9 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Fri, 21 Aug 2026 21:50:11 -0400
Subject: [PATCH 03/10] fix: clarify shared-role impact recommendations
---
frontend/src/App.css | 3 +
frontend/src/App.test.tsx | 4 +-
.../workspaces/editor/DraftImpactTesting.tsx | 41 ++++++++-
.../FullOrganizationImpactCanvas.test.tsx | 87 +++++++++++++++++++
.../editor/FullOrganizationImpactCanvas.tsx | 23 ++++-
5 files changed, 152 insertions(+), 6 deletions(-)
create mode 100644 frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx
diff --git a/frontend/src/App.css b/frontend/src/App.css
index 31cad50..4e6a8f2 100644
--- a/frontend/src/App.css
+++ b/frontend/src/App.css
@@ -1638,6 +1638,9 @@
.draft-recommendation-card > div > strong { font-size: 0.82rem; }
.draft-recommendation-card > button { min-width: 9.5rem; }
.draft-recommendation-rank { display: grid; width: 2rem; height: 2rem; place-items: center; border-radius: 50%; background: #21382c; color: #8de0b5; font-size: 0.7rem; font-weight: 900; }
+.recommendation-alignment { width: fit-content; padding: 0.22rem 0.42rem; border-radius: 999px; font-size: 0.58rem; font-weight: 850; letter-spacing: 0.025em; }
+.recommendation-alignment.aligned { background: #173b2a; color: #8de0b5; }
+.recommendation-alignment.review { background: #332a1a; color: #f5ca72; }
.draft-recommendation-evidence { display: flex; flex-wrap: wrap; gap: 0.35rem; }
.draft-recommendation-evidence span { padding: 0.22rem 0.38rem; border-radius: 999px; background: #222a26; color: #9dc4ad; font-size: 0.56rem; font-weight: 700; }
.draft-candidate-exclusions { border-top: 1px solid #2d3240; padding-top: 0.8rem; }
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx
index 4785b37..8181b32 100644
--- a/frontend/src/App.test.tsx
+++ b/frontend/src/App.test.tsx
@@ -498,7 +498,9 @@ describe('App', () => {
expect(screen.getByLabelText('Complete organization impact map')).toBeInTheDocument()
expect(screen.getByLabelText(/member Arjun Mehta.*Recommended #1/i)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Reset to baseline' })).toBeInTheDocument()
- expect(screen.getByRole('heading', { name: 'Test a safe replacement' })).toBeInTheDocument()
+ expect(screen.getByRole('heading', { name: 'Compare technically viable replacements' })).toBeInTheDocument()
+ expect(screen.getByText('Best aligned · same team')).toBeInTheDocument()
+ expect(screen.getByText(/Ranked #1 because Arjun Mehta is in the same team as Maya Singh/)).toBeInTheDocument()
fireEvent.click(screen.getByLabelText(/member Arjun Mehta.*Recommended #1/i))
const selectedArjun = screen.getByLabelText('Selected Member Arjun Mehta')
await user.click(within(selectedArjun).getByRole('button', { name: 'Try as replacement for Release Manager' }))
diff --git a/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx b/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx
index 3fab01f..bc8f30a 100644
--- a/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx
+++ b/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx
@@ -172,6 +172,7 @@ export default function DraftImpactTesting({ workspaceId, catalog, risks, isCont
{mitigationMutation.data ? : null}
{originalResult ? (
- Step 3
Test a safe replacement These options come from the same deterministic eligibility and workflow rules used by the impact test.
{result.recommendations.length} safe option{result.recommendations.length === 1 ? '' : 's'}
+ Step 3
Compare technically viable replacements Every option restores the configured workflow rules. Team alignment and added access explain why one option ranks above another.
{result.recommendations.length} viable option{result.recommendations.length === 1 ? '' : 's'}
{result.recommendations.map((recommendation) => {
const tested = mitigation?.changeSet.replacementEmployee?.id === recommendation.candidate.id
+ const alignment = describeRecommendationAlignment(catalog, result, recommendation)
return (
{String(recommendation.rank).padStart(2, '0')}
- Assign {recommendation.role.name} to {recommendation.candidate.name} This restores {formatEntityNames(recommendation.restoredWorkflowSteps)} with {recommendation.gainedPermissions.length} additional effective permission{recommendation.gainedPermissions.length === 1 ? '' : 's'}.
{recommendation.evidence.map((evidence) => {evidenceLabel(evidence)} )}
+ {alignment.label} Assign {recommendation.role.name} to {recommendation.candidate.name} {alignment.reason}
This restores {formatEntityNames(recommendation.restoredWorkflowSteps)} with {recommendation.gainedPermissions.length} additional effective permission{recommendation.gainedPermissions.length === 1 ? '' : 's'}.
{recommendation.evidence.map((evidence) => {evidenceLabel(evidence)} )}
onTest(recommendation.candidate.id)}>{isPending ? 'Testing mitigation…' : tested ? 'Test mitigation again' : 'Test this mitigation'}
)
@@ -254,6 +257,38 @@ function DraftMitigationPanel({ result, mitigation, isPending, error, onTest }:
)
}
+function describeRecommendationAlignment(
+ catalog: DraftCatalog,
+ result: DraftImpactResult,
+ recommendation: DraftImpactResult['recommendations'][number],
+) {
+ const source = catalog.members.find((member) => member.id === result.changeSet.employee.id)
+ const candidate = catalog.members.find((member) => member.id === recommendation.candidate.id)
+ const sourceTeam = catalog.teams.find((team) => team.id === source?.teamId)
+ const candidateTeam = catalog.teams.find((team) => team.id === candidate?.teamId)
+ const addedAccess = `${recommendation.gainedPermissions.length} new effective permission${recommendation.gainedPermissions.length === 1 ? '' : 's'}`
+
+ if (sourceTeam && candidateTeam && sourceTeam.id === candidateTeam.id) {
+ return {
+ label: recommendation.rank === 1 ? 'Best aligned · same team' : 'Same-team alternative',
+ tone: 'aligned',
+ reason: `Ranked #${recommendation.rank} because ${recommendation.candidate.name} is in the same team as ${result.changeSet.employee.name}. The proposed assignment requires ${addedAccess}.`,
+ }
+ }
+ if (sourceTeam && candidateTeam && sourceTeam.department === candidateTeam.department) {
+ return {
+ label: 'Cross-team · same department',
+ tone: 'review',
+ reason: `Ranked #${recommendation.rank} as a technically viable cross-team option within ${sourceTeam.department}. Review the transfer of responsibility before granting ${addedAccess}.`,
+ }
+ }
+ return {
+ label: 'Cross-department alternative',
+ tone: 'review',
+ reason: `Ranked #${recommendation.rank} because the configured workflow rules are restored, but this crosses organizational boundaries and requires ${addedAccess}.`,
+ }
+}
+
function CandidateExclusions({ result }: { result: DraftImpactResult }) {
return (
Why other members were not recommended {result.excludedCandidateReasons.map((exclusion) =>
{exclusion.candidate.name}: {exclusion.reasons.map((reason) => reason.detail).join(' ')}
)}
diff --git a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx
new file mode 100644
index 0000000..65cd865
--- /dev/null
+++ b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx
@@ -0,0 +1,87 @@
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+import type { DraftCatalog } from '../../../api/draftCatalog'
+import type { DraftContinuityRisk, DraftImpactResult } from '../../../api/draftImpact'
+import { OrganizationImpactCanvas } from './OrganizationCanvas'
+
+describe('FullOrganizationImpactCanvas', () => {
+ it('keeps a shared role available when removing one holder leaves other eligible holders', async () => {
+ render(
+
,
+ )
+
+ expect(await screen.findByLabelText(/member Maya Singh.*Assignment removed/i)).toBeInTheDocument()
+ expect(screen.getByLabelText(/role Invoice Processor.*2 holders remain/i)).toBeInTheDocument()
+ expect(screen.queryByLabelText(/role Invoice Processor.*Removed/i)).not.toBeInTheDocument()
+ expect(screen.getByLabelText(/responsibility Validate supplier invoice.*Still operational/i)).toBeInTheDocument()
+ expect(screen.getByLabelText(/workflow Daily Vendor Payment Run.*Still operational/i)).toBeInTheDocument()
+ })
+})
+
+const safeSharedRoleCatalog: DraftCatalog = {
+ workspaceId: 'workspace-1',
+ teams: [{ id: 'team-ap', name: 'Accounts Payable', department: 'Finance', memberCount: 3 }],
+ members: [
+ { id: 'member-maya', teamId: 'team-ap', employeeNumber: null, name: 'Maya Singh', email: null, status: 'ACTIVE', region: 'NORTH_AMERICA', shift: 'DAY', roleIds: ['role-1'] },
+ { id: 'member-neha', teamId: 'team-ap', employeeNumber: null, name: 'Neha Kapoor', email: null, status: 'ACTIVE', region: 'NORTH_AMERICA', shift: 'DAY', roleIds: ['role-1'] },
+ { id: 'member-omar', teamId: 'team-ap', employeeNumber: null, name: 'Omar Haddad', email: null, status: 'ACTIVE', region: 'NORTH_AMERICA', shift: 'DAY', roleIds: ['role-1'] },
+ ],
+ roles: [{ id: 'role-1', name: 'Invoice Processor', description: 'Validates supplier invoices', sensitivity: 'MEDIUM', ownerMemberId: null, memberCount: 3 }],
+ workflows: [{
+ id: 'workflow-1',
+ name: 'Daily Vendor Payment Run',
+ criticality: 'CRITICAL',
+ quickManaged: true,
+ requirements: [{ id: 'requirement-1', name: 'Validate supplier invoice', position: 1, minimumActors: 1, resilienceTarget: 2, requiredDepartment: null, requiredRegion: null, requiredShift: null, roleIds: ['role-1'] }],
+ }],
+}
+
+const safeSharedRoleRisks: DraftContinuityRisk[] = [{
+ key: 'workflow-1:requirement-1:role-1',
+ workflowId: 'workflow-1',
+ workflowName: 'Daily Vendor Payment Run',
+ criticality: 'CRITICAL',
+ requirementId: 'requirement-1',
+ requirementName: 'Validate supplier invoice',
+ minimumActors: 1,
+ resilienceTarget: 2,
+ roleId: 'role-1',
+ roleName: 'Invoice Processor',
+ eligibleMembers: [
+ { id: 'member-maya', name: 'Maya Singh' },
+ { id: 'member-neha', name: 'Neha Kapoor' },
+ { id: 'member-omar', name: 'Omar Haddad' },
+ ],
+ members: [{ id: 'member-maya', name: 'Maya Singh', eligible: true, losesCoverage: true, remainingEligibleActorCount: 2, scenarioStatus: 'OPERATIONAL' }],
+}]
+
+const safeSharedRoleResult = {
+ changeSet: {
+ type: 'REVOKE_EMPLOYEE_ROLE',
+ employee: { id: 'member-maya', name: 'Maya Singh' },
+ role: { id: 'role-1', name: 'Invoice Processor' },
+ replacementEmployee: null,
+ },
+ workflowImpacts: [{
+ workflowId: 'workflow-1',
+ workflowName: 'Daily Vendor Payment Run',
+ baselineStatus: 'OPERATIONAL',
+ scenarioStatus: 'OPERATIONAL',
+ steps: [{ stepId: 'requirement-1', baselineStatus: 'OPERATIONAL', scenarioStatus: 'OPERATIONAL' }],
+ }],
+ recommendations: [],
+ excludedCandidateReasons: [],
+ diagnostics: { resultHash: 'safe-shared-role' },
+} as unknown as DraftImpactResult
diff --git a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx
index a6efec4..98da1bd 100644
--- a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx
+++ b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx
@@ -329,7 +329,7 @@ function buildImpactModel(
if (entityId === replacementMemberId) {
simulationState = replacementState; badge = replacementState === 'restored' ? 'Tried · restores coverage' : 'Tried · does not restore'; detail = 'Proposed role holder · click another member to compare'
} else if (displayedResult && entityId === sourceMemberId) {
- simulationState = 'removed'; badge = 'Role removed'
+ simulationState = 'removed'; badge = 'Assignment removed'
} else if (recommendationRank.has(entityId)) {
simulationState = 'candidate'; badge = `Recommended #${recommendationRank.get(entityId)}`; detail = 'Click to test as replacement'
} else if (originalResult && exclusions.has(entityId) && entityId !== sourceMemberId) {
@@ -340,7 +340,25 @@ function buildImpactModel(
simulationState = 'source'; badge = 'Selected source'
}
} else if (node.data.entityType === 'role' && entityId === roleId && displayedResult) {
- simulationState = replacementState ?? 'removed'; badge = replacementState === 'restored' ? 'Reassigned · restored' : replacementState ? 'Reassigned · insufficient' : 'Removed'
+ if (replacementState) {
+ simulationState = replacementState
+ badge = replacementState === 'restored' ? 'Reassigned · restored' : 'Reassigned · insufficient'
+ } else {
+ const remainingHolderCount = catalog.members.filter((member) => member.id !== sourceMemberId && member.roleIds.includes(entityId)).length
+ if (remainingHolderCount === 0) {
+ simulationState = 'removed'
+ badge = 'No holders remain'
+ } else {
+ const supportingStates = catalog.workflows
+ .flatMap((workflow) => workflow.requirements)
+ .filter((requirement) => requirement.roleIds.includes(entityId))
+ .map((requirement) => stepStates.get(requirement.id))
+ simulationState = supportingStates.includes('blocked') ? 'blocked' : supportingStates.includes('degraded') ? 'degraded' : 'source'
+ badge = `${remainingHolderCount} holder${remainingHolderCount === 1 ? '' : 's'} remain`
+ const sourceName = catalog.members.find((member) => member.id === sourceMemberId)?.name ?? 'the selected member'
+ detail = `Only ${sourceName}'s assignment is removed. This shared role remains available through ${remainingHolderCount} other holder${remainingHolderCount === 1 ? '' : 's'}.`
+ }
+ }
} else if (node.data.entityType === 'responsibility') {
simulationState = stepStates.get(entityId)
if (simulationState) badge = stateBadge(simulationState)
@@ -468,6 +486,7 @@ function stateBadge(state: OrganizationSimulationState) {
if (state === 'blocked') return 'Blocked'
if (state === 'degraded') return 'Degraded'
if (state === 'restored') return 'Restored'
+ if (state === 'source') return 'Still operational'
return undefined
}
From e3649edb6fcac560d0ed59fb84246d5908c0c8a2 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Fri, 21 Aug 2026 21:52:30 -0400
Subject: [PATCH 04/10] feat: add stable organization public codes
---
.../V7__add_organization_public_codes.sql | 53 +++++++++++++++++++
.../CatalogMigrationIntegrationTest.java | 22 +++++++-
2 files changed, 74 insertions(+), 1 deletion(-)
create mode 100644 backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql
diff --git a/backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql b/backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql
new file mode 100644
index 0000000..3a1edf4
--- /dev/null
+++ b/backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql
@@ -0,0 +1,53 @@
+ALTER TABLE organizations ADD COLUMN public_code VARCHAR(10);
+
+CREATE FUNCTION pg_temp.encode_workspace_number(value BIGINT)
+RETURNS TEXT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ alphabet CONSTANT TEXT := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
+ encoded TEXT := '';
+ remainder INTEGER;
+BEGIN
+ FOR position IN 1..6 LOOP
+ remainder := MOD(value, 32);
+ encoded := SUBSTRING(alphabet FROM remainder + 1 FOR 1) || encoded;
+ value := value / 32;
+ END LOOP;
+ RETURN encoded;
+END;
+$$;
+
+WITH ranked_organizations AS (
+ SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS code_number
+ FROM organizations
+)
+UPDATE organizations organization
+SET public_code = RPAD(
+ SUBSTRING(
+ TRANSLATE(
+ COALESCE(NULLIF(UPPER(REGEXP_REPLACE(organization.name, '[^A-Za-z0-9]', '', 'g')), ''), 'ORG'),
+ 'OI01',
+ 'QJ23'
+ )
+ FROM 1 FOR 3
+ ),
+ 3,
+ 'X'
+ ) || '-' || pg_temp.encode_workspace_number(ranked.code_number)
+FROM ranked_organizations ranked
+WHERE ranked.id = organization.id;
+
+ALTER TABLE organizations
+ ALTER COLUMN public_code SET NOT NULL,
+ ADD CONSTRAINT ck_organizations_public_code_format
+ CHECK (public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$');
+
+CREATE UNIQUE INDEX uq_organizations_public_code_ci
+ ON organizations (UPPER(public_code));
+
+DROP INDEX IF EXISTS idx_organizations_source_template;
+
+ALTER TABLE organizations
+ DROP CONSTRAINT IF EXISTS ck_organizations_not_own_template,
+ DROP COLUMN source_template_organization_id;
diff --git a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
index 213659d..124854c 100644
--- a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
@@ -74,6 +74,26 @@ class CatalogMigrationIntegrationTest {
@Autowired
private ObjectMapper objectMapper;
+ @Test
+ void assignsPublicCodesAndRemovesCloneMetadata() {
+ var publicCodes = jdbcClient.sql("SELECT public_code FROM organizations ORDER BY id")
+ .query(String.class)
+ .list();
+ var cloneColumnCount = jdbcClient.sql("""
+ SELECT COUNT(*)
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'organizations'
+ AND column_name = 'source_template_organization_id'
+ """).query(Integer.class).single();
+
+ assertThat(publicCodes).isNotEmpty()
+ .allSatisfy(code -> assertThat(code).matches("[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}"));
+ assertThat(publicCodes.stream().map(String::toUpperCase).distinct().count())
+ .isEqualTo(publicCodes.size());
+ assertThat(cloneColumnCount).isZero();
+ }
+
@Test
void appliesSchemaAndLoadsTheCompleteHarborlineBaseline() {
assertThat(count("organizations")).isEqualTo(1);
@@ -95,7 +115,7 @@ SELECT COUNT(*)
.query(Integer.class)
.single();
- assertThat(successfulMigrations).isEqualTo(6);
+ assertThat(successfulMigrations).isEqualTo(7);
var employeeNumberNullable = jdbcClient.sql("""
SELECT is_nullable
FROM information_schema.columns
From 7f27ae799cee5fdb6b3c595fe58cd364f91c3802 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Fri, 21 Aug 2026 22:03:34 -0400
Subject: [PATCH 05/10] feat: resolve editable organizations by public code
---
.../workspace/api/WorkspaceController.java | 22 +-
.../workspace/api/WorkspaceResource.java | 2 +-
.../workspace/application/WorkspaceCode.java | 64 +++++
.../WorkspaceNotFoundException.java | 4 +
.../application/WorkspaceService.java | 65 +++--
.../application/DraftCatalogService.java | 2 +-
.../PublishedWorkspaceMutationException.java | 2 +-
.../persistence/WorkspaceRepository.java | 229 ++----------------
.../workspace/WorkspaceIntegrationTest.java | 142 +++--------
.../application/WorkspaceCodeTest.java | 29 +++
.../application/WorkspaceServiceTest.java | 59 +++++
...zation-deep-linking-implementation-plan.md | 35 +--
12 files changed, 257 insertions(+), 398 deletions(-)
create mode 100644 backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
create mode 100644 backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
create mode 100644 backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java
diff --git a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java
index ba89a03..865a1c4 100644
--- a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java
+++ b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java
@@ -1,7 +1,6 @@
package com.roleimpact.workspace.api;
import java.net.URI;
-import java.util.List;
import java.util.UUID;
import com.roleimpact.workspace.application.WorkspaceService;
@@ -27,32 +26,25 @@ public WorkspaceController(WorkspaceService workspaceService) {
this.workspaceService = workspaceService;
}
- @GetMapping
- public List list() {
- return workspaceService.list();
- }
-
@GetMapping("/{workspaceId}")
public WorkspaceResource get(@PathVariable UUID workspaceId) {
return workspaceService.get(workspaceId);
}
+ @GetMapping("/by-code/{publicCode}")
+ public WorkspaceResource getByCode(@PathVariable String publicCode) {
+ return workspaceService.getEditableByCode(publicCode);
+ }
+
@PostMapping
public ResponseEntity create(@Valid @RequestBody WorkspaceRequest request) {
return created(workspaceService.createBlank(request));
}
- @PostMapping("/{sourceWorkspaceId}/clones")
- public ResponseEntity clone(
- @PathVariable UUID sourceWorkspaceId,
- @Valid @RequestBody WorkspaceRequest request) {
- return created(workspaceService.clonePublished(sourceWorkspaceId, request));
- }
-
private ResponseEntity created(WorkspaceResource workspace) {
URI location = ServletUriComponentsBuilder.fromCurrentContextPath()
- .path("/api/v1/workspaces/{id}")
- .buildAndExpand(workspace.id())
+ .path("/api/v1/workspaces/by-code/{publicCode}")
+ .buildAndExpand(workspace.publicCode())
.toUri();
return ResponseEntity.created(location).body(workspace);
}
diff --git a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java
index ce3b010..8a46b30 100644
--- a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java
+++ b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java
@@ -9,7 +9,7 @@ public record WorkspaceResource(
String name,
String status,
int currentVersion,
- UUID sourceTemplateOrganizationId,
+ String publicCode,
Instant createdAt,
Instant updatedAt,
WorkspaceCounts counts) {
diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
new file mode 100644
index 0000000..b25eb71
--- /dev/null
+++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
@@ -0,0 +1,64 @@
+package com.roleimpact.workspace.application;
+
+import java.security.SecureRandom;
+import java.text.Normalizer;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class WorkspaceCode {
+
+ private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
+ private static final Pattern COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{9}$");
+ private static final Pattern DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$");
+
+ private final SecureRandom random;
+
+ public WorkspaceCode() {
+ this(new SecureRandom());
+ }
+
+ WorkspaceCode(SecureRandom random) {
+ this.random = random;
+ }
+
+ public String generate(String organizationName) {
+ String asciiName = Normalizer.normalize(organizationName, Normalizer.Form.NFD)
+ .replaceAll("\\p{M}", "")
+ .toUpperCase(Locale.ROOT);
+ String initials = Arrays.stream(asciiName.split("[^A-Z0-9]+"))
+ .filter(token -> !token.isBlank())
+ .map(token -> token.substring(0, 1))
+ .collect(Collectors.joining());
+ String compactName = asciiName.replaceAll("[^A-Z0-9]", "");
+ String prefixSeed = sanitize(initials + compactName + "ORG");
+ StringBuilder suffix = new StringBuilder(6);
+ for (int index = 0; index < 6; index++) {
+ suffix.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
+ }
+ return prefixSeed.substring(0, 3) + "-" + suffix;
+ }
+
+ public static String normalize(String rawCode) {
+ if (rawCode == null) {
+ return null;
+ }
+ String candidate = rawCode.trim().toUpperCase(Locale.ROOT);
+ if (COMPACT.matcher(candidate).matches()) {
+ candidate = candidate.substring(0, 3) + "-" + candidate.substring(3);
+ }
+ return DISPLAYED.matcher(candidate).matches() ? candidate : null;
+ }
+
+ private static String sanitize(String value) {
+ return value.replace('O', 'Q')
+ .replace('I', 'J')
+ .replace('0', '2')
+ .replace('1', '3')
+ .replaceAll("[^A-HJ-NP-Z2-9]", "");
+ }
+}
diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java
index 2ba9209..ca2e55e 100644
--- a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java
+++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java
@@ -7,4 +7,8 @@ public class WorkspaceNotFoundException extends RuntimeException {
public WorkspaceNotFoundException(UUID id) {
super("Workspace not found: " + id);
}
+
+ public WorkspaceNotFoundException(String publicCode) {
+ super("Organization not found: " + publicCode);
+ }
}
diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java
index 9cf14bf..9058a51 100644
--- a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java
+++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java
@@ -1,7 +1,6 @@
package com.roleimpact.workspace.application;
import java.text.Normalizer;
-import java.util.List;
import java.util.Locale;
import java.util.UUID;
@@ -9,7 +8,6 @@
import com.roleimpact.workspace.api.WorkspaceResource;
import com.roleimpact.workspace.persistence.WorkspaceRepository;
-import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -17,14 +15,11 @@
public class WorkspaceService {
private final WorkspaceRepository workspaceRepository;
+ private final WorkspaceCode workspaceCode;
- public WorkspaceService(WorkspaceRepository workspaceRepository) {
+ public WorkspaceService(WorkspaceRepository workspaceRepository, WorkspaceCode workspaceCode) {
this.workspaceRepository = workspaceRepository;
- }
-
- @Transactional(readOnly = true)
- public List list() {
- return workspaceRepository.findAll();
+ this.workspaceCode = workspaceCode;
}
@Transactional(readOnly = true)
@@ -33,43 +28,39 @@ public WorkspaceResource get(UUID id) {
.orElseThrow(() -> new WorkspaceNotFoundException(id));
}
- @Transactional
- public WorkspaceResource createBlank(WorkspaceRequest request) {
- String name = request.name().trim();
- String slug = resolveSlug(request, name);
- UUID workspaceId = UUID.randomUUID();
-
- insertDraft(workspaceId, slug, name, null);
- return get(workspaceId);
+ @Transactional(readOnly = true)
+ public WorkspaceResource getEditableByCode(String rawCode) {
+ String publicCode = WorkspaceCode.normalize(rawCode);
+ if (publicCode == null) {
+ throw new WorkspaceNotFoundException(rawCode);
+ }
+ return workspaceRepository.findDraftByPublicCode(publicCode)
+ .orElseThrow(() -> new WorkspaceNotFoundException(rawCode));
}
@Transactional
- public WorkspaceResource clonePublished(UUID sourceId, WorkspaceRequest request) {
- String status = workspaceRepository.findStatus(sourceId)
- .orElseThrow(() -> new WorkspaceNotFoundException(sourceId));
- if (!"PUBLISHED".equals(status)) {
- throw new WorkspaceValidationException("Only a published workspace can be cloned");
- }
-
+ public WorkspaceResource createBlank(WorkspaceRequest request) {
String name = request.name().trim();
String slug = resolveSlug(request, name);
- UUID workspaceId = UUID.randomUUID();
-
- insertDraft(workspaceId, slug, name, sourceId);
- workspaceRepository.cloneCatalog(sourceId, workspaceId);
- return get(workspaceId);
- }
-
- private void insertDraft(UUID id, String slug, String name, UUID sourceTemplateId) {
if (workspaceRepository.existsBySlug(slug)) {
- throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
- }
- try {
- workspaceRepository.insertDraft(id, slug, name, sourceTemplateId);
+ throw slugConflict(slug);
}
- catch (DataIntegrityViolationException exception) {
- throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
+
+ for (int attempt = 0; attempt < 5; attempt++) {
+ UUID workspaceId = UUID.randomUUID();
+ String publicCode = workspaceCode.generate(name);
+ if (workspaceRepository.insertDraft(workspaceId, slug, name, publicCode)) {
+ return get(workspaceId);
+ }
+ if (workspaceRepository.existsBySlug(slug)) {
+ throw slugConflict(slug);
+ }
}
+ throw new WorkspaceConflictException("A unique organization ID could not be generated; try again");
+ }
+
+ private WorkspaceConflictException slugConflict(String slug) {
+ return new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
}
private String resolveSlug(WorkspaceRequest request, String name) {
diff --git a/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java b/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java
index a1d01e1..d84093b 100644
--- a/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java
+++ b/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java
@@ -168,7 +168,7 @@ public DraftCatalogResource addWorkflowRequirement(
throw new DraftCatalogNotFoundException("Workflow", workflowId);
}
if (!repository.quickWorkflowExists(workspaceId, workflowId)) {
- throw new DraftCatalogConflictException("The example workflow is read-only for now; clone its pattern into a custom workflow to edit requirements");
+ throw new DraftCatalogConflictException("The example workflow is read-only; create a custom workflow to edit requirements");
}
requireRole(workspaceId, request.roleId());
requireCoverage(request.minimumActors(), request.resilienceTarget());
diff --git a/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java b/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java
index 8e6577e..0e87212 100644
--- a/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java
+++ b/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java
@@ -3,6 +3,6 @@
public class PublishedWorkspaceMutationException extends RuntimeException {
public PublishedWorkspaceMutationException() {
- super("Published workspaces are immutable; clone this workspace before editing it");
+ super("Published examples are read-only; create a new organization to make changes");
}
}
diff --git a/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java b/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java
index 062dc88..382699b 100644
--- a/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java
+++ b/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java
@@ -2,7 +2,6 @@
import java.sql.Timestamp;
import java.time.Instant;
-import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -17,7 +16,7 @@ public class WorkspaceRepository {
private static final String WORKSPACE_SELECT = """
SELECT o.id, o.slug, o.name, o.workspace_status, o.current_version,
- o.source_template_organization_id, o.created_at, o.updated_at,
+ o.public_code, o.created_at, o.updated_at,
(SELECT COUNT(*) FROM teams t WHERE t.organization_id = o.id) AS team_count,
(SELECT COUNT(*) FROM employees e WHERE e.organization_id = o.id) AS member_count,
(SELECT COUNT(*) FROM roles r WHERE r.organization_id = o.id) AS role_count,
@@ -33,12 +32,6 @@ public WorkspaceRepository(JdbcClient jdbcClient) {
this.jdbcClient = jdbcClient;
}
- public List findAll() {
- return jdbcClient.sql(WORKSPACE_SELECT + " ORDER BY o.created_at, o.id")
- .query(this::mapWorkspace)
- .list();
- }
-
public Optional findById(UUID id) {
return jdbcClient.sql(WORKSPACE_SELECT + " WHERE o.id = :id")
.param("id", id)
@@ -46,6 +39,14 @@ public Optional findById(UUID id) {
.optional();
}
+ public Optional findDraftByPublicCode(String publicCode) {
+ return jdbcClient.sql(WORKSPACE_SELECT
+ + " WHERE UPPER(o.public_code) = :publicCode AND o.workspace_status = 'DRAFT'")
+ .param("publicCode", publicCode)
+ .query(this::mapWorkspace)
+ .optional();
+ }
+
public boolean existsBySlug(String slug) {
return jdbcClient.sql("SELECT EXISTS (SELECT 1 FROM organizations WHERE slug = :slug)")
.param("slug", slug)
@@ -53,218 +54,22 @@ public boolean existsBySlug(String slug) {
.single();
}
- public Optional findStatus(UUID id) {
- return jdbcClient.sql("SELECT workspace_status FROM organizations WHERE id = :id")
- .param("id", id)
- .query(String.class)
- .optional();
- }
-
- public void insertDraft(UUID id, String slug, String name, UUID sourceTemplateId) {
- jdbcClient.sql("""
+ public boolean insertDraft(UUID id, String slug, String name, String publicCode) {
+ return jdbcClient.sql("""
INSERT INTO organizations (
id, slug, name, current_version, workspace_status,
- source_template_organization_id, created_at, updated_at
+ public_code, created_at, updated_at
) VALUES (
- :id, :slug, :name, 0, 'DRAFT', :sourceTemplateId,
+ :id, :slug, :name, 0, 'DRAFT', :publicCode,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
+ ON CONFLICT DO NOTHING
""")
.param("id", id)
.param("slug", slug)
.param("name", name)
- .param("sourceTemplateId", sourceTemplateId)
- .update();
- }
-
- public void cloneCatalog(UUID sourceId, UUID targetId) {
- jdbcClient.sql("""
- CREATE TEMP TABLE workspace_clone_ids (
- entity_type VARCHAR(20) NOT NULL,
- source_id UUID NOT NULL,
- target_id UUID NOT NULL,
- PRIMARY KEY (entity_type, source_id)
- ) ON COMMIT DROP
- """).update();
-
- mapIds("team", "teams", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO teams (id, organization_id, name, department, manager_employee_id)
- SELECT m.target_id, :targetId, t.name, t.department, NULL
- FROM teams t
- JOIN workspace_clone_ids m ON m.entity_type = 'team' AND m.source_id = t.id
- WHERE t.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
-
- mapIds("employee", "employees", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO employees (
- id, organization_id, team_id, employee_no, name, email, status, region, shift
- )
- SELECT em.target_id, :targetId, tm.target_id, e.employee_no, e.name, e.email,
- e.status, e.region, e.shift
- FROM employees e
- JOIN workspace_clone_ids em ON em.entity_type = 'employee' AND em.source_id = e.id
- JOIN workspace_clone_ids tm ON tm.entity_type = 'team' AND tm.source_id = e.team_id
- WHERE e.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
- jdbcClient.sql("""
- UPDATE teams target_team
- SET manager_employee_id = manager_map.target_id
- FROM teams source_team
- JOIN workspace_clone_ids team_map
- ON team_map.entity_type = 'team' AND team_map.source_id = source_team.id
- JOIN workspace_clone_ids manager_map
- ON manager_map.entity_type = 'employee'
- AND manager_map.source_id = source_team.manager_employee_id
- WHERE target_team.id = team_map.target_id
- AND source_team.organization_id = :sourceId
- """).param("sourceId", sourceId).update();
-
- mapIds("role", "roles", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO roles (id, organization_id, name, description, sensitivity, owner_employee_id)
- SELECT rm.target_id, :targetId, r.name, r.description, r.sensitivity, owner_map.target_id
- FROM roles r
- JOIN workspace_clone_ids rm ON rm.entity_type = 'role' AND rm.source_id = r.id
- LEFT JOIN workspace_clone_ids owner_map
- ON owner_map.entity_type = 'employee' AND owner_map.source_id = r.owner_employee_id
- WHERE r.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
- jdbcClient.sql("""
- INSERT INTO employee_roles (employee_id, role_id, assigned_at, assigned_by)
- SELECT em.target_id, rm.target_id, er.assigned_at, 'workspace clone'
- FROM employee_roles er
- JOIN workspace_clone_ids em ON em.entity_type = 'employee' AND em.source_id = er.employee_id
- JOIN workspace_clone_ids rm ON rm.entity_type = 'role' AND rm.source_id = er.role_id
- """).update();
-
- mapIds("application", "applications", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO applications (id, organization_id, name, category, owner_employee_id)
- SELECT am.target_id, :targetId, a.name, a.category, owner_map.target_id
- FROM applications a
- JOIN workspace_clone_ids am ON am.entity_type = 'application' AND am.source_id = a.id
- LEFT JOIN workspace_clone_ids owner_map
- ON owner_map.entity_type = 'employee' AND owner_map.source_id = a.owner_employee_id
- WHERE a.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
-
- mapIdsThroughOrganization("resource", "resources", "application_id", "applications", sourceId);
- jdbcClient.sql("""
- INSERT INTO resources (id, application_id, name, resource_type)
- SELECT res_map.target_id, app_map.target_id, r.name, r.resource_type
- FROM resources r
- JOIN workspace_clone_ids res_map ON res_map.entity_type = 'resource' AND res_map.source_id = r.id
- JOIN workspace_clone_ids app_map ON app_map.entity_type = 'application' AND app_map.source_id = r.application_id
- """).update();
-
- mapIds("permission", "permissions", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO permissions (
- id, organization_id, application_id, resource_id, action, sensitivity
- )
- SELECT pm.target_id, :targetId, am.target_id, rm.target_id, p.action, p.sensitivity
- FROM permissions p
- JOIN workspace_clone_ids pm ON pm.entity_type = 'permission' AND pm.source_id = p.id
- JOIN workspace_clone_ids am ON am.entity_type = 'application' AND am.source_id = p.application_id
- JOIN workspace_clone_ids rm ON rm.entity_type = 'resource' AND rm.source_id = p.resource_id
- WHERE p.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
- jdbcClient.sql("""
- INSERT INTO role_permissions (role_id, permission_id)
- SELECT rm.target_id, pm.target_id
- FROM role_permissions rp
- JOIN workspace_clone_ids rm ON rm.entity_type = 'role' AND rm.source_id = rp.role_id
- JOIN workspace_clone_ids pm ON pm.entity_type = 'permission' AND pm.source_id = rp.permission_id
- """).update();
-
- mapIds("capability", "capabilities", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO capabilities (id, organization_id, name, description)
- SELECT cm.target_id, :targetId, c.name, c.description
- FROM capabilities c
- JOIN workspace_clone_ids cm ON cm.entity_type = 'capability' AND cm.source_id = c.id
- WHERE c.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
- jdbcClient.sql("""
- INSERT INTO capability_permissions (capability_id, permission_id)
- SELECT cm.target_id, pm.target_id
- FROM capability_permissions cp
- JOIN workspace_clone_ids cm ON cm.entity_type = 'capability' AND cm.source_id = cp.capability_id
- JOIN workspace_clone_ids pm ON pm.entity_type = 'permission' AND pm.source_id = cp.permission_id
- """).update();
-
- mapIds("workflow", "workflows", "organization_id", sourceId);
- jdbcClient.sql("""
- INSERT INTO workflows (id, organization_id, name, criticality, owner_employee_id)
- SELECT wm.target_id, :targetId, w.name, w.criticality, owner_map.target_id
- FROM workflows w
- JOIN workspace_clone_ids wm ON wm.entity_type = 'workflow' AND wm.source_id = w.id
- LEFT JOIN workspace_clone_ids owner_map
- ON owner_map.entity_type = 'employee' AND owner_map.source_id = w.owner_employee_id
- WHERE w.organization_id = :sourceId
- """).param("targetId", targetId).param("sourceId", sourceId).update();
-
- mapIdsThroughOrganization("workflow_step", "workflow_steps", "workflow_id", "workflows", sourceId);
- jdbcClient.sql("""
- INSERT INTO workflow_steps (
- id, workflow_id, step_key, name, position, required_capability_id,
- minimum_actors, resilience_target, required_department, required_region,
- required_shift, required_application_id
- )
- SELECT sm.target_id, wm.target_id, s.step_key, s.name, s.position, cm.target_id,
- s.minimum_actors, s.resilience_target, s.required_department, s.required_region,
- s.required_shift, am.target_id
- FROM workflow_steps s
- JOIN workspace_clone_ids sm ON sm.entity_type = 'workflow_step' AND sm.source_id = s.id
- JOIN workspace_clone_ids wm ON wm.entity_type = 'workflow' AND wm.source_id = s.workflow_id
- JOIN workspace_clone_ids cm ON cm.entity_type = 'capability' AND cm.source_id = s.required_capability_id
- LEFT JOIN workspace_clone_ids am
- ON am.entity_type = 'application' AND am.source_id = s.required_application_id
- """).update();
-
- mapIdsThroughOrganization("constraint", "workflow_constraints", "workflow_id", "workflows", sourceId);
- jdbcClient.sql("""
- INSERT INTO workflow_constraints (id, workflow_id, type, parameters)
- SELECT cm.target_id, wm.target_id, c.type, c.parameters
- FROM workflow_constraints c
- JOIN workspace_clone_ids cm ON cm.entity_type = 'constraint' AND cm.source_id = c.id
- JOIN workspace_clone_ids wm ON wm.entity_type = 'workflow' AND wm.source_id = c.workflow_id
- """).update();
- jdbcClient.sql("""
- INSERT INTO workflow_step_constraints (workflow_step_id, constraint_id)
- SELECT sm.target_id, cm.target_id
- FROM workflow_step_constraints sc
- JOIN workspace_clone_ids sm ON sm.entity_type = 'workflow_step' AND sm.source_id = sc.workflow_step_id
- JOIN workspace_clone_ids cm ON cm.entity_type = 'constraint' AND cm.source_id = sc.constraint_id
- """).update();
- }
-
- private void mapIds(String entityType, String table, String organizationColumn, UUID sourceId) {
- String sql = "INSERT INTO workspace_clone_ids (entity_type, source_id, target_id) "
- + "SELECT :entityType, id, gen_random_uuid() FROM " + table
- + " WHERE " + organizationColumn + " = :sourceId";
- jdbcClient.sql(sql)
- .param("entityType", entityType)
- .param("sourceId", sourceId)
- .update();
- }
-
- private void mapIdsThroughOrganization(
- String entityType,
- String table,
- String parentColumn,
- String parentTable,
- UUID sourceId) {
- String sql = "INSERT INTO workspace_clone_ids (entity_type, source_id, target_id) "
- + "SELECT :entityType, child.id, gen_random_uuid() FROM " + table + " child "
- + "JOIN " + parentTable + " parent ON parent.id = child." + parentColumn + " "
- + "WHERE parent.organization_id = :sourceId";
- jdbcClient.sql(sql)
- .param("entityType", entityType)
- .param("sourceId", sourceId)
- .update();
+ .param("publicCode", publicCode)
+ .update() == 1;
}
private WorkspaceResource mapWorkspace(java.sql.ResultSet resultSet, int rowNumber) throws java.sql.SQLException {
@@ -276,7 +81,7 @@ private WorkspaceResource mapWorkspace(java.sql.ResultSet resultSet, int rowNumb
resultSet.getString("name"),
resultSet.getString("workspace_status"),
resultSet.getInt("current_version"),
- resultSet.getObject("source_template_organization_id", UUID.class),
+ resultSet.getString("public_code"),
toInstant(createdAt),
toInstant(updatedAt),
new WorkspaceCounts(
diff --git a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
index b2927ef..f106adb 100644
--- a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
@@ -50,90 +50,56 @@ class WorkspaceIntegrationTest {
private JdbcClient jdbcClient;
@Test
- void createsBlankAndClonedDraftsWithoutChangingThePublishedTemplate() throws Exception {
- mockMvc.perform(get("/api/v1/workspaces"))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$[0].id").value(HARBORLINE_ID.toString()))
- .andExpect(jsonPath("$[0].status").value("PUBLISHED"))
- .andExpect(jsonPath("$[0].currentVersion").value(1))
- .andExpect(jsonPath("$[0].counts.members").value(25))
- .andExpect(jsonPath("$[0].counts.workflows").value(4));
-
+ void createsAndResolvesAnEditableDraftByPublicCode() throws Exception {
var blankResponse = mockMvc.perform(post("/api/v1/workspaces")
.contentType(MediaType.APPLICATION_JSON)
- .content(workspaceRequest("Northstar Labs", null)))
+ .content(workspaceRequest("Northstar Medical Supplies", null)))
.andExpect(status().isCreated())
- .andExpect(header().string("Location", org.hamcrest.Matchers.containsString("/api/v1/workspaces/")))
- .andExpect(jsonPath("$.slug").value("northstar-labs"))
+ .andExpect(header().string("Location", org.hamcrest.Matchers.containsString("/api/v1/workspaces/by-code/")))
+ .andExpect(jsonPath("$.slug").value("northstar-medical-supplies"))
.andExpect(jsonPath("$.status").value("DRAFT"))
.andExpect(jsonPath("$.currentVersion").value(0))
- .andExpect(jsonPath("$.sourceTemplateOrganizationId").doesNotExist())
+ .andExpect(jsonPath("$.publicCode")
+ .value(org.hamcrest.Matchers.matchesPattern("NMS-[A-HJ-NP-Z2-9]{6}")))
.andExpect(jsonPath("$.counts.members").value(0))
.andExpect(jsonPath("$.counts.workflows").value(0))
.andReturn();
- UUID blankId = responseId(blankResponse.getResponse().getContentAsString());
-
- var cloneResponse = mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", HARBORLINE_ID)
- .contentType(MediaType.APPLICATION_JSON)
- .content(workspaceRequest("Harborline Sandbox", "harborline-sandbox")))
- .andExpect(status().isCreated())
- .andExpect(jsonPath("$.status").value("DRAFT"))
- .andExpect(jsonPath("$.currentVersion").value(0))
- .andExpect(jsonPath("$.sourceTemplateOrganizationId").value(HARBORLINE_ID.toString()))
- .andExpect(jsonPath("$.counts.teams").value(5))
- .andExpect(jsonPath("$.counts.members").value(25))
- .andExpect(jsonPath("$.counts.roles").value(8))
- .andExpect(jsonPath("$.counts.permissions").value(23))
- .andExpect(jsonPath("$.counts.capabilities").value(10))
- .andExpect(jsonPath("$.counts.workflows").value(4))
- .andReturn();
- UUID cloneId = responseId(cloneResponse.getResponse().getContentAsString());
+ var blankJson = objectMapper.readTree(blankResponse.getResponse().getContentAsString());
+ UUID blankId = UUID.fromString(blankJson.path("id").asText());
+ String publicCode = blankJson.path("publicCode").asText();
- mockMvc.perform(get("/api/v1/workspaces/{workspaceId}", cloneId))
+ mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", publicCode.toLowerCase()))
.andExpect(status().isOk())
- .andExpect(jsonPath("$.slug").value("harborline-sandbox"));
+ .andExpect(jsonPath("$.id").value(blankId.toString()))
+ .andExpect(jsonPath("$.publicCode").value(publicCode));
assertThat(workspaceState(HARBORLINE_ID)).isEqualTo("PUBLISHED|1");
assertThat(workspaceState(blankId)).isEqualTo("DRAFT|0");
- assertThat(workspaceState(cloneId)).isEqualTo("DRAFT|0");
- assertThat(countOrganizationVersions(cloneId)).isZero();
- assertThat(countSharedEmployeeIds(HARBORLINE_ID, cloneId)).isZero();
- assertThat(countNamedEmployees(cloneId, "Priya Sharma")).isOne();
-
- var clonedCatalog = mockMvc.perform(get("/api/v1/workspaces/{workspaceId}/catalog", cloneId))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.workflows[?(@.name == 'Vendor Payment')].requirements[?(@.name == 'High-Value Payment Approval')]").exists())
- .andReturn();
- var catalogJson = objectMapper.readTree(clonedCatalog.getResponse().getContentAsString());
- UUID priyaId = findId(catalogJson, "members", "Priya Sharma");
- UUID aishaId = findId(catalogJson, "members", "Aisha Khan");
- UUID sofiaId = findId(catalogJson, "members", "Sofia Martinez");
- UUID financeApproverId = findId(catalogJson, "roles", "Finance Approver");
- UUID seniorSupportId = findId(catalogJson, "roles", "Senior Support");
- UUID supportAgentId = findId(catalogJson, "roles", "Support Agent");
- assertPreview(cloneId, priyaId, financeApproverId, "CRITICAL", 1, 1);
- assertPreview(cloneId, aishaId, seniorSupportId, "MEDIUM", 0, 1);
- assertPreview(cloneId, sofiaId, supportAgentId, "LOW", 0, 0);
-
- UUID clonedWorkflowId = UUID.fromString(catalogJson
- .path("workflows").get(0).path("id").asText());
- mockMvc.perform(delete("/api/v1/workspaces/{workspaceId}/catalog/workflows/{workflowId}", cloneId, clonedWorkflowId))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.workflows.length()").value(3));
- assertThat(countForOrganization("workflows", cloneId)).isEqualTo(3);
- assertThat(countForOrganization("workflows", HARBORLINE_ID)).isEqualTo(4);
+ }
- mockMvc.perform(post("/api/v1/workspaces")
- .contentType(MediaType.APPLICATION_JSON)
- .content(workspaceRequest("Duplicate", "harborline-sandbox")))
- .andExpect(status().isConflict())
- .andExpect(jsonPath("$.code").value("WORKSPACE_CONFLICT"));
+ @Test
+ void hidesPublishedAndUnknownOrganizationsFromPublicCodeLookup() throws Exception {
+ String harborlinePublicCode = jdbcClient.sql("SELECT public_code FROM organizations WHERE id = :id")
+ .param("id", HARBORLINE_ID)
+ .query(String.class)
+ .single();
+
+ mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", harborlinePublicCode))
+ .andExpect(status().isNotFound());
+ mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", "BAD-CODE"))
+ .andExpect(status().isNotFound());
+ mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", "NMS-AAAAAA"))
+ .andExpect(status().isNotFound());
+ }
- mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", blankId)
+ @Test
+ void removesWorkspaceListingAndCloningEndpoints() throws Exception {
+ mockMvc.perform(get("/api/v1/workspaces"))
+ .andExpect(status().isMethodNotAllowed());
+ mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", HARBORLINE_ID)
.contentType(MediaType.APPLICATION_JSON)
- .content(workspaceRequest("Invalid Clone", null)))
- .andExpect(status().isUnprocessableEntity())
- .andExpect(jsonPath("$.code").value("INVALID_WORKSPACE"));
+ .content(workspaceRequest("Removed Clone", null)))
+ .andExpect(status().isNotFound());
}
@Test
@@ -398,7 +364,7 @@ void buildsTeamsMembersAndRolesInsideADraftOnly() throws Exception {
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Illegal\",\"department\":\"Test\"}"))
.andExpect(status().isConflict())
- .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("immutable")));
+ .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("read-only")));
mockMvc.perform(delete("/api/v1/workspaces/{workspaceId}/catalog/workflows/{workflowId}", workspaceId, workflowId))
.andExpect(status().isOk())
@@ -446,24 +412,6 @@ private com.fasterxml.jackson.databind.JsonNode findById(
throw new IllegalArgumentException(id + " was not found in " + collection);
}
- private void assertPreview(
- UUID workspaceId,
- UUID memberId,
- UUID roleId,
- String severity,
- int blocked,
- int degraded) throws Exception {
- mockMvc.perform(post("/api/v1/workspaces/{workspaceId}/impact-previews", workspaceId)
- .contentType(MediaType.APPLICATION_JSON)
- .content("""
- {"memberId":"%s","roleId":"%s"}
- """.formatted(memberId, roleId)))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.overallSeverity").value(severity))
- .andExpect(jsonPath("$.executiveSummary.workflowsBlocked").value(blocked))
- .andExpect(jsonPath("$.executiveSummary.workflowsDegraded").value(degraded));
- }
-
private String workspaceState(UUID id) {
return jdbcClient.sql("""
SELECT workspace_status || '|' || current_version
@@ -472,26 +420,6 @@ private String workspaceState(UUID id) {
""").param("id", id).query(String.class).single();
}
- private int countOrganizationVersions(UUID id) {
- return jdbcClient.sql("SELECT COUNT(*) FROM organization_versions WHERE organization_id = :id")
- .param("id", id).query(Integer.class).single();
- }
-
- private int countSharedEmployeeIds(UUID sourceId, UUID cloneId) {
- return jdbcClient.sql("""
- SELECT COUNT(*)
- FROM employees source
- JOIN employees clone ON clone.id = source.id
- WHERE source.organization_id = :sourceId AND clone.organization_id = :cloneId
- """).param("sourceId", sourceId).param("cloneId", cloneId).query(Integer.class).single();
- }
-
- private int countNamedEmployees(UUID organizationId, String name) {
- return jdbcClient.sql("""
- SELECT COUNT(*) FROM employees WHERE organization_id = :organizationId AND name = :name
- """).param("organizationId", organizationId).param("name", name).query(Integer.class).single();
- }
-
private int countForOrganization(String table, UUID organizationId) {
var allowed = java.util.Set.of("applications", "permissions", "capabilities", "workflows");
if (!allowed.contains(table)) throw new IllegalArgumentException("Unexpected table: " + table);
diff --git a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
new file mode 100644
index 0000000..0deae69
--- /dev/null
+++ b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
@@ -0,0 +1,29 @@
+package com.roleimpact.workspace.application;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.security.SecureRandom;
+
+import org.junit.jupiter.api.Test;
+
+class WorkspaceCodeTest {
+
+ @Test
+ void normalizesTypedCodesWithOrWithoutTheHyphen() {
+ assertThat(WorkspaceCode.normalize(" nsm-7k4p9d ")).isEqualTo("NSM-7K4P9D");
+ assertThat(WorkspaceCode.normalize("nsm7k4p9d")).isEqualTo("NSM-7K4P9D");
+ }
+
+ @Test
+ void rejectsMalformedOrAmbiguousCodes() {
+ assertThat(WorkspaceCode.normalize("NSM-7K4P0D")).isNull();
+ assertThat(WorkspaceCode.normalize("not-a-code")).isNull();
+ }
+
+ @Test
+ void generatesANamePrefixAndAllowedRandomSuffix() {
+ var code = new WorkspaceCode(new SecureRandom()).generate("Northstar Medical Supplies");
+
+ assertThat(code).matches("NMS-[A-HJ-NP-Z2-9]{6}");
+ }
+}
diff --git a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java
new file mode 100644
index 0000000..d708db0
--- /dev/null
+++ b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java
@@ -0,0 +1,59 @@
+package com.roleimpact.workspace.application;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.time.Instant;
+import java.util.Optional;
+import java.util.UUID;
+
+import com.roleimpact.workspace.api.WorkspaceRequest;
+import com.roleimpact.workspace.api.WorkspaceResource;
+import com.roleimpact.workspace.persistence.WorkspaceRepository;
+
+import org.junit.jupiter.api.Test;
+class WorkspaceServiceTest {
+
+ @Test
+ void retriesAPublicCodeCollisionWithoutChangingTheSlug() {
+ var repository = mock(WorkspaceRepository.class);
+ var workspaceCode = mock(WorkspaceCode.class);
+ when(repository.existsBySlug("northstar-medical-supplies")).thenReturn(false);
+ when(workspaceCode.generate("Northstar Medical Supplies"))
+ .thenReturn("NMS-AAAAAA", "NMS-AAAAAB");
+ when(repository.insertDraft(
+ any(UUID.class),
+ eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"),
+ eq("NMS-AAAAAA"))).thenReturn(false);
+ when(repository.insertDraft(
+ any(UUID.class),
+ eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"),
+ eq("NMS-AAAAAB"))).thenReturn(true);
+ when(repository.findById(any(UUID.class))).thenAnswer(invocation -> Optional.of(
+ workspace(invocation.getArgument(0), "NMS-AAAAAB")));
+
+ var service = new WorkspaceService(repository, workspaceCode);
+ var created = service.createBlank(new WorkspaceRequest("Northstar Medical Supplies", null));
+
+ assertThat(created.publicCode()).isEqualTo("NMS-AAAAAB");
+ }
+
+ private WorkspaceResource workspace(UUID id, String publicCode) {
+ var timestamp = Instant.parse("2026-08-21T12:00:00Z");
+ return new WorkspaceResource(
+ id,
+ "northstar-medical-supplies",
+ "Northstar Medical Supplies",
+ "DRAFT",
+ 0,
+ publicCode,
+ timestamp,
+ timestamp,
+ new WorkspaceResource.WorkspaceCounts(0, 0, 0, 0, 0, 0));
+ }
+}
diff --git a/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md b/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md
index 66c38b8..0b2696c 100644
--- a/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md
+++ b/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md
@@ -288,11 +288,10 @@ class WorkspaceServiceTest {
when(repository.existsBySlug("northstar-medical-supplies")).thenReturn(false);
when(workspaceCode.generate("Northstar Medical Supplies"))
.thenReturn("NMS-AAAAAA", "NMS-AAAAAB");
- doThrow(new DataIntegrityViolationException("public code collision"))
- .doNothing()
- .when(repository).insertDraft(any(UUID.class), eq("northstar-medical-supplies"),
- eq("Northstar Medical Supplies"), anyString());
- when(repository.existsByPublicCode("NMS-AAAAAA")).thenReturn(true);
+ when(repository.insertDraft(any(UUID.class), eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"), eq("NMS-AAAAAA"))).thenReturn(false);
+ when(repository.insertDraft(any(UUID.class), eq("northstar-medical-supplies"),
+ eq("Northstar Medical Supplies"), eq("NMS-AAAAAB"))).thenReturn(true);
when(repository.findById(any(UUID.class))).thenAnswer(invocation -> Optional.of(
workspace(invocation.getArgument(0), "NMS-AAAAAB")));
@@ -396,26 +395,20 @@ public Optional findDraftByPublicCode(String publicCode) {
.optional();
}
-public boolean existsByPublicCode(String publicCode) {
- return jdbcClient.sql("SELECT EXISTS (SELECT 1 FROM organizations WHERE UPPER(public_code) = :publicCode)")
- .param("publicCode", publicCode)
- .query(Boolean.class)
- .single();
-}
-
-public void insertDraft(UUID id, String slug, String name, String publicCode) {
- jdbcClient.sql("""
+public boolean insertDraft(UUID id, String slug, String name, String publicCode) {
+ return jdbcClient.sql("""
INSERT INTO organizations (
id, slug, name, current_version, workspace_status, public_code, created_at, updated_at
) VALUES (
:id, :slug, :name, 0, 'DRAFT', :publicCode, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
+ ON CONFLICT DO NOTHING
""")
.param("id", id)
.param("slug", slug)
.param("name", name)
.param("publicCode", publicCode)
- .update();
+ .update() == 1;
}
```
@@ -433,17 +426,11 @@ public WorkspaceResource createBlank(WorkspaceRequest request) {
for (int attempt = 0; attempt < 5; attempt++) {
UUID workspaceId = UUID.randomUUID();
String publicCode = workspaceCode.generate(name);
- try {
- workspaceRepository.insertDraft(workspaceId, slug, name, publicCode);
+ if (workspaceRepository.insertDraft(workspaceId, slug, name, publicCode)) {
return get(workspaceId);
}
- catch (DataIntegrityViolationException exception) {
- if (workspaceRepository.existsBySlug(slug)) {
- throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
- }
- if (!workspaceRepository.existsByPublicCode(publicCode)) {
- throw exception;
- }
+ if (workspaceRepository.existsBySlug(slug)) {
+ throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists");
}
}
throw new WorkspaceConflictException("A unique organization ID could not be generated; try again");
From b7b7b9fa8f3435d46d3be7989087dfbee94fd441 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Fri, 21 Aug 2026 22:23:25 -0400
Subject: [PATCH 06/10] feat: add refresh-safe organization links
---
README.md | 27 +++
frontend/src/App.css | 116 +++++++++-
frontend/src/App.test.tsx | 90 ++++----
frontend/src/App.tsx | 41 ++--
frontend/src/WorkspaceRouting.test.tsx | 189 ++++++++++++++++
frontend/src/api/workspaces.ts | 28 +--
.../components/workspaces/DraftWorkspace.tsx | 59 ++++-
.../workspaces/OrganizationRoute.tsx | 86 ++++++++
.../workspaces/WorkspaceWelcome.tsx | 208 ++++++++++--------
.../workspaces/editor/DraftEditor.tsx | 23 +-
10 files changed, 666 insertions(+), 201 deletions(-)
create mode 100644 frontend/src/WorkspaceRouting.test.tsx
create mode 100644 frontend/src/components/workspaces/OrganizationRoute.tsx
diff --git a/README.md b/README.md
index d0db98e..b56f961 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,8 @@ and mitigation vertical slice:
- Ranked, evidence-backed replacement recommendations
- Persisted parent/child mitigation simulations with idempotent replay
- Stateless impact and mitigation previews for user-built draft organizations
+- Stable public organization IDs and refresh-safe links for reopening editable
+ organization maps, inventories, and impact screens
- Draft recommendations that verify eligibility and workflow recovery after the
proposed role assignment, even when the candidate does not already have the
access that the new role would grant
@@ -75,6 +77,25 @@ amber impact paths, review Bob Chen's recommendation, and test the mitigation to
see the restored green relationship graph alongside the Low residual access
impact.
+Editable organizations can be reopened from the homepage using their public ID
+with or without the displayed hyphen. Anyone with an organization ID or link can
+edit that organization in this portfolio MVP, so do not enter confidential or
+personal data.
+
+## Frontend routes
+
+- `/example` opens the read-only Harborline example.
+- `/organizations/{publicCode}/map` opens an editable organization map.
+- `/organizations/{publicCode}/inventory` opens its detailed inventory.
+- `/organizations/{publicCode}/impact` opens a fresh impact-testing screen.
+
+Refreshing any of these routes keeps the same organization and screen. Impact
+and mitigation results are intentionally temporary, so refreshing the impact
+route clears the previous result while preserving the selected screen. Vite's
+development and preview servers provide the required history fallback locally.
+Production hosting must rewrite non-asset, non-API routes to
+`frontend/index.html` so pasted organization links load correctly.
+
## API endpoints
- `GET /api/v1/dashboard` loads the default Harborline Commerce dashboard.
@@ -84,6 +105,12 @@ impact.
- `GET /api/v1/simulations/{simulationId}` retrieves an immutable saved result.
- `POST /api/v1/simulations/{simulationId}/branches` tests and saves a
recommendation as a child mitigation simulation.
+- `POST /api/v1/workspaces` creates a blank editable organization and returns
+ its stable public code.
+- `GET /api/v1/workspaces/by-code/{publicCode}` resolves an editable
+ organization. The Harborline example is intentionally excluded.
+- `GET /api/v1/workspaces/{workspaceId}/catalog` loads the editable catalog
+ after the public code has been resolved.
- `POST /api/v1/workspaces/{workspaceId}/impact-previews` tests a role removal
against the current draft without changing it.
- `POST /api/v1/workspaces/{workspaceId}/impact-previews/mitigations` verifies a
diff --git a/frontend/src/App.css b/frontend/src/App.css
index 4e6a8f2..10dae4d 100644
--- a/frontend/src/App.css
+++ b/frontend/src/App.css
@@ -146,7 +146,7 @@
.workspace-mini-stats {
display: grid;
- grid-template-columns: repeat(4, 1fr);
+ grid-template-columns: repeat(3, 1fr);
margin-bottom: 1rem;
padding: 0.9rem 0;
border-top: 1px solid #2c3040;
@@ -1909,6 +1909,98 @@
backdrop-filter: blur(16px);
}
+.draft-topbar {
+ position: sticky;
+ z-index: 20;
+ top: 0;
+}
+
+.organization-recovery {
+ display: flex;
+ align-items: center;
+ gap: 0.65rem;
+}
+
+.organization-recovery code {
+ padding: 0.42rem 0.65rem;
+ border: 1px solid #3b4051;
+ border-radius: 0.55rem;
+ background: #11131c;
+ color: #d8ccff;
+ font-weight: 750;
+ letter-spacing: 0.08em;
+}
+
+.organization-recovery button,
+.organization-onboarding-actions button,
+.recovery-actions button {
+ padding: 0.58rem 0.8rem;
+ border: 1px solid #47405f;
+ border-radius: 0.6rem;
+ background: #211b35;
+ color: #eee9ff;
+ font: inherit;
+ font-size: 0.78rem;
+ font-weight: 700;
+ cursor: pointer;
+}
+
+.copy-feedback {
+ position: sticky;
+ z-index: 10;
+ top: 5.2rem;
+ width: fit-content;
+ margin: -2.4rem 0 1.25rem auto;
+ padding: 0.65rem 0.85rem;
+ border: 1px solid #3c5f51;
+ border-radius: 0.65rem;
+ background: #14251e;
+ color: #9df0c8;
+ box-shadow: 0 14px 34px rgb(0 0 0 / 28%);
+ font-size: 0.8rem;
+}
+
+.organization-onboarding {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 2rem;
+ margin-bottom: 2.5rem;
+ padding: 1.25rem 1.4rem;
+ border: 1px solid #6551ad;
+ border-radius: 1rem;
+ background: linear-gradient(135deg, rgb(79 59 147 / 26%), rgb(20 22 32 / 96%));
+}
+
+.organization-onboarding h2,
+.organization-onboarding p {
+ margin: 0;
+}
+
+.organization-onboarding p:last-child {
+ max-width: 50rem;
+ margin-top: 0.55rem;
+ color: #aeb5c8;
+ line-height: 1.55;
+}
+
+.organization-onboarding-actions,
+.recovery-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.65rem;
+}
+
+.organization-recovery-screen {
+ max-width: 42rem;
+ margin: 0 auto;
+ text-align: center;
+}
+
+.organization-recovery-screen .recovery-actions {
+ justify-content: center;
+}
+
.brand {
display: inline-flex;
align-items: center;
@@ -3147,6 +3239,28 @@ a:focus-visible {
padding: 0 1rem;
}
+ .draft-topbar {
+ align-items: flex-start;
+ flex-direction: column;
+ gap: 0.75rem;
+ padding-top: 0.8rem;
+ padding-bottom: 0.8rem;
+ }
+
+ .organization-recovery {
+ width: 100%;
+ flex-wrap: wrap;
+ }
+
+ .organization-recovery .draft-status {
+ width: 100%;
+ }
+
+ .organization-onboarding {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+
.baseline-chip {
max-width: 11rem;
overflow: hidden;
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx
index 8181b32..9af291c 100644
--- a/frontend/src/App.test.tsx
+++ b/frontend/src/App.test.tsx
@@ -1,6 +1,7 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { MemoryRouter } from 'react-router-dom'
import { afterEach, describe, expect, it, vi } from 'vitest'
import App from './App'
import type { DraftCatalog } from './api/draftCatalog'
@@ -13,18 +14,24 @@ afterEach(() => {
localStorage.clear()
})
-function renderApp() {
+function renderApp(initialEntries = ['/']) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return render(
-
-
- ,
+
+
+
+
+ ,
)
}
+const editableMapRoute = '/organizations/HCS-7K4P9D/map'
+const editableInventoryRoute = '/organizations/HCS-7K4P9D/inventory'
+const editableImpactRoute = '/organizations/HCS-7K4P9D/impact'
+
describe('App', () => {
it('renders the seeded organization dashboard', async () => {
const user = userEvent.setup()
@@ -129,28 +136,26 @@ describe('App', () => {
expect(screen.getByLabelText('Graph state legend')).toHaveTextContent('Restored')
})
- it('clones the example into an isolated editable draft', async () => {
+ it('opens an editable organization from its stable route', async () => {
const user = userEvent.setup()
- vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
- if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
+ if (url.endsWith('/impact-previews/continuity')) return jsonResponse([])
return new Response(null, { status: 404 })
})
- renderApp()
-
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
+ renderApp([editableMapRoute])
expect(await screen.findByRole('heading', { name: 'Harborline Sandbox' })).toBeInTheDocument()
- expect(screen.getByText('Draft · not yet published')).toBeInTheDocument()
- expect(screen.getByText(/fresh identity/)).toBeInTheDocument()
- expect(screen.getByLabelText('Draft catalog summary')).toHaveTextContent('1members')
+ expect(screen.getByText('Editable organization')).toBeInTheDocument()
+ expect(screen.getByText(/return later using the organization ID or link/)).toBeInTheDocument()
+ expect(await screen.findByLabelText('Draft catalog summary')).toHaveTextContent('1members')
expect(await screen.findByRole('heading', { name: 'Map how your organization works' })).toBeInTheDocument()
expect(await screen.findByLabelText('Organization relationship canvas')).toBeInTheDocument()
expect(screen.getByLabelText('Organization inventory')).toHaveTextContent('Finance Approver')
- expect(screen.getByRole('button', { name: 'Show full map' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Fit graph' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Detailed inventory' }))
expect(screen.getByRole('button', { name: /Teams/ })).toHaveAttribute('aria-current', 'step')
})
@@ -159,9 +164,8 @@ describe('App', () => {
const user = userEvent.setup()
const requests = mockEditableClone(clonedCatalogFixture)
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
- await user.click(await screen.findByRole('button', { name: 'Detailed inventory' }))
+ renderApp([editableInventoryRoute])
+ await screen.findByRole('button', { name: 'Detailed inventory' })
await user.click(screen.getByRole('button', { name: /Roles/ }))
await user.type(screen.getByLabelText('Role name'), 'Release Manager')
await user.type(screen.getByLabelText('Description'), 'Approves production releases')
@@ -178,9 +182,8 @@ describe('App', () => {
const user = userEvent.setup()
const requests = mockEditableClone(clonedCatalogFixture)
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
- await user.click(await screen.findByRole('button', { name: 'Detailed inventory' }))
+ renderApp([editableInventoryRoute])
+ await screen.findByRole('button', { name: 'Detailed inventory' })
await user.click(screen.getByRole('button', { name: /Roles/ }))
const financeRole = screen.getByText('Finance Approver', { selector: 'strong' }).closest('article')
expect(financeRole).not.toBeNull()
@@ -198,8 +201,8 @@ describe('App', () => {
const user = userEvent.setup()
const requests = mockEditableClone(clonedCatalogFixture)
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
+ renderApp([editableMapRoute])
+ await screen.findByRole('button', { name: 'Add Role' })
await user.click(await screen.findByRole('button', { name: 'Add Role' }))
await user.type(screen.getByLabelText('Role name'), 'Release Manager')
await user.click(screen.getByRole('checkbox', { name: 'Priya Sharma' }))
@@ -215,8 +218,8 @@ describe('App', () => {
const user = userEvent.setup()
const requests = mockEditableClone(clonedCatalogFixture)
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
+ renderApp([editableMapRoute])
+ await screen.findByRole('button', { name: 'Add Role' })
await user.click(await screen.findByRole('button', { name: 'Add Role' }))
await user.type(screen.getByLabelText('Role name'), 'Finance Approver')
expect(screen.getByRole('checkbox', { name: 'Priya Sharma' })).toBeChecked()
@@ -232,8 +235,8 @@ describe('App', () => {
const user = userEvent.setup()
mockEditableClone(clonedCatalogFixture)
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
+ renderApp([editableMapRoute])
+ await screen.findByRole('button', { name: 'Add Role' })
await user.click(await screen.findByRole('button', { name: 'Add Role' }))
await user.type(screen.getByLabelText('Role name'), 'Finance Approver')
@@ -241,20 +244,16 @@ describe('App', () => {
})
it('opens impact testing after a deferred continuity projection resolves', async () => {
- const user = userEvent.setup()
const projection = deferred()
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
- if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity') && !init?.method) return projection.promise
return new Response(null, { status: 404 })
})
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
- await user.click(await screen.findByRole('button', { name: 'Test impact' }))
+ renderApp([editableImpactRoute])
expect(await screen.findByRole('heading', { name: 'Loading continuity analysis' })).toBeInTheDocument()
projection.resolve(jsonResponse(clonedContinuityFixture))
@@ -268,8 +267,7 @@ describe('App', () => {
let continuityAttempts = 0
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
- if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity') && !init?.method) {
continuityAttempts += 1
@@ -280,9 +278,7 @@ describe('App', () => {
return new Response(null, { status: 404 })
})
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
- await user.click(await screen.findByRole('button', { name: 'Test impact' }))
+ renderApp([editableImpactRoute])
expect(await screen.findByRole('heading', { name: 'Continuity analysis is unavailable' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Retry continuity analysis' }))
@@ -292,7 +288,6 @@ describe('App', () => {
})
it('renders a degraded engine verdict with the warning continuity treatment', async () => {
- const user = userEvent.setup()
const degradedContinuity = clonedContinuityFixture.map((risk) => ({
...risk,
members: risk.members.map((member) => ({
@@ -303,16 +298,13 @@ describe('App', () => {
}))
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
- if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity') && !init?.method) return jsonResponse(degradedContinuity)
return new Response(null, { status: 404 })
})
- renderApp()
- await user.click(await screen.findByRole('button', { name: 'Clone and customize' }))
- await user.click(await screen.findByRole('button', { name: 'Test impact' }))
+ renderApp([editableImpactRoute])
const heading = await screen.findByText('This workflow would lose resilience')
const signal = heading.closest('.continuity-signal')
@@ -330,6 +322,7 @@ describe('App', () => {
const url = input.toString()
if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
if (url.endsWith('/api/v1/workspaces') && init?.method === 'POST') return jsonResponse(blankWorkspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/ATS-7K4P9E')) return jsonResponse(blankWorkspaceFixture)
if (url.endsWith('/catalog') && !init?.method) return jsonResponse(catalog)
if (url.endsWith('/impact-previews/continuity') && !init?.method) {
continuityRequests += 1
@@ -595,8 +588,7 @@ function mockEditableClone(initialCatalog: DraftCatalog) {
const memberRoleRequests: string[] = []
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
- if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog') && !init?.method) return jsonResponse(catalog)
if (url.endsWith('/impact-previews/continuity') && !init?.method) return jsonResponse([])
if (url.endsWith('/catalog/roles') && init?.method === 'POST') {
@@ -641,7 +633,7 @@ const workspaceFixture = [
name: 'Harborline Commerce',
status: 'PUBLISHED',
currentVersion: 1,
- sourceTemplateOrganizationId: null,
+ publicCode: 'HBR-7K4P9D',
createdAt: '2026-08-12T20:00:00Z',
updatedAt: '2026-08-12T20:00:00Z',
counts: { teams: 5, members: 25, roles: 8, permissions: 23, capabilities: 10, workflows: 4 },
@@ -655,7 +647,7 @@ const clonedWorkspaceFixture = {
name: 'Harborline Sandbox',
status: 'DRAFT',
currentVersion: 0,
- sourceTemplateOrganizationId: workspaceFixture[0].id,
+ publicCode: 'HCS-7K4P9D',
}
const blankWorkspaceFixture = {
@@ -665,7 +657,7 @@ const blankWorkspaceFixture = {
name: 'Atlas Systems',
status: 'DRAFT',
currentVersion: 0,
- sourceTemplateOrganizationId: null,
+ publicCode: 'ATS-7K4P9E',
counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 },
}
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4681d7e..7b47896 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,36 +1,33 @@
-import { lazy, Suspense, useState } from 'react'
+import { lazy, Suspense } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
+import { Navigate, Route, Routes, useNavigate, useParams } from 'react-router-dom'
import { fetchDashboard } from './api/dashboard'
import { runMitigationBranch, runPrimarySimulation } from './api/simulations'
-import type { Workspace } from './api/workspaces'
import WorkspaceWelcome from './components/workspaces/WorkspaceWelcome'
-import DraftWorkspace from './components/workspaces/DraftWorkspace'
+import OrganizationRoute from './components/workspaces/OrganizationRoute'
import './App.css'
const ImpactGraph = lazy(() => import('./components/ImpactGraph'))
-type AppView = { page: 'home' } | { page: 'example' } | { page: 'draft'; workspace: Workspace }
-
export default function App() {
- const [view, setView] = useState({ page: 'home' })
-
- if (view.page === 'home') {
- return (
- setView({ page: 'example' })}
- onOpenDraft={(workspace) => setView({ page: 'draft', workspace })}
- />
- )
- }
-
- if (view.page === 'draft') {
- return setView({ page: 'home' })} />
- }
+ return (
+
+ } />
+ } />
+ } />
+ } />
+ } />
+
+ )
+}
- return setView({ page: 'home' })} />
+function OrganizationIndexRedirect() {
+ const { publicCode = '' } = useParams()
+ return
}
-function HarborlineDashboard({ onBack }: { onBack: () => void }) {
+function HarborlineDashboard() {
+ const navigate = useNavigate()
const dashboardQuery = useQuery({
queryKey: ['dashboard', 'harborline-commerce'],
queryFn: ({ signal }) => fetchDashboard(signal),
@@ -79,7 +76,7 @@ function HarborlineDashboard({ onBack }: { onBack: () => void }) {
return (
-
+ navigate('/')} aria-label="Back to workspaces">
R
RoleImpact
diff --git a/frontend/src/WorkspaceRouting.test.tsx b/frontend/src/WorkspaceRouting.test.tsx
new file mode 100644
index 0000000..4e45d0a
--- /dev/null
+++ b/frontend/src/WorkspaceRouting.test.tsx
@@ -0,0 +1,189 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import App from './App'
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ Reflect.deleteProperty(navigator, 'clipboard')
+})
+
+describe('organization routing', () => {
+ it('replaces Harborline cloning with organization ID access', async () => {
+ mockWorkspaceRequests()
+ renderApp(['/'])
+
+ expect(await screen.findByRole('heading', { name: 'Open your organization' })).toBeInTheDocument()
+ expect(screen.getByLabelText('Organization ID')).toBeInTheDocument()
+ expect(screen.queryByText('Clone Harborline')).not.toBeInTheDocument()
+ })
+
+ it('opens an existing organization from a code without its hyphen', async () => {
+ const user = userEvent.setup()
+ mockWorkspaceRequests()
+ renderApp(['/'])
+
+ await user.type(await screen.findByLabelText('Organization ID'), 'nms7k4p9d')
+ await user.click(screen.getByRole('button', { name: 'Open organization' }))
+
+ expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument()
+ expect(screen.getByText('NMS-7K4P9D')).toBeInTheDocument()
+ })
+
+ it('loads the inventory route directly', async () => {
+ mockWorkspaceRequests()
+ renderApp(['/organizations/NMS-7K4P9D/inventory'])
+
+ expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument()
+ expect(await screen.findByRole('button', { name: 'Detailed inventory' })).toHaveAttribute('aria-pressed', 'true')
+ })
+
+ it('rejects a malformed organization ID before making a lookup request', async () => {
+ const user = userEvent.setup()
+ const fetchMock = mockWorkspaceRequests()
+ renderApp(['/'])
+
+ await user.type(await screen.findByLabelText('Organization ID'), 'bad-id')
+ await user.click(screen.getByRole('button', { name: 'Open organization' }))
+
+ expect(screen.getByRole('alert')).toHaveTextContent('Enter an organization ID such as NMS-7K4P9D')
+ expect(fetchMock.mock.calls.some(([input]) => input.toString().includes('/by-code/'))).toBe(false)
+ })
+
+ it('keeps an unknown organization route open and offers recovery actions', async () => {
+ mockWorkspaceRequests()
+ renderApp(['/organizations/ABC-234567/map'])
+
+ expect(await screen.findByRole('heading', { name: 'Organization not found' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Try another organization ID' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Return home' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Create a new organization' })).toBeInTheDocument()
+ })
+
+ it('loads the impact route directly without returning to the home page', async () => {
+ mockWorkspaceRequests()
+ renderApp(['/organizations/NMS-7K4P9D/impact'])
+
+ expect(await screen.findByRole('button', { name: 'Test impact' })).toHaveAttribute('aria-pressed', 'true')
+ expect(await screen.findByRole('heading', { name: 'Create one workflow first' })).toBeInTheDocument()
+ })
+
+ it.each([
+ '/organizations/NMS-7K4P9D',
+ '/organizations/NMS-7K4P9D/not-a-view',
+ ])('redirects %s to the organization map', async (entry) => {
+ mockWorkspaceRequests()
+ renderApp([entry])
+
+ expect(await screen.findByRole('button', { name: 'Organization map' })).toHaveAttribute('aria-pressed', 'true')
+ })
+
+ it('loads the read-only example directly', async () => {
+ mockWorkspaceRequests()
+ renderApp(['/example'])
+
+ expect(await screen.findByRole('heading', { name: 'See the blast radius before access changes go live.' })).toBeInTheDocument()
+ })
+
+ it('copies the stable organization ID and canonical map link', async () => {
+ const user = userEvent.setup()
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
+ mockWorkspaceRequests()
+ renderApp(['/organizations/NMS-7K4P9D/inventory'])
+
+ await user.click(await screen.findByRole('button', { name: 'Copy organization ID' }))
+ await user.click(screen.getByRole('button', { name: 'Copy organization link' }))
+
+ expect(writeText).toHaveBeenNthCalledWith(1, 'NMS-7K4P9D')
+ expect(writeText).toHaveBeenNthCalledWith(
+ 2,
+ `${window.location.origin}/organizations/NMS-7K4P9D/map`,
+ )
+ expect(screen.queryByRole('heading', { name: 'Save this organization ID' })).not.toBeInTheDocument()
+ })
+
+ it('shows recovery onboarding immediately after creating an organization', async () => {
+ const user = userEvent.setup()
+ mockWorkspaceRequests()
+ renderApp(['/'])
+
+ await user.type(await screen.findByLabelText('Organization name'), 'Northstar Medical Supplies')
+ await user.click(screen.getByRole('button', { name: 'Start blank' }))
+
+ expect(await screen.findByRole('heading', { name: 'Save this organization ID' })).toBeInTheDocument()
+ expect(screen.getByText(/Anyone with this link or ID can edit this organization/)).toBeInTheDocument()
+ expect(screen.getByText(/Do not enter confidential company or personal information/)).toBeInTheDocument()
+ })
+})
+
+function renderApp(initialEntries: string[]) {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ return render(
+
+
+
+
+ ,
+ )
+}
+
+function mockWorkspaceRequests() {
+ return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ const url = input.toString()
+ if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture)
+ if (url.endsWith('/api/v1/workspaces') && init?.method === 'POST') return jsonResponse(workspaceFixture, 201)
+ if (url.endsWith('/api/v1/workspaces/by-code/NMS-7K4P9D')) return jsonResponse(workspaceFixture)
+ if (url.endsWith('/catalog')) return jsonResponse(catalogFixture)
+ if (url.endsWith('/impact-previews/continuity')) return jsonResponse([])
+ return jsonResponse({ message: 'Organization not found' }, 404)
+ })
+}
+
+function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
+}
+
+const workspaceFixture = {
+ id: '10000000-0000-0000-0000-000000000001',
+ slug: 'northstar-medical-supplies',
+ name: 'Northstar Medical Supplies',
+ status: 'DRAFT',
+ currentVersion: 0,
+ publicCode: 'NMS-7K4P9D',
+ createdAt: '2026-08-21T12:00:00Z',
+ updatedAt: '2026-08-21T12:00:00Z',
+ counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 },
+}
+
+const catalogFixture = {
+ workspaceId: workspaceFixture.id,
+ teams: [],
+ members: [],
+ roles: [],
+ workflows: [],
+}
+
+const dashboardFixture = {
+ organization: {
+ id: '00000000-0000-0000-0000-000000000001',
+ slug: 'harborline-commerce',
+ name: 'Harborline Commerce',
+ baselineVersion: 1,
+ contentHash: 'dbafb569ae3beaa13277897a7700ab32867675e31ee90cad74a9dc544d5c1fb4',
+ },
+ counts: {
+ employees: 25,
+ activeEmployees: 24,
+ teams: 5,
+ roles: 8,
+ applications: 6,
+ permissions: 23,
+ capabilities: 10,
+ workflows: 4,
+ },
+ workflows: [],
+}
diff --git a/frontend/src/api/workspaces.ts b/frontend/src/api/workspaces.ts
index 03b991f..38d8c2b 100644
--- a/frontend/src/api/workspaces.ts
+++ b/frontend/src/api/workspaces.ts
@@ -4,7 +4,7 @@ export type Workspace = {
name: string
status: 'DRAFT' | 'PUBLISHED'
currentVersion: number
- sourceTemplateOrganizationId: string | null
+ publicCode: string
createdAt: string
updatedAt: string
counts: {
@@ -24,27 +24,27 @@ type WorkspaceInput = {
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? ''
-export async function fetchWorkspaces(signal?: AbortSignal): Promise {
- const response = await fetch(`${apiBaseUrl}/api/v1/workspaces`, { signal })
- return readResponse(response, 'Workspace list could not be loaded')
+export function normalizeWorkspaceCode(rawCode: string): string | null {
+ const candidate = rawCode.trim().toUpperCase()
+ if (/^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$/.test(candidate)) return candidate
+ if (!/^[A-HJ-NP-Z2-9]{9}$/.test(candidate)) return null
+ return `${candidate.slice(0, 3)}-${candidate.slice(3)}`
}
-export async function createWorkspace(input: WorkspaceInput): Promise {
- const response = await fetch(`${apiBaseUrl}/api/v1/workspaces`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(input),
- })
- return readResponse(response, 'Workspace could not be created')
+export async function fetchWorkspaceByCode(rawCode: string, signal?: AbortSignal): Promise {
+ const code = normalizeWorkspaceCode(rawCode)
+ if (!code) throw new Error('Enter an organization ID such as NMS-7K4P9D')
+ const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/by-code/${code}`, { signal })
+ return readResponse(response, 'Organization not found')
}
-export async function cloneWorkspace(sourceWorkspaceId: string, input: WorkspaceInput): Promise {
- const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/${sourceWorkspaceId}/clones`, {
+export async function createWorkspace(input: WorkspaceInput): Promise {
+ const response = await fetch(`${apiBaseUrl}/api/v1/workspaces`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
})
- return readResponse(response, 'Workspace could not be cloned')
+ return readResponse(response, 'Organization could not be created')
}
async function readResponse(response: Response, fallbackMessage: string): Promise {
diff --git a/frontend/src/components/workspaces/DraftWorkspace.tsx b/frontend/src/components/workspaces/DraftWorkspace.tsx
index 6f3d0af..cf4ceda 100644
--- a/frontend/src/components/workspaces/DraftWorkspace.tsx
+++ b/frontend/src/components/workspaces/DraftWorkspace.tsx
@@ -1,32 +1,73 @@
+import { useState } from 'react'
+import { useNavigate } from 'react-router-dom'
import type { Workspace } from '../../api/workspaces'
-import DraftEditor from './editor/DraftEditor'
+import DraftEditor, { type DraftEditorView } from './editor/DraftEditor'
type DraftWorkspaceProps = {
workspace: Workspace
- onBack: () => void
+ view: DraftEditorView
+ newlyCreated?: boolean
+ onViewChange: (view: DraftEditorView) => void
}
-export default function DraftWorkspace({ workspace, onBack }: DraftWorkspaceProps) {
+export default function DraftWorkspace({ workspace, view, newlyCreated = false, onViewChange }: DraftWorkspaceProps) {
+ const navigate = useNavigate()
+ const [showOnboarding, setShowOnboarding] = useState(newlyCreated)
+ const [copyMessage, setCopyMessage] = useState(null)
const isEmpty = workspace.counts.members === 0
+
+ async function copyValue(value: string, message: string) {
+ try {
+ await navigator.clipboard.writeText(value)
+ setCopyMessage(message)
+ } catch {
+ setCopyMessage('Copy failed. Select the organization ID and copy it manually.')
+ }
+ }
+
+ const organizationLink = `${window.location.origin}/organizations/${workspace.publicCode}/map`
+
return (
-
-
+
+ navigate('/')} aria-label="Back to workspaces">
R
RoleImpact
- Draft · not yet published
+
+ Editable organization
+ {workspace.publicCode}
+ void copyValue(workspace.publicCode, 'Organization ID copied.')}>Copy organization ID
+ void copyValue(organizationLink, 'Organization link copied.')}>Copy organization link
+
+ {copyMessage ? {copyMessage}
: null}
+ {showOnboarding ? (
+
+
+
Keep access to your work
+
Save this organization ID
+
+ Bookmark this page or copy the organization ID. Anyone with this link or ID can edit this
+ organization. Do not enter confidential company or personal information.
+
+
+
+ void copyValue(organizationLink, 'Organization link copied.')}>Copy organization link
+ setShowOnboarding(false)}>Got it
+
+
+ ) : null}
Organization builder
{workspace.name}
{isEmpty
? 'Your organization is ready. Add its first team and build outward from there.'
- : 'Your Harborline copy is ready. Every record has a fresh identity, so changes here cannot affect the example.'}
+ : 'Edit the model, test access changes, and return later using the organization ID or link.'}
-
- ← Back to workspace choices
+
+ navigate('/')}>← Back to workspace choices
)
diff --git a/frontend/src/components/workspaces/OrganizationRoute.tsx b/frontend/src/components/workspaces/OrganizationRoute.tsx
new file mode 100644
index 0000000..57fedf9
--- /dev/null
+++ b/frontend/src/components/workspaces/OrganizationRoute.tsx
@@ -0,0 +1,86 @@
+import { useEffect } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { Navigate, useLocation, useNavigate, useParams } from 'react-router-dom'
+import { fetchWorkspaceByCode, normalizeWorkspaceCode } from '../../api/workspaces'
+import DraftWorkspace from './DraftWorkspace'
+import type { DraftEditorView } from './editor/DraftEditor'
+
+const validViews: DraftEditorView[] = ['map', 'impact', 'inventory']
+
+export default function OrganizationRoute() {
+ const { publicCode = '', view = '' } = useParams()
+ const navigate = useNavigate()
+ const location = useLocation()
+ const routeState = location.state as { newlyCreated?: boolean } | null
+ const normalizedCode = normalizeWorkspaceCode(publicCode)
+ const validView = validViews.includes(view as DraftEditorView) ? view as DraftEditorView : null
+ const workspaceQuery = useQuery({
+ queryKey: ['workspace', normalizedCode],
+ queryFn: ({ signal }) => fetchWorkspaceByCode(normalizedCode!, signal),
+ enabled: Boolean(normalizedCode),
+ retry: false,
+ })
+
+ useEffect(() => {
+ if (routeState?.newlyCreated) {
+ navigate(location.pathname, { replace: true, state: null })
+ }
+ }, [location.pathname, navigate, routeState?.newlyCreated])
+
+ if (normalizedCode && !validView) {
+ return
+ }
+
+ if (!normalizedCode) {
+ return
+ }
+
+ if (workspaceQuery.isPending) {
+ return (
+
+
+ Opening your organization…
+
+ )
+ }
+
+ if (workspaceQuery.isError) {
+ return (
+ void workspaceQuery.refetch()}
+ />
+ )
+ }
+
+ return (
+ navigate(`/organizations/${workspaceQuery.data.publicCode}/${nextView}`)}
+ />
+ )
+}
+
+function OrganizationRecovery({ title, detail, onRetry }: {
+ title: string
+ detail?: string
+ onRetry?: () => void
+}) {
+ const navigate = useNavigate()
+ return (
+
+ Organization access
+ {title}
+ {detail ?? 'Check the organization ID and try again.'}
+
+ {onRetry ? Retry : null}
+ navigate('/')}>Try another organization ID
+ navigate('/')}>Return home
+ navigate('/')}>Create a new organization
+
+
+ )
+}
diff --git a/frontend/src/components/workspaces/WorkspaceWelcome.tsx b/frontend/src/components/workspaces/WorkspaceWelcome.tsx
index 8980f51..be8ce79 100644
--- a/frontend/src/components/workspaces/WorkspaceWelcome.tsx
+++ b/frontend/src/components/workspaces/WorkspaceWelcome.tsx
@@ -1,50 +1,57 @@
import { useState, type FormEvent } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { cloneWorkspace, createWorkspace, fetchWorkspaces, type Workspace } from '../../api/workspaces'
+import { useNavigate } from 'react-router-dom'
+import { fetchDashboard } from '../../api/dashboard'
+import {
+ createWorkspace,
+ fetchWorkspaceByCode,
+ normalizeWorkspaceCode,
+} from '../../api/workspaces'
-type WorkspaceWelcomeProps = {
- onExploreTemplate: () => void
- onOpenDraft: (workspace: Workspace) => void
-}
-
-export default function WorkspaceWelcome({ onExploreTemplate, onOpenDraft }: WorkspaceWelcomeProps) {
+export default function WorkspaceWelcome() {
+ const navigate = useNavigate()
const queryClient = useQueryClient()
+ const [organizationCode, setOrganizationCode] = useState('')
const [blankName, setBlankName] = useState('')
- const [cloneName, setCloneName] = useState('Harborline Sandbox')
- const workspacesQuery = useQuery({
- queryKey: ['workspaces'],
- queryFn: ({ signal }) => fetchWorkspaces(signal),
+ const [codeError, setCodeError] = useState(null)
+ const dashboardQuery = useQuery({
+ queryKey: ['dashboard', 'harborline-commerce'],
+ queryFn: ({ signal }) => fetchDashboard(signal),
retry: 1,
})
- const harborline = workspacesQuery.data?.find((workspace) => workspace.slug === 'harborline-commerce')
-
- const blankMutation = useMutation({
- mutationFn: createWorkspace,
+ const openMutation = useMutation({
+ mutationFn: (code: string) => fetchWorkspaceByCode(code),
onSuccess: (workspace) => {
- queryClient.setQueryData(['workspaces'], (current = []) => [...current, workspace])
- onOpenDraft(workspace)
+ queryClient.setQueryData(['workspace', workspace.publicCode], workspace)
+ navigate(`/organizations/${workspace.publicCode}/map`)
},
})
- const cloneMutation = useMutation({
- mutationFn: ({ sourceId, name }: { sourceId: string; name: string }) => cloneWorkspace(sourceId, { name }),
+ const blankMutation = useMutation({
+ mutationFn: createWorkspace,
onSuccess: (workspace) => {
- queryClient.setQueryData(['workspaces'], (current = []) => [...current, workspace])
- onOpenDraft(workspace)
+ queryClient.setQueryData(['workspace', workspace.publicCode], workspace)
+ navigate(`/organizations/${workspace.publicCode}/map`, { state: { newlyCreated: true } })
},
})
- function submitBlank(event: FormEvent) {
+ function submitCode(event: FormEvent) {
event.preventDefault()
- if (blankName.trim()) blankMutation.mutate({ name: blankName.trim() })
+ setCodeError(null)
+ const normalizedCode = normalizeWorkspaceCode(organizationCode)
+ if (!normalizedCode) {
+ setCodeError('Enter an organization ID such as NMS-7K4P9D')
+ return
+ }
+ openMutation.mutate(normalizedCode)
}
- function submitClone(event: FormEvent) {
+ function submitBlank(event: FormEvent) {
event.preventDefault()
- if (harborline && cloneName.trim()) {
- cloneMutation.mutate({ sourceId: harborline.id, name: cloneName.trim() })
- }
+ if (blankName.trim()) blankMutation.mutate({ name: blankName.trim() })
}
+ const counts = dashboardQuery.data?.counts
+
return (
@@ -63,81 +70,88 @@ export default function WorkspaceWelcome({ onExploreTemplate, onOpenDraft }: Wor
Model your organization
Build the access graph your business actually runs on.
- Start with a working example or build a clean model of your own people, roles,
- permissions, capabilities, and workflows.
+ Start with a working example, reopen an existing organization, or build a clean model
+ of your own people, roles, responsibilities, and workflows.
- {workspacesQuery.isError ? (
-
- Workspaces could not be loaded.
- workspacesQuery.refetch()}>Retry
-
- ) : (
-
-
- 01
-
-
Learn from the example
-
Explore Harborline
-
See Priya’s role change travel through a complete, realistic business workflow.
-
-
-
Members {harborline?.counts.members ?? '—'}
-
Roles {harborline?.counts.roles ?? '—'}
-
Workflows {harborline?.counts.workflows ?? '—'}
-
-
- Explore the example
-
-
+
+
+ 01
+
+
Learn from the example
+
Explore Harborline
+
See Priya’s role change travel through a complete, realistic business workflow.
+
+
+
Members {counts?.employees ?? '—'}
+
Roles {counts?.roles ?? '—'}
+
Workflows {counts?.workflows ?? '—'}
+
+ navigate('/example')}>
+ Explore the example
+
+ {dashboardQuery.isError ? (
+ Example statistics are temporarily unavailable.
+ ) : null}
+
-
- 02
-
-
Fastest way to customize
-
Clone Harborline
-
Copy the full example into an editable draft, then reshape it into your own organization.
-
-
-
+
+ 02
+
+
Continue where you left off
+
Open your organization
+
Enter the editable organization ID you saved when the workspace was created.
+
+
+
-
- 03
-
-
Start from first principles
-
Create a blank organization
-
Begin with an empty draft and add only the teams and relationships you need.
-
-
-
-
- )}
+
+ 03
+
+
Start from first principles
+
Create a blank organization
+
Begin with an empty draft and add only the teams and relationships you need.
+
+
+
+
)
diff --git a/frontend/src/components/workspaces/editor/DraftEditor.tsx b/frontend/src/components/workspaces/editor/DraftEditor.tsx
index 99d1413..72081ef 100644
--- a/frontend/src/components/workspaces/editor/DraftEditor.tsx
+++ b/frontend/src/components/workspaces/editor/DraftEditor.tsx
@@ -25,9 +25,14 @@ const DraftImpactTesting = lazy(() => import('./DraftImpactTesting'))
type EditorStage = 'teams' | 'members' | 'roles' | 'workflows'
-export default function DraftEditor({ workspaceId, isTemplateClone }: { workspaceId: string; isTemplateClone: boolean }) {
+export type DraftEditorView = 'map' | 'impact' | 'inventory'
+
+export default function DraftEditor({ workspaceId, view, onViewChange }: {
+ workspaceId: string
+ view: DraftEditorView
+ onViewChange: (view: DraftEditorView) => void
+}) {
const [stage, setStage] = useState('teams')
- const [view, setView] = useState<'map' | 'impact' | 'inventory'>('map')
const editorRef = useRef(null)
const catalogQuery = useQuery({
queryKey: ['draft-catalog', workspaceId],
@@ -67,7 +72,7 @@ export default function DraftEditor({ workspaceId, isTemplateClone }: { workspac
function openInventory(nextStage?: EditorStage) {
if (nextStage) setStage(nextStage)
- setView('inventory')
+ onViewChange('inventory')
window.requestAnimationFrame(() => editorRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }))
}
@@ -79,9 +84,9 @@ export default function DraftEditor({ workspaceId, isTemplateClone }: { workspac
{view === 'impact' ? 'Test a change before it happens' : 'Map how your organization works'}
- setView('map')}>Organization map
- setView('impact')}>Test impact
- setView('inventory')}>Detailed inventory
+ onViewChange('map')}>Organization map
+ onViewChange('impact')}>Test impact
+ onViewChange('inventory')}>Detailed inventory
@@ -95,14 +100,14 @@ export default function DraftEditor({ workspaceId, isTemplateClone }: { workspac
!
{singlePointRisks.length} critical coverage gap{singlePointRisks.length === 1 ? '' : 's'} found According to the impact engine, removing {firstBlockedRisk.roleName} from {firstBlockedMember.name} would block {firstBlockedRisk.workflowName}.
- setView('impact')}>Test this risk
+ onViewChange('impact')}>Test this risk
) : null}
{view === 'map' ? (
- Opening the organization map…
}> openInventory()} onOpenWorkflows={() => openInventory('workflows')} onTestImpact={() => setView('impact')} />
+ Opening the organization map…}> openInventory()} onOpenWorkflows={() => openInventory('workflows')} onTestImpact={() => onViewChange('impact')} />
) : view === 'impact' ? (
- Preparing impact testing…}> void continuityQuery.refetch()} onBackToMap={() => setView('map')} />
+ Preparing impact testing…}> void continuityQuery.refetch()} onBackToMap={() => onViewChange('map')} />
) : (
<>
From 50c68af62d4404f837cd75c6e4eeef6dd5c009e3 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Sat, 22 Aug 2026 18:09:36 -0400
Subject: [PATCH 07/10] security(backend): harden deployment configuration
Upgrade the Spring Boot runtime and patched dependency set, keep diagnostics development-only, align organization-scoped employee uniqueness, and add supporting foreign-key indexes. Update the Boot 4 test infrastructure so fresh database migrations remain covered.
---
README.md | 4 +-
backend/pom.xml | 42 ++++++++++++++++---
.../catalog/persistence/EmployeeEntity.java | 14 +++++--
.../src/main/resources/application-dev.yml | 7 ++++
backend/src/main/resources/application.yml | 6 +++
...V8__add_foreign_key_supporting_indexes.sql | 5 +++
.../CatalogMigrationIntegrationTest.java | 26 ++++++++++--
.../workspace/WorkspaceIntegrationTest.java | 6 +--
...yProjectionConcurrencyIntegrationTest.java | 6 +--
9 files changed, 97 insertions(+), 19 deletions(-)
create mode 100644 backend/src/main/resources/application-dev.yml
create mode 100644 backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql
diff --git a/README.md b/README.md
index b56f961..2b78d6a 100644
--- a/README.md
+++ b/README.md
@@ -62,9 +62,11 @@ docker compose up -d
In a second terminal, start the API:
```powershell
-.\backend\mvnw.cmd spring-boot:run
+\.\backend\mvnw.cmd spring-boot:run -Dspring-boot.run.profiles=dev
```
+With the `dev` profile active, Boot UI is available at .
+
In a third terminal, install and start the frontend:
```powershell
diff --git a/backend/pom.xml b/backend/pom.xml
index 4d9024a..b000ee9 100644
--- a/backend/pom.xml
+++ b/backend/pom.xml
@@ -5,7 +5,7 @@
org.springframework.boot
spring-boot-starter-parent
- 3.5.16
+ 4.1.0
com.roleimpact
@@ -28,7 +28,23 @@
21
+ 1.14.1
+ 3.1.5
+ 2.21.5
+ 2.25.5
+ 42.7.12
+
+
+
+ com.fasterxml.jackson
+ jackson-bom
+ ${jackson2-bom.version}
+ pom
+ import
+
+
+
org.springframework.boot
@@ -39,8 +55,8 @@
spring-boot-starter-data-jpa
- org.flywaydb
- flyway-core
+ org.springframework.boot
+ spring-boot-starter-flyway
org.springframework.boot
@@ -50,11 +66,22 @@
org.springframework.boot
spring-boot-starter-web
+
+ org.springframework.boot
+ spring-boot-jackson2
+
org.flywaydb
flyway-database-postgresql
+
+ com.julien-dubois.bootui
+ bootui-spring-boot-starter
+ ${bootui.version}
+ runtime
+
+
org.postgresql
postgresql
@@ -65,6 +92,11 @@
spring-boot-starter-test
test
+
+ org.springframework.boot
+ spring-boot-starter-webmvc-test
+ test
+
org.springframework.boot
spring-boot-testcontainers
@@ -72,12 +104,12 @@
org.testcontainers
- junit-jupiter
+ testcontainers-junit-jupiter
test
org.testcontainers
- postgresql
+ testcontainers-postgresql
test
diff --git a/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java b/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java
index bad1008..c9ff79b 100644
--- a/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java
+++ b/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java
@@ -12,9 +12,17 @@
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
+import jakarta.persistence.UniqueConstraint;
@Entity
-@Table(name = "employees")
+@Table(name = "employees", uniqueConstraints = {
+ @UniqueConstraint(
+ name = "uq_employees_organization_employee_no",
+ columnNames = { "organization_id", "employee_no" }),
+ @UniqueConstraint(
+ name = "uq_employees_organization_email",
+ columnNames = { "organization_id", "email" })
+})
public class EmployeeEntity {
@Id
@@ -26,13 +34,13 @@ public class EmployeeEntity {
@Column(name = "team_id", nullable = false)
private UUID teamId;
- @Column(name = "employee_no", unique = true, length = 40)
+ @Column(name = "employee_no", length = 40)
private String employeeNumber;
@Column(nullable = false, length = 160)
private String name;
- @Column(unique = true, length = 254)
+ @Column(length = 254)
private String email;
@Enumerated(EnumType.STRING)
diff --git a/backend/src/main/resources/application-dev.yml b/backend/src/main/resources/application-dev.yml
new file mode 100644
index 0000000..f6c5884
--- /dev/null
+++ b/backend/src/main/resources/application-dev.yml
@@ -0,0 +1,7 @@
+bootui:
+ enabled: true
+
+management:
+ endpoint:
+ health:
+ show-details: always
diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml
index 67a7a62..77713f6 100644
--- a/backend/src/main/resources/application.yml
+++ b/backend/src/main/resources/application.yml
@@ -12,7 +12,13 @@ spring:
flyway:
enabled: true
+bootui:
+ enabled: false
+
management:
+ endpoint:
+ health:
+ show-details: never
endpoints:
web:
exposure:
diff --git a/backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql b/backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql
new file mode 100644
index 0000000..1877b2e
--- /dev/null
+++ b/backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql
@@ -0,0 +1,5 @@
+CREATE INDEX idx_permissions_resource_application
+ ON permissions(resource_id, application_id);
+
+CREATE INDEX idx_simulations_organization_baseline_version
+ ON simulations(organization_id, baseline_version);
diff --git a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
index 124854c..b8cb73c 100644
--- a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
@@ -22,13 +22,13 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.test.web.servlet.MockMvc;
-import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.postgresql.PostgreSQLContainer;
@SpringBootTest
@Testcontainers
@@ -42,7 +42,7 @@ class CatalogMigrationIntegrationTest {
@Container
@ServiceConnection
- static final PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:17-alpine")
+ static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine")
.withDatabaseName("roleimpact")
.withUsername("roleimpact")
.withPassword("roleimpact");
@@ -115,7 +115,7 @@ SELECT COUNT(*)
.query(Integer.class)
.single();
- assertThat(successfulMigrations).isEqualTo(7);
+ assertThat(successfulMigrations).isEqualTo(8);
var employeeNumberNullable = jdbcClient.sql("""
SELECT is_nullable
FROM information_schema.columns
@@ -124,6 +124,24 @@ SELECT COUNT(*)
assertThat(employeeNumberNullable).isEqualTo("YES");
}
+ @Test
+ void addsCompositeIndexesForForeignKeyLookups() {
+ var indexes = jdbcClient.sql("""
+ SELECT indexname
+ FROM pg_indexes
+ WHERE schemaname = 'public'
+ AND indexname IN (
+ 'idx_permissions_resource_application',
+ 'idx_simulations_organization_baseline_version'
+ )
+ ORDER BY indexname
+ """).query(String.class).list();
+
+ assertThat(indexes).containsExactly(
+ "idx_permissions_resource_application",
+ "idx_simulations_organization_baseline_version");
+ }
+
@Test
void mapsSeededCatalogDataThroughJpa() {
var organization = organizationRepository.findBySlug("harborline-commerce").orElseThrow();
diff --git a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
index f106adb..03f342f 100644
--- a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
@@ -16,15 +16,15 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.test.web.servlet.MockMvc;
-import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.postgresql.PostgreSQLContainer;
@SpringBootTest
@Testcontainers
@@ -35,7 +35,7 @@ class WorkspaceIntegrationTest {
@Container
@ServiceConnection
- static final PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:17-alpine")
+ static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine")
.withDatabaseName("roleimpact")
.withUsername("roleimpact")
.withPassword("roleimpact");
diff --git a/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java
index ceb505d..9b741c7 100644
--- a/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java
@@ -20,15 +20,15 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.MockMvc;
-import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.postgresql.PostgreSQLContainer;
@SpringBootTest
@Testcontainers
@@ -37,7 +37,7 @@ class DraftContinuityProjectionConcurrencyIntegrationTest {
@Container
@ServiceConnection
- static final PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:17-alpine")
+ static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine")
.withDatabaseName("roleimpact")
.withUsername("roleimpact")
.withPassword("roleimpact");
From 1a3a665e22046dca4509cf965b86fa813b86f543 Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Sat, 22 Aug 2026 18:25:19 -0400
Subject: [PATCH 08/10] feat(impact): refine organization-wide testing
---
.../DeterministicImpactEngine.java | 2 -
.../DeterministicImpactEngineTest.java | 37 +++++++++
frontend/src/App.css | 39 ++++++++++
frontend/src/App.test.tsx | 62 +++++++++++----
.../components/workspaces/DraftWorkspace.tsx | 23 +++---
.../workspaces/editor/DraftEditor.tsx | 26 ++++---
.../workspaces/editor/DraftImpactTesting.tsx | 58 ++++++++++----
...ullOrganizationImpactCanvas.edges.test.tsx | 78 +++++++++++++++++++
.../FullOrganizationImpactCanvas.test.tsx | 64 ++++++++++++++-
.../editor/FullOrganizationImpactCanvas.tsx | 38 ++++++---
.../workspaces/editor/OrganizationCanvas.tsx | 4 +-
11 files changed, 368 insertions(+), 63 deletions(-)
create mode 100644 frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.edges.test.tsx
diff --git a/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java b/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java
index dcffb9a..f6cd7a9 100644
--- a/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java
+++ b/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java
@@ -59,7 +59,6 @@ public final class DeterministicImpactEngine implements ImpactEngine {
public static final String SCHEMA_VERSION = REQUEST_SCHEMA_VERSION;
public static final String ENGINE_VERSION = "1.2.0";
- private static final int MAX_RECOMMENDATIONS = 2;
private static final Comparator UUID_ORDER = Comparator.comparing(UUID::toString);
private static final Comparator ENTITY_ORDER = Comparator
.comparing(EntityRef::name)
@@ -848,7 +847,6 @@ private static RecommendationOutcome recommendMitigations(
var role = snapshot.roles().get(roleId);
var orderedCandidates = safeCandidates.stream()
.sorted(RECOMMENDATION_ORDER)
- .limit(MAX_RECOMMENDATIONS)
.toList();
var recommendations = new ArrayList();
for (var index = 0; index < orderedCandidates.size(); index++) {
diff --git a/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java b/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java
index 27454f4..7bbbf8b 100644
--- a/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java
+++ b/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java
@@ -51,6 +51,9 @@ class DeterministicImpactEngineTest {
private static final UUID OLIVIA_ID = id("20000000", 3);
private static final UUID DYLAN_ID = id("20000000", 4);
private static final UUID INEZ_ID = id("20000000", 5);
+ private static final UUID ALICE_ID = id("20000000", 6);
+ private static final UUID CARLOS_ID = id("20000000", 7);
+ private static final UUID ELENA_ID = id("20000000", 8);
private static final UUID FINANCE_ANALYST_ID = id("30000000", 1);
private static final UUID FINANCE_APPROVER_ID = id("30000000", 2);
private static final UUID CLOSE_BACKUP_ID = id("30000000", 3);
@@ -113,6 +116,18 @@ void recommendsBobWithStableEvidenceAndExplainsUnsafeCandidates() {
.containsExactly(CandidateExclusionReasonCode.SOURCE_EMPLOYEE);
}
+ @Test
+ void returnsEverySafeReplacementCandidateInRankOrder() {
+ var result = engine.analyze(snapshotWithAdditionalSafeCandidates(), revokePriyaApprover());
+
+ assertThat(result.recommendations())
+ .extracting(recommendation -> recommendation.candidate().name())
+ .containsExactly("Bob Chen", "Alice Morgan", "Carlos Ruiz", "Elena Rossi");
+ assertThat(result.recommendations())
+ .extracting(recommendation -> recommendation.rank())
+ .containsExactly(1, 2, 3, 4);
+ }
+
@Test
void producesTheSameResultAndHashRegardlessOfSnapshotInsertionOrder() {
var first = engine.analyze(snapshot(false, false), revokePriyaApprover());
@@ -411,6 +426,28 @@ private static OrganizationSnapshot snapshot(boolean reverseOrder, boolean overl
Map.entry(APPROVE_PAYMENT_STEP_ID, linkedSet(DIFFERENT_ACTORS_ID)))));
}
+ private static OrganizationSnapshot snapshotWithAdditionalSafeCandidates() {
+ var baseline = snapshot(false, false);
+ var employees = new LinkedHashMap<>(baseline.employees());
+ employees.put(ALICE_ID, employee(ALICE_ID, "Alice Morgan", EmployeeStatus.ACTIVE, WorkShift.EVENING));
+ employees.put(CARLOS_ID, employee(CARLOS_ID, "Carlos Ruiz", EmployeeStatus.ACTIVE, WorkShift.EVENING));
+ employees.put(ELENA_ID, employee(ELENA_ID, "Elena Rossi", EmployeeStatus.ACTIVE, WorkShift.EVENING));
+ return new OrganizationSnapshot(
+ baseline.organization(),
+ baseline.teams(),
+ employees,
+ baseline.roles(),
+ baseline.applications(),
+ baseline.resources(),
+ baseline.permissions(),
+ baseline.capabilities(),
+ baseline.workflows(),
+ baseline.roleIdsByEmployeeId(),
+ baseline.permissionIdsByRoleId(),
+ baseline.permissionIdsByCapabilityId(),
+ baseline.constraintIdsByWorkflowStepId());
+ }
+
private static EmployeeNode employee(
UUID id,
String name,
diff --git a/frontend/src/App.css b/frontend/src/App.css
index 10dae4d..4e96317 100644
--- a/frontend/src/App.css
+++ b/frontend/src/App.css
@@ -944,7 +944,9 @@
.organization-node.simulation-removed,
.organization-node.simulation-blocked { border-color: #fb7185; background: linear-gradient(145deg, #321a23, #1c1217); box-shadow: 0 0 0 3px rgb(251 113 133 / 12%), 0 12px 30px rgb(0 0 0 / 28%); }
.organization-node.simulation-degraded { border-color: #fbbf24; background: linear-gradient(145deg, #302816, #1b1710); }
+.organization-node.simulation-operational,
.organization-node.simulation-restored { border-color: #4ade80; background: linear-gradient(145deg, #173322, #101d16); box-shadow: 0 0 0 3px rgb(74 222 128 / 13%), 0 12px 30px rgb(0 0 0 / 28%); }
+.organization-node.simulation-operational .organization-node-icon,
.organization-node.simulation-restored .organization-node-icon { background: #174d30; color: #8ff0b1; }
.organization-node.simulation-removed .organization-node-icon,
.organization-node.simulation-blocked .organization-node-icon { background: #5a2433; color: #ffadba; }
@@ -971,6 +973,7 @@
.organization-node.simulation-degraded .organization-node-badge { color: #fbbf24; }
.organization-node.simulation-removed .organization-node-badge,
.organization-node.simulation-blocked .organization-node-badge { color: #fb7185; }
+.organization-node.simulation-operational .organization-node-badge,
.organization-node.simulation-restored .organization-node-badge { color: #4ade80; }
.organization-node.has-impact-actions > span:nth-of-type(2) { padding-right: 1.35rem; }
.organization-node-impact-actions {
@@ -1559,6 +1562,30 @@
background: #0d1017;
}
+.full-impact-map-canvas .react-flow__controls {
+ overflow: hidden;
+ border: 1px solid #333849;
+ border-radius: 0.55rem;
+ box-shadow: 0 10px 24px rgb(0 0 0 / 24%);
+}
+
+.full-impact-map-canvas .react-flow__controls-button {
+ border: 0;
+ border-bottom: 1px solid #333849;
+ border-radius: 0;
+ background: #171a24;
+ color: #bdc3d2;
+ fill: #bdc3d2;
+}
+
+.full-impact-map-canvas .react-flow__controls-button:hover {
+ background: #242836;
+}
+
+.full-impact-map-canvas .react-flow__controls-button svg {
+ fill: currentcolor;
+}
+
.full-impact-map .organization-node.member { cursor: pointer; }
.full-impact-map .organization-node.dimmed { opacity: 0.38; }
.full-impact-map .scenario-context-menu small { color: #c7a66a; font-size: 0.58rem; line-height: 1.45; }
@@ -1643,6 +1670,18 @@
.recommendation-alignment.review { background: #332a1a; color: #f5ca72; }
.draft-recommendation-evidence { display: flex; flex-wrap: wrap; gap: 0.35rem; }
.draft-recommendation-evidence span { padding: 0.22rem 0.38rem; border-radius: 999px; background: #222a26; color: #9dc4ad; font-size: 0.56rem; font-weight: 700; }
+.draft-alternative-recommendations { border: 1px solid #303546; border-radius: 0.75rem; background: #141821; }
+.draft-alternative-recommendations summary { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; padding: 0.8rem 0.9rem; color: #c7cddd; cursor: pointer; list-style: none; }
+.draft-alternative-recommendations summary::-webkit-details-marker { display: none; }
+.draft-alternative-recommendations summary::after { content: '+'; color: #9c89e8; font-size: 1rem; }
+.draft-alternative-recommendations[open] summary::after { content: '−'; }
+.draft-alternative-recommendations summary span { font-size: 0.74rem; font-weight: 800; }
+.draft-alternative-recommendations summary small { margin-left: auto; color: #777f92; font-size: 0.62rem; }
+.draft-alternative-list { display: grid; gap: 1px; border-top: 1px solid #303546; background: #303546; }
+.draft-alternative-card { display: grid; gap: 0.25rem; padding: 0.85rem 0.9rem; background: #151922; }
+.draft-alternative-card strong { font-size: 0.78rem; }
+.draft-alternative-card span { color: #9c89e8; font-size: 0.6rem; font-weight: 750; }
+.draft-alternative-card p { max-width: 56rem; color: #858da1; }
.draft-candidate-exclusions { border-top: 1px solid #2d3240; padding-top: 0.8rem; }
.draft-candidate-exclusions summary { color: #b6bdcc; cursor: pointer; font-size: 0.7rem; font-weight: 700; }
.draft-candidate-exclusions > div { display: grid; gap: 0.45rem; padding-top: 0.65rem; }
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx
index 9af291c..989c867 100644
--- a/frontend/src/App.test.tsx
+++ b/frontend/src/App.test.tsx
@@ -28,9 +28,12 @@ function renderApp(initialEntries = ['/']) {
)
}
-const editableMapRoute = '/organizations/HCS-7K4P9D/map'
-const editableInventoryRoute = '/organizations/HCS-7K4P9D/inventory'
-const editableImpactRoute = '/organizations/HCS-7K4P9D/impact'
+const harborlineCode = 'HBR-0123456789ABCDEF0123456789ABCDEF'
+const editableCode = 'HCS-1123456789ABCDEF0123456789ABCDEF'
+const blankCode = 'ATS-2123456789ABCDEF0123456789ABCDEF'
+const editableMapRoute = `/organizations/${editableCode}/map`
+const editableInventoryRoute = `/organizations/${editableCode}/inventory`
+const editableImpactRoute = `/organizations/${editableCode}/impact`
describe('App', () => {
it('renders the seeded organization dashboard', async () => {
@@ -140,7 +143,7 @@ describe('App', () => {
const user = userEvent.setup()
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity')) return jsonResponse([])
return new Response(null, { status: 404 })
@@ -247,7 +250,7 @@ describe('App', () => {
const projection = deferred()
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity') && !init?.method) return projection.promise
return new Response(null, { status: 404 })
@@ -260,6 +263,8 @@ describe('App', () => {
expect(await screen.findByRole('heading', { name: 'Test impact map' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Vendor Payment.*would block/ })).toBeInTheDocument()
+ expect(screen.queryByRole('heading', { name: 'Harborline Sandbox' })).not.toBeInTheDocument()
+ expect(screen.queryByText('Organization builder')).not.toBeInTheDocument()
})
it('opens impact testing after retrying a failed continuity projection', async () => {
@@ -267,7 +272,7 @@ describe('App', () => {
let continuityAttempts = 0
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity') && !init?.method) {
continuityAttempts += 1
@@ -298,7 +303,7 @@ describe('App', () => {
}))
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture)
if (url.endsWith('/impact-previews/continuity') && !init?.method) return jsonResponse(degradedContinuity)
return new Response(null, { status: 404 })
@@ -322,7 +327,7 @@ describe('App', () => {
const url = input.toString()
if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture)
if (url.endsWith('/api/v1/workspaces') && init?.method === 'POST') return jsonResponse(blankWorkspaceFixture, 201)
- if (url.endsWith('/api/v1/workspaces/by-code/ATS-7K4P9E')) return jsonResponse(blankWorkspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${blankCode}`)) return jsonResponse(blankWorkspaceFixture)
if (url.endsWith('/catalog') && !init?.method) return jsonResponse(catalog)
if (url.endsWith('/impact-previews/continuity') && !init?.method) {
continuityRequests += 1
@@ -404,6 +409,11 @@ describe('App', () => {
await user.click(screen.getByRole('button', { name: 'Create member' }))
expect(await screen.findByText('Member created')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Add Member' }))
+ await user.type(screen.getByLabelText('Member name'), 'Neha Kapoor')
+ await user.click(screen.getByRole('button', { name: 'Create member' }))
+ expect(await screen.findByText('Member created')).toBeInTheDocument()
+
await user.click(screen.getByRole('button', { name: 'Add Role' }))
await user.type(screen.getByLabelText('Role name'), 'Release Manager')
await user.selectOptions(screen.getByLabelText('Sensitivity'), 'HIGH')
@@ -430,10 +440,11 @@ describe('App', () => {
await user.click(screen.getByRole('button', { name: 'Organization map' }))
expect(screen.getByLabelText('Organization inventory')).toHaveTextContent('Production Deployment')
expect(screen.getByLabelText('Organization relationship canvas')).toBeInTheDocument()
- expect(screen.getByText('6 objects · 5 connections')).toBeInTheDocument()
+ expect(screen.getByText('7 objects · 6 connections')).toBeInTheDocument()
expect(screen.getByLabelText('Team Platform')).toBeInTheDocument()
expect(screen.getByLabelText('Member Maya Singh')).toBeInTheDocument()
expect(screen.getByLabelText('Member Arjun Mehta')).toBeInTheDocument()
+ expect(screen.getByLabelText('Member Neha Kapoor')).toBeInTheDocument()
expect(screen.getByLabelText('Role Release Manager')).toBeInTheDocument()
expect(screen.getByLabelText('Responsibility Release Manager responsibility')).toBeInTheDocument()
expect(screen.getByLabelText('Workflow Production Deployment')).toBeInTheDocument()
@@ -456,7 +467,7 @@ describe('App', () => {
await user.click(screen.getByRole('button', { name: 'Organization map' }))
await user.click(screen.getByRole('button', { name: 'Test this risk' }))
- expect(await screen.findByRole('heading', { name: 'Test a change before it happens' })).toBeInTheDocument()
+ expect(await screen.findByRole('region', { name: 'Test impact workspace' })).toBeInTheDocument()
expect(await screen.findByRole('heading', { name: 'Test impact map' })).toBeInTheDocument()
expect(await screen.findByLabelText('Complete organization impact map')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Show full map' }))
@@ -474,6 +485,9 @@ describe('App', () => {
expect(screen.getByRole('button', { name: 'Fit selection' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Clear selection' }))
expect(screen.queryByRole('button', { name: 'Fit selection' })).not.toBeInTheDocument()
+ const scenarioComposer = screen.getByRole('region', { name: 'Choose what to test' })
+ await user.click(within(scenarioComposer).getByRole('button', { name: /Release Manager responsibility/ }))
+ expect(screen.getByLabelText('Selected Responsibility Release Manager responsibility')).toHaveTextContent('Eligible now')
const mayaImpactActions = document.querySelector('button[aria-label="Impact actions for Maya Singh"]')
const arjunImpactActions = document.querySelector('button[aria-label="Impact actions for Arjun Mehta"]')
expect(mayaImpactActions).toBeInTheDocument()
@@ -490,10 +504,19 @@ describe('App', () => {
expect(await screen.findByRole('heading', { name: 'A workflow would be blocked' })).toBeInTheDocument()
expect(screen.getByLabelText('Complete organization impact map')).toBeInTheDocument()
expect(screen.getByLabelText(/member Arjun Mehta.*Recommended #1/i)).toBeInTheDocument()
+ expect(screen.queryByLabelText(/member Neha Kapoor.*Recommended #2/i)).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Reset to baseline' })).toBeInTheDocument()
- expect(screen.getByRole('heading', { name: 'Compare technically viable replacements' })).toBeInTheDocument()
+ expect(screen.getByRole('heading', { name: 'Recommended replacement' })).toBeInTheDocument()
expect(screen.getByText('Best aligned · same team')).toBeInTheDocument()
expect(screen.getByText(/Ranked #1 because Arjun Mehta is in the same team as Maya Singh/)).toBeInTheDocument()
+ const alternatives = screen.getByRole('group', { name: 'Alternative replacements' })
+ expect(within(alternatives).getByText('1 alternative')).toBeInTheDocument()
+ expect(alternatives).not.toHaveAttribute('open')
+ await user.click(within(alternatives).getByText('1 alternative'))
+ expect(alternatives).toHaveAttribute('open')
+ expect(within(alternatives).getByText('Neha Kapoor')).toBeInTheDocument()
+ expect(within(alternatives).getByText(/adds another dependency/i)).toBeInTheDocument()
+ expect(within(alternatives).queryByRole('button')).not.toBeInTheDocument()
fireEvent.click(screen.getByLabelText(/member Arjun Mehta.*Recommended #1/i))
const selectedArjun = screen.getByLabelText('Selected Member Arjun Mehta')
await user.click(within(selectedArjun).getByRole('button', { name: 'Try as replacement for Release Manager' }))
@@ -588,7 +611,7 @@ function mockEditableClone(initialCatalog: DraftCatalog) {
const memberRoleRequests: string[] = []
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const url = input.toString()
- if (url.endsWith('/api/v1/workspaces/by-code/HCS-7K4P9D')) return jsonResponse(clonedWorkspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture)
if (url.endsWith('/catalog') && !init?.method) return jsonResponse(catalog)
if (url.endsWith('/impact-previews/continuity') && !init?.method) return jsonResponse([])
if (url.endsWith('/catalog/roles') && init?.method === 'POST') {
@@ -633,7 +656,7 @@ const workspaceFixture = [
name: 'Harborline Commerce',
status: 'PUBLISHED',
currentVersion: 1,
- publicCode: 'HBR-7K4P9D',
+ publicCode: harborlineCode,
createdAt: '2026-08-12T20:00:00Z',
updatedAt: '2026-08-12T20:00:00Z',
counts: { teams: 5, members: 25, roles: 8, permissions: 23, capabilities: 10, workflows: 4 },
@@ -647,7 +670,7 @@ const clonedWorkspaceFixture = {
name: 'Harborline Sandbox',
status: 'DRAFT',
currentVersion: 0,
- publicCode: 'HCS-7K4P9D',
+ publicCode: editableCode,
}
const blankWorkspaceFixture = {
@@ -657,7 +680,7 @@ const blankWorkspaceFixture = {
name: 'Atlas Systems',
status: 'DRAFT',
currentVersion: 0,
- publicCode: 'ATS-7K4P9E',
+ publicCode: blankCode,
counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 },
}
@@ -1009,6 +1032,15 @@ const customDraftImpactFixture: DraftImpactResult = {
restoredWorkflows: [{ id: 'workflow-1', name: 'Production Deployment' }],
restoredWorkflowSteps: [{ id: 'requirement-1', name: 'Release Manager responsibility' }],
},
+ {
+ ...(simulationFixture.result.recommendations[0] as DraftImpactResult['recommendations'][number]),
+ id: 'recommendation-2',
+ rank: 2,
+ candidate: { id: 'member-3', name: 'Neha Kapoor' },
+ role: { id: 'role-1', name: 'Release Manager' },
+ restoredWorkflows: [{ id: 'workflow-1', name: 'Production Deployment' }],
+ restoredWorkflowSteps: [{ id: 'requirement-1', name: 'Release Manager responsibility' }],
+ },
],
excludedCandidateReasons: [],
}
diff --git a/frontend/src/components/workspaces/DraftWorkspace.tsx b/frontend/src/components/workspaces/DraftWorkspace.tsx
index cf4ceda..a800920 100644
--- a/frontend/src/components/workspaces/DraftWorkspace.tsx
+++ b/frontend/src/components/workspaces/DraftWorkspace.tsx
@@ -15,6 +15,7 @@ export default function DraftWorkspace({ workspace, view, newlyCreated = false,
const [showOnboarding, setShowOnboarding] = useState(newlyCreated)
const [copyMessage, setCopyMessage] = useState(null)
const isEmpty = workspace.counts.members === 0
+ const isImpactView = view === 'impact'
async function copyValue(value: string, message: string) {
try {
@@ -41,9 +42,9 @@ export default function DraftWorkspace({ workspace, view, newlyCreated = false,
void copyValue(organizationLink, 'Organization link copied.')}>Copy organization link
-
+
{copyMessage ? {copyMessage}
: null}
- {showOnboarding ? (
+ {showOnboarding && !isImpactView ? (
Keep access to your work
@@ -59,13 +60,17 @@ export default function DraftWorkspace({ workspace, view, newlyCreated = false,
) : null}
- Organization builder
- {workspace.name}
-
- {isEmpty
- ? 'Your organization is ready. Add its first team and build outward from there.'
- : 'Edit the model, test access changes, and return later using the organization ID or link.'}
-
+ {!isImpactView ? (
+ <>
+ Organization builder
+ {workspace.name}
+
+ {isEmpty
+ ? 'Your organization is ready. Add its first team and build outward from there.'
+ : 'Edit the model, test access changes, and return later using the organization ID or link.'}
+
+ >
+ ) : null}
navigate('/')}>← Back to workspace choices
diff --git a/frontend/src/components/workspaces/editor/DraftEditor.tsx b/frontend/src/components/workspaces/editor/DraftEditor.tsx
index 72081ef..ee37981 100644
--- a/frontend/src/components/workspaces/editor/DraftEditor.tsx
+++ b/frontend/src/components/workspaces/editor/DraftEditor.tsx
@@ -77,12 +77,14 @@ export default function DraftEditor({ workspaceId, view, onViewChange }: {
}
return (
-
-
-
-
{view === 'impact' ? 'Business continuity lab' : 'Visual organization builder'}
-
{view === 'impact' ? 'Test a change before it happens' : 'Map how your organization works'}
-
+
+
+ {view !== 'impact' ? (
+
+
Visual organization builder
+
Map how your organization works
+
+ ) : null}
onViewChange('map')}>Organization map
onViewChange('impact')}>Test impact
@@ -90,11 +92,13 @@ export default function DraftEditor({ workspaceId, view, onViewChange }: {
-
- {liveCounts.map((count) => (
-
{count.value} {count.label}
- ))}
-
+ {view !== 'impact' ? (
+
+ {liveCounts.map((count) => (
+
{count.value} {count.label}
+ ))}
+
+ ) : null}
{view === 'map' && !continuityQuery.isFetching && !continuityQuery.isError && firstBlockedRisk && firstBlockedMember ? (
diff --git a/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx b/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx
index bc8f30a..afae56c 100644
--- a/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx
+++ b/frontend/src/components/workspaces/editor/DraftImpactTesting.tsx
@@ -31,6 +31,7 @@ export default function DraftImpactTesting({ workspaceId, catalog, risks, isCont
: initialRisk?.workflowId ?? ''
const workflowRisks = testableRisks.filter((risk) => risk.workflowId === selectedWorkflowId)
const [selectedRiskKeyState, setSelectedRiskKey] = useState(initialRisk?.key ?? '')
+ const [graphSelectionRequest, setGraphSelectionRequest] = useState<{ nodeId: string; requestId: number } | null>(null)
const selectedRiskKey = workflowRisks.some((risk) => risk.key === selectedRiskKeyState)
? selectedRiskKeyState
: workflowRisks[0]?.key ?? ''
@@ -83,8 +84,10 @@ export default function DraftImpactTesting({ workspaceId, catalog, risks, isCont
}
function chooseRisk(riskKey: string) {
- if (riskKey === selectedRiskKey) return
const risk = workflowRisks.find((candidate) => candidate.key === riskKey)
+ if (!risk) return
+ setGraphSelectionRequest((current) => ({ nodeId: `responsibility:${risk.requirementId}`, requestId: (current?.requestId ?? 0) + 1 }))
+ if (riskKey === selectedRiskKey) return
setSelectedRiskKey(riskKey)
setSelectedMemberId(risk?.members[0]?.id ?? '')
resetResults()
@@ -154,6 +157,7 @@ export default function DraftImpactTesting({ workspaceId, catalog, risks, isCont
isPending={mutation.isPending || mitigationMutation.isPending}
onRunScenario={runScenario}
onTryReplacement={tryReplacement}
+ selectionRequest={graphSelectionRequest}
/>
{originalResult && showOutcomeExplanation ? setShowOutcomeExplanation(false)} /> : null}
@@ -235,28 +239,56 @@ function DraftMitigationPanel({ catalog, result, mitigation, isPending, error, o
)
}
+ const [primaryRecommendation, ...alternativeRecommendations] = result.recommendations.toSorted((left, right) => left.rank - right.rank)
+ const primaryTested = mitigation?.changeSet.replacementEmployee?.id === primaryRecommendation.candidate.id
+ const primaryAlignment = describeRecommendationAlignment(catalog, result, primaryRecommendation)
+
return (
- Step 3
Compare technically viable replacements Every option restores the configured workflow rules. Team alignment and added access explain why one option ranks above another.
{result.recommendations.length} viable option{result.recommendations.length === 1 ? '' : 's'}
+ Step 3
Recommended replacement Start with the best available member. Other valid choices stay collapsed until you need them.
Best fit
- {result.recommendations.map((recommendation) => {
- const tested = mitigation?.changeSet.replacementEmployee?.id === recommendation.candidate.id
- const alignment = describeRecommendationAlignment(catalog, result, recommendation)
- return (
-
- {String(recommendation.rank).padStart(2, '0')}
- {alignment.label} Assign {recommendation.role.name} to {recommendation.candidate.name} {alignment.reason}
This restores {formatEntityNames(recommendation.restoredWorkflowSteps)} with {recommendation.gainedPermissions.length} additional effective permission{recommendation.gainedPermissions.length === 1 ? '' : 's'}.
{recommendation.evidence.map((evidence) => {evidenceLabel(evidence)} )}
- onTest(recommendation.candidate.id)}>{isPending ? 'Testing mitigation…' : tested ? 'Test mitigation again' : 'Test this mitigation'}
-
- )
- })}
+
+ 01
+ {primaryAlignment.label} Assign {primaryRecommendation.role.name} to {primaryRecommendation.candidate.name} {primaryAlignment.reason}
This restores {formatEntityNames(primaryRecommendation.restoredWorkflowSteps)} with {primaryRecommendation.gainedPermissions.length} additional effective permission{primaryRecommendation.gainedPermissions.length === 1 ? '' : 's'}.
{primaryRecommendation.evidence.map((evidence) => {evidenceLabel(evidence)} )}
+ onTest(primaryRecommendation.candidate.id)}>{isPending ? 'Testing mitigation…' : primaryTested ? 'Test mitigation again' : `Preview ${primaryRecommendation.candidate.name}`}
+
+ {alternativeRecommendations.length > 0 ? (
+
+ {alternativeRecommendations.length} alternative{alternativeRecommendations.length === 1 ? '' : 's'} Valid options with trade-offs
+
+ {alternativeRecommendations.map((recommendation) => (
+
+ {recommendation.candidate.name} {recommendation.role.name} {describeAlternativeTradeoff(catalog, result, recommendation)}
+
+ ))}
+
+
+ ) : null}
{error ? {error.message}
: null}
{result.excludedCandidateReasons.length > 0 ? : null}
)
}
+function describeAlternativeTradeoff(
+ catalog: DraftCatalog,
+ result: DraftImpactResult,
+ recommendation: DraftImpactResult['recommendations'][number],
+) {
+ const candidate = catalog.members.find((member) => member.id === recommendation.candidate.id)
+ const currentRoleIds = new Set(candidate?.roleIds ?? [])
+ const existingResponsibilities = catalog.workflows.reduce(
+ (count, workflow) => count + workflow.requirements.filter((requirement) => requirement.roleIds.some((roleId) => currentRoleIds.has(roleId))).length,
+ 0,
+ )
+ const alignment = describeRecommendationAlignment(catalog, result, recommendation)
+ const existingCoverage = existingResponsibilities > 0
+ ? `${recommendation.candidate.name} already supports ${existingResponsibilities} mapped responsibilit${existingResponsibilities === 1 ? 'y' : 'ies'}, so this adds another dependency.`
+ : `This adds another dependency and ranks behind the best-fit member.`
+ return `${alignment.reason} ${existingCoverage}`
+}
+
function describeRecommendationAlignment(
catalog: DraftCatalog,
result: DraftImpactResult,
diff --git a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.edges.test.tsx b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.edges.test.tsx
new file mode 100644
index 0000000..abaea91
--- /dev/null
+++ b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.edges.test.tsx
@@ -0,0 +1,78 @@
+import { render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { DraftCatalog } from '../../../api/draftCatalog'
+import type { DraftContinuityRisk, DraftImpactResult } from '../../../api/draftImpact'
+import FullOrganizationImpactCanvas from './FullOrganizationImpactCanvas'
+
+const reactFlowProps = vi.hoisted(() => ({ current: null as null | { edges: Array> } }))
+
+vi.mock('@xyflow/react', async () => {
+ const actual = await vi.importActual('@xyflow/react')
+ return {
+ ...actual,
+ Background: () => null,
+ Controls: () => null,
+ ReactFlow: ({ edges }: { edges: Array> }) => {
+ reactFlowProps.current = { edges }
+ return
+ },
+ useReactFlow: () => ({ fitView: vi.fn() }),
+ }
+})
+
+describe('FullOrganizationImpactCanvas edge presentation', () => {
+ beforeEach(() => { reactFlowProps.current = null })
+
+ it('supplies a dark background for recommendation edge labels', () => {
+ render(
+ new Set()}
+ />,
+ )
+
+ expect(screen.getByTestId('impact-flow')).toBeInTheDocument()
+ const candidateEdge = reactFlowProps.current?.edges.find((edge) => edge.label === 'recommended #1')
+ expect(candidateEdge).toMatchObject({
+ labelBgStyle: { fill: '#12151e', fillOpacity: 0.95 },
+ })
+ })
+
+})
+
+const catalog = {
+ workspaceId: 'workspace-1',
+ teams: [{ id: 'team-1', name: 'Platform', department: 'Engineering', memberCount: 2 }],
+ members: [
+ { id: 'member-maya', teamId: 'team-1', employeeNumber: null, name: 'Maya Singh', email: null, status: 'ACTIVE', region: 'NORTH_AMERICA', shift: 'DAY', roleIds: ['role-1'] },
+ { id: 'member-arjun', teamId: 'team-1', employeeNumber: null, name: 'Arjun Mehta', email: null, status: 'ACTIVE', region: 'NORTH_AMERICA', shift: 'DAY', roleIds: [] },
+ ],
+ roles: [{ id: 'role-1', name: 'Release Manager', description: '', sensitivity: 'HIGH', ownerMemberId: null, memberCount: 1 }],
+ workflows: [{ id: 'workflow-1', name: 'Production Deployment', criticality: 'CRITICAL', quickManaged: true, requirements: [{ id: 'responsibility-1', name: 'Approve release', position: 1, minimumActors: 1, resilienceTarget: 1, requiredDepartment: null, requiredRegion: null, requiredShift: null, roleIds: ['role-1'] }] }],
+} satisfies DraftCatalog
+
+const risks = [{
+ key: 'risk-1', workflowId: 'workflow-1', workflowName: 'Production Deployment', criticality: 'CRITICAL', requirementId: 'responsibility-1', requirementName: 'Approve release', minimumActors: 1, resilienceTarget: 1, roleId: 'role-1', roleName: 'Release Manager', eligibleMembers: [{ id: 'member-maya', name: 'Maya Singh' }], members: [{ id: 'member-maya', name: 'Maya Singh', eligible: true, losesCoverage: true, remainingEligibleActorCount: 0, scenarioStatus: 'BLOCKED' }],
+}] satisfies DraftContinuityRisk[]
+
+const result = {
+ changeSet: { type: 'REVOKE_EMPLOYEE_ROLE', employee: { id: 'member-maya', name: 'Maya Singh' }, role: { id: 'role-1', name: 'Release Manager' }, replacementEmployee: null },
+ workflowImpacts: [],
+ recommendations: [{ id: 'recommendation-1', rank: 1, candidate: { id: 'member-arjun', name: 'Arjun Mehta' } }],
+ excludedCandidateReasons: [],
+ diagnostics: { resultHash: 'result-1' },
+} as unknown as DraftImpactResult
diff --git a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx
index 65cd865..e44d0a0 100644
--- a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx
+++ b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.test.tsx
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest'
import type { DraftCatalog } from '../../../api/draftCatalog'
import type { DraftContinuityRisk, DraftImpactResult } from '../../../api/draftImpact'
import { OrganizationImpactCanvas } from './OrganizationCanvas'
+import '../../../App.css'
describe('FullOrganizationImpactCanvas', () => {
it('keeps a shared role available when removing one holder leaves other eligible holders', async () => {
@@ -25,8 +26,48 @@ describe('FullOrganizationImpactCanvas', () => {
expect(await screen.findByLabelText(/member Maya Singh.*Assignment removed/i)).toBeInTheDocument()
expect(screen.getByLabelText(/role Invoice Processor.*2 holders remain/i)).toBeInTheDocument()
expect(screen.queryByLabelText(/role Invoice Processor.*Removed/i)).not.toBeInTheDocument()
- expect(screen.getByLabelText(/responsibility Validate supplier invoice.*Still operational/i)).toBeInTheDocument()
- expect(screen.getByLabelText(/workflow Daily Vendor Payment Run.*Still operational/i)).toBeInTheDocument()
+ expect(screen.getByLabelText(/responsibility Validate supplier invoice.*Still operational/i).firstElementChild).toHaveClass('simulation-operational')
+ expect(screen.getByLabelText(/workflow Daily Vendor Payment Run.*Still operational/i).firstElementChild).toHaveClass('simulation-operational')
+ })
+
+ it('keeps every member of a participating team visible in workflow focus', async () => {
+ render(
+ ,
+ )
+
+ expect(await screen.findByLabelText(/member Arjun Mehta/i)).toBeInTheDocument()
+ })
+
+ it('renders graph controls with dark backgrounds', () => {
+ const { container } = render(
+ ,
+ )
+
+ const controlButton = container.querySelector('.full-impact-map-canvas .react-flow__controls-button')
+ expect(controlButton).not.toBeNull()
+ expect(getComputedStyle(controlButton!).backgroundColor).toBe('rgb(23, 26, 36)')
})
})
@@ -85,3 +126,22 @@ const safeSharedRoleResult = {
excludedCandidateReasons: [],
diagnostics: { resultHash: 'safe-shared-role' },
} as unknown as DraftImpactResult
+
+const candidateCatalog: DraftCatalog = {
+ ...safeSharedRoleCatalog,
+ teams: [{ ...safeSharedRoleCatalog.teams[0], memberCount: 4 }],
+ members: [
+ ...safeSharedRoleCatalog.members,
+ { id: 'member-arjun', teamId: 'team-ap', employeeNumber: null, name: 'Arjun Mehta', email: null, status: 'ACTIVE', region: 'NORTH_AMERICA', shift: 'DAY', roleIds: [] },
+ ],
+}
+
+const candidateResult = {
+ ...safeSharedRoleResult,
+ recommendations: [{
+ id: 'recommendation-1',
+ rank: 1,
+ candidate: { id: 'member-arjun', name: 'Arjun Mehta' },
+ }],
+ diagnostics: { resultHash: 'candidate-result' },
+} as unknown as DraftImpactResult
diff --git a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx
index 98da1bd..615cf0e 100644
--- a/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx
+++ b/frontend/src/components/workspaces/editor/FullOrganizationImpactCanvas.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react'
import {
Background,
Controls,
@@ -14,7 +14,7 @@ import type { DraftContinuityRisk, DraftImpactResult } from '../../../api/draftI
import type { CanvasNode, OrganizationSimulationState } from './OrganizationCanvas'
type ImpactContextMenu = { x: number; y: number; memberId: string }
-type ImpactEdgeState = 'removed' | 'blocked' | 'degraded' | 'restored' | 'candidate'
+type ImpactEdgeState = 'removed' | 'blocked' | 'degraded' | 'operational' | 'restored' | 'candidate'
export type FullOrganizationImpactCanvasProps = {
workspaceId: string
@@ -28,6 +28,7 @@ export type FullOrganizationImpactCanvasProps = {
isPending: boolean
onRunScenario: (riskKey: string, memberId: string) => void
onTryReplacement: (memberId: string) => void
+ selectionRequest?: { nodeId: string; requestId: number } | null
}
export default function FullOrganizationImpactCanvas({
@@ -41,6 +42,7 @@ export default function FullOrganizationImpactCanvas({
isPending,
onRunScenario,
onTryReplacement,
+ selectionRequest,
baseNodes,
baseEdges,
baseFocusIds,
@@ -54,6 +56,7 @@ export default function FullOrganizationImpactCanvas({
getRelatedPathIds: (selectedNodeId: string) => Set
}) {
const { fitView } = useReactFlow()
+ const mapRef = useRef(null)
const [scope, setScope] = useState<'workflow' | 'full'>('workflow')
const [selectedNodeId, setSelectedNodeId] = useState(null)
const [contextMenu, setContextMenu] = useState(null)
@@ -102,6 +105,19 @@ export default function FullOrganizationImpactCanvas({
setScope('workflow')
}, [workflowId])
+ useEffect(() => {
+ if (!selectionRequest) return
+ setContextMenu(null)
+ setSelectedNodeId(selectionRequest.nodeId)
+ const pathIds = getRelatedPathIds(selectionRequest.nodeId)
+ const pathNodes = model.nodes.filter((node) => pathIds.has(node.id))
+ const frame = window.requestAnimationFrame(() => {
+ mapRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' })
+ if (pathNodes.length > 0) void fitView({ nodes: pathNodes, duration: 350, maxZoom: 1.05, padding: 0.45 })
+ })
+ return () => window.cancelAnimationFrame(frame)
+ }, [fitView, getRelatedPathIds, model.nodes, selectionRequest])
+
function fitSelection() {
if (!selectedPathIds) return
const nodes = visibleNodes.filter((node) => selectedPathIds.has(node.id))
@@ -109,7 +125,7 @@ export default function FullOrganizationImpactCanvas({
}
return (
-
+
Test impact map {selectedNode ? `${impactTypeLabels[selectedNode.data.entityType]} selected · connected path highlighted` : `${selectedWorkflow?.name ?? 'Selected workflow'} · select any object to trace its path`}
@@ -117,7 +133,7 @@ export default function FullOrganizationImpactCanvas({
{selectedNode ?
Fit selection : null}
{selectedNode ?
setSelectedNodeId(null)}>Clear selection : null}
void fitView({ duration: 350, padding: 0.25 })}>Fit graph
-
Legend Selected Candidate Blocked Degraded Restored
+
Legend Selected Candidate Blocked Degraded Healthy / restored
@@ -300,7 +316,8 @@ function buildImpactModel(
: displayedResult?.workflowImpacts.some((workflow) => workflow.scenarioStatus === 'DEGRADED' && workflow.scenarioStatus !== workflow.baselineStatus) ? 'degraded'
: 'restored'
: undefined
- const recommendationRank = new Map(originalResult?.recommendations.map((candidate) => [candidate.candidate.id, candidate.rank]) ?? [])
+ const primaryRecommendation = originalResult?.recommendations.toSorted((left, right) => left.rank - right.rank)[0]
+ const recommendationRank = new Map(primaryRecommendation ? [[primaryRecommendation.candidate.id, 1]] : [])
const exclusions = new Map(originalResult?.excludedCandidateReasons.map((candidate) => [candidate.candidate.id, candidate]) ?? [])
const stepStates = new Map()
const workflowStates = new Map()
@@ -353,7 +370,7 @@ function buildImpactModel(
.flatMap((workflow) => workflow.requirements)
.filter((requirement) => requirement.roleIds.includes(entityId))
.map((requirement) => stepStates.get(requirement.id))
- simulationState = supportingStates.includes('blocked') ? 'blocked' : supportingStates.includes('degraded') ? 'degraded' : 'source'
+ simulationState = supportingStates.includes('blocked') ? 'blocked' : supportingStates.includes('degraded') ? 'degraded' : 'operational'
badge = `${remainingHolderCount} holder${remainingHolderCount === 1 ? '' : 's'} remain`
const sourceName = catalog.members.find((member) => member.id === sourceMemberId)?.name ?? 'the selected member'
detail = `Only ${sourceName}'s assignment is removed. This shared role remains available through ${remainingHolderCount} other holder${remainingHolderCount === 1 ? '' : 's'}.`
@@ -415,12 +432,13 @@ function buildImpactEdges(
}
function styleImpactEdge(edge: Edge, state: ImpactEdgeState | undefined, relevant: boolean): Edge {
- const color = state === 'removed' || state === 'blocked' ? '#fb7185' : state === 'degraded' ? '#fbbf24' : state === 'candidate' ? '#38bdf8' : state === 'restored' ? '#4ade80' : '#7f6ce5'
+ const color = state === 'removed' || state === 'blocked' ? '#fb7185' : state === 'degraded' ? '#fbbf24' : state === 'candidate' ? '#38bdf8' : state === 'operational' || state === 'restored' ? '#4ade80' : '#7f6ce5'
return {
...edge,
animated: state === 'restored' || state === 'candidate',
style: { ...edge.style, stroke: color, strokeWidth: state ? 2.5 : 1.6, opacity: relevant ? 1 : 0.12, strokeDasharray: state === 'candidate' || state === 'removed' ? '6 5' : undefined },
labelStyle: { ...edge.labelStyle, fill: state ? color : '#aeb5c7', opacity: relevant ? 1 : 0.08 },
+ labelBgStyle: { ...edge.labelBgStyle, fill: '#12151e', fillOpacity: 0.95 },
markerEnd: { type: MarkerType.ArrowClosed, color, width: 16, height: 16 },
}
}
@@ -474,11 +492,11 @@ function resultState(scenario: DraftImpactResult['workflowImpacts'][number]['sce
if (mitigation && scenario === baseline) return 'restored'
if (scenario === 'BLOCKED') return 'blocked'
if (scenario === 'DEGRADED') return 'degraded'
- return mitigation ? 'restored' : 'source'
+ return mitigation ? 'restored' : 'operational'
}
function toEdgeState(state: OrganizationSimulationState | undefined): ImpactEdgeState | undefined {
- if (state === 'blocked' || state === 'degraded' || state === 'restored') return state
+ if (state === 'blocked' || state === 'degraded' || state === 'operational' || state === 'restored') return state
return undefined
}
@@ -486,7 +504,7 @@ function stateBadge(state: OrganizationSimulationState) {
if (state === 'blocked') return 'Blocked'
if (state === 'degraded') return 'Degraded'
if (state === 'restored') return 'Restored'
- if (state === 'source') return 'Still operational'
+ if (state === 'operational') return 'Still operational'
return undefined
}
diff --git a/frontend/src/components/workspaces/editor/OrganizationCanvas.tsx b/frontend/src/components/workspaces/editor/OrganizationCanvas.tsx
index 7f13dcb..a2d6d7c 100644
--- a/frontend/src/components/workspaces/editor/OrganizationCanvas.tsx
+++ b/frontend/src/components/workspaces/editor/OrganizationCanvas.tsx
@@ -37,7 +37,7 @@ import FullOrganizationImpactCanvas, { type FullOrganizationImpactCanvasProps }
type EntityType = 'team' | 'member' | 'role' | 'workflow'
type GraphEntityType = EntityType | 'responsibility'
-export type OrganizationSimulationState = 'source' | 'candidate' | 'unsafe' | 'removed' | 'blocked' | 'degraded' | 'restored'
+export type OrganizationSimulationState = 'source' | 'candidate' | 'unsafe' | 'removed' | 'blocked' | 'degraded' | 'operational' | 'restored'
export type CanvasNodeData = {
label: string
entityType: GraphEntityType
@@ -715,6 +715,8 @@ function focusedNodeIds(catalog: DraftCatalog, workflowId: string) {
ids.add(nodeId('member', member.id))
ids.add(nodeId('team', member.teamId))
})
+ const participatingTeamIds = new Set(catalog.teams.filter((team) => ids.has(nodeId('team', team.id))).map((team) => team.id))
+ catalog.members.filter((member) => participatingTeamIds.has(member.teamId)).forEach((member) => ids.add(nodeId('member', member.id)))
return ids
}
From 5ace006b31edcf48aa402824c51fa89f7653bc2d Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Sat, 22 Aug 2026 18:25:33 -0400
Subject: [PATCH 09/10] security(workspace): strengthen editable organization
codes
---
.../workspace/application/WorkspaceCode.java | 19 ++++++------
...__strengthen_organization_public_codes.sql | 14 +++++++++
.../CatalogMigrationIntegrationTest.java | 4 +--
.../workspace/WorkspaceIntegrationTest.java | 2 +-
.../application/WorkspaceCodeTest.java | 11 ++++---
...-08-21-organization-deep-linking-design.md | 4 +--
frontend/src/WorkspaceRouting.test.tsx | 29 ++++++++++---------
frontend/src/api/workspaces.test.ts | 12 ++++++++
frontend/src/api/workspaces.ts | 8 ++---
.../workspaces/WorkspaceWelcome.tsx | 6 ++--
10 files changed, 70 insertions(+), 39 deletions(-)
create mode 100644 backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql
create mode 100644 frontend/src/api/workspaces.test.ts
diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
index b25eb71..504a4f4 100644
--- a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
+++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
@@ -3,6 +3,7 @@
import java.security.SecureRandom;
import java.text.Normalizer;
import java.util.Arrays;
+import java.util.HexFormat;
import java.util.Locale;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -12,9 +13,9 @@
@Component
public class WorkspaceCode {
- private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
- private static final Pattern COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{9}$");
- private static final Pattern DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$");
+ private static final int TOKEN_BYTES = 16;
+ private static final Pattern SECURE_COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$");
+ private static final Pattern SECURE_DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$");
private final SecureRandom random;
@@ -36,11 +37,9 @@ public String generate(String organizationName) {
.collect(Collectors.joining());
String compactName = asciiName.replaceAll("[^A-Z0-9]", "");
String prefixSeed = sanitize(initials + compactName + "ORG");
- StringBuilder suffix = new StringBuilder(6);
- for (int index = 0; index < 6; index++) {
- suffix.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
- }
- return prefixSeed.substring(0, 3) + "-" + suffix;
+ byte[] token = new byte[TOKEN_BYTES];
+ random.nextBytes(token);
+ return prefixSeed.substring(0, 3) + "-" + HexFormat.of().withUpperCase().formatHex(token);
}
public static String normalize(String rawCode) {
@@ -48,10 +47,10 @@ public static String normalize(String rawCode) {
return null;
}
String candidate = rawCode.trim().toUpperCase(Locale.ROOT);
- if (COMPACT.matcher(candidate).matches()) {
+ if (SECURE_COMPACT.matcher(candidate).matches()) {
candidate = candidate.substring(0, 3) + "-" + candidate.substring(3);
}
- return DISPLAYED.matcher(candidate).matches() ? candidate : null;
+ return SECURE_DISPLAYED.matcher(candidate).matches() ? candidate : null;
}
private static String sanitize(String value) {
diff --git a/backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql b/backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql
new file mode 100644
index 0000000..1bdf17c
--- /dev/null
+++ b/backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql
@@ -0,0 +1,14 @@
+ALTER TABLE organizations
+ DROP CONSTRAINT IF EXISTS ck_organizations_public_code_format;
+
+ALTER TABLE organizations
+ ALTER COLUMN public_code TYPE VARCHAR(36);
+
+UPDATE organizations
+SET public_code = SUBSTRING(public_code FROM 1 FOR 3)
+ || '-'
+ || UPPER(MD5(gen_random_uuid()::TEXT || gen_random_uuid()::TEXT || id::TEXT));
+
+ALTER TABLE organizations
+ ADD CONSTRAINT ck_organizations_public_code_format
+ CHECK (public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$');
diff --git a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
index b8cb73c..1dafe0f 100644
--- a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
@@ -88,7 +88,7 @@ SELECT COUNT(*)
""").query(Integer.class).single();
assertThat(publicCodes).isNotEmpty()
- .allSatisfy(code -> assertThat(code).matches("[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}"));
+ .allSatisfy(code -> assertThat(code).matches("[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}"));
assertThat(publicCodes.stream().map(String::toUpperCase).distinct().count())
.isEqualTo(publicCodes.size());
assertThat(cloneColumnCount).isZero();
@@ -115,7 +115,7 @@ SELECT COUNT(*)
.query(Integer.class)
.single();
- assertThat(successfulMigrations).isEqualTo(8);
+ assertThat(successfulMigrations).isEqualTo(9);
var employeeNumberNullable = jdbcClient.sql("""
SELECT is_nullable
FROM information_schema.columns
diff --git a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
index 03f342f..05cdedf 100644
--- a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
@@ -60,7 +60,7 @@ void createsAndResolvesAnEditableDraftByPublicCode() throws Exception {
.andExpect(jsonPath("$.status").value("DRAFT"))
.andExpect(jsonPath("$.currentVersion").value(0))
.andExpect(jsonPath("$.publicCode")
- .value(org.hamcrest.Matchers.matchesPattern("NMS-[A-HJ-NP-Z2-9]{6}")))
+ .value(org.hamcrest.Matchers.matchesPattern("NMS-[A-F0-9]{32}")))
.andExpect(jsonPath("$.counts.members").value(0))
.andExpect(jsonPath("$.counts.workflows").value(0))
.andReturn();
diff --git a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
index 0deae69..9153f5f 100644
--- a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
@@ -10,20 +10,23 @@ class WorkspaceCodeTest {
@Test
void normalizesTypedCodesWithOrWithoutTheHyphen() {
- assertThat(WorkspaceCode.normalize(" nsm-7k4p9d ")).isEqualTo("NSM-7K4P9D");
- assertThat(WorkspaceCode.normalize("nsm7k4p9d")).isEqualTo("NSM-7K4P9D");
+ var displayed = "NSM-0123456789ABCDEF0123456789ABCDEF";
+
+ assertThat(WorkspaceCode.normalize(" " + displayed.toLowerCase() + " ")).isEqualTo(displayed);
+ assertThat(WorkspaceCode.normalize(displayed.replace("-", ""))).isEqualTo(displayed);
}
@Test
void rejectsMalformedOrAmbiguousCodes() {
assertThat(WorkspaceCode.normalize("NSM-7K4P0D")).isNull();
+ assertThat(WorkspaceCode.normalize("NSM-7K4P9D")).isNull();
assertThat(WorkspaceCode.normalize("not-a-code")).isNull();
}
@Test
- void generatesANamePrefixAndAllowedRandomSuffix() {
+ void generatesANamePrefixAndA128BitRandomSuffix() {
var code = new WorkspaceCode(new SecureRandom()).generate("Northstar Medical Supplies");
- assertThat(code).matches("NMS-[A-HJ-NP-Z2-9]{6}");
+ assertThat(code).matches("NMS-[A-F0-9]{32}");
}
}
diff --git a/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
index 08b9556..f3f5ae5 100644
--- a/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
+++ b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
@@ -1,6 +1,6 @@
# Organization Deep Linking and Recovery Design
-**Date:** 2026-08-21
+**Date:** 2026-08-21
**Status:** Approved in conversation; awaiting written-spec review
## Purpose
@@ -92,7 +92,7 @@ Code properties:
- short enough to type accurately;
- excludes visually ambiguous characters such as `0`, `O`, `1`, and `I`.
-Displayed codes use a three-letter name-derived prefix followed by six random Base32-style characters, for example `NSM-7K4P9D`. The name prefix is cosmetic and is not recalculated after rename. Uniqueness is enforced by the database, and the service retries generation on the unlikely event of a collision.
+Displayed codes use a three-letter name-derived prefix followed by a 128-bit random token, for example `NSM-0123456789ABCDEF0123456789ABCDEF`. The name prefix is cosmetic and is not recalculated after rename. The full code is an editable bearer capability, uniqueness is enforced by the database, and the service retries generation on the unlikely event of a collision.
The code is an unguessable locator, not authentication. The UI must state that real or sensitive company information should not be entered until authentication is added.
diff --git a/frontend/src/WorkspaceRouting.test.tsx b/frontend/src/WorkspaceRouting.test.tsx
index 4e45d0a..2be9b00 100644
--- a/frontend/src/WorkspaceRouting.test.tsx
+++ b/frontend/src/WorkspaceRouting.test.tsx
@@ -5,6 +5,9 @@ import { MemoryRouter } from 'react-router-dom'
import { afterEach, describe, expect, it, vi } from 'vitest'
import App from './App'
+const workspaceCode = 'NMS-0123456789ABCDEF0123456789ABCDEF'
+const compactWorkspaceCode = workspaceCode.replace('-', '')
+
afterEach(() => {
cleanup()
vi.restoreAllMocks()
@@ -26,16 +29,16 @@ describe('organization routing', () => {
mockWorkspaceRequests()
renderApp(['/'])
- await user.type(await screen.findByLabelText('Organization ID'), 'nms7k4p9d')
+ await user.type(await screen.findByLabelText('Organization ID'), compactWorkspaceCode.toLowerCase())
await user.click(screen.getByRole('button', { name: 'Open organization' }))
expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument()
- expect(screen.getByText('NMS-7K4P9D')).toBeInTheDocument()
+ expect(screen.getByText(workspaceCode)).toBeInTheDocument()
})
it('loads the inventory route directly', async () => {
mockWorkspaceRequests()
- renderApp(['/organizations/NMS-7K4P9D/inventory'])
+ renderApp([`/organizations/${workspaceCode}/inventory`])
expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument()
expect(await screen.findByRole('button', { name: 'Detailed inventory' })).toHaveAttribute('aria-pressed', 'true')
@@ -49,13 +52,13 @@ describe('organization routing', () => {
await user.type(await screen.findByLabelText('Organization ID'), 'bad-id')
await user.click(screen.getByRole('button', { name: 'Open organization' }))
- expect(screen.getByRole('alert')).toHaveTextContent('Enter an organization ID such as NMS-7K4P9D')
+ expect(screen.getByRole('alert')).toHaveTextContent('Paste the complete organization ID from your saved link')
expect(fetchMock.mock.calls.some(([input]) => input.toString().includes('/by-code/'))).toBe(false)
})
it('keeps an unknown organization route open and offers recovery actions', async () => {
mockWorkspaceRequests()
- renderApp(['/organizations/ABC-234567/map'])
+ renderApp(['/organizations/ABC-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF/map'])
expect(await screen.findByRole('heading', { name: 'Organization not found' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Try another organization ID' })).toBeInTheDocument()
@@ -65,15 +68,15 @@ describe('organization routing', () => {
it('loads the impact route directly without returning to the home page', async () => {
mockWorkspaceRequests()
- renderApp(['/organizations/NMS-7K4P9D/impact'])
+ renderApp([`/organizations/${workspaceCode}/impact`])
expect(await screen.findByRole('button', { name: 'Test impact' })).toHaveAttribute('aria-pressed', 'true')
expect(await screen.findByRole('heading', { name: 'Create one workflow first' })).toBeInTheDocument()
})
it.each([
- '/organizations/NMS-7K4P9D',
- '/organizations/NMS-7K4P9D/not-a-view',
+ `/organizations/${workspaceCode}`,
+ `/organizations/${workspaceCode}/not-a-view`,
])('redirects %s to the organization map', async (entry) => {
mockWorkspaceRequests()
renderApp([entry])
@@ -93,15 +96,15 @@ describe('organization routing', () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
mockWorkspaceRequests()
- renderApp(['/organizations/NMS-7K4P9D/inventory'])
+ renderApp([`/organizations/${workspaceCode}/inventory`])
await user.click(await screen.findByRole('button', { name: 'Copy organization ID' }))
await user.click(screen.getByRole('button', { name: 'Copy organization link' }))
- expect(writeText).toHaveBeenNthCalledWith(1, 'NMS-7K4P9D')
+ expect(writeText).toHaveBeenNthCalledWith(1, workspaceCode)
expect(writeText).toHaveBeenNthCalledWith(
2,
- `${window.location.origin}/organizations/NMS-7K4P9D/map`,
+ `${window.location.origin}/organizations/${workspaceCode}/map`,
)
expect(screen.queryByRole('heading', { name: 'Save this organization ID' })).not.toBeInTheDocument()
})
@@ -136,7 +139,7 @@ function mockWorkspaceRequests() {
const url = input.toString()
if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture)
if (url.endsWith('/api/v1/workspaces') && init?.method === 'POST') return jsonResponse(workspaceFixture, 201)
- if (url.endsWith('/api/v1/workspaces/by-code/NMS-7K4P9D')) return jsonResponse(workspaceFixture)
+ if (url.endsWith(`/api/v1/workspaces/by-code/${workspaceCode}`)) return jsonResponse(workspaceFixture)
if (url.endsWith('/catalog')) return jsonResponse(catalogFixture)
if (url.endsWith('/impact-previews/continuity')) return jsonResponse([])
return jsonResponse({ message: 'Organization not found' }, 404)
@@ -153,7 +156,7 @@ const workspaceFixture = {
name: 'Northstar Medical Supplies',
status: 'DRAFT',
currentVersion: 0,
- publicCode: 'NMS-7K4P9D',
+ publicCode: workspaceCode,
createdAt: '2026-08-21T12:00:00Z',
updatedAt: '2026-08-21T12:00:00Z',
counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 },
diff --git a/frontend/src/api/workspaces.test.ts b/frontend/src/api/workspaces.test.ts
new file mode 100644
index 0000000..c5106a4
--- /dev/null
+++ b/frontend/src/api/workspaces.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest'
+import { normalizeWorkspaceCode } from './workspaces'
+
+describe('normalizeWorkspaceCode', () => {
+ it('accepts a 128-bit organization edit code with or without its separator', () => {
+ const displayed = 'NMS-0123456789ABCDEF0123456789ABCDEF'
+
+ expect(normalizeWorkspaceCode(displayed.toLowerCase())).toBe(displayed)
+ expect(normalizeWorkspaceCode(displayed.replace('-', ''))).toBe(displayed)
+ expect(normalizeWorkspaceCode('NMS-7K4P9D')).toBeNull()
+ })
+})
diff --git a/frontend/src/api/workspaces.ts b/frontend/src/api/workspaces.ts
index 38d8c2b..893546b 100644
--- a/frontend/src/api/workspaces.ts
+++ b/frontend/src/api/workspaces.ts
@@ -26,14 +26,14 @@ const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? ''
export function normalizeWorkspaceCode(rawCode: string): string | null {
const candidate = rawCode.trim().toUpperCase()
- if (/^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$/.test(candidate)) return candidate
- if (!/^[A-HJ-NP-Z2-9]{9}$/.test(candidate)) return null
- return `${candidate.slice(0, 3)}-${candidate.slice(3)}`
+ if (/^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$/.test(candidate)) return candidate
+ if (/^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$/.test(candidate)) return `${candidate.slice(0, 3)}-${candidate.slice(3)}`
+ return null
}
export async function fetchWorkspaceByCode(rawCode: string, signal?: AbortSignal): Promise {
const code = normalizeWorkspaceCode(rawCode)
- if (!code) throw new Error('Enter an organization ID such as NMS-7K4P9D')
+ if (!code) throw new Error('Paste the complete organization ID from your saved link')
const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/by-code/${code}`, { signal })
return readResponse(response, 'Organization not found')
}
diff --git a/frontend/src/components/workspaces/WorkspaceWelcome.tsx b/frontend/src/components/workspaces/WorkspaceWelcome.tsx
index be8ce79..711b8b6 100644
--- a/frontend/src/components/workspaces/WorkspaceWelcome.tsx
+++ b/frontend/src/components/workspaces/WorkspaceWelcome.tsx
@@ -39,7 +39,7 @@ export default function WorkspaceWelcome() {
setCodeError(null)
const normalizedCode = normalizeWorkspaceCode(organizationCode)
if (!normalizedCode) {
- setCodeError('Enter an organization ID such as NMS-7K4P9D')
+ setCodeError('Paste the complete organization ID from your saved link')
return
}
openMutation.mutate(normalizedCode)
@@ -108,9 +108,9 @@ export default function WorkspaceWelcome() {
{
setOrganizationCode(event.target.value)
setCodeError(null)
From 33e2b14b7cf318a8f20d9151b7ffc0370d5a9acb Mon Sep 17 00:00:00 2001
From: Sourav Chandhok
Date: Sat, 22 Aug 2026 19:15:13 -0400
Subject: [PATCH 10/10] feat: update organization code format to support
shorter Base32-style tokens
---
.gitignore | 1 +
.../workspace/application/WorkspaceCode.java | 24 ++++++++++++-------
...llow_shorter_organization_public_codes.sql | 9 +++++++
.../CatalogMigrationIntegrationTest.java | 2 +-
.../workspace/WorkspaceIntegrationTest.java | 2 +-
.../application/WorkspaceCodeTest.java | 13 +++++++---
...-08-21-organization-deep-linking-design.md | 2 +-
frontend/src/api/workspaces.test.ts | 10 ++++++--
frontend/src/api/workspaces.ts | 2 ++
.../workspaces/WorkspaceWelcome.tsx | 2 +-
10 files changed, 49 insertions(+), 18 deletions(-)
create mode 100644 backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql
diff --git a/.gitignore b/.gitignore
index 5eddd35..b2b8378 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,4 @@ frontend/coverage/
.DS_Store
Thumbs.db
+.codex/config.toml
diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
index 504a4f4..32c682b 100644
--- a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
+++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java
@@ -3,7 +3,6 @@
import java.security.SecureRandom;
import java.text.Normalizer;
import java.util.Arrays;
-import java.util.HexFormat;
import java.util.Locale;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -13,9 +12,12 @@
@Component
public class WorkspaceCode {
- private static final int TOKEN_BYTES = 16;
- private static final Pattern SECURE_COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$");
- private static final Pattern SECURE_DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$");
+ private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
+ private static final int TOKEN_LENGTH = 16;
+ private static final Pattern SHORT_COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{19}$");
+ private static final Pattern SHORT_DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{16}$");
+ private static final Pattern LONG_COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$");
+ private static final Pattern LONG_DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$");
private final SecureRandom random;
@@ -37,9 +39,11 @@ public String generate(String organizationName) {
.collect(Collectors.joining());
String compactName = asciiName.replaceAll("[^A-Z0-9]", "");
String prefixSeed = sanitize(initials + compactName + "ORG");
- byte[] token = new byte[TOKEN_BYTES];
- random.nextBytes(token);
- return prefixSeed.substring(0, 3) + "-" + HexFormat.of().withUpperCase().formatHex(token);
+ StringBuilder token = new StringBuilder(TOKEN_LENGTH);
+ for (int index = 0; index < TOKEN_LENGTH; index++) {
+ token.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
+ }
+ return prefixSeed.substring(0, 3) + "-" + token;
}
public static String normalize(String rawCode) {
@@ -47,10 +51,12 @@ public static String normalize(String rawCode) {
return null;
}
String candidate = rawCode.trim().toUpperCase(Locale.ROOT);
- if (SECURE_COMPACT.matcher(candidate).matches()) {
+ if (SHORT_COMPACT.matcher(candidate).matches() || LONG_COMPACT.matcher(candidate).matches()) {
candidate = candidate.substring(0, 3) + "-" + candidate.substring(3);
}
- return SECURE_DISPLAYED.matcher(candidate).matches() ? candidate : null;
+ return SHORT_DISPLAYED.matcher(candidate).matches() || LONG_DISPLAYED.matcher(candidate).matches()
+ ? candidate
+ : null;
}
private static String sanitize(String value) {
diff --git a/backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql b/backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql
new file mode 100644
index 0000000..8057daa
--- /dev/null
+++ b/backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql
@@ -0,0 +1,9 @@
+ALTER TABLE organizations
+ DROP CONSTRAINT IF EXISTS ck_organizations_public_code_format;
+
+ALTER TABLE organizations
+ ADD CONSTRAINT ck_organizations_public_code_format
+ CHECK (
+ public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{16}$'
+ OR public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$'
+ );
diff --git a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
index 1dafe0f..d84d9ff 100644
--- a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java
@@ -115,7 +115,7 @@ SELECT COUNT(*)
.query(Integer.class)
.single();
- assertThat(successfulMigrations).isEqualTo(9);
+ assertThat(successfulMigrations).isEqualTo(10);
var employeeNumberNullable = jdbcClient.sql("""
SELECT is_nullable
FROM information_schema.columns
diff --git a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
index 05cdedf..5000eaf 100644
--- a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java
@@ -60,7 +60,7 @@ void createsAndResolvesAnEditableDraftByPublicCode() throws Exception {
.andExpect(jsonPath("$.status").value("DRAFT"))
.andExpect(jsonPath("$.currentVersion").value(0))
.andExpect(jsonPath("$.publicCode")
- .value(org.hamcrest.Matchers.matchesPattern("NMS-[A-F0-9]{32}")))
+ .value(org.hamcrest.Matchers.matchesPattern("NMS-[A-HJ-NP-Z2-9]{16}")))
.andExpect(jsonPath("$.counts.members").value(0))
.andExpect(jsonPath("$.counts.workflows").value(0))
.andReturn();
diff --git a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
index 9153f5f..929bd4f 100644
--- a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
+++ b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java
@@ -10,12 +10,19 @@ class WorkspaceCodeTest {
@Test
void normalizesTypedCodesWithOrWithoutTheHyphen() {
- var displayed = "NSM-0123456789ABCDEF0123456789ABCDEF";
+ var displayed = "NSM-7K4P9D8XM2QR6WBC";
assertThat(WorkspaceCode.normalize(" " + displayed.toLowerCase() + " ")).isEqualTo(displayed);
assertThat(WorkspaceCode.normalize(displayed.replace("-", ""))).isEqualTo(displayed);
}
+ @Test
+ void keepsExistingLongCodesValid() {
+ var existing = "NSM-0123456789ABCDEF0123456789ABCDEF";
+
+ assertThat(WorkspaceCode.normalize(existing)).isEqualTo(existing);
+ }
+
@Test
void rejectsMalformedOrAmbiguousCodes() {
assertThat(WorkspaceCode.normalize("NSM-7K4P0D")).isNull();
@@ -24,9 +31,9 @@ void rejectsMalformedOrAmbiguousCodes() {
}
@Test
- void generatesANamePrefixAndA128BitRandomSuffix() {
+ void generatesANamePrefixAndAn80BitRandomSuffix() {
var code = new WorkspaceCode(new SecureRandom()).generate("Northstar Medical Supplies");
- assertThat(code).matches("NMS-[A-F0-9]{32}");
+ assertThat(code).matches("NMS-[A-HJ-NP-Z2-9]{16}");
}
}
diff --git a/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
index f3f5ae5..fd9843b 100644
--- a/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
+++ b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md
@@ -92,7 +92,7 @@ Code properties:
- short enough to type accurately;
- excludes visually ambiguous characters such as `0`, `O`, `1`, and `I`.
-Displayed codes use a three-letter name-derived prefix followed by a 128-bit random token, for example `NSM-0123456789ABCDEF0123456789ABCDEF`. The name prefix is cosmetic and is not recalculated after rename. The full code is an editable bearer capability, uniqueness is enforced by the database, and the service retries generation on the unlikely event of a collision.
+New codes use a three-letter name-derived prefix followed by a 16-character Base32-style random token (80 bits), for example `NSM-7K4P9D8XM2QR6WBC`. The name prefix is cosmetic and is not recalculated after rename. Existing 32-character IDs remain valid and unchanged until the development database is cleared. The full code is an editable bearer capability, uniqueness is enforced by the database, and the service retries generation on the unlikely event of a collision.
The code is an unguessable locator, not authentication. The UI must state that real or sensitive company information should not be entered until authentication is added.
diff --git a/frontend/src/api/workspaces.test.ts b/frontend/src/api/workspaces.test.ts
index c5106a4..46f130a 100644
--- a/frontend/src/api/workspaces.test.ts
+++ b/frontend/src/api/workspaces.test.ts
@@ -2,11 +2,17 @@ import { describe, expect, it } from 'vitest'
import { normalizeWorkspaceCode } from './workspaces'
describe('normalizeWorkspaceCode', () => {
- it('accepts a 128-bit organization edit code with or without its separator', () => {
- const displayed = 'NMS-0123456789ABCDEF0123456789ABCDEF'
+ it('accepts a 16-character organization edit code with or without its separator', () => {
+ const displayed = 'NMS-7K4P9D8XM2QR6WBC'
expect(normalizeWorkspaceCode(displayed.toLowerCase())).toBe(displayed)
expect(normalizeWorkspaceCode(displayed.replace('-', ''))).toBe(displayed)
expect(normalizeWorkspaceCode('NMS-7K4P9D')).toBeNull()
})
+
+ it('keeps existing 32-character organization IDs valid', () => {
+ const existing = 'NMS-0123456789ABCDEF0123456789ABCDEF'
+
+ expect(normalizeWorkspaceCode(existing)).toBe(existing)
+ })
})
diff --git a/frontend/src/api/workspaces.ts b/frontend/src/api/workspaces.ts
index 893546b..f1c9aac 100644
--- a/frontend/src/api/workspaces.ts
+++ b/frontend/src/api/workspaces.ts
@@ -26,6 +26,8 @@ const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? ''
export function normalizeWorkspaceCode(rawCode: string): string | null {
const candidate = rawCode.trim().toUpperCase()
+ if (/^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{16}$/.test(candidate)) return candidate
+ if (/^[A-HJ-NP-Z2-9]{19}$/.test(candidate)) return `${candidate.slice(0, 3)}-${candidate.slice(3)}`
if (/^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$/.test(candidate)) return candidate
if (/^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$/.test(candidate)) return `${candidate.slice(0, 3)}-${candidate.slice(3)}`
return null
diff --git a/frontend/src/components/workspaces/WorkspaceWelcome.tsx b/frontend/src/components/workspaces/WorkspaceWelcome.tsx
index 711b8b6..bb219b9 100644
--- a/frontend/src/components/workspaces/WorkspaceWelcome.tsx
+++ b/frontend/src/components/workspaces/WorkspaceWelcome.tsx
@@ -110,7 +110,7 @@ export default function WorkspaceWelcome() {
value={organizationCode}
maxLength={36}
autoCapitalize="characters"
- placeholder="NMS-0123456789ABCDEF0123456789ABCDEF"
+ placeholder="NMS-7K4P9D8XM2QR6WBC"
onChange={(event) => {
setOrganizationCode(event.target.value)
setCodeError(null)