@stalfh233/omc-cli 0.6.83 → 0.6.85

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.
@@ -11,28 +11,66 @@ function arrayEntryKey(entry) {
11
11
  }
12
12
  return undefined;
13
13
  }
14
+ /** Entries cap; the walk itself is uncapped so totalKnown stays exact. */
15
+ const SHAPE_WARNING_LIMIT = 8;
14
16
  /**
15
- * Field-level deep diff for the plan surface. Returns at most `limit`
16
- * changed paths plus the total count. Arrays of objects with a business key
17
- * (`code`/`id`/…) are aligned by that key; index-only comparison is the
18
- * fallback for scalars / unkeyed rows (r30a F14).
17
+ * Field-level deep diff. Arrays of objects with a business key
18
+ * (`code`/`id`/…) are aligned by that key; unkeyed arrays are compared
19
+ * sequentially AND report tail additions/deletions (the old face only walked
20
+ * the shared length, so a trailing add/del was silently invisible). Duplicate
21
+ * or missing business keys and unparseable JSON-looking strings produce
22
+ * `shapeWarnings` instead of a silent index alignment.
19
23
  */
20
- export function deepDiff(before, current, path = "", limit = 40, acc = []) {
21
- const walk = (b, c, p) => {
22
- if (acc.length >= limit)
24
+ export function deepDiff(before, current, options = {}) {
25
+ // An EXPLICIT limit 0 means "counts only" (entries stay empty, totalKnown is
26
+ // still exact) — the coarse-coverage mode config.diff uses for its deep scan.
27
+ const rawLimit = options.limit ?? 40;
28
+ const limit = options.limit === 0 ? 0 : Number.isSafeInteger(rawLimit) && rawLimit > 0 ? rawLimit : 40;
29
+ const entries = [];
30
+ const warnings = [];
31
+ let totalKnown = 0;
32
+ let nonAdditionCount = 0;
33
+ const push = (entry) => {
34
+ // `undefined` is not a JSON value: a key set to undefined on one side is
35
+ // ABSENT, so it must read as the `<absent>` sentinel, never as a literal
36
+ // "current: undefined" ghost difference (JS objects can carry such keys;
37
+ // the wire's JSON round-trip cannot).
38
+ const normalized = {
39
+ path: entry.path,
40
+ before: entry.before === undefined ? "<absent>" : entry.before,
41
+ current: entry.current === undefined ? "<absent>" : entry.current,
42
+ };
43
+ if (normalized.before === "<absent>" && normalized.current === "<absent>")
23
44
  return;
45
+ totalKnown += 1;
46
+ if (normalized.before !== "<absent>")
47
+ nonAdditionCount += 1;
48
+ if (entries.length < limit)
49
+ entries.push(normalized);
50
+ };
51
+ const warn = (warning) => {
52
+ warnings.push(warning);
53
+ };
54
+ const walk = (b, c, p) => {
24
55
  if (b === null && c === null)
25
56
  return;
26
57
  const bothObject = b !== null && c !== null && typeof b === "object" && typeof c === "object";
27
58
  if (!bothObject) {
28
59
  if (b !== c && !(Number.isNaN(b) && Number.isNaN(c))) {
29
60
  if (typeof b === "string" || typeof c === "string") {
30
- const bp = tryParseJson(b);
31
- const cp = tryParseJson(c);
61
+ const bp = jsonProbe(b);
62
+ const cp = jsonProbe(c);
32
63
  if (bp.ok && cp.ok)
33
64
  return walk(bp.value, cp.value, p);
65
+ // A string that LOOKS like structured JSON but does not parse is a
66
+ // shape problem worth naming: the raw-text comparison below may hide
67
+ // a semantically small break behind a large textual diff.
68
+ for (const probe of [bp, cp]) {
69
+ if (probe.looksLikeJson && !probe.ok)
70
+ warn({ path: p, kind: "unparseable-json-string", detail: `字符串以 {/[ 开头但 JSON 解析失败,按原文本比较(前 40 字符:${probe.head})` });
71
+ }
34
72
  }
35
- acc.push({ path: p, before: b, current: c });
73
+ push({ path: p, before: b, current: c });
36
74
  }
37
75
  return;
38
76
  }
@@ -40,52 +78,79 @@ export function deepDiff(before, current, path = "", limit = 40, acc = []) {
40
78
  const cArr = Array.isArray(c);
41
79
  if (bArr || cArr) {
42
80
  if (!bArr || !cArr) {
43
- acc.push({ path: p, before: b, current: c });
81
+ push({ path: p, before: b, current: c });
44
82
  return;
45
83
  }
46
84
  const bA = b;
47
85
  const cA = c;
48
- if (bA.length !== cA.length)
49
- acc.push({ path: p, before: `<array×${bA.length}>`, current: `<array×${cA.length}>` });
50
86
  const bKeys = bA.map(arrayEntryKey);
51
87
  const cKeys = cA.map(arrayEntryKey);
52
- const canAlign = bKeys.every((key) => key !== undefined) && cKeys.every((key) => key !== undefined)
53
- && new Set(bKeys).size === bKeys.length && new Set(cKeys).size === cKeys.length;
88
+ const bDup = firstDuplicateKey(bKeys);
89
+ const cDup = firstDuplicateKey(cKeys);
90
+ // Only OBJECT rows are expected to carry a business key; a scalar array
91
+ // (["a","b"]) is legitimately keyed by index, so it never warns.
92
+ const bMissing = firstKeylessObjectRow(bA, bKeys);
93
+ const cMissing = firstKeylessObjectRow(cA, cKeys);
94
+ const canAlign = bMissing < 0 && cMissing < 0 && bA.every((_, i) => bKeys[i] !== undefined) && cA.every((_, i) => cKeys[i] !== undefined)
95
+ && bDup === undefined && cDup === undefined;
54
96
  if (canAlign) {
55
97
  const bMap = new Map(bKeys.map((key, index) => [key, bA[index]]));
56
98
  const cMap = new Map(cKeys.map((key, index) => [key, cA[index]]));
57
99
  for (const key of new Set([...bMap.keys(), ...cMap.keys()])) {
58
- if (acc.length >= limit)
59
- return;
60
100
  const inB = bMap.has(key);
61
101
  const inC = cMap.has(key);
62
102
  const short = key.includes(":") ? key.slice(key.indexOf(":") + 1) : key;
63
103
  if (!inB) {
64
- acc.push({ path: `${p}[+${short}]`, before: "<absent>", current: cMap.get(key) });
104
+ push({ path: `${p}[+${short}]`, before: "<absent>", current: cMap.get(key) });
65
105
  continue;
66
106
  }
67
107
  if (!inC) {
68
- acc.push({ path: `${p}[-${short}]`, before: bMap.get(key), current: "<absent>" });
108
+ push({ path: `${p}[-${short}]`, before: bMap.get(key), current: "<absent>" });
69
109
  continue;
70
110
  }
71
111
  walk(bMap.get(key), cMap.get(key), `${p}[${short}]`);
72
112
  }
73
113
  return;
74
114
  }
115
+ // Named fallback: key alignment is unavailable, so compare sequentially
116
+ // — and report the tail the shared length never covered. The warning
117
+ // names WHY alignment fell back, but only when this subtree actually
118
+ // produced differences: an unchanged keyless array (seqNoSetting rows,
119
+ // designer defaults) is compared correctly by position and warning on
120
+ // it would be pure noise for every clean diff.
121
+ const knownBefore = totalKnown;
122
+ const sequential = [];
123
+ if (bDup !== undefined)
124
+ sequential.push({ path: p, kind: "duplicate-array-key", detail: `before 侧业务键重复(${bDup})——键对齐不可用,退回按序比较` });
125
+ if (cDup !== undefined)
126
+ sequential.push({ path: p, kind: "duplicate-array-key", detail: `current 侧业务键重复(${cDup})——键对齐不可用,退回按序比较` });
127
+ if (bMissing >= 0)
128
+ sequential.push({ path: p, kind: "missing-array-key", detail: `before 侧第 ${bMissing} 行是没有业务键的对象行(code/id/propertyCode/activityCode/ruleCode/nodeCode 均缺)——退回按序比较` });
129
+ if (cMissing >= 0)
130
+ sequential.push({ path: p, kind: "missing-array-key", detail: `current 侧第 ${cMissing} 行是没有业务键的对象行(code/id/propertyCode/activityCode/ruleCode/nodeCode 均缺)——退回按序比较` });
75
131
  const shared = Math.min(bA.length, cA.length);
76
- for (let i = 0; i < shared && acc.length < limit; i += 1)
132
+ for (let i = 0; i < shared; i += 1)
77
133
  walk(bA[i], cA[i], `${p}[${i}]`);
134
+ for (let i = shared; i < cA.length; i += 1)
135
+ push({ path: `${p}[+${i}]`, before: "<absent>", current: cA[i] });
136
+ for (let i = shared; i < bA.length; i += 1)
137
+ push({ path: `${p}[-${i}]`, before: bA[i], current: "<absent>" });
138
+ if (totalKnown > knownBefore)
139
+ for (const warning of sequential)
140
+ warn(warning);
78
141
  return;
79
142
  }
80
143
  const bRec = b;
81
144
  const cRec = c;
82
145
  for (const key of new Set([...Object.keys(bRec), ...Object.keys(cRec)])) {
83
- if (acc.length >= limit)
84
- return;
85
- const inB = key in bRec;
86
- const inC = key in cRec;
146
+ // A key whose VALUE is undefined is absent for diff purposes (JSON has no
147
+ // undefined); only a real value counts as present.
148
+ const inB = key in bRec && bRec[key] !== undefined;
149
+ const inC = key in cRec && cRec[key] !== undefined;
150
+ if (!inB && !inC)
151
+ continue;
87
152
  if (!inB || !inC) {
88
- acc.push({
153
+ push({
89
154
  path: joinPath(p, key),
90
155
  before: inB ? bRec[key] : "<absent>",
91
156
  current: inC ? cRec[key] : "<absent>",
@@ -95,8 +160,34 @@ export function deepDiff(before, current, path = "", limit = 40, acc = []) {
95
160
  walk(bRec[key], cRec[key], joinPath(p, key));
96
161
  }
97
162
  };
98
- walk(before, current, path);
99
- return { changes: acc, total: acc.length };
163
+ walk(before, current, options.path ?? "");
164
+ return {
165
+ entries,
166
+ totalKnown,
167
+ truncated: totalKnown > entries.length,
168
+ remaining: totalKnown - entries.length,
169
+ shapeWarnings: warnings.slice(0, SHAPE_WARNING_LIMIT),
170
+ ...(warnings.length > SHAPE_WARNING_LIMIT ? { shapeWarningsOmitted: warnings.length - SHAPE_WARNING_LIMIT } : {}),
171
+ nonAdditionCount,
172
+ };
173
+ }
174
+ function firstDuplicateKey(keys) {
175
+ const seen = new Set();
176
+ for (const key of keys) {
177
+ if (key === undefined)
178
+ continue;
179
+ if (seen.has(key))
180
+ return key;
181
+ seen.add(key);
182
+ }
183
+ return undefined;
184
+ }
185
+ function isRecordish(value) {
186
+ return value !== null && typeof value === "object" && !Array.isArray(value);
187
+ }
188
+ /** Index of the first OBJECT row that carries no business key (-1 when none). */
189
+ function firstKeylessObjectRow(values, keys) {
190
+ return keys.findIndex((key, index) => key === undefined && isRecordish(values[index]));
100
191
  }
101
192
  /**
102
193
  * Drop null/undefined values from inverse-call args, recursively (live r55
@@ -197,17 +288,24 @@ export function canonicalForVerify(value) {
197
288
  function joinPath(base, key) {
198
289
  return base === "" ? key : `${base}.${key}`;
199
290
  }
200
- function tryParseJson(value) {
291
+ /**
292
+ * Probe a value for "stringified JSON" semantics: `ok` when the string parses
293
+ * as an object/array, `looksLikeJson && !ok` when it starts like structured
294
+ * JSON but fails to parse (the shapeWarning case — never silently compared as
295
+ * opaque text without naming the break).
296
+ */
297
+ function jsonProbe(value) {
201
298
  if (typeof value !== "string")
202
- return { ok: false };
299
+ return { ok: false, looksLikeJson: false, head: "" };
203
300
  const trimmed = value.trim();
204
301
  if (!trimmed.startsWith("{") && !trimmed.startsWith("["))
205
- return { ok: false };
302
+ return { ok: false, looksLikeJson: false, head: "" };
303
+ const head = trimmed.slice(0, 40);
206
304
  try {
207
- return { ok: true, value: JSON.parse(trimmed) };
305
+ return { ok: true, looksLikeJson: true, head, value: JSON.parse(trimmed) };
208
306
  }
209
307
  catch {
210
- return { ok: false };
308
+ return { ok: false, looksLikeJson: true, head };
211
309
  }
212
310
  }
213
311
  //# sourceMappingURL=rollback-spec.js.map
package/dist/rollback.js CHANGED
@@ -7,8 +7,13 @@ import { runToolCall } from "./call.js";
7
7
  import { readJournal, resolveJournalEntry, laterWritesOnTarget } from "./journal.js";
8
8
  import { canonicalForVerify, deepDiff, pruneNullish } from "./rollback-spec.js";
9
9
  import { sha256 } from "./support.js";
10
- import { emitTransportResult } from "./command-transport.js";
10
+ import { emitTransportResult, emitInvalid } from "./command-transport.js";
11
11
  import { acquireWriteLock } from "./write-lock.js";
12
+ import { resolveSinceRef } from "./duration.js";
13
+ import { normalizeWriteReason } from "./write-audit.js";
14
+ /** Invalid `--since`: the CLI maps it to invalid-input (exit 10), never a guessed window. */
15
+ export class SinceRefError extends Error {
16
+ }
12
17
  /** Pure runtime assembly: an injected context (tests) or the default one. */
13
18
  function runtime(context) {
14
19
  return context ?? makeToolContext({ sessions: new SessionManager(new ConfigStore(defaultPaths())) });
@@ -38,8 +43,24 @@ function findSpec(toolName) {
38
43
  }
39
44
  export async function listRollback(options, context) {
40
45
  const ctx = runtime(context);
46
+ // Validate `--since` BEFORE resolving the environment: bad caller input must
47
+ // not depend on (or require) a valid environment binding.
48
+ const since = options.since === undefined ? undefined : resolveSinceRef(options.since);
49
+ if (since !== undefined && "error" in since)
50
+ throw new SinceRefError(since.error);
41
51
  const environment = resolvedEnvironment(options.environment);
42
52
  let entries = readJournal(environment, ctx.artifactsDir);
53
+ const beforeSince = entries.length;
54
+ let sinceFilteredOut = 0;
55
+ if (since !== undefined) {
56
+ // `ts` is the journal's own ISO clock. An entry whose ts cannot be parsed is
57
+ // NOT inside the requested window (never silently kept).
58
+ entries = entries.filter((entry) => {
59
+ const at = Date.parse(entry.ts);
60
+ return Number.isFinite(at) && at >= since.cutoffMs;
61
+ });
62
+ sinceFilteredOut = beforeSince - entries.length;
63
+ }
43
64
  if (options.target)
44
65
  entries = entries.filter((entry) => entry.target.includes(options.target));
45
66
  if (options.tool)
@@ -61,6 +82,17 @@ export async function listRollback(options, context) {
61
82
  status: "ok",
62
83
  environment,
63
84
  journalFile: `.omc/journal/${environment}.ndjson(随本项目 artifacts 目录,本机边界:不跨机器)`,
85
+ ...(since !== undefined
86
+ ? {
87
+ since: {
88
+ input: since.input,
89
+ mode: since.mode,
90
+ cutoff: new Date(since.cutoffMs).toISOString(),
91
+ rule: "保留 ts ≥ cutoff 的写",
92
+ filteredOut: sinceFilteredOut,
93
+ },
94
+ }
95
+ : {}),
64
96
  entries: timeline.length,
65
97
  writes: timeline.map((entry) => ({
66
98
  seq: entry.seq,
@@ -68,12 +100,17 @@ export async function listRollback(options, context) {
68
100
  tool: entry.tool,
69
101
  target: entry.target,
70
102
  rollbackable: entry.rollbackable,
103
+ // R88 #3:旧 entry 没有审计列 —— 缺省即不回(不回假 actor/reason)。
104
+ ...(entry.actor !== undefined ? { actor: entry.actor } : {}),
105
+ ...(entry.actorSource !== undefined ? { actorSource: entry.actorSource } : {}),
106
+ ...(entry.actorUnavailableReason !== undefined ? { actorUnavailableReason: entry.actorUnavailableReason } : {}),
107
+ ...(entry.reason !== undefined ? { reason: entry.reason } : {}),
71
108
  ...(entry.note ? { note: entry.note } : {}),
72
109
  ...(entry.steps !== undefined ? { steps: entry.steps } : {}),
73
110
  artifact: basename(entry.artifactFile),
74
111
  })),
75
112
  ...(unrollbackable.length > 0 ? { unrollbackable } : {}),
76
- hint: "omc rollback plan <seq> 预览恢复(不写);omc rollback apply <seq> 执行恢复;unrollbackable[] 是本窗口内撤不了的写",
113
+ hint: "omc rollback plan <seq> 预览恢复(不写);omc rollback apply <seq> 执行恢复;unrollbackable[] 是本窗口内撤不了的写;actor 为 token 解码(actorSource:token-claim,非平台 currentUser);旧 entry 无审计列、解不出时见 actorUnavailableReason",
77
114
  };
78
115
  }
79
116
  async function buildPlan(ref, environmentOption, context) {
@@ -95,7 +132,7 @@ async function buildPlan(ref, environmentOption, context) {
95
132
  before: undefined,
96
133
  artifactArgs: {},
97
134
  context: ctx,
98
- plan: { environmentMatch: true, diff: { changes: [], total: 0 }, laterWrites: laterWritesOnTarget(environment, ctx.artifactsDir, entry.seq, entry.target), inverse: { kind: "irreversible", reason } },
135
+ plan: { environmentMatch: true, diff: { entries: [], totalKnown: 0, truncated: false, remaining: 0, shapeWarnings: [], nonAdditionCount: 0 }, laterWrites: laterWritesOnTarget(environment, ctx.artifactsDir, entry.seq, entry.target), inverse: { kind: "irreversible", reason } },
99
136
  });
100
137
  if (!entry.rollbackable)
101
138
  return unrollbackable(entry.note ?? "该写的 before 快照捕获失败,无法回滚");
@@ -147,7 +184,14 @@ export async function planRollback(ref, options, context) {
147
184
  return {
148
185
  status: "ok",
149
186
  rollbackOf: { seq: entry.seq, tool: entry.tool, target: entry.target, ts: entry.ts },
150
- diff: { changedPaths: plan.diff.changes.map((change) => ({ path: change.path, before: preview(change.before), current: preview(change.current) })), total: plan.diff.total },
187
+ diff: {
188
+ changedPaths: plan.diff.entries.map((change) => ({ path: change.path, before: preview(change.before), current: preview(change.current) })),
189
+ // totalKnown is the EXACT difference count (the walk never stops at the
190
+ // inline cap); truncated/remaining say how much lives beyond this list.
191
+ total: plan.diff.totalKnown,
192
+ ...(plan.diff.truncated ? { truncated: true, remaining: plan.diff.remaining } : {}),
193
+ ...(plan.diff.shapeWarnings.length > 0 ? { shapeWarnings: plan.diff.shapeWarnings } : {}),
194
+ },
151
195
  // r30a F12: do not claim "will overwrite later writes" when inverse is irreversible.
152
196
  ...(plan.laterWrites.length > 0 && !irreversible
153
197
  ? { warning: `该目标在此写之后还有 ${plan.laterWrites.length} 次写(seq ${plan.laterWrites.map((w) => w.seq).join(", ")});本次回滚会用 before 参数覆盖这些后续变更`, laterWrites: plan.laterWrites.map((w) => ({ seq: w.seq, tool: w.tool, ts: w.ts })) }
@@ -192,6 +236,9 @@ export async function applyRollback(ref, options, context) {
192
236
  };
193
237
  }
194
238
  const results = [];
239
+ // R88 #3:恢复写本身也是写——journal 行要能回答「为什么」。调用方没给
240
+ // --reason 时记机器可证实的出处(回滚了哪个 seq),不发明人类理由。
241
+ const restoreReason = normalizeWriteReason(options.reason) ?? `rollback of seq ${entry.seq}(${entry.tool})`;
195
242
  // The inverse plan is intentionally kept as the seam for future inverse
196
243
  // extensions (for example onlinejs.compose remove:true): all new restore
197
244
  // shapes still become governed calls here, without changing the evidence
@@ -221,6 +268,7 @@ export async function applyRollback(ref, options, context) {
221
268
  args: { ...call.args, environment: entry.environment, ...(options.confirmProduction ? { confirmProduction: true } : {}) },
222
269
  requestId: `omc-rollback-${entry.seq}-${index + 1}`,
223
270
  context: ctx,
271
+ reason: restoreReason,
224
272
  print: () => undefined,
225
273
  });
226
274
  results.push({
@@ -254,13 +302,17 @@ export async function applyRollback(ref, options, context) {
254
302
  verify = "restored";
255
303
  else {
256
304
  const residual = deepDiff(canonicalForVerify(before), canonicalForVerify(restored));
257
- verify = residual.changes.every((change) => change.before === "<absent>") ? "restored" : "mismatch";
305
+ // nonAdditionCount counts entries beyond the inline cap too, so the
306
+ // explicitification tolerance can never hide a real mismatch past limit.
307
+ verify = residual.nonAdditionCount === 0 ? "restored" : "mismatch";
258
308
  }
259
309
  return {
260
310
  status: "ok",
261
311
  rollbackOf: { seq: entry.seq, tool: entry.tool, target: entry.target },
262
312
  calls: results,
263
313
  verify,
314
+ // R88 #3:恢复写落 journal 时记的 reason(journal 是唯一审计真相源)。
315
+ reason: restoreReason,
264
316
  // Stable evidence is present on both the restored and mismatch paths.
265
317
  // `recoveredTo` deliberately identifies the original journal target; the
266
318
  // replay writes are separately journaled and can be rolled back again.
@@ -272,7 +324,16 @@ export async function applyRollback(ref, options, context) {
272
324
  };
273
325
  }
274
326
  export async function cmdRollbackList(options, transport) {
275
- return emitTransportResult(await listRollback(options), transport);
327
+ try {
328
+ return emitTransportResult(await listRollback(options), transport);
329
+ }
330
+ catch (error) {
331
+ // Invalid `--since` is caller input, not an internal failure: exit 10 with
332
+ // the accepted shapes (never a silently guessed window).
333
+ if (error instanceof SinceRefError)
334
+ return emitInvalid(transport, { message: error.message, blocker: "since-invalid" });
335
+ throw error;
336
+ }
276
337
  }
277
338
  export async function cmdRollbackPlan(ref, options, transport) {
278
339
  return emitTransportResult(await planRollback(ref, options), transport);
package/dist/script.js CHANGED
@@ -87,6 +87,7 @@ export async function runScript(lines, options = {}) {
87
87
  dryRun: line.dryRun === true,
88
88
  requestId: randomUUID(),
89
89
  context,
90
+ ...(options.reason !== undefined ? { reason: options.reason } : {}),
90
91
  print: () => undefined,
91
92
  });
92
93
  const rendered = JSON.stringify({ index, tool: line.tool, exitCode, result });
@@ -225,6 +225,9 @@ const TOOL_PARENTS = Object.freeze({
225
225
  // R79 三期:流程清单以模型为索引(应用树→模型→逐模型解析流程)——句子里
226
226
  // 点模型时给 workflow.list 父对象信号(与 listview/form 同族)。
227
227
  "workflow.list": ["model"],
228
+ // R88 #1:双面排查 diff 的目标是「某模型/流程/表单」——句子里点流程或表单
229
+ // 时给 config.diff 父对象信号(「流程和表单的草稿发布差异」两侧都命中)。
230
+ "config.diff": ["workflow", "form"],
228
231
  "method.create": ["service"], "method.update": ["service"], "method.get": ["service"], "method.delete": ["service"], "method.test": ["service"], "method.list": ["service"],
229
232
  // 业务服务调用日志:对象段是 servicelog,句子里同时点「服务」或「模型/单据」
230
233
  // (schemaCode/bizObjectId 是核心过滤面)都该给父对象信号。
package/dist/tools.js CHANGED
@@ -17,6 +17,7 @@ import { registerRuleLogLane } from "./lanes/rulelog.js";
17
17
  import { registerRuleLifecycleLane } from "./lanes/rule-lifecycle.js";
18
18
  import { registerRuntimeDataLane } from "./lanes/runtime-data.js";
19
19
  import { registerWorkflowLane } from "./lanes/workflow.js";
20
+ import { registerConfigDiffTool } from "./lanes/config-diff.js";
20
21
  import { registerOrganizationLane } from "./lanes/organization.js";
21
22
  import { registerOnlineJsLane } from "./lanes/online-js.js";
22
23
  import { registerProgrammingLane } from "./lanes/programming.js";
@@ -31,6 +32,7 @@ import { attachRefusalRecovery } from "./refusal-guidance.js";
31
32
  import { defineTool, ToolRefusalError } from "./tool-types.js";
32
33
  import { environmentArg } from "./args.js";
33
34
  import { appendJournalEntry } from "./journal.js";
35
+ import { journalAudit } from "./write-audit.js";
34
36
  import { listRequestArtifacts } from "./write.js";
35
37
  export { ToolRefusalError, ToolUncertainError } from "./tool-types.js";
36
38
  export { makeToolContext };
@@ -64,6 +66,11 @@ export function buildToolRegistry() {
64
66
  registerRuleLifecycleLane(tools);
65
67
  registerRuntimeDataLane(tools);
66
68
  registerWorkflowLane(tools);
69
+ // R88 #1: draft↔published triage diff. Registered after the workflow lane
70
+ // (it declares the workflow lane's scope but lives in its own module to
71
+ // keep the diff adapters separate from the write lane) — importing it from
72
+ // workflow.ts instead would create a module cycle.
73
+ registerConfigDiffTool(tools);
67
74
  registerOrganizationLane(tools);
68
75
  registerOnlineJsLane(tools);
69
76
  registerProgrammingLane(tools);
@@ -119,6 +126,8 @@ export function buildToolRegistry() {
119
126
  rollbackable: false,
120
127
  note: "复合写无逆操作,只记录(不假装可回滚)",
121
128
  ...(steps !== undefined ? { steps: steps.map((step) => (step && typeof step === "object" ? { step: step.step, skipped: step.skipped } : step)) } : {}),
129
+ // R88 #3:复合写同样记「谁/为什么」——审计列不由写面分叉。
130
+ ...journalAudit(ctx.sessions.config(), environment, ctx.writeAudit?.reason),
122
131
  artifactFile: typeof record.detailFile === "string" ? record.detailFile : `${toolName}.compound.json`,
123
132
  artifactId: typeof record.detailFile === "string" ? basename(record.detailFile) : `${toolName}-compound`,
124
133
  artifactSha: typeof record.artifactFingerprint === "string" ? record.artifactFingerprint : typeof record.detailSha256 === "string" ? record.detailSha256 : "compound",
@@ -0,0 +1,43 @@
1
+ import { sessionAccountForEnvironment } from "./session-account.js";
2
+ /**
3
+ * Write-audit context for the journal (R88 #3).
4
+ *
5
+ * Two questions the journal could not answer before: WHO wrote a config change
6
+ * and WHY. Both are recorded on every journal line, but neither may be invented:
7
+ *
8
+ * - actor comes from the locally cached login token (`session-account.ts`):
9
+ * zero extra wire, and `actorSource:"token-claim"` says exactly what it is —
10
+ * the JWT claim of the session that wrote, NOT the platform's `currentUser`.
11
+ * An undecodable token records `actorUnavailableReason` instead.
12
+ * - reason is the caller's own statement (`omc call --reason`,
13
+ * `omc intent apply --reason`, `omc rollback apply --reason`). It is audit
14
+ * metadata only: it never gates, delays, or refuses a write.
15
+ *
16
+ * The reason is NOT a tool input-schema field on purpose: adding it to ~170
17
+ * write tools would grow the tools/list payload for a field no schema validates.
18
+ * It rides the per-invocation `ToolContext.writeAudit`, which every governed
19
+ * entry point (call / batch / intent apply / rollback replay) can set.
20
+ */
21
+ /** Longest reason persisted to the journal (long prose belongs in the plan/summary). */
22
+ export const WRITE_REASON_MAX_LENGTH = 500;
23
+ /** Trim + bound a caller-declared reason; empty / non-string → undefined (absent, not ""). */
24
+ export function normalizeWriteReason(reason) {
25
+ if (typeof reason !== "string")
26
+ return undefined;
27
+ const trimmed = reason.trim();
28
+ if (trimmed.length === 0)
29
+ return undefined;
30
+ return trimmed.length > WRITE_REASON_MAX_LENGTH ? `${trimmed.slice(0, WRITE_REASON_MAX_LENGTH)}…` : trimmed;
31
+ }
32
+ /**
33
+ * Resolve the journal audit columns for one write. Never throws: an unreadable
34
+ * token cache / unresolved environment degrades to `actorUnavailableReason`,
35
+ * because a missing actor must not fail the write the line is describing.
36
+ */
37
+ export function journalAudit(store, environment, reason) {
38
+ const account = sessionAccountForEnvironment(store, environment);
39
+ const identity = "id" in account ? { actor: { ...account }, actorSource: "token-claim" } : { actorUnavailableReason: account.unavailableReason };
40
+ const normalized = normalizeWriteReason(reason);
41
+ return { ...identity, ...(normalized !== undefined ? { reason: normalized } : {}) };
42
+ }
43
+ //# sourceMappingURL=write-audit.js.map
package/dist/write.js CHANGED
@@ -17,6 +17,7 @@ import { writeSummary } from "./human-summary.js";
17
17
  import { planFor } from "./plan.js";
18
18
  import { isUncertainWireError, sha256, wireErrorKind, writeArtifact } from "./support.js";
19
19
  import { appendJournalEntry } from "./journal.js";
20
+ import { journalAudit } from "./write-audit.js";
20
21
  import { capabilityArg, confirmProductionArg, environmentArg, WRITE_PROTOCOL } from "./args.js";
21
22
  import { plannableArgsRaw } from "./plan.js";
22
23
  import { defineTool, ToolRefusalError } from "./tool-types.js";
@@ -49,6 +50,9 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
49
50
  dryRun: args.dryRun,
50
51
  capability: args.capability,
51
52
  args,
53
+ // R88 #3:写入原因来自本次调用的审计上下文(omc call --reason 等),
54
+ // 不是工具入参 schema 的字段——工具面零增长。
55
+ ...(ctx.writeAudit?.reason !== undefined ? { reason: ctx.writeAudit.reason } : {}),
52
56
  ...(readOnlyEscape !== undefined ? { readOnlyEscape } : {}),
53
57
  coverage: { lane: args.capability ?? tool.lane, scope: tool.scope ?? "" },
54
58
  plan: (session) => planFor(ctx, args.environment, tool.name, args),
@@ -84,7 +88,7 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
84
88
  });
85
89
  if (outcome.kind === "settled")
86
90
  return outcome.result;
87
- const { session, plan, productionConfirmed, readOnlyEscape: readOnlyEscapeNote } = outcome.admission;
91
+ const { session, plan, productionConfirmed, readOnlyEscape: readOnlyEscapeNote, reason } = outcome.admission;
88
92
  return ctx.lease.run(session.environmentName, `${tool.name}:${randomUUID().slice(0, 8)}`, async () => {
89
93
  // Rollback before-capture: the pre-write state of the declared target is
90
94
  // fetched INSIDE the lease (serialized with the write itself) and stored
@@ -204,6 +208,7 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
204
208
  readback,
205
209
  ...(steps !== undefined ? { steps } : {}),
206
210
  ...(productionConfirmed ? { productionConfirmed: true } : {}),
211
+ ...(reason !== undefined ? { reason } : {}),
207
212
  ...(tool.rollback
208
213
  ? {
209
214
  rollback: {
@@ -238,6 +243,9 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
238
243
  beforeSha: artifact.rollback.beforeSha,
239
244
  rollbackable: rollbackBefore !== undefined && !rollbackCaptureError,
240
245
  ...(rollbackCaptureError ? { note: `before-capture failed: ${rollbackCaptureError}` } : {}),
246
+ // R88 #3:每一行都带「谁写的」(token 解码,0 wire;解不出记原因)与
247
+ // 「为什么写」(调用方 --reason;缺省则不记,不发明理由)。
248
+ ...journalAudit(ctx.sessions.config(), session.environmentName, reason),
241
249
  artifactFile: artifactRef.detailFile,
242
250
  artifactId: basename(artifactRef.detailFile).replace(/\.artifact$/, "") || basename(artifactRef.detailFile),
243
251
  artifactSha: artifactRef.detailSha256,
@@ -259,6 +267,7 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
259
267
  // r30a F1: first write → replay:"none"; duplicate only on true replay.
260
268
  ...(args.requestId ? { requestId: args.requestId, idempotency: idempotencyDeclaration(tool.name, "none") } : {}),
261
269
  ...(productionConfirmed ? { productionConfirmed: true } : {}),
270
+ ...(reason !== undefined ? { reason } : {}),
262
271
  ...(rollbackRef
263
272
  ? { rollback: { ...(rollbackReceipt ?? {}), seq: rollbackRef.seq, ...(rollbackReceipt ? {} : { hint: rollbackRef.hint }) } }
264
273
  : {}),
@@ -530,7 +530,7 @@ omc intent readback intent.yaml --env test # 解码回 intent 形状做等价
530
530
  - 顶层 `models[]` / `services[]`;`models[].{code,name,fields,datarules,rules,form,listview,workflow,onlinejs}`。
531
531
  - `intent apply` 既可以吃 `plan` 文件,也可以直接吃 YAML(`omc intent apply intent.yaml --env <env>`,自动编译);大 plan 会自动外置,回 `planFile`。
532
532
  - **幂等收敛**:已达标环境重跑 plan/apply → 零变更、零重复创建。
533
- - 显式缺席(删除):`models[].absent:true` 删整模型、`fields[].absent:true` 删单字段;plan 的 `riskClass` 升为 `destructive`。
533
+ - 显式缺席(删除):`models[].absent:true` 删整模型、`fields[].absent:true` 删单字段、`listview.absent:true` 删列表视图、`datarules[].absent:true` 删数据规则;plan 的 `riskClass` 升为 `destructive`,`cleanup` 逐项列出。
534
534
  - 生产 apply 加 `--confirm-production`;`--dry-run` 预览,`--no-verify` 跳过最终读回。
535
535
 
536
536
  ### 5.3 复合命令 —— 一条命令 = 一个变更包
@@ -544,7 +544,7 @@ omc intent readback intent.yaml --env test # 解码回 intent 形状做等价
544
544
  | `omc workflow-update-publish` | 显式合成最终模板(默认保留旧节点,`--confirm-replace` 才丢弃) |
545
545
  | `omc call apply_changes` | 批量提交异构变更清单 `changes:[{tool,args}]`,首败即停、逐步读回、整批时间预算 |
546
546
  | `omc script` | NDJSON 多调脚本,一个进程一次会话跑完全部 |
547
- | `omc rollback` | 配置回滚(list / plan / apply),git-revert 语义;journal 与 before 快照是本机边界(不跨机器),publish 类生命周期推进不可逆 |
547
+ | `omc rollback` | 配置回滚(list / plan / apply),git-revert 语义;journal 兼作**项目级写审计面**:每行带 `actor`(token 解码,`actorSource:token-claim`,不是平台 currentUser;解不出回 `actorUnavailableReason`)与 `reason`(写时 `--reason`),`list --since <ISO\|30m\|2h>` 收窄窗口。journal 与 before 快照是本机边界(不跨机器、不跨项目;故意不设第二个 `omc audit` 真相源),publish 类生命周期推进不可逆 |
548
548
 
549
549
  另有若干「不写环境」的辅助命令:`compute`(聚合公式编译)、`rule-when`、`approval-flow`、`form-default`、
550
550
  `bench`(跑分)、`usage`(用量账本)、`next`(目标 → 工具一步定位)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.6.83",
3
+ "version": "0.6.85",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "commander": "14.0.3",
59
- "omc-core": "0.6.83",
59
+ "omc-core": "0.6.85",
60
60
  "proper-lockfile": "4.1.2",
61
61
  "write-file-atomic": "6.0.0",
62
62
  "zod": "^3.23.8",
@@ -74,6 +74,6 @@
74
74
  "directory": "packages/omc-cli"
75
75
  },
76
76
  "optionalDependencies": {
77
- "@stalfh233/omc-fake-platform": "0.6.83"
77
+ "@stalfh233/omc-fake-platform": "0.6.85"
78
78
  }
79
79
  }
@@ -168,8 +168,8 @@ only the section for the capability you need —
168
168
 
169
169
  ## 流程模板 `workflow`
170
170
 
171
- - **能做哪些事**:流程模板 workflow.list(应用内流程清单,以模型为索引)、get_draft/get_published、create、update、publish、bindRule/unbindRule(事件处理器规则绑定与解绑)、delete、workitem.list、workflow.instanceActivity(实例节点状态诊断);参与人用组织对象。**流程运维三件套**(r64,测试提速定位):workflow.transfer 换审批人(回执 newWorkItems 带补查的新 workItemId)/ workflow.activate 跳转节点 / workflow.finish 手动结束(end 规则照常触发)——运维过的实例不能用于真实流程/权限验证。
172
- - **工具**:`workflow.list`、`workflow.get_draft`、`workflow.setButtons`(节点「表单操作」按钮勾选)、`workflow.get_published`、`workflow.validate`、`workflow.create`、`workflow.update`、`workflow.publish`、`workflow.bindRule`、`workflow.unbindRule`(镜像 bindRule 两形态做减法;移空按平台 canonical 未绑态写回,不自动 disable 规则)、`workflow.delete`、`workflow.permissions`、`workflow.addPermission`、`workflow.removePermission`(发起权限:发布流程不会自动建这一行,缺它一律 40009)、`configure_workflow`、`workitem.list`、`workflow.instanceActivity`、`workflow.transfer`、`workflow.activate`、`workflow.finish`、`org.role.list`、`org.department.list`、`org.user.search`、`org.role.users`、`org.role.userScope`、`org.roleGroup.create`、`org.role.create`、`org.role.update`、`org.role.addUsers`、`org.role.removeUsers`、`org.role.setUserScope`、`org.department.create`、`org.department.update`、`org.department.delete`、`org.department.users`、`org.user.create`、`org.user.update`、`org.user.delete`、`org.user.info`、`org.user.departments`、`org.role.delete`、`org.roleGroup.delete`、`org.user.transferDepartment`
171
+ - **能做哪些事**:流程模板 workflow.list(应用内流程清单,以模型为索引)、get_draft/get_published、create、update、publish、bindRule/unbindRule(事件处理器规则绑定与解绑)、delete、workitem.list、workflow.instanceActivity(实例节点状态诊断);参与人用组织对象。**症状排查先 `config.diff`**(domain 另支持 form 表单布局双面):「按钮不见了/规则没生效/表单没更新/改了没生效」先 diff 双面定位哪一面落后(活动/连线/**三类绑定分别报**:流程级 ruleBindings、节点事件 nodeRuleBindings、SYSTEM_ACTIVITY 顶层 systemRuleBindings;changed:null=一面缺失看 verdict,不是空 diff)。**流程运维三件套**(r64,测试提速定位):workflow.transfer 换审批人(回执 newWorkItems 带补查的新 workItemId)/ workflow.activate 跳转节点 / workflow.finish 手动结束(end 规则照常触发)——运维过的实例不能用于真实流程/权限验证。
172
+ - **工具**:`config.diff`(草稿↔发布双面差异,只读)、`workflow.list`、`workflow.get_draft`、`workflow.setButtons`(节点「表单操作」按钮勾选)、`workflow.get_published`、`workflow.validate`、`workflow.create`、`workflow.update`、`workflow.publish`、`workflow.bindRule`、`workflow.unbindRule`(镜像 bindRule 两形态做减法;移空按平台 canonical 未绑态写回,不自动 disable 规则)、`workflow.delete`、`workflow.permissions`、`workflow.addPermission`、`workflow.removePermission`(发起权限:发布流程不会自动建这一行,缺它一律 40009)、`configure_workflow`、`workitem.list`、`workflow.instanceActivity`、`workflow.transfer`、`workflow.activate`、`workflow.finish`、`org.role.list`、`org.department.list`、`org.user.search`、`org.role.users`、`org.role.userScope`、`org.roleGroup.create`、`org.role.create`、`org.role.update`、`org.role.addUsers`、`org.role.removeUsers`、`org.role.setUserScope`、`org.department.create`、`org.department.update`、`org.department.delete`、`org.department.users`、`org.user.create`、`org.user.update`、`org.user.delete`、`org.user.info`、`org.user.departments`、`org.role.delete`、`org.roleGroup.delete`、`org.user.transferDepartment`
173
173
  - **recipe**:`omc describe workflow.bindRule --example workflow-handler-binding`;条件两级/一级:`omc describe workflow.update --example workflow-conditional-two-level-approval`
174
174
  - **边界 / 陷阱**:greenfield 首版;`publish`/`bindRule` 不得在 `ValidateMessage[]` 拒绝时报告成功。运行时 workitem(提交/审批)走 `data.submit`;想知道实例停在哪/是否错派,用 `workflow.instanceActivity`(无 status=1=真停,参与人全是发起人=解析为空退回)。**发起权限**(`workflow.permissions` / `addPermission`)只有部门/角色/用户三种白名单,**没有「全员」选项**——缺权限行时非管理员通常不能发起(40009),想放开只能授一个够宽的部门/角色,不是「不建行=全员」。**行级数据权限 / 可见范围 / 申请人只看自己的单据不在工具覆盖内**(没有按登录人动态过滤的读面/写面);`org.role.setUserScope` 是角色成员的部门管理范围,不是单据行级可见范围。
175
175