@forwardimpact/libwiki 0.2.24 → 0.2.26

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,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { yearMonth } from "@forwardimpact/libutil";
3
+ import { createLogger } from "@forwardimpact/libtelemetry";
3
4
  import { createScriptConfig } from "@forwardimpact/libconfig";
4
5
  import { scanMarkers } from "../marker-scanner.js";
5
6
  import { renderBlock, BlockRenderError } from "../block-renderer.js";
@@ -26,6 +27,7 @@ async function renderForBlock(block, projectRoot, ghContext, runtime) {
26
27
  return renderBlock({
27
28
  metric: block.metric,
28
29
  csvPath: block.csvPath,
30
+ priorReadAnchor: block.priorReadAnchor,
29
31
  projectRoot,
30
32
  fs: runtime.fsSync,
31
33
  });
@@ -69,6 +71,7 @@ function readStoryboardOrNull(runtime, storyboardPath) {
69
71
  export async function runRefreshCommand(ctx) {
70
72
  const { runtime, gitClient } = ctx.deps;
71
73
  const options = ctx.options;
74
+ const logger = createLogger("wiki", runtime);
72
75
  const projectRoot = resolveProjectRoot(runtime);
73
76
 
74
77
  const storyboardPath = path.resolve(
@@ -77,11 +80,11 @@ export async function runRefreshCommand(ctx) {
77
80
  );
78
81
  const text = readStoryboardOrNull(runtime, storyboardPath);
79
82
  if (text === null) {
80
- runtime.proc.stderr.write(`refresh: no storyboard at ${storyboardPath}\n`);
83
+ logger.warn("refresh", `no storyboard at ${storyboardPath}`);
81
84
  return { ok: true };
82
85
  }
83
86
  const blocks = scanMarkers(text, {
84
- warn: (message) => runtime.proc.stderr.write(message),
87
+ warn: (message) => logger.warn("refresh", message),
85
88
  });
86
89
  if (blocks.length === 0) return { ok: true };
87
90
 
@@ -122,8 +125,9 @@ export async function runRefreshCommand(ctx) {
122
125
  spliced = true;
123
126
  } catch (err) {
124
127
  if (!(err instanceof BlockRenderError)) throw err;
125
- runtime.proc.stderr.write(
126
- `refresh-error ${storyboardPath}:${block.openLine + 1} ${err.message}\n`,
128
+ logger.error(
129
+ "refresh",
130
+ `refresh-error ${storyboardPath}:${block.openLine + 1} ${err.message}`,
127
131
  );
128
132
  }
129
133
  }
@@ -1,24 +1,28 @@
1
+ import { createLogger } from "@forwardimpact/libtelemetry";
1
2
  import { rotateIfOverBudget, weeklyLogPath } from "../weekly-log.js";
2
3
  import { currentDayIso } from "../util/clock.js";
4
+ import { requireAgentFlag } from "../util/agent-flag.js";
3
5
  import { resolveWikiRoot } from "../util/wiki-dir.js";
4
6
 
5
- /** Force-rotate the current weekly log to a sealed part file. */
7
+ /**
8
+ * Rotate the current weekly log to a sealed part file. Refuses an under-budget
9
+ * target (exit 2) unless `--force`; the header-only floor stays a zero-exit
10
+ * no-op even under `--force`; a missing target exits 2.
11
+ */
6
12
  export function runRotateCommand(ctx) {
7
13
  const { runtime } = ctx.deps;
14
+ const logger = createLogger("wiki", runtime);
8
15
  const options = ctx.options;
9
- const agent = options.agent || runtime.proc.env.LIBEVAL_AGENT_PROFILE;
10
- if (!agent) {
11
- return {
12
- ok: false,
13
- code: 2,
14
- error: "rotate requires --agent or LIBEVAL_AGENT_PROFILE",
15
- };
16
- }
16
+ const resolved = requireAgentFlag(options, {
17
+ command: "rotate",
18
+ example: "fit-wiki rotate --agent staff-engineer",
19
+ });
20
+ if (!resolved.ok) return resolved;
21
+ const agent = resolved.agent;
17
22
  const wikiRoot = resolveWikiRoot(runtime, options);
18
23
  const today = options.today || currentDayIso(runtime);
19
24
  // Name the resolved target before any seal: the file follows from agent +
20
- // current week, not from any audit finding, so an env-default agent can
21
- // silently select a different file than the one the operator has in mind.
25
+ // current week, not from any audit finding.
22
26
  runtime.proc.stdout.write(
23
27
  `target → ${weeklyLogPath(wikiRoot, agent, today)}\n`,
24
28
  );
@@ -29,18 +33,37 @@ export function runRotateCommand(ctx) {
29
33
  wikiRoot,
30
34
  agent,
31
35
  today,
32
- 0,
33
- { force: true },
36
+ { lines: 0, words: 0 },
37
+ { force: Boolean(options.force) },
34
38
  runtime.fsSync,
35
39
  );
36
40
  } catch (e) {
37
- runtime.proc.stderr.write(`rotate failed: ${e.message}\n`);
41
+ logger.error("rotate", `rotate failed: ${e.message}`);
38
42
  return { ok: false, code: 1 };
39
43
  }
40
44
  switch (result.status) {
41
45
  case "noop":
42
- runtime.proc.stdout.write(`no rotation needed for ${agent}\n`);
43
- return { ok: true };
46
+ // The header-only floor is a benign no-op; an under-budget or missing
47
+ // target fails closed so a stale/typo'd invocation cannot pass silently.
48
+ if (result.reason === "floor") {
49
+ runtime.proc.stdout.write(`no rotation needed for ${agent}\n`);
50
+ return { ok: true };
51
+ }
52
+ if (result.reason === "missing") {
53
+ return {
54
+ ok: false,
55
+ code: 2,
56
+ error: `no weekly log for ${agent} at ${result.fromPath}`,
57
+ };
58
+ }
59
+ return {
60
+ ok: false,
61
+ code: 2,
62
+ error:
63
+ `${result.fromPath} is under budget ` +
64
+ `(${result.lines} lines, ${result.words} words); ` +
65
+ `pass --force to seal it early`,
66
+ };
44
67
  case "sealed":
45
68
  for (const part of result.parts) {
46
69
  runtime.proc.stdout.write(`sealed → ${part}\n`);
@@ -51,12 +74,13 @@ export function runRotateCommand(ctx) {
51
74
  runtime.proc.stdout.write(`sealed → ${part}\n`);
52
75
  }
53
76
  const { section, lines, words, path: residuePath } = result.residue;
54
- runtime.proc.stderr.write(
55
- `day-section ${section} alone exceeds the budget ` +
56
- `(${lines} lines, ${words} words) and cannot be split at a day ` +
57
- `seam: ${residuePath}\n` +
58
- `recover it by hand — bisect the section at a finer seam ` +
59
- `(see the memory protocol's manual-recovery convention)\n`,
77
+ logger.error(
78
+ "rotate",
79
+ `section ${section} alone exceeds the budget ` +
80
+ `(${lines} lines, ${words} words) and has no finer seam to split ` +
81
+ `at: ${residuePath}\n` +
82
+ `recover it by hand — shorten the section ` +
83
+ `(see the memory protocol's manual-recovery convention)`,
60
84
  );
61
85
  return { ok: false, code: 1 };
62
86
  }
@@ -1,35 +1,85 @@
1
- import { WikiPullConflict } from "../wiki-sync.js";
1
+ import { createLogger } from "@forwardimpact/libtelemetry";
2
+ import { refusalEnvelope } from "../secret-gate.js";
3
+ import { AncestryRefusal, WikiPullConflict } from "../wiki-sync.js";
4
+ import { sweepTier2, renderDetections } from "../integrity.js";
5
+ import { resolveWikiRoot } from "../util/wiki-dir.js";
2
6
 
3
- /** Commit all wiki changes and push them to the remote wiki repository. */
7
+ /**
8
+ * Commit all wiki changes and push them through the secret-gated push path.
9
+ * A detected secret or unavailable scanner fails the command closed and names
10
+ * the cause on stderr without attempting the push; a clean write pushes or
11
+ * reports nothing to push. The post-push tier-1 integrity detections surface in
12
+ * the output; they never gate the push.
13
+ */
4
14
  export async function runPushCommand(ctx) {
5
15
  const { runtime, wikiSync } = ctx.deps;
6
16
  await wikiSync.inheritIdentity();
7
17
 
8
- const result = await wikiSync.commitAndPush("wiki: update from session");
18
+ let result;
19
+ try {
20
+ result = await wikiSync.commitAndPush("wiki: update from session");
21
+ } catch (err) {
22
+ if (err instanceof AncestryRefusal) {
23
+ runtime.proc.stderr.write(`${err.message}\n`);
24
+ return { ok: false, code: 1 };
25
+ }
26
+ throw err;
27
+ }
28
+ // Fail the command closed on a secret-gate refusal (secret detected or scanner
29
+ // unavailable); a clean push falls through to the normal reporting below.
30
+ const refusal = refusalEnvelope(runtime, result);
31
+ if (refusal) return refusal;
9
32
  if (result.pushed) {
10
33
  runtime.proc.stdout.write("push: committed and pushed\n");
11
34
  } else {
12
35
  runtime.proc.stdout.write("push: nothing to push\n");
13
36
  }
37
+ if (result.detections?.length) {
38
+ runtime.proc.stdout.write(renderDetections(result.detections));
39
+ }
14
40
  return { ok: true };
15
41
  }
16
42
 
17
- /** Fetch and rebase the local wiki on origin/master; on rebase conflict, return a non-zero envelope with a message to resolve manually or push first. */
43
+ /** Fetch and rebase the local wiki on origin/master; on rebase conflict, return a non-zero envelope with a message to resolve manually or push first. After a clean pull, the tier-2 lane-record sweep surfaces any previous-session content absent at the fetched tip; it never gates the boot. */
18
44
  export async function runPullCommand(ctx) {
19
- const { runtime, wikiSync } = ctx.deps;
45
+ const { runtime, wikiSync, gitClient } = ctx.deps;
20
46
  await wikiSync.inheritIdentity();
21
47
 
22
48
  try {
23
49
  await wikiSync.pull();
24
50
  runtime.proc.stdout.write("pull: up to date\n");
25
- return { ok: true };
26
51
  } catch (err) {
27
52
  if (err instanceof WikiPullConflict) {
28
- runtime.proc.stderr.write(
29
- "fit-wiki pull: rebase conflict — local divergence detected; resolve manually or push first\n",
53
+ createLogger("wiki", runtime).error(
54
+ "pull",
55
+ "rebase conflict — local divergence detected; resolve manually or push first",
30
56
  );
31
57
  return { ok: false, code: 1 };
32
58
  }
33
59
  throw err;
34
60
  }
61
+
62
+ // Tier-2 sweep on the just-rebased tree. Detection-only: any failure degrades
63
+ // to no detections, never throws into the flow, never changes the exit code.
64
+ try {
65
+ const wikiDir = resolveWikiRoot(runtime, ctx.options);
66
+ // `--today` (ISO date) overrides the wall clock for deterministic tests;
67
+ // a malformed value falls back to the runtime clock rather than NaN.
68
+ const today = ctx.options.today
69
+ ? Date.parse(ctx.options.today)
70
+ : Number.NaN;
71
+ const now = Number.isNaN(today) ? runtime.clock.now() : today;
72
+ const detections = await sweepTier2({
73
+ runtime,
74
+ gitClient,
75
+ wikiDir,
76
+ agent: ctx.options.agent,
77
+ now,
78
+ });
79
+ if (detections.length)
80
+ runtime.proc.stdout.write(renderDetections(detections));
81
+ } catch {
82
+ // Detection-only instrument: a sweep error never gates the boot flow.
83
+ }
84
+ return { ok: true };
35
85
  }
@@ -0,0 +1,78 @@
1
+ // Structural detector for unresolved git conflict markers, shared by the wiki
2
+ // audit's `conflict.markers` rule (audit/conflict-markers-rule.js) and the
3
+ // WikiSync pre-push guard (wiki-sync.js). One home so the two layers cannot
4
+ // drift on what counts as a marker.
5
+ //
6
+ // Detection is line-anchored and structural, not a naive grep, so it does not
7
+ // fire on markers legitimately quoted in prose:
8
+ //
9
+ // - Open (`<<<<<<<`) and close (`>>>>>>>`) marker lines fire UNCONDITIONALLY,
10
+ // per file. A seal rotation can sever one conflict block across two sealed
11
+ // files (the open in one, the separator + close in the other); a
12
+ // complete-in-file-block matcher would miss both, so each marker form stands
13
+ // alone. The single-space-or-end-of-line guard after the 7-char run admits
14
+ // the stash-pop label forms (`<<<<<<< Updated upstream`,
15
+ // `>>>>>>> Stashed changes`) and the branch/sha label forms while rejecting
16
+ // longer `<`/`>` runs.
17
+ // - The separator (`=======`) fires ONLY while a conflict block is open in the
18
+ // same file (block-conditioned). A lone separator with no open above it is
19
+ // indistinguishable from a setext-heading underline and is a deliberate
20
+ // accepted non-detection.
21
+ // - In a `fenceExempt` (prose) surface, occurrences inside a fenced code block
22
+ // are suppressed — a fence quotes content. Markers quoted in a backtick code
23
+ // SPAN are handled by the column-1 anchor itself: a span sits mid-line, so
24
+ // `^` never matches. STATUS.md and non-markdown push targets pass
25
+ // `fenceExempt:false`: their fenced rows are data, where a marker is never
26
+ // legitimate, so fence state never suppresses.
27
+
28
+ const OPEN_RE = /^<{7}( |$)/;
29
+ const CLOSE_RE = /^>{7}( |$)/;
30
+ const SEPARATOR_RE = /^={7}\s*$/;
31
+ // A fenced-code delimiter: three or more backticks or tildes, up to three
32
+ // leading spaces of indentation (CommonMark). The info string after the run is
33
+ // ignored — a delimiter line is never itself a marker.
34
+ const FENCE_RE = /^\s{0,3}(`{3,}|~{3,})/;
35
+
36
+ /**
37
+ * Scan `text` for unresolved git conflict markers.
38
+ *
39
+ * @param {string} text - The file (or diff-added) content to scan.
40
+ * @param {object} [options]
41
+ * @param {boolean} [options.fenceExempt=true] - When true, suppress markers
42
+ * inside fenced code blocks (prose surfaces). When false, fence state never
43
+ * suppresses (STATUS.md, non-markdown targets).
44
+ * @returns {Array<{lineNo: number, kind: "open"|"separator"|"close"}>}
45
+ * One entry per detected marker line, in document order.
46
+ */
47
+ export function scanConflictMarkers(text, { fenceExempt = true } = {}) {
48
+ const lines = text.split("\n");
49
+ const hits = [];
50
+ let insideFence = false;
51
+ let openDepth = 0;
52
+ for (let i = 0; i < lines.length; i++) {
53
+ // Strip a trailing CR so a CRLF checkout is matched identically to LF — a
54
+ // bare marker (`<<<<<<<\r`) would otherwise escape the `( |$)` anchor and
55
+ // a CRLF corruption block would publish undetected.
56
+ const line = lines[i].replace(/\r$/, "");
57
+ if (FENCE_RE.test(line)) {
58
+ insideFence = !insideFence;
59
+ continue;
60
+ }
61
+ if (fenceExempt && insideFence) continue;
62
+ const kind = classify(line, openDepth);
63
+ if (!kind) continue;
64
+ hits.push({ lineNo: i + 1, kind });
65
+ if (kind === "open") openDepth++;
66
+ else if (kind === "close" && openDepth > 0) openDepth--;
67
+ }
68
+ return hits;
69
+ }
70
+
71
+ // Classify a single line as a marker kind, or null. The separator is
72
+ // block-conditioned: it only counts while a conflict block is open.
73
+ function classify(line, openDepth) {
74
+ if (OPEN_RE.test(line)) return "open";
75
+ if (CLOSE_RE.test(line)) return "close";
76
+ if (openDepth > 0 && SEPARATOR_RE.test(line)) return "separator";
77
+ return null;
78
+ }
package/src/constants.js CHANGED
@@ -3,6 +3,21 @@ export const INBOX_HEADING = "## Message Inbox";
3
3
  export const BROADCAST_TARGET = "all";
4
4
 
5
5
  export const MEMORY_FILE = "MEMORY.md";
6
+
7
+ // Row-structured singleton surfaces under the sync-merge discipline: when a
8
+ // landing on one of these is contended, the resolution re-runs the row
9
+ // operation against the fresh remote tip (rebase the operation, not the
10
+ // lines), never a textual merge. Founding member: MEMORY.md (the Active Claims
11
+ // table). STATUS.md phase rows join as their own re-apply operations land.
12
+ // Metrics CSV appends take the complementary union-merge path below.
13
+ export const SINGLETON_PATHS = new Set([MEMORY_FILE]);
14
+
15
+ // The tracked `.gitattributes` declaration that makes concurrent appends to
16
+ // metrics CSVs union-merge (keep both sides' rows) on every publish path,
17
+ // instead of conflicting or side-picking. Carried by the wiki repo itself so
18
+ // it governs every clone.
19
+ export const GITATTRIBUTES_FILE = ".gitattributes";
20
+ export const METRICS_CSV_MERGE_ATTRIBUTE = "metrics/**/*.csv merge=union";
6
21
  export const ACTIVE_CLAIMS_HEADING = "## Active Claims";
7
22
  export const ACTIVE_CLAIMS_TABLE_HEADER =
8
23
  "| agent | target | branch | pr | claimed_at | expires_at |";
@@ -53,12 +68,27 @@ export const WEEKLY_LOG_NAME_RE = /^([a-z][a-z-]*)-(\d{4})-W(\d{2})\.md$/;
53
68
  export const WEEKLY_LOG_PART_NAME_RE =
54
69
  /^([a-z][a-z-]*)-(\d{4})-W(\d{2})-part\d+\.md$/;
55
70
 
71
+ // Day-section seam: `## YYYY-MM-DD` at line start, a trailing suffix tolerated
72
+ // (e.g. `## 2026-05-19 (third activation)`). One home so the rotation
73
+ // seam-finder (weekly-log.js), the `log` command's last-entry probe
74
+ // (commands/log.js), and the audit's heading-grammar-drift rule (audit/rules.js)
75
+ // cannot disagree on what a conforming entry heading is. Source has no flags;
76
+ // call sites add `g`/`m` as needed via `new RegExp(WEEKLY_LOG_SEAM_RE.source, …)`.
77
+ export const WEEKLY_LOG_SEAM_RE = /^## (\d{4}-\d{2}-\d{2})/;
78
+
79
+ // Tier-2 integrity sweep idle-gap: lane-authored commits separated by more
80
+ // than this delimit sessions in the wiki history. 30 minutes.
81
+ export const SESSION_GAP_MS = 30 * 60 * 1000;
82
+
56
83
  // Storyboard marker syntax. An open or close marker tolerates optional trailing
57
84
  // text after the tag (typically an inline "Do not edit. Generated from fit-wiki
58
85
  // refresh." notice). One home so the marker scanner (marker-scanner.js) and the
59
86
  // audit's balance check (audit/rules.js) cannot drift on the syntax.
87
+ // Capture groups: 1 metric, 2 csvPath, 3 optional prior-read anchor date. The
88
+ // `prior=YYYY-MM-DD` token sits before the trailing-text group so the "Do not
89
+ // edit" notice is still tolerated and does not swallow the anchor.
60
90
  export const XMR_OPEN_RE =
61
- /^<!--\s*xmr:([^:\s]+):(\S+)(?:\s+[^>]*?)?\s*-->\s*$/;
91
+ /^<!--\s*xmr:([^:\s]+):(\S+)(?:\s+prior=(\d{4}-\d{2}-\d{2}))?(?:\s+[^>]*?)?\s*-->\s*$/;
62
92
  export const XMR_CLOSE_RE = /^<!--\s*\/xmr(?:\s+[^>]*?)?\s*-->\s*$/;
63
93
  export const ISSUE_OPEN_RE =
64
94
  /^<!--\s*(obstacles|experiments):(open|closed)(?::(\d+d))?(?:\s+[^>]*?)?\s*-->\s*$/;
@@ -0,0 +1,40 @@
1
+ import path from "node:path";
2
+ import {
3
+ GITATTRIBUTES_FILE,
4
+ METRICS_CSV_MERGE_ATTRIBUTE,
5
+ } from "./constants.js";
6
+
7
+ /**
8
+ * Ensure the wiki's tracked `.gitattributes` declares the metrics-CSV union
9
+ * merge attribute (`metrics/**\/*.csv merge=union`), idempotently.
10
+ *
11
+ * Present-and-correct means no write: if the exact attribute line already
12
+ * appears in the file, the file is left byte-unchanged and `{ changed: false }`
13
+ * is returned. Otherwise the line is appended (preserving any existing
14
+ * `.gitattributes` content) or the file is created with just that line, and
15
+ * `{ changed: true }` is returned.
16
+ *
17
+ * The single union declaration governs every clone because it is a tracked
18
+ * worktree file; per-clone config (`core.attributesFile`, `.git/info/attributes`)
19
+ * would not propagate to the sibling sessions that cause the loss.
20
+ *
21
+ * @param {string} wikiDir - The wiki clone directory.
22
+ * @param {import('node:fs')} fsSync - Synchronous filesystem surface (`runtime.fsSync`).
23
+ * @returns {{ changed: boolean }}
24
+ */
25
+ export function ensureMetricsCsvMergeAttribute(wikiDir, fsSync) {
26
+ const filePath = path.join(wikiDir, GITATTRIBUTES_FILE);
27
+ if (fsSync.existsSync(filePath)) {
28
+ const text = fsSync.readFileSync(filePath, "utf-8");
29
+ const present = text
30
+ .split("\n")
31
+ .some((line) => line.trim() === METRICS_CSV_MERGE_ATTRIBUTE);
32
+ if (present) return { changed: false };
33
+ // Append the line, keeping existing content and ending with a newline.
34
+ const base = text.endsWith("\n") || text === "" ? text : `${text}\n`;
35
+ fsSync.writeFileSync(filePath, `${base}${METRICS_CSV_MERGE_ATTRIBUTE}\n`);
36
+ return { changed: true };
37
+ }
38
+ fsSync.writeFileSync(filePath, `${METRICS_CSV_MERGE_ATTRIBUTE}\n`);
39
+ return { changed: true };
40
+ }
package/src/index.js CHANGED
@@ -18,9 +18,10 @@ export {
18
18
  SUMMARY_WORD_BUDGET,
19
19
  } from "./constants.js";
20
20
  export { scanMarkers } from "./marker-scanner.js";
21
+ export { scanConflictMarkers } from "./conflict-markers.js";
21
22
  export { renderBlock } from "./block-renderer.js";
22
23
  export { renderIssueList } from "./issue-list-renderer.js";
23
- export { WikiSync, WikiPullConflict } from "./wiki-sync.js";
24
+ export { WikiSync, WikiPullConflict, WikiSyncRefusal } from "./wiki-sync.js";
24
25
  export { listSkills } from "./skill-roster.js";
25
26
  export {
26
27
  parseClaims,