Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions apps/api/src/isms/documents/generate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ function buildTx() {
ismsInterestedParty: registerTable(),
ismsInterestedPartyRequirement: registerTable(),
ismsObjective: registerTable(),
ismsDocument: { findFirst: jest.fn().mockResolvedValue(null) },
ismsDocumentVersion: {
ismsDocument: {
findFirst: jest.fn().mockResolvedValue(null),
create: jest.fn().mockResolvedValue({}),
// CS-701: the draft narrative lives on IsmsDocument, not a version row.
findUnique: jest.fn().mockResolvedValue(null),
update: jest.fn().mockResolvedValue({}),
},
};
Expand Down Expand Up @@ -132,24 +132,27 @@ describe('runDerivation', () => {
expect(tx.ismsObjective.createMany).toHaveBeenCalled();
});

it('creates a version with the derived narrative for isms_scope', async () => {
it('writes the derived narrative onto an empty document draft (isms_scope)', async () => {
const tx = buildTx();
await runDerivation({ tx: asTx(tx), type: 'isms_scope', ...baseArgs });
expect(tx.ismsDocumentVersion.create).toHaveBeenCalled();
const created = tx.ismsDocumentVersion.create.mock.calls[0][0].data;
expect(created.narrative.certificateScopeSentence).toBeDefined();
expect(tx.ismsDocument.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: 'doc_1' } }),
);
const updated = tx.ismsDocument.update.mock.calls[0][0].data;
expect(updated.draftNarrative.certificateScopeSentence).toBeDefined();
});

it('updates the existing version narrative for leadership', async () => {
it('preserves a non-empty existing draft narrative (CS-437 override)', async () => {
const tx = buildTx();
tx.ismsDocumentVersion.findFirst.mockResolvedValue({ id: 'ver_1' });
tx.ismsDocument.findUnique.mockResolvedValue({
draftNarrative: { certificateScopeSentence: 'Manual edit' },
});
await runDerivation({
tx: asTx(tx),
type: 'leadership_commitment',
...baseArgs,
});
expect(tx.ismsDocumentVersion.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: 'ver_1' } }),
);
// A regenerate must never clobber the customer's manual narrative.
expect(tx.ismsDocument.update).not.toHaveBeenCalled();
});
});
25 changes: 10 additions & 15 deletions apps/api/src/isms/documents/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,22 +174,17 @@ async function generateNarrative({
if (!derived) return;
const narrative: Prisma.InputJsonValue = JSON.parse(JSON.stringify(derived));

const latest = await tx.ismsDocumentVersion.findFirst({
where: { documentId, isLatest: true },
// The draft narrative lives on IsmsDocument (CS-701). Preserve a non-empty
// existing draft so a regenerate never clobbers the customer's manual edits
// (CS-437 override); seed an absent/empty draft with the derived narrative.
const document = await tx.ismsDocument.findUnique({
where: { id: documentId },
select: { draftNarrative: true },
});
if (latest) {
// Preserve a non-empty narrative so a regenerate never clobbers the
// customer's manual edits (CS-437 override). An absent or empty ({}) value —
// e.g. a snapshot-only version — is still seeded with the derived narrative.
if (hasNarrativeContent(latest.narrative)) return;
await tx.ismsDocumentVersion.update({
where: { id: latest.id },
data: { narrative },
});
return;
}
await tx.ismsDocumentVersion.create({
data: { documentId, version: 1, isLatest: true, narrative },
if (document && hasNarrativeContent(document.draftNarrative)) return;
await tx.ismsDocument.update({

@cubic-dev-ai cubic-dev-ai Bot Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Regenerating an already approved narrative document can change the working draft without marking the document as draft, so the UI/API may still report the existing approval while draft content has changed. Consider invalidating approval in the regenerate path when draftNarrative is written, matching IsmsNarrativeService.save.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/isms/documents/generate.ts, line 185:

<comment>Regenerating an already approved narrative document can change the working draft without marking the document as draft, so the UI/API may still report the existing approval while draft content has changed. Consider invalidating approval in the regenerate path when `draftNarrative` is written, matching `IsmsNarrativeService.save`.</comment>

<file context>
@@ -174,22 +174,17 @@ async function generateNarrative({
-  await tx.ismsDocumentVersion.create({
-    data: { documentId, version: 1, isLatest: true, narrative },
+  if (document && hasNarrativeContent(document.draftNarrative)) return;
+  await tx.ismsDocument.update({
+    where: { id: documentId },
+    data: { draftNarrative: narrative },
</file context>
Fix with cubic

where: { id: documentId },
data: { draftNarrative: narrative },
});
}

Expand Down
14 changes: 11 additions & 3 deletions apps/api/src/isms/documents/org-profile.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { db } from '@db';
import type { Prisma } from '@db';
import { DEFAULT_INTENDED_OUTCOMES } from '../wizard/wizard-defaults';
import { parseStoredAnswers } from '../wizard/wizard-schema';
import type { IsmsKeyValue } from '../utils/export-shared';
Expand Down Expand Up @@ -29,23 +30,30 @@ const QUESTIONS = {
export async function loadOrgProfile({
organizationId,
frameworkId,
client = db,
}: {
organizationId: string;
frameworkId: string;
/**
* DB client to read through. Defaults to the global `db`; the approve flow
* passes its transaction client so the snapshot's org profile reads share the
* same isolation context as the register rows written in the same transaction.
*/
client?: Prisma.TransactionClient;
}): Promise<IsmsOrgProfile> {
const [organization, contextEntries, profile] = await Promise.all([
db.organization.findUnique({
client.organization.findUnique({
where: { id: organizationId },
select: { name: true, website: true },
}),
db.context.findMany({
client.context.findMany({
where: { organizationId },
// Deterministic ordering so duplicate questions resolve to the same answer
// every export; the earliest-created entry wins (id breaks createdAt ties).
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
select: { question: true, answer: true },
}),
db.ismsProfile.findUnique({
client.ismsProfile.findUnique({
where: { organizationId_frameworkId: { organizationId, frameworkId } },
select: { answers: true },
}),
Expand Down
13 changes: 11 additions & 2 deletions apps/api/src/isms/dto/export-isms-document.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsIn } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsIn, IsOptional, IsString } from 'class-validator';

export class ExportIsmsDocumentDto {
@ApiProperty({
Expand All @@ -9,4 +9,13 @@ export class ExportIsmsDocumentDto {
})
@IsIn(['pdf', 'docx'])
format!: 'pdf' | 'docx';

@ApiPropertyOptional({
description:
'Published version to export. Omit to export the current working draft; ' +
'provide a version id to download exactly what was approved at that version.',
})
@IsOptional()
@IsString()
versionId?: string;
}
Loading
Loading