dsh-spec-collab 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ import { type PreparedSpecCommit } from './git-store.ts';
2
+ import { type CollaborationState } from './protocol.ts';
3
+ export declare class CollaborationLedger {
4
+ private readonly path;
5
+ private readonly publishSpec;
6
+ private readonly legacyPath?;
7
+ private readonly pendingPath;
8
+ constructor(path: string, publishSpec: (change: PreparedSpecCommit) => void, legacyPath?: string | undefined);
9
+ save(state: CollaborationState, spec?: PreparedSpecCommit): void;
10
+ load(): CollaborationState;
11
+ private recover;
12
+ private finish;
13
+ }
14
+ //# sourceMappingURL=collaboration-ledger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collaboration-ledger.d.ts","sourceRoot":"","sources":["../../src/collaboration-ledger.ts"],"names":[],"mappings":"AAGA,OAAO,EAAwB,KAAK,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AAE9E,OAAO,EAAkB,KAAK,kBAAkB,EAAoD,MAAM,eAAe,CAAA;AAEzH,qBAAa,mBAAmB;IAGlB,OAAO,CAAC,QAAQ,CAAC,IAAI;IAAU,OAAO,CAAC,QAAQ,CAAC,WAAW;IAAwC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;IAF3I,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;gBAEP,IAAI,EAAE,MAAM,EAAmB,WAAW,EAAE,CAAC,MAAM,EAAE,kBAAkB,KAAK,IAAI,EAAmB,UAAU,CAAC,EAAE,MAAM,YAAA;IAInJ,IAAI,CAAC,KAAK,EAAE,kBAAkB,EAAE,IAAI,CAAC,EAAE,kBAAkB,GAAG,IAAI;IAehE,IAAI,IAAI,kBAAkB;IAsB1B,OAAO,CAAC,OAAO;IAqBf,OAAO,CAAC,MAAM;CAKf"}
@@ -1,5 +1,7 @@
1
1
  import { GitRequirementStore } from './git-store.ts';
2
- import { type ActionResult, type AiReviewRun, type CollaborationAction, type CollaborationEvent, type CollaborationState, type CommentThread, type Insight, type InsightImportance, type MyActionItem, type MyItemCategory, type Notification, type ParticipantSnapshot, type ReadinessCheck, type RequirementRecord, type RequirementSummary, type RequirementVersion, type RequirementView, type ReviewItem, type ReviewKind, type StructuredDiff } from './protocol.ts';
2
+ import { type InsightPage, type InsightQuery } from './insights.ts';
3
+ import { type ActionResult, type AiReviewRun, type CollaborationAction, type CollaborationEvent, type CollaborationState, type CommentThread, type MyActionItem, type MyItemCategory, type Notification, type ParticipantSnapshot, type RequirementSummary, type RequirementVersion, type RequirementView, type ReviewItem, type ReviewKind, type StructuredDiff } from './protocol.ts';
4
+ export { readiness } from './spec-lifecycle.ts';
3
5
  export interface AiCoordinator {
4
6
  requestReview(input: {
5
7
  requirement: RequirementView;
@@ -12,43 +14,31 @@ export interface AiCoordinator {
12
14
  sessionId?: string;
13
15
  }): Promise<string>;
14
16
  }
15
- type EngineResult = ActionResult;
16
17
  export declare class CollaborationEngine {
17
- private readonly eventPath;
18
18
  private readonly versions;
19
- private readonly options;
20
19
  private state;
20
+ private readonly ledger;
21
21
  private coordinator?;
22
22
  private readonly listeners;
23
23
  private readonly seen;
24
- private eventContext;
25
24
  constructor(eventPath: string, versions: GitRequirementStore, options?: {
26
25
  legacyPath?: string;
27
26
  });
28
27
  setCoordinator(coordinator: AiCoordinator): void;
28
+ get revision(): number;
29
29
  snapshot(): CollaborationState;
30
+ overview(): {
31
+ revision: number;
32
+ participants: ParticipantSnapshot[];
33
+ requirements: RequirementSummary[];
34
+ };
30
35
  directory(): ParticipantSnapshot[];
31
36
  notifications(participantId: string, page?: number, pageSize?: number): {
32
37
  items: Notification[];
33
38
  total: number;
34
39
  unread: number;
35
40
  };
36
- insights(query?: {
37
- requirementId?: string;
38
- customerId?: string;
39
- companyId?: string;
40
- sourceId?: string;
41
- importance?: InsightImportance;
42
- page?: number;
43
- pageSize?: number;
44
- }): {
45
- items: Insight[];
46
- total: number;
47
- links: CollaborationState['insightLinks'];
48
- customers: CollaborationState['customers'];
49
- companies: CollaborationState['companies'];
50
- sources: CollaborationState['feedbackSources'];
51
- };
41
+ insights(query?: InsightQuery): InsightPage;
52
42
  subscribe(listener: (event: CollaborationEvent) => void): () => void;
53
43
  list(): RequirementView[];
54
44
  summaries(): RequirementSummary[];
@@ -57,7 +47,7 @@ export declare class CollaborationEngine {
57
47
  myItems(participant: ParticipantSnapshot, category?: MyItemCategory): MyActionItem[];
58
48
  hasAiSession(requirementId: string, sessionId: string): boolean;
59
49
  view(id: string): RequirementView;
60
- apply(requestId: string, action: CollaborationAction): EngineResult;
50
+ apply(requestId: string, action: CollaborationAction): ActionResult;
61
51
  submitReview(input: {
62
52
  requirementId: string;
63
53
  commit: string;
@@ -85,17 +75,17 @@ export declare class CollaborationEngine {
85
75
  }): void;
86
76
  markAiFailure(requirementId: string, sourceId: string, error: string): void;
87
77
  private applyFresh;
88
- private createInsight;
89
- private addInsightLink;
78
+ private changeVersion;
90
79
  private rememberStageConversation;
91
80
  private notify;
92
81
  private saveConflict;
93
- private enqueueReview;
82
+ private queueReview;
83
+ private launchAiTask;
84
+ private recordAiSession;
85
+ private changeAi;
86
+ private transact;
87
+ private emit;
94
88
  private record;
95
89
  private comment;
96
- private persist;
97
- private load;
98
90
  }
99
- export declare function readiness(markdown: string, record: RequirementRecord): ReadinessCheck[];
100
- export {};
101
91
  //# sourceMappingURL=engine.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAAwB,MAAM,gBAAgB,CAAA;AAC1E,OAAO,EAAmC,KAAK,YAAY,EAAE,KAAK,WAAW,EAAuB,KAAK,mBAAmB,EAAE,KAAK,kBAAkB,EAAE,KAAK,kBAAkB,EAAE,KAAK,aAAa,EAAuB,KAAK,OAAO,EAAE,KAAK,iBAAiB,EAAoB,KAAK,YAAY,EAAE,KAAK,cAAc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AY;IAmBpB,OAAO,CAAC,eAAe;IAuBvB,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,QAAQ;IAmBhB,OAAO,CAAC,IAAI;IAQZ,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;CAChB"}
@@ -16,11 +16,17 @@ export interface SaveVersionInput {
16
16
  participant: ParticipantSnapshot;
17
17
  summary: string;
18
18
  }
19
+ export interface PreparedSpecCommit {
20
+ requirementId: string;
21
+ operation: 'create' | 'update' | 'delete';
22
+ baseHead?: string;
23
+ commit: string;
24
+ }
25
+ type VersionMetadata = Omit<RequirementVersion, 'markdown'>;
19
26
  export declare class GitRequirementStore {
20
27
  readonly root: string;
21
- private readonly versionCache;
22
- private readonly headCache;
23
28
  private readonly historyCache;
29
+ private readonly versionCache;
24
30
  private commitBaseUrl;
25
31
  constructor(root: string);
26
32
  create(input: CreateRequirementInput): {
@@ -28,19 +34,27 @@ export declare class GitRequirementStore {
28
34
  version: RequirementVersion;
29
35
  };
30
36
  save(input: SaveVersionInput): RequirementVersion;
37
+ remove(requirementId: string, participant: ParticipantSnapshot): void;
38
+ prepareCreate(input: CreateRequirementInput): PreparedSpecCommit;
39
+ prepareSave(input: SaveVersionInput): PreparedSpecCommit;
40
+ prepareRemove(requirementId: string, baseCommit: string, participant: ParticipantSnapshot): PreparedSpecCommit;
41
+ /** Publish a prepared commit and synchronize its one owned path. Safe to repeat after interruption. */
42
+ publish(change: PreparedSpecCommit): void;
31
43
  read(requirementId: string, commit?: string): RequirementVersion;
32
- history(requirementId: string): Array<Omit<RequirementVersion, 'markdown'>>;
44
+ history(requirementId: string, head?: string | undefined): VersionMetadata[];
33
45
  diff(requirementId: string, baseCommit: string, headCommit?: string): string;
34
46
  commitUrl(commit: string): string | undefined;
35
- remove(requirementId: string, participant: ParticipantSnapshot): void;
36
47
  head(requirementId: string): string;
37
- private commit;
38
- private commitStaged;
39
- private rememberCommittedVersion;
40
- private ensureRepository;
48
+ private requirementHead;
49
+ private assertCurrent;
50
+ private prepareCommit;
51
+ private assertClean;
52
+ private assertRecoverableCheckout;
53
+ private repositoryHead;
54
+ private body;
41
55
  private relativeSpecPath;
42
- private specPath;
43
- private gitText;
44
56
  private git;
45
57
  }
58
+ export declare function isPreparedSpecCommit(value: unknown): value is PreparedSpecCommit;
59
+ export {};
46
60
  //# sourceMappingURL=git-store.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"git-store.d.ts","sourceRoot":"","sources":["../../src/git-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAE7F,qBAAa,oBAAqB,SAAQ,KAAK;IACjC,QAAQ,CAAC,aAAa,EAAE,MAAM;gBAArB,aAAa,EAAE,MAAM;CAC3C;AAED,MAAM,WAAW,sBAAsB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,eAAe,EAAE,CAAC;IAAC,WAAW,EAAE,mBAAmB,CAAA;CAAE;AAC/I,MAAM,WAAW,gBAAgB;IAAG,aAAa,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,mBAAmB,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AAEpJ,qBAAa,mBAAmB;IAMlB,QAAQ,CAAC,IAAI,EAAE,MAAM;IALjC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAwC;IACrE,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA4B;IACtD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAiE;IAC9F,OAAO,CAAC,aAAa,CAA2B;gBAE3B,IAAI,EAAE,MAAM;IAEjC,MAAM,CAAC,KAAK,EAAE,sBAAsB,GAAG;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,kBAAkB,CAAA;KAAE;IAkB7F,IA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AAe,EAAE;IAY/E,IAAI,CAAC,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,SAA2B,GAAG,MAAM;IAM9F,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAiB7C,IAAI,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM;IAInC,OAAO,CAAC,eAAe;IAKvB,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,aAAa;IA0BrB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,yBAAyB;IAmBjC,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,IAAI;IAKZ,OAAO,CAAC,gBAAgB;IAKxB,OAAO,CAAC,GAAG;CAGZ;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,kBAAkB,CAOhF"}
@@ -0,0 +1,29 @@
1
+ import type { CollaborationAction, CollaborationState, FeedbackSource, Insight, InsightImportance, InsightLink, RequirementMetrics } from './protocol.ts';
2
+ export declare function safeHttpUrl(value: string | undefined): boolean;
3
+ export declare function insightHash(sourceId: string, body: string): string;
4
+ export interface InsightQuery {
5
+ requirementId?: string;
6
+ customerId?: string;
7
+ companyId?: string;
8
+ sourceId?: string;
9
+ importance?: InsightImportance;
10
+ page?: number;
11
+ pageSize?: number;
12
+ }
13
+ export interface InsightPage {
14
+ items: Insight[];
15
+ total: number;
16
+ links: InsightLink[];
17
+ customers: CollaborationState['customers'];
18
+ companies: CollaborationState['companies'];
19
+ sources: FeedbackSource[];
20
+ }
21
+ export declare function queryInsights(state: CollaborationState, query?: InsightQuery): InsightPage;
22
+ export declare function insightMetrics(state: CollaborationState, requirementId: string): Pick<RequirementMetrics, 'insightCount' | 'customerImportanceScore' | 'customerCount' | 'companyCount' | 'anonymousInsightCount'>;
23
+ type InsightAction = Extract<CollaborationAction, {
24
+ kind: 'source.upsert' | 'company.upsert' | 'customer.upsert' | `insight.${string}`;
25
+ }>;
26
+ export declare function isInsightAction(action: CollaborationAction): action is InsightAction;
27
+ export declare function applyInsightAction(state: CollaborationState, action: InsightAction, now: number): void;
28
+ export {};
29
+ //# sourceMappingURL=insights.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"insights.d.ts","sourceRoot":"","sources":["../../src/insights.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,cAAc,EAAE,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAuB,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAE9K,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAG9D;AAsBD,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAA+I;AASlN,MAAM,WAAW,YAAY;IAC3B,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,UAAU,CAAC,EAAE,iBAAiB,CAAA;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,WAAW,EAAE,CAAA;IACpB,SAAS,EAAE,kBAAkB,CAAC,WAAW,CAAC,CAAA;IAC1C,SAAS,EAAE,kBAAkB,CAAC,WAAW,CAAC,CAAA;IAC1C,OAAO,EAAE,cAAc,EAAE,CAAA;CAC1B;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,kBAAkB,EAAE,KAAK,GAAE,YAAiB,GAAG,WAAW,CAM9F;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC,kBAAkB,EAAE,cAAc,GAAG,yBAAyB,GAAG,eAAe,GAAG,cAAc,GAAG,uBAAuB,CAAC,CAiBlN;AAGD,KAAK,aAAa,GAAG,OAAO,CAAC,mBAAmB,EAAE;IAAE,IAAI,EAAE,eAAe,GAAG,gBAAgB,GAAG,iBAAiB,GAAG,WAAW,MAAM,EAAE,CAAA;CAAE,CAAC,CAAA;AAEzI,wBAAgB,eAAe,CAAC,MAAM,EAAE,mBAAmB,GAAG,MAAM,IAAI,aAAa,CAEpF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,kBAAkB,EAAE,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAoDtG"}
@@ -1,5 +1,6 @@
1
1
  import type { ParticipantRole, ReadinessCheck, RequirementRecord, ReviewKind } from './protocol.ts';
2
2
  export declare function hasCompletedCurrentReview(record: Pick<RequirementRecord, 'aiRuns' | 'currentCommit'>, kind: ReviewKind): boolean;
3
+ export declare function currentVersionConfirmations(record: Pick<RequirementRecord, 'confirmations' | 'currentCommit'>, role: ParticipantRole): import("./protocol.ts").Confirmation[];
3
4
  export declare function hasVersionConfirmation(record: Pick<RequirementRecord, 'confirmations' | 'currentCommit'>, role: ParticipantRole): boolean;
4
5
  /** Shared by workflow guidance and the authoritative Ready write. Checks must come from the current Git body. */
5
6
  export declare function readyAdmission(record: RequirementRecord, checks: ReadinessCheck[]): {
@@ -1 +1 @@
1
- {"version":3,"file":"ready-admission.d.ts","sourceRoot":"","sources":["../../src/ready-admission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAEnG,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAGhI;AAED,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAEzI;AAED,iHAAiH;AACjH,wBAAgB,cAAc,CAAC,MAAM,EAAE,iBAAiB,EAAE,MAAM,EAAE,cAAc,EAAE;;;;;;;;EAgBjF"}
1
+ {"version":3,"file":"ready-admission.d.ts","sourceRoot":"","sources":["../../src/ready-admission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAEnG,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAGhI;AAED,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,eAAe,0CAEpI;AAED,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAEzI;AAED,iHAAiH;AACjH,wBAAgB,cAAc,CAAC,MAAM,EAAE,iBAAiB,EAAE,MAAM,EAAE,cAAc,EAAE;;;;;;;;EAgBjF"}
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/routes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAA;AAC/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAGtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAQ/D,wBAAgB,UAAU,CAAC,MAAM,EAAE,mBAAmB,EAAE,WAAW,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAmErG"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/routes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAA;AAC/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAGtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAQ/D,wBAAgB,UAAU,CAAC,MAAM,EAAE,mBAAmB,EAAE,WAAW,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAqErG"}
@@ -0,0 +1,18 @@
1
+ import type { ActionItem, CollaborationAction, ParticipantSnapshot, ReadinessCheck, RequirementRecord } from './protocol.ts';
2
+ type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, {
3
+ kind: 'decision.create';
4
+ }>['sourceAnchors']>[number];
5
+ export declare function enterStage(record: RequirementRecord, stage: RequirementRecord['stage']): void;
6
+ export declare function advance(record: RequirementRecord, participant: ParticipantSnapshot): void;
7
+ export declare function normalizeAnchorText(value: string): string;
8
+ export declare function decisionScopeAnchors(markdown: string, affectedSections: string[], affectedAcceptanceIds: string[]): DecisionSourceAnchor[];
9
+ export declare function invalidateAffected(record: RequirementRecord, changedSections: string[], changedAcceptanceIds: string[], currentMarkdown?: string): void;
10
+ export declare function readiness(markdown: string, record: RequirementRecord): ReadinessCheck[];
11
+ export declare function versionChanged(record: RequirementRecord, previousMarkdown: string, version: {
12
+ commit: string;
13
+ markdown: string;
14
+ }, now: number): void;
15
+ export declare function retireActionItems(record: RequirementRecord, sourceType: ActionItem['sourceType'], sourceId: string, status: 'handled' | 'invalidated', now: number): void;
16
+ export declare function readyMarkdown(record: RequirementRecord, markdown: string): string;
17
+ export {};
18
+ //# sourceMappingURL=spec-lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spec-lifecycle.d.ts","sourceRoot":"","sources":["../../src/spec-lifecycle.ts"],"names":[],"mapp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C,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,GAAG,aAAa,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAOzK;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAgBjF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-spec-collab",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "AI-assisted requirement clarification and Git-backed Spec co-creation for DeepSeek Harness, ending at a human-confirmed Ready Spec.",
5
5
  "keywords": [
6
6
  "deepseek-harness",
@@ -0,0 +1,168 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { basename, dirname, extname, join } from 'node:path'
4
+ import { isPreparedSpecCommit, type PreparedSpecCommit } from './git-store.ts'
5
+ import { insightHash, safeHttpUrl } from './insights.ts'
6
+ import { SCHEMA_VERSION, type CollaborationState, type ParticipantSnapshot, type RequirementRecord } from './protocol.ts'
7
+
8
+ export class CollaborationLedger {
9
+ private readonly pendingPath: string
10
+
11
+ constructor(private readonly path: string, private readonly publishSpec: (change: PreparedSpecCommit) => void, private readonly legacyPath?: string) {
12
+ this.pendingPath = `${path}.pending`
13
+ }
14
+
15
+ save(state: CollaborationState, spec?: PreparedSpecCommit): void {
16
+ if (existsSync(this.pendingPath)) throw new Error('collaboration transaction requires recovery before further writes')
17
+ if (spec === undefined) {
18
+ atomicWrite(this.path, state)
19
+ return
20
+ }
21
+ // Persist the intended ledger before the Git ref or worktree can move.
22
+ atomicWrite(this.pendingPath, { state, spec })
23
+ try {
24
+ this.finish(state, spec)
25
+ } catch (error) {
26
+ throw new Error(`collaboration transaction requires recovery: ${errorMessage(error)}`, { cause: error })
27
+ }
28
+ }
29
+
30
+ load(): CollaborationState {
31
+ if (existsSync(this.pendingPath)) return this.recover()
32
+ const source = existsSync(this.path) ? this.path : this.legacyPath
33
+ if (source === undefined || !existsSync(source)) return emptyState()
34
+ let parsed: unknown
35
+ try { parsed = JSON.parse(readFileSync(source, 'utf8')) }
36
+ catch (error) { throw new Error(`collaboration ledger is corrupted: ${errorMessage(error)}`, { cause: error }) }
37
+ if (!isRecord(parsed) || typeof parsed.schemaVersion !== 'number') throw new Error('collaboration ledger has no schema version')
38
+ if (parsed.schemaVersion === SCHEMA_VERSION) {
39
+ validateV3Ledger(parsed)
40
+ return normalizeV3(parsed)
41
+ }
42
+ if (parsed.schemaVersion !== 2) throw new Error(`unsupported collaboration schema: ${parsed.schemaVersion}`)
43
+ validateV2Ledger(parsed)
44
+ const migrated = migrateV2(parsed)
45
+ const extension = extname(source)
46
+ const stem = basename(source, extension).replace(/-v2$/, '')
47
+ copyFileSync(source, join(dirname(source), `${stem}-v2.backup-${Date.now()}${extension || '.json'}`))
48
+ atomicWrite(this.path, migrated)
49
+ return migrated
50
+ }
51
+
52
+ private recover(): CollaborationState {
53
+ let state: unknown
54
+ let spec: PreparedSpecCommit | undefined
55
+ try {
56
+ const pending: unknown = JSON.parse(readFileSync(this.pendingPath, 'utf8'))
57
+ if (isRecord(pending) && 'spec' in pending) {
58
+ if (!isPreparedSpecCommit(pending.spec)) throw new Error('invalid prepared Git commit')
59
+ spec = pending.spec
60
+ state = pending.state
61
+ } else {
62
+ // Previous v3 releases wrote a bare ledger after the Git commit.
63
+ state = pending
64
+ }
65
+ validateV3Ledger(state)
66
+ } catch (error) {
67
+ throw new Error(`pending collaboration transaction is corrupted: ${errorMessage(error)}`, { cause: error })
68
+ }
69
+ this.finish(state, spec)
70
+ return normalizeV3(state)
71
+ }
72
+
73
+ private finish(state: CollaborationState, spec?: PreparedSpecCommit): void {
74
+ if (spec !== undefined) this.publishSpec(spec)
75
+ atomicWrite(this.path, state)
76
+ unlinkSync(this.pendingPath)
77
+ }
78
+ }
79
+
80
+ function emptyState(): CollaborationState {
81
+ return { schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [], companies: [], customers: [], feedbackSources: [], insights: [], insightLinks: [], notifications: [] }
82
+ }
83
+
84
+ function errorMessage(error: unknown): string {
85
+ return error instanceof Error ? error.message : String(error)
86
+ }
87
+
88
+ function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null && !Array.isArray(value) }
89
+ function validateV2Ledger(value: unknown): asserts value is Record<string, unknown> {
90
+ if (!isRecord(value) || !Array.isArray(value.requirements) || (value.participants !== undefined && !Array.isArray(value.participants))) throw new Error('invalid collaboration v2 ledger: requirements and participants must be arrays')
91
+ }
92
+ function validateV3Ledger(value: unknown): asserts value is CollaborationState {
93
+ if (!isRecord(value)) throw new Error('invalid collaboration v3 ledger: object required')
94
+ const arrays = ['participants', 'requirements', 'companies', 'customers', 'feedbackSources', 'insights', 'insightLinks', 'notifications'] as const
95
+ if (value.schemaVersion !== SCHEMA_VERSION || !Number.isFinite(value.revision) || arrays.some(key => !Array.isArray(value[key]))) throw new Error('invalid collaboration v3 ledger: required collections are missing or invalid')
96
+ for (const candidate of value.requirements as unknown[]) {
97
+ if (!isRecord(candidate) || typeof candidate.id !== 'string' || typeof candidate.title !== 'string' || typeof candidate.currentCommit !== 'string' || !['product-review', 'product-confirmation', 'joint-review', 'ready'].includes(String(candidate.stage))) throw new Error('invalid collaboration v3 ledger: malformed requirement')
98
+ const recordArrays = ['sources', 'reviewItems', 'comments', 'patches', 'decisions', 'confirmations', 'actionItems', 'aiRuns'] as const
99
+ if (recordArrays.some(key => !Array.isArray(candidate[key])) || (candidate.aiConversations !== undefined && !Array.isArray(candidate.aiConversations))) throw new Error('invalid collaboration v3 ledger: malformed requirement collections')
100
+ }
101
+ }
102
+
103
+ function atomicWrite(path: string, value: unknown): void {
104
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
105
+ const tmp = `${path}.tmp`
106
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 })
107
+ const descriptor = openSync(tmp, 'r')
108
+ try { fsyncSync(descriptor) } finally { closeSync(descriptor) }
109
+ renameSync(tmp, path)
110
+ }
111
+
112
+ function normalizeV3(value: CollaborationState): CollaborationState {
113
+ value.participants ??= []
114
+ value.requirements ??= []
115
+ value.companies ??= []
116
+ value.customers ??= []
117
+ value.feedbackSources ??= []
118
+ value.insights ??= []
119
+ value.insightLinks ??= []
120
+ value.notifications ??= []
121
+ for (const record of value.requirements) {
122
+ record.sources ??= []; record.reviewItems ??= []; record.comments ??= []; record.patches ??= []; record.decisions ??= []; record.confirmations ??= []; record.actionItems ??= []; record.aiRuns ??= []; record.aiConversations ??= []; record.stageCycle ??= 0
123
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle
124
+ if (record.stage === 'ready' && record.readyPackage?.commit !== record.currentCommit) {
125
+ delete record.readyPackage
126
+ record.stage = 'joint-review'
127
+ record.stageCycle += 1
128
+ } else if (record.aiConversations.length === 0 && (record.stage === 'product-review' || record.stage === 'joint-review')) {
129
+ const recent = [
130
+ ...record.aiRuns.filter(item => item.sessionId && (item.kind === 'change-review' || (record.stage === 'product-review' ? item.kind === 'product-first' || item.kind === 'product-second' : item.kind === 'engineering-precheck'))).map(item => ({ sessionId: item.sessionId!, createdAt: item.createdAt, updatedAt: item.updatedAt })),
131
+ ...record.comments.filter(item => item.aiSessionId).map(item => ({ sessionId: item.aiSessionId!, createdAt: item.createdAt, updatedAt: item.updatedAt })),
132
+ ].sort((left, right) => right.updatedAt - left.updatedAt)[0]
133
+ if (recent) record.aiConversations.push({ stage: record.stage, stageCycle: record.stageCycle, ...recent })
134
+ }
135
+ for (const comment of record.comments) {
136
+ comment.scope ??= comment.anchor === undefined ? 'page' : 'inline'
137
+ comment.mentions ??= []
138
+ comment.replies ??= []
139
+ for (const reply of comment.replies) reply.mentions ??= []
140
+ }
141
+ }
142
+ return value
143
+ }
144
+
145
+ function migrateV2(value: Record<string, unknown>): CollaborationState {
146
+ const legacyRequirements = Array.isArray(value.requirements) ? value.requirements as RequirementRecord[] : []
147
+ const requirements = structuredClone(legacyRequirements)
148
+ const feedbackSources: CollaborationState['feedbackSources'] = []
149
+ const insights: CollaborationState['insights'] = []
150
+ const insightLinks: CollaborationState['insightLinks'] = []
151
+ const migrationActor: ParticipantSnapshot = { participantId: 'migration-v2', nickname: '数据迁移', role: 'product', kind: 'ai', sessionId: 'migration-v2' }
152
+ for (const record of requirements) {
153
+ record.sources ??= []; record.reviewItems ??= []; record.comments ??= []; record.patches ??= []; record.decisions ??= []; record.confirmations ??= []; record.actionItems ??= []; record.aiRuns ??= []; record.aiConversations ??= []; record.stageCycle ??= 0
154
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle
155
+ for (const comment of record.comments) {
156
+ comment.scope = comment.anchor === undefined ? 'page' : 'inline'; comment.mentions = []; comment.replies ??= []
157
+ for (const reply of comment.replies) reply.mentions = []
158
+ }
159
+ for (const source of record.sources) {
160
+ const sourceId = `legacy-${createHash('sha256').update(`${record.id}:${source.id}`).digest('hex').slice(0, 16)}`
161
+ const insightId = `legacy-${createHash('sha256').update(`${record.id}:${source.id}:insight`).digest('hex').slice(0, 16)}`
162
+ feedbackSources.push({ id: sourceId, kind: source.sourceType === 'link' ? 'url' : source.sourceType === 'markdown' ? 'markdown' : 'text', label: source.label, ...(source.sourceType === 'link' && safeHttpUrl(source.stableId) ? { url: source.stableId } : {}), ...(source.stableId ? { externalRef: source.stableId } : {}), accessStatus: source.accessStatus, createdAt: record.createdAt, updatedAt: record.updatedAt })
163
+ insights.push({ id: insightId, sourceId, title: source.label, body: `历史来源:${source.label}`, importance: 'unknown', capturedAt: record.createdAt, dedupeHash: insightHash(sourceId, source.label), createdBy: migrationActor, createdAt: record.createdAt, updatedAt: record.updatedAt })
164
+ insightLinks.push({ id: randomUUID(), insightId, requirementId: record.id, targetType: 'requirement', createdBy: migrationActor, createdAt: record.createdAt })
165
+ }
166
+ }
167
+ return normalizeV3({ schemaVersion: SCHEMA_VERSION, revision: typeof value.revision === 'number' ? value.revision : 0, participants: Array.isArray(value.participants) ? value.participants as ParticipantSnapshot[] : [], requirements, companies: [], customers: [], feedbackSources, insights, insightLinks, notifications: [] })
168
+ }