@akagilnc/pi-workflow-roles 0.1.5212 → 0.1.5235

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.
@@ -1,16 +1,10 @@
1
1
  /**
2
- * Sitian Appender kernel (ADR 0065).
2
+ * Sitian Appender kernel (ADR 0065 / ADR 0086).
3
3
  * Computes destination automatically from ledger topology without destination parameters.
4
- * Owns volume open, torn-tail recovery, entry-level idempotency, and commit boundary.
4
+ * Log4j-style append-only record sink: appends one row, no deduplication, no read-back, no torn-tail repair.
5
5
  */
6
- import { createHash, randomUUID } from "node:crypto";
7
- import {
8
- appendFileSync,
9
- existsSync,
10
- readFileSync,
11
- unlinkSync,
12
- writeFileSync,
13
- } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
7
+ import { appendFileSync } from "node:fs";
14
8
  import { dirname, join } from "node:path";
15
9
 
16
10
  import { resolveBookKeyFromGit } from "./activation-ledger-git.ts";
@@ -29,59 +23,13 @@ import {
29
23
  type SitianRecordInput,
30
24
  } from "./sitian-contracts.ts";
31
25
 
32
- function isRecord(value: unknown): value is Record<string, unknown> {
33
- return typeof value === "object" && value !== null && !Array.isArray(value);
34
- }
35
-
36
- function errorCodeOf(error: unknown): unknown {
37
- return (error as { code?: unknown }).code;
38
- }
39
-
40
- function identityClaimPath(recordFile: string, identity: string): string {
41
- const digest = createHash("sha256").update(identity, "utf8").digest("hex");
42
- return `${recordFile}.id-${digest}`;
43
- }
44
-
45
- /**
46
- * Exclusive create at `path` exactly once across processes.
47
- * Reuses the package's existing `wx` / O_EXCL zero-content occupancy primitive
48
- * (same shape as activation-ledger-session / archivist-record-entry).
49
- */
50
- function createExclusiveFile(path: string, contents: string): void {
51
- writeFileSync(path, contents, { encoding: "utf8", flag: "wx" });
52
- }
53
-
54
- function sealTornTail(recordFile: string): void {
55
- if (!existsSync(recordFile)) return;
56
- const buffer = readFileSync(recordFile);
57
- if (buffer.length > 0 && buffer[buffer.length - 1] !== 0x0a) {
58
- appendFileSync(recordFile, "\n", "utf8");
59
- }
60
- }
61
-
62
26
  /** Assign already-recorded lines, preserving their original text and malformed lines. */
63
27
  export function appendSitianRecordBlock(input: SitianRecordInput, block: string): void {
64
28
  if (block === "") return;
65
29
  try {
66
30
  const { sessionDir, recordFile, ledgerHome } = resolveSitianRecordPath(input);
67
31
  ensureRealDirectoryTree(ledgerHome, sessionDir);
68
- appendFileSync(recordFile, "", "utf8");
69
- sealTornTail(recordFile);
70
- const identityOf = (line: string): string | undefined => {
71
- try {
72
- const row: unknown = JSON.parse(line);
73
- return isRecord(row) && typeof row.identity === "string" ? row.identity : undefined;
74
- } catch {
75
- return undefined;
76
- }
77
- };
78
- const identities = new Set(readFileSync(recordFile, "utf8").split("\n").map(identityOf).filter((id): id is string => id !== undefined));
79
- for (const line of block.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
80
- const identity = identityOf(line);
81
- if (identity !== undefined && identities.has(identity)) continue;
82
- appendFileSync(recordFile, line, "utf8");
83
- if (identity !== undefined) identities.add(identity);
84
- }
32
+ appendFileSync(recordFile, block, "utf8");
85
33
  } catch (error) {
86
34
  if (error instanceof SitianInfrastructureError) throw error;
87
35
  throw new SitianInfrastructureError(
@@ -91,134 +39,6 @@ export function appendSitianRecordBlock(input: SitianRecordInput, block: string)
91
39
  }
92
40
  }
93
41
 
94
- function findIdentityPointer(
95
- recordFile: string,
96
- identity: string,
97
- kind: string,
98
- level: SitianRecord["level"],
99
- ): RecordPointer | undefined {
100
- if (!existsSync(recordFile)) return undefined;
101
- const text = readFileSync(recordFile, "utf8");
102
- for (const line of text.split("\n")) {
103
- const trimmed = line.trim();
104
- if (!trimmed) continue;
105
- try {
106
- const parsed = JSON.parse(trimmed);
107
- if (isRecord(parsed) && parsed.identity === identity) {
108
- return { identity, recordFile, kind, level };
109
- }
110
- } catch {
111
- // Malformed lines (including substate b preserved bad lines) are ignored during self-check
112
- }
113
- }
114
- return undefined;
115
- }
116
-
117
- function unlinkAbsentOk(path: string): Error | undefined {
118
- try {
119
- unlinkSync(path);
120
- return undefined;
121
- } catch (error) {
122
- if (errorCodeOf(error) === "ENOENT") return undefined;
123
- return error instanceof Error ? error : new Error(errorText(error));
124
- }
125
- }
126
-
127
- /**
128
- * Same-identity uniqueness under normal concurrent writers.
129
- *
130
- * Exclusive per-identity claim (`wx`) makes check+append atomic for one
131
- * identity. The winner appends under the claim and always releases it on both
132
- * normal and throwing exits. A loser that already sees the published row
133
- * returns that pointer; a loser that hits claim EEXIST without a published row
134
- * fails as SitianInfrastructureError (knownCause session). Crash residue can
135
- * leave that one identity blocked — identity-scoped, never a volume lock. No
136
- * wait loop, write-ahead recovery, PID reclaim, or compare-and-unlink.
137
- */
138
- function appendWithIdentityClaim(
139
- recordFile: string,
140
- record: SitianRecord,
141
- row: string,
142
- ): RecordPointer {
143
- sealTornTail(recordFile);
144
- const claimPath = identityClaimPath(recordFile, record.identity);
145
- const existing = findIdentityPointer(
146
- recordFile,
147
- record.identity,
148
- record.kind,
149
- record.level,
150
- );
151
- if (existing !== undefined) {
152
- // Best-effort: drop leftover claim after a prior crash-after-append.
153
- unlinkAbsentOk(claimPath);
154
- return existing;
155
- }
156
-
157
- try {
158
- createExclusiveFile(claimPath, "");
159
- } catch (error) {
160
- if (errorCodeOf(error) !== "EEXIST") throw error;
161
- sealTornTail(recordFile);
162
- const published = findIdentityPointer(
163
- recordFile,
164
- record.identity,
165
- record.kind,
166
- record.level,
167
- );
168
- if (published !== undefined) {
169
- unlinkAbsentOk(claimPath);
170
- return published;
171
- }
172
- throw new SitianInfrastructureError(
173
- `Sitian identity claim at ${claimPath} already exists for identity ${record.identity}`,
174
- { cause: error },
175
- );
176
- }
177
-
178
- let primaryFailure: unknown;
179
- let result: RecordPointer | undefined;
180
- let cleanupFailure: Error | undefined;
181
- try {
182
- sealTornTail(recordFile);
183
- const raced = findIdentityPointer(
184
- recordFile,
185
- record.identity,
186
- record.kind,
187
- record.level,
188
- );
189
- if (raced !== undefined) {
190
- result = raced;
191
- } else {
192
- appendFileSync(recordFile, row, "utf8");
193
- result = {
194
- identity: record.identity,
195
- recordFile,
196
- kind: record.kind,
197
- level: record.level,
198
- };
199
- }
200
- } catch (error) {
201
- primaryFailure = error;
202
- } finally {
203
- cleanupFailure = unlinkAbsentOk(claimPath);
204
- }
205
-
206
- if (primaryFailure !== undefined) {
207
- if (primaryFailure instanceof SitianInfrastructureError) throw primaryFailure;
208
- throw new SitianInfrastructureError(
209
- `Sitian appender persistence failure: ${errorText(primaryFailure)}`,
210
- { cause: primaryFailure },
211
- );
212
- }
213
- if (cleanupFailure !== undefined) {
214
- throw new SitianInfrastructureError(
215
- `Sitian identity claim at ${claimPath} could not be released after append for identity ${record.identity}: ${errorText(cleanupFailure)}`,
216
- { cause: cleanupFailure },
217
- );
218
- }
219
- return result as RecordPointer;
220
- }
221
-
222
42
  /** Authorized S4 submission ledger kinds that share a common run submission volume. */
223
43
  export const S4_SUBMISSION_LEDGER_KINDS = new Set([
224
44
  "candidate",
@@ -331,11 +151,10 @@ export function resolveSitianRecordPath(input: SitianRecordInput): SitianRecordP
331
151
  }
332
152
 
333
153
  /**
334
- * Appends a canonical record to its self-computed volume under the Sitian contract.
335
- * - Idempotency: checks volume by deterministic canonical identity; returns existing pointer on hit.
336
- * - Torn-tail recovery: checks file tail; un-terminated trailing bytes are sealed with a newline and re-parsed.
337
- * Substate a (valid JSON): committed on recovery, returns existing pointer.
338
- * Substate b (malformed): preserved as bad line, check misses, appends new row.
154
+ * Appends a canonical record to its self-computed volume under the Sitian contract (ADR 0086).
155
+ * - Log4j-style append-only record sink: O(1) append, unconditionally writes a new line.
156
+ * - Zero read-back, zero per-append identity check / idempotency deduplication.
157
+ * - Zero torn-tail repair.
339
158
  * - Commit point: full JSON string ending with newline.
340
159
  */
341
160
  export function appendSitianRecord(input: SitianRecordInput): RecordPointer {
@@ -362,7 +181,13 @@ export function appendSitianRecord(input: SitianRecordInput): RecordPointer {
362
181
  };
363
182
 
364
183
  const row = `${JSON.stringify(record)}\n`;
365
- return appendWithIdentityClaim(recordFile, record, row);
184
+ appendFileSync(recordFile, row, "utf8");
185
+ return {
186
+ identity: record.identity,
187
+ recordFile,
188
+ kind: record.kind,
189
+ level: record.level,
190
+ };
366
191
  } catch (error) {
367
192
  if (error instanceof SitianInfrastructureError) throw error;
368
193
  throw new SitianInfrastructureError(
@@ -1,10 +1,9 @@
1
1
  /**
2
- * 起居录(ticket-provenance)typed 形状 —— ADR 0075「2026-09-14 修订」/ #901 / #918。
2
+ * 起居录(ticket-provenance)typed 形状 —— ADR 0075 / ADR 0081 / #1090。
3
3
  *
4
- * 一册=一个追加式 records.jsonl;逻辑册子头与对话由读取时折叠不可变投影提交得到。
5
- * 既有「首行册子头+裸对话行」snapshot 向后可读,后续提交不回写旧行。
6
- * sessions 为 prior ∪ 各轮累计并集(遗漏不删除),已结转正文不因历史源重读而改。
7
- * 交卷 `sessions` 输入语义仍是「本轮对话边界」;累计并集是机械合并,不是角色交什么。
4
+ * 一册=一个追加式 records.jsonl。每轮交卷的 `sessions`=本轮对话边界;
5
+ * 成录接缝按该边界从宿主卷投影并追加,不回读已成录历史去重或折叠。
6
+ * 既有「首行册子头+裸对话行」snapshot 仍可读;后续提交不回写旧行。
8
7
  */
9
8
 
10
9
  /** Sitian kind for per-ticket court diary volumes. */
@@ -30,14 +29,14 @@ export type TicketProvenanceRange = {
30
29
 
31
30
  /**
32
31
  * 一卷:会话卷路径 + 区间声明。
33
- * 交卷时=本轮边界;写入册子头后=累计并集(#918),二者同型。
32
+ * 交卷与每条追加提交的 payload.sessions 同型=该次边界。
34
33
  */
35
34
  export type TicketProvenanceSession = {
36
35
  readonly path: string;
37
36
  readonly ranges: readonly TicketProvenanceRange[];
38
37
  };
39
38
 
40
- /** 读取时折叠出的逻辑册子头。sessions 为累计区间;reopen 与跨宿主并入,不新建册。 */
39
+ /** 旧 snapshot 册子头形状(存量可读;#1090 后新提交不再维护折叠头)。 */
41
40
  export type TicketProvenanceHeader = {
42
41
  readonly repo: string;
43
42
  readonly ticket: number | null;
@@ -48,15 +47,15 @@ export type TicketProvenanceHeader = {
48
47
 
49
48
  /**
50
49
  * 一条对话(存于不可变投影提交;旧 snapshot 中也可为裸行)。
51
- * `id` 按源事实存在则记、不存在不编;`s` 保留卷定位。
50
+ * `id` 按源事实存在则记、不存在不编;`s` 为本轮 sessions 下标。
52
51
  */
53
52
  export type TicketProvenanceLine = {
54
53
  readonly speaker: TicketProvenanceSpeaker;
55
- /** 卷下标(册子头 `sessions` 的位置)。 */
54
+ /** 本轮 sessions 下标。 */
56
55
  readonly s: number;
57
- /** Logical source order for display. */
56
+ /** Logical source order within the source volume at projection time. */
58
57
  readonly sourcePosition?: number;
59
- /** Replay-invariant structural identity used for id-less cumulative coverage. */
58
+ /** Replay-invariant structural identity for id-less source rows. */
60
59
  readonly sourceIdentity?: string;
61
60
  readonly id?: string;
62
61
  readonly text: string;
@@ -75,19 +74,6 @@ function positiveInteger(value: unknown): number | undefined {
75
74
  return undefined;
76
75
  }
77
76
 
78
- function nonNegativeInteger(value: unknown): number | undefined {
79
- if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return value;
80
- if (typeof value === "string" && /^(0|[1-9][0-9]*)$/.test(value)) {
81
- const parsed = Number(value);
82
- if (Number.isSafeInteger(parsed)) return parsed;
83
- }
84
- return undefined;
85
- }
86
-
87
- function projectSpeaker(value: unknown): TicketProvenanceSpeaker | undefined {
88
- return value === "owner" || value === "runner" ? value : undefined;
89
- }
90
-
91
77
  function projectBound(value: unknown): TicketProvenanceBound | undefined {
92
78
  if (!isRecord(value)) return undefined;
93
79
  const id = typeof value.id === "string" && value.id !== "" ? value.id : undefined;
@@ -149,27 +135,3 @@ export function projectTicketProvenanceHeader(
149
135
  sessions,
150
136
  };
151
137
  }
152
-
153
- /** 读回一条对话行。 */
154
- export function projectTicketProvenanceLine(
155
- value: unknown,
156
- ): TicketProvenanceLine | undefined {
157
- if (!isRecord(value)) return undefined;
158
- const speaker = projectSpeaker(value.speaker);
159
- const s = nonNegativeInteger(value.s);
160
- if (speaker === undefined || s === undefined) return undefined;
161
- if (typeof value.text !== "string") return undefined;
162
- const sourcePosition = nonNegativeInteger(value.sourcePosition);
163
- const sourceIdentity = typeof value.sourceIdentity === "string" && value.sourceIdentity !== ""
164
- ? value.sourceIdentity
165
- : undefined;
166
- const id = typeof value.id === "string" && value.id !== "" ? value.id : undefined;
167
- return {
168
- speaker,
169
- s,
170
- ...(sourcePosition === undefined ? {} : { sourcePosition }),
171
- ...(sourceIdentity === undefined ? {} : { sourceIdentity }),
172
- ...(id === undefined ? {} : { id }),
173
- text: value.text,
174
- };
175
- }