@digital-lake/lognexus 1.3.7 → 1.4.1

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.
Files changed (87) hide show
  1. package/LICENSE +2 -2
  2. package/NOTICE.md +2 -2
  3. package/README.md +72 -47
  4. package/dist/audit/audit.d.ts +37 -2
  5. package/dist/audit/audit.d.ts.map +1 -1
  6. package/dist/audit/audit.js +540 -57
  7. package/dist/audit/audit.js.map +1 -1
  8. package/dist/cli.d.ts +9 -0
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +342 -34
  11. package/dist/cli.js.map +1 -1
  12. package/dist/commit.d.ts +6 -0
  13. package/dist/commit.d.ts.map +1 -1
  14. package/dist/commit.js +61 -23
  15. package/dist/commit.js.map +1 -1
  16. package/dist/doctor.d.ts +1 -0
  17. package/dist/doctor.d.ts.map +1 -1
  18. package/dist/doctor.js +31 -8
  19. package/dist/doctor.js.map +1 -1
  20. package/dist/index.d.ts +2 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/mcp/prompts.d.ts.map +1 -1
  25. package/dist/mcp/prompts.js +14 -10
  26. package/dist/mcp/prompts.js.map +1 -1
  27. package/dist/notes/attach.d.ts +11 -0
  28. package/dist/notes/attach.d.ts.map +1 -1
  29. package/dist/notes/attach.js +22 -5
  30. package/dist/notes/attach.js.map +1 -1
  31. package/dist/routing/profile.d.ts +44 -0
  32. package/dist/routing/profile.d.ts.map +1 -0
  33. package/dist/routing/profile.js +261 -0
  34. package/dist/routing/profile.js.map +1 -0
  35. package/dist/scaffold.d.ts +3 -3
  36. package/dist/scaffold.d.ts.map +1 -1
  37. package/dist/scaffold.js +31 -19
  38. package/dist/scaffold.js.map +1 -1
  39. package/dist/state/handoff.d.ts +18 -0
  40. package/dist/state/handoff.d.ts.map +1 -1
  41. package/dist/state/handoff.js +60 -10
  42. package/dist/state/handoff.js.map +1 -1
  43. package/dist/state/manager.d.ts.map +1 -1
  44. package/dist/state/manager.js +60 -1
  45. package/dist/state/manager.js.map +1 -1
  46. package/dist/state/schema.d.ts +38 -0
  47. package/dist/state/schema.d.ts.map +1 -1
  48. package/dist/state/schema.js +9 -0
  49. package/dist/state/schema.js.map +1 -1
  50. package/dist/status.d.ts +10 -0
  51. package/dist/status.d.ts.map +1 -1
  52. package/dist/status.js +171 -42
  53. package/dist/status.js.map +1 -1
  54. package/dist/telemetry/benchmark.d.ts +51 -0
  55. package/dist/telemetry/benchmark.d.ts.map +1 -0
  56. package/dist/telemetry/benchmark.js +541 -0
  57. package/dist/telemetry/benchmark.js.map +1 -0
  58. package/dist/telemetry/collector.d.ts +109 -3
  59. package/dist/telemetry/collector.d.ts.map +1 -1
  60. package/dist/telemetry/collector.js +737 -178
  61. package/dist/telemetry/collector.js.map +1 -1
  62. package/dist/telemetry/consent-prompt.d.ts +35 -0
  63. package/dist/telemetry/consent-prompt.d.ts.map +1 -0
  64. package/dist/telemetry/consent-prompt.js +215 -0
  65. package/dist/telemetry/consent-prompt.js.map +1 -0
  66. package/dist/telemetry/detector.d.ts +16 -1
  67. package/dist/telemetry/detector.d.ts.map +1 -1
  68. package/dist/telemetry/detector.js +362 -38
  69. package/dist/telemetry/detector.js.map +1 -1
  70. package/dist/telemetry/index.d.ts +5 -4
  71. package/dist/telemetry/index.d.ts.map +1 -1
  72. package/dist/telemetry/index.js +5 -4
  73. package/dist/telemetry/index.js.map +1 -1
  74. package/dist/telemetry/report.d.ts +3 -2
  75. package/dist/telemetry/report.d.ts.map +1 -1
  76. package/dist/telemetry/report.js +66 -14
  77. package/dist/telemetry/report.js.map +1 -1
  78. package/dist/telemetry/schema.d.ts +305 -2
  79. package/dist/telemetry/schema.d.ts.map +1 -1
  80. package/dist/telemetry/schema.js +142 -4
  81. package/dist/telemetry/schema.js.map +1 -1
  82. package/dist/update/gate.d.ts +1 -1
  83. package/dist/update/gate.d.ts.map +1 -1
  84. package/dist/update/gate.js +2 -0
  85. package/dist/update/gate.js.map +1 -1
  86. package/package.json +2 -2
  87. package/server.json +3 -3
package/dist/cli.js CHANGED
@@ -13,15 +13,20 @@ import { generateContextHandoff, renderCompactDispatchPrompt, renderContextHando
13
13
  import { clearState, finishSubtask, loadState, parseSetTaskArgs, setSubtask, } from "./state/manager.js";
14
14
  import { syncStateFromGit } from "./state/sync.js";
15
15
  import { getProjectStatus } from "./status.js";
16
- import { buildAnonymousCommunityPayload, clearTelemetry, disableTelemetry, enableTelemetry, isTelemetryGloballyDisabled, LOCAL_ONLY_TELEMETRY_ERROR, loadTelemetry, } from "./telemetry/collector.js";
16
+ import { aggregateBenchmarkCohort, exportTelemetrySnapshot, formatCohortMarkdownReport, generateCohortBenchmarkReportFile, } from "./telemetry/benchmark.js";
17
+ import { buildAnonymousDiagnosticPayload, clearTelemetry, declineTelemetry, disableTelemetry, enableTelemetry, getTelemetryConsentState, isTelemetryGloballyDisabled, LOCAL_ONLY_TELEMETRY_ERROR, loadTelemetry, syncTelemetryFromGitNotes, } from "./telemetry/collector.js";
18
+ import { isAgentEnvironment, maybePromptTelemetryConsent } from "./telemetry/consent-prompt.js";
17
19
  import { generateTelemetryReportFile } from "./telemetry/report.js";
20
+ import { TELEMETRY_POLICY_VERSION } from "./telemetry/schema.js";
18
21
  import { getJourneyTimeline } from "./timeline/timeline.js";
19
22
  import { acceptTerms, checkUpdateGate, formatUpdateGateResult, readTermsConsent, UPGRADE_COMMAND, } from "./update/gate.js";
20
- const __cliDir = dirname(fileURLToPath(import.meta.url));
23
+ function getCliDir() {
24
+ return dirname(fileURLToPath(import.meta.url));
25
+ }
21
26
  export { parseCommitArgs } from "./commit.js";
22
27
  export function getCliVersion() {
23
28
  try {
24
- const pkgPath = join(__cliDir, "..", "package.json");
29
+ const pkgPath = join(getCliDir(), "..", "package.json");
25
30
  if (existsSync(pkgPath)) {
26
31
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
27
32
  if (pkg.version)
@@ -31,19 +36,29 @@ export function getCliVersion() {
31
36
  catch {
32
37
  // fallback
33
38
  }
34
- return "1.3.7";
39
+ return "1.4.1";
35
40
  }
36
41
  function printHeader() {
37
42
  console.log("\n🔷 LogNexus CLI — Digital Lake");
38
43
  console.log(" The Universal Git-Powered Context & Rules Framework for Native AI Agents\n");
39
44
  }
45
+ const STARTUP_GATE_EXEMPT_COMMANDS = new Set([
46
+ "mcp",
47
+ "terms",
48
+ "version",
49
+ "help",
50
+ "--help",
51
+ "-h",
52
+ "--version",
53
+ "-v",
54
+ ]);
40
55
  /**
41
56
  * Runs the non-interactive startup gate. The MCP transport is exempt because stdout
42
- * carries JSON-RPC frames there, and the gate is also skipped for `mcp`, `terms` and
43
- * `version` so an operator can always inspect or clear a block.
57
+ * carries JSON-RPC frames there, and the gate is also skipped for `mcp`, `terms`,
58
+ * `version`, and `help` aliases so an operator can always inspect or clear a block.
44
59
  */
45
60
  function runStartupGate(command) {
46
- if (command === "mcp" || command === "terms" || command === "version")
61
+ if (command !== undefined && STARTUP_GATE_EXEMPT_COMMANDS.has(command))
47
62
  return;
48
63
  const result = checkUpdateGate({ currentVersion: getCliVersion() });
49
64
  const notice = formatUpdateGateResult(result);
@@ -76,7 +91,7 @@ async function handleTerms(args) {
76
91
  }
77
92
  function readLocalTermsVersion() {
78
93
  try {
79
- const pkgPath = join(__cliDir, "..", "package.json");
94
+ const pkgPath = join(getCliDir(), "..", "package.json");
80
95
  if (existsSync(pkgPath)) {
81
96
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
82
97
  const version = pkg?.lognexusPolicy?.termsVersion;
@@ -97,6 +112,7 @@ function printUsage() {
97
112
  Commands:
98
113
  init Scaffold .lognexus/ configuration and rules in current repository
99
114
  (--protect-tokens) also writes multi-model token-ignore files
115
+ (--enable-telemetry | --no-telemetry | --disable-telemetry) set local telemetry choice
100
116
  doctor Check Git, GitHub CLI authentication, and repository rules health
101
117
  status Inspect current branch, active issue, and recommended tier
102
118
  commit Atomic commit with trailers, contract validation, and Git Note
@@ -114,8 +130,14 @@ Commands:
114
130
  Telemetry Subcommands:
115
131
  lognexus telemetry [status] Show current telemetry mode and project metrics
116
132
  lognexus telemetry enable Enable local telemetry (zero network calls, strictly local storage)
117
- lognexus telemetry inspect Inspect the exact Zero-PII payload before sending
118
- lognexus telemetry report [-o f] Generate .lognexus/telemetry.md report with ROI metrics
133
+ lognexus telemetry report [-o f] [--issue <id>] [--since <iso>] [--branch <ref>]
134
+ Generate .lognexus/telemetry.md report with ROI metrics
135
+ lognexus telemetry inspect [--issue <id>] [--since <iso>] [--branch <ref>]
136
+ Print the Zero-PII payload, optionally scoped
137
+ lognexus telemetry snapshot [-o f] [--issue <id>] [--since <iso>] [--branch <ref>]
138
+ Write a Zero-PII .lognexus/snapshot-v2.json, never uploaded
139
+ lognexus telemetry benchmark <paths...> [-o f] [--json]
140
+ Aggregate exported snapshots into a cohort benchmark
119
141
  lognexus telemetry disable Disable all telemetry immediately
120
142
  lognexus telemetry clear Reset local telemetry store
121
143
 
@@ -131,17 +153,25 @@ Commit Command:
131
153
  --allow-empty Allow creating empty commits
132
154
  --tier <tier-1|tier-2|tier-3> Override the routing tier (defaults to the author tier)
133
155
  --escalated Acknowledge a tier-1 author working on a tier-3 subtask
156
+ --swarm-workers <n> Number of active swarm workers cooperating on subtask
157
+ --swarm-posts <n> Total swarm board posts coordinated for subtask
134
158
 
135
159
  State Subcommands:
136
160
  lognexus state [show] Display current active issue and task state
137
161
  lognexus state sync Sync state from current Git branch & GitHub
138
162
  lognexus state set-task <id> [t] Set active subtask (e.g. lognexus state set-task T1 "Add schema")
163
+ [--assignee "<identity>"] [--tier <tier-1|tier-2|tier-3>]
164
+ [--isolation <subagent|swarm|worktree|branch|shared>]
165
+ [--swarm-workers <n>] [--swarm-posts <n>]
166
+ [--allowed <csv>] [--forbidden <csv>]
167
+ [--budget <none|low|medium|high>] [--verify "<cmd>"]
139
168
  lognexus state finish-task <id> Mark subtask as completed (e.g. lognexus state finish-task T1)
140
169
  lognexus state clear Reset persistent state to empty
141
170
 
142
171
  Note Subcommands:
143
172
  lognexus note [show] [commit] Display LogNexus Git Note for commit (default: HEAD)
144
173
  lognexus note attach [commit] Attach current session state as Git Note to commit
174
+ [--swarm-workers <n>] [--swarm-posts <n>]
145
175
  lognexus note list List all commits with LogNexus Git Notes
146
176
  lognexus note search [query] Recall past decisions stored in refs/notes/lognexus
147
177
  [--file <path>] [--author <model>] [--issue <num>]
@@ -185,18 +215,31 @@ Examples:
185
215
  async function handleInit(args = []) {
186
216
  printHeader();
187
217
  let protectTokens = false;
218
+ let enableTelemetryFlag = false;
219
+ let disableTelemetryFlag = false;
188
220
  for (const arg of args) {
189
221
  if (arg === "--protect-tokens") {
190
222
  protectTokens = true;
191
223
  }
224
+ else if (arg === "--enable-telemetry") {
225
+ enableTelemetryFlag = true;
226
+ }
227
+ else if (arg === "--no-telemetry" || arg === "--disable-telemetry") {
228
+ disableTelemetryFlag = true;
229
+ }
192
230
  else if (arg.startsWith("-")) {
193
231
  console.error(`[ERROR] Unknown init option: ${arg}\n`);
194
232
  printUsage();
195
233
  process.exit(1);
196
234
  }
197
235
  }
236
+ if (enableTelemetryFlag && disableTelemetryFlag) {
237
+ console.error("[ERROR] Cannot combine --enable-telemetry with --no-telemetry or --disable-telemetry.\n");
238
+ process.exit(1);
239
+ }
198
240
  console.log("Initializing LogNexus in current repository...\n");
199
- const res = initProject(process.cwd(), { protectTokens });
241
+ const cwd = process.cwd();
242
+ const res = initProject(cwd, { protectTokens });
200
243
  if (res.created.length > 0) {
201
244
  console.log("Created files:");
202
245
  for (const f of res.created) {
@@ -209,6 +252,24 @@ async function handleInit(args = []) {
209
252
  console.log(` [.] ${f}`);
210
253
  }
211
254
  }
255
+ if (enableTelemetryFlag) {
256
+ if (isAgentEnvironment()) {
257
+ process.stderr.write("Confirm telemetry opt-in from an interactive human terminal (automated agent sealing is disabled).\n");
258
+ }
259
+ else {
260
+ enableTelemetry({ cwd, acceptTerms: true });
261
+ }
262
+ }
263
+ else if (disableTelemetryFlag) {
264
+ declineTelemetry(cwd);
265
+ }
266
+ else {
267
+ await maybePromptTelemetryConsent({
268
+ command: "init",
269
+ args,
270
+ targetDir: cwd,
271
+ });
272
+ }
212
273
  console.log("\nNext Steps:");
213
274
  console.log(" • Claude Code / Cursor / Codex / Antigravity / Gemini / Kimi: use /lognexus plan");
214
275
  console.log(" • Configure model tiers in .lognexus/routing.md");
@@ -228,14 +289,16 @@ async function handleDoctor() {
228
289
  }
229
290
  console.log("\nDiagnostic complete.\n");
230
291
  }
231
- async function handleStatus() {
292
+ export async function handleStatus(targetDir = process.cwd()) {
232
293
  printHeader();
233
- const st = getProjectStatus();
294
+ const st = getProjectStatus(targetDir);
234
295
  console.log(`Git Repository: ${st.isInsideGit ? "Yes" : "No"}`);
235
296
  console.log(`Current Branch: ${st.branch}`);
236
297
  console.log(`Project Version: ${st.projectVersion ? `${st.projectVersion} (${st.publishedReleases} release(s) published)` : "(no manifest detected)"}`);
237
298
  console.log(`Active Issue: ${st.activeIssue ?? "(none — on base branch)"}`);
238
299
  console.log(`Rules Routing Mode: ${st.routingMode}`);
300
+ console.log(`Ecosystem Profile: ${st.ecosystemProfile}`);
301
+ console.log(`Review Gate Mode: ${st.reviewGateMode}`);
239
302
  console.log(`Recommended Tier: ${st.recommendedTier}`);
240
303
  if (st.scopeDrift.detected) {
241
304
  console.log(`Scope Drift: [SCOPE DRIFT DETECTED] ${st.scopeDrift.unauthorizedFiles.join(", ")}`);
@@ -245,12 +308,12 @@ async function handleStatus() {
245
308
  }
246
309
  console.log("");
247
310
  }
248
- async function handleState(args) {
311
+ export async function handleState(args, targetDir = process.cwd()) {
249
312
  const sub = args[0]?.toLowerCase() || "show";
250
313
  switch (sub) {
251
314
  case "show": {
252
315
  printHeader();
253
- const state = loadState();
316
+ const state = loadState(targetDir);
254
317
  console.log("Persistent Agent State (.lognexus/state.json):\n");
255
318
  if (state.activeIssue) {
256
319
  console.log(`Active Issue: #${state.activeIssue.id} — ${state.activeIssue.title}`);
@@ -269,6 +332,16 @@ async function handleState(args) {
269
332
  console.log(` Title: ${state.currentSubtask.title}`);
270
333
  }
271
334
  if (state.currentSubtask.contract) {
335
+ if (state.currentSubtask.contract.assignee) {
336
+ console.log(` Assigned Agent: ${state.currentSubtask.contract.assignee}`);
337
+ }
338
+ if (state.currentSubtask.contract.isolation) {
339
+ console.log(` Isolation Mode: ${state.currentSubtask.contract.isolation}`);
340
+ }
341
+ if (state.currentSubtask.contract.swarmWorkers !== undefined ||
342
+ state.currentSubtask.contract.swarmPosts !== undefined) {
343
+ console.log(` Swarm Metrics: ${state.currentSubtask.contract.swarmWorkers ?? 0} worker(s), ${state.currentSubtask.contract.swarmPosts ?? 0} post(s)`);
344
+ }
272
345
  console.log(` Allowed Files: ${state.currentSubtask.contract.allowedFiles.join(", ") || "(all)"}`);
273
346
  console.log(` Decision Budget: ${state.currentSubtask.contract.decisionBudget}`);
274
347
  if (state.currentSubtask.contract.verificationCmd) {
@@ -286,7 +359,7 @@ async function handleState(args) {
286
359
  case "sync": {
287
360
  printHeader();
288
361
  console.log("Synchronizing state from current Git branch and GitHub...\n");
289
- const synced = syncStateFromGit();
362
+ const synced = syncStateFromGit(targetDir);
290
363
  if (synced.activeIssue) {
291
364
  console.log(`[OK] Synchronized with Issue #${synced.activeIssue.id} (${synced.activeIssue.title})`);
292
365
  console.log(` Branch: ${synced.activeIssue.branch}`);
@@ -312,7 +385,7 @@ async function handleState(args) {
312
385
  process.exit(1);
313
386
  }
314
387
  printHeader();
315
- setSubtask(parsed.taskId, parsed.title, parsed.contract, undefined, { tier: parsed.tier });
388
+ setSubtask(parsed.taskId, parsed.title, parsed.contract, targetDir, { tier: parsed.tier });
316
389
  console.log(`[OK] Active subtask set to: ${parsed.taskId}${parsed.title ? ` — ${parsed.title}` : ""}\n`);
317
390
  break;
318
391
  }
@@ -323,13 +396,13 @@ async function handleState(args) {
323
396
  process.exit(1);
324
397
  }
325
398
  printHeader();
326
- finishSubtask(taskId);
399
+ finishSubtask(taskId, targetDir);
327
400
  console.log(`[OK] Subtask ${taskId} marked as completed.\n`);
328
401
  break;
329
402
  }
330
403
  case "clear": {
331
404
  printHeader();
332
- clearState();
405
+ clearState(targetDir);
333
406
  console.log("[OK] Persistent state cleared.\n");
334
407
  break;
335
408
  }
@@ -358,9 +431,38 @@ async function handleNote(args) {
358
431
  break;
359
432
  }
360
433
  case "attach": {
361
- const commit = args[1] || "HEAD";
434
+ let commit = "HEAD";
435
+ let swarmWorkers;
436
+ let swarmPosts;
437
+ for (let i = 1; i < args.length; i++) {
438
+ const arg = args[i];
439
+ if (arg === "--swarm-workers") {
440
+ const val = args[++i];
441
+ if (!val || !/^\d+$/.test(val)) {
442
+ console.error("Error: --swarm-workers must be a non-negative integer.\n");
443
+ process.exit(1);
444
+ }
445
+ swarmWorkers = Number.parseInt(val, 10);
446
+ }
447
+ else if (arg === "--swarm-posts") {
448
+ const val = args[++i];
449
+ if (!val || !/^\d+$/.test(val)) {
450
+ console.error("Error: --swarm-posts must be a non-negative integer.\n");
451
+ process.exit(1);
452
+ }
453
+ swarmPosts = Number.parseInt(val, 10);
454
+ }
455
+ else if (arg.startsWith("-")) {
456
+ console.error(`Unknown option for note attach: ${arg}\n`);
457
+ printUsage();
458
+ process.exit(1);
459
+ }
460
+ else {
461
+ commit = arg;
462
+ }
463
+ }
362
464
  printHeader();
363
- const payload = attachCurrentStateToCommit(commit);
465
+ const payload = attachCurrentStateToCommit(commit, { swarmWorkers, swarmPosts });
364
466
  console.log(`[OK] Attached LogNexus note to commit [${commit}] (refs/notes/lognexus):`);
365
467
  console.log(` Issue: ${payload.issue ? `#${payload.issue.id} — ${payload.issue.title}` : "(none)"}`);
366
468
  console.log(` Subtask: ${payload.subtask ? `${payload.subtask.id} (${payload.subtask.title})` : "(none)"}`);
@@ -614,6 +716,8 @@ async function handleCommit(args) {
614
716
  tier: parsed.tier,
615
717
  escalated: parsed.escalated,
616
718
  stageAllowed: parsed.stageAllowed,
719
+ swarmWorkers: parsed.swarmWorkers,
720
+ swarmPosts: parsed.swarmPosts,
617
721
  });
618
722
  console.log(`[OK] Committed [${res.shortSha}] ${res.subject}`);
619
723
  console.log(` Authored-by: ${res.author}`);
@@ -631,23 +735,103 @@ async function handleCommit(args) {
631
735
  process.exit(1);
632
736
  }
633
737
  }
738
+ /**
739
+ * Parses the scoping flags shared by `telemetry inspect`, `report` and `snapshot`.
740
+ *
741
+ * A missing flag value or an unrecognised `-` prefixed argument aborts instead of being
742
+ * silently ignored, so a scoped command can never fall back to the whole history unnoticed.
743
+ */
744
+ function parseTelemetryScopeFlags(args, allowPositionals = false) {
745
+ const filter = {};
746
+ const positionals = [];
747
+ let outputPath;
748
+ let json = false;
749
+ const readValue = (flag, index) => {
750
+ const value = args[index + 1];
751
+ if (value === undefined || value.startsWith("-") || value.trim() === "") {
752
+ console.error(`[FAIL] ${flag} requires a value.\n`);
753
+ process.exit(1);
754
+ }
755
+ return value;
756
+ };
757
+ for (let index = 0; index < args.length; index += 1) {
758
+ const arg = args[index];
759
+ if (arg === "--issue") {
760
+ filter.issue = readValue("--issue", index);
761
+ index += 1;
762
+ }
763
+ else if (arg === "--since") {
764
+ filter.since = readValue("--since", index);
765
+ index += 1;
766
+ }
767
+ else if (arg === "--branch") {
768
+ filter.branch = readValue("--branch", index);
769
+ index += 1;
770
+ }
771
+ else if (arg === "--output" || arg === "-o") {
772
+ outputPath = readValue(arg, index);
773
+ index += 1;
774
+ }
775
+ else if (arg === "--json") {
776
+ json = true;
777
+ }
778
+ else if (arg.startsWith("-")) {
779
+ console.error(`[FAIL] Unknown telemetry flag: ${arg}\n`);
780
+ process.exit(1);
781
+ }
782
+ else if (allowPositionals) {
783
+ positionals.push(arg);
784
+ }
785
+ else {
786
+ console.error(`[FAIL] Unexpected telemetry argument: ${arg}\n`);
787
+ process.exit(1);
788
+ }
789
+ }
790
+ return { filter, outputPath, positionals, json };
791
+ }
792
+ function hasFilterScope(filter) {
793
+ return filter.issue !== undefined || filter.since !== undefined || filter.branch !== undefined;
794
+ }
634
795
  async function handleTelemetry(args) {
635
796
  const sub = args[0]?.toLowerCase() || "status";
636
797
  switch (sub) {
637
798
  case "status": {
638
799
  printHeader();
639
- const store = loadTelemetry();
800
+ const cwd = process.cwd();
801
+ const store = loadTelemetry(cwd);
802
+ const consentState = getTelemetryConsentState(cwd);
640
803
  const globallyDisabled = isTelemetryGloballyDisabled();
804
+ let consentLabel;
805
+ switch (consentState) {
806
+ case "accepted":
807
+ consentLabel = `Accepted (v${TELEMETRY_POLICY_VERSION} — Local Only)`;
808
+ break;
809
+ case "declined":
810
+ consentLabel = `Declined (v${TELEMETRY_POLICY_VERSION})`;
811
+ break;
812
+ case "outdated":
813
+ consentLabel = `Paused — Re-consent Required (v${store.consent.policyVersion} -> v${TELEMETRY_POLICY_VERSION})`;
814
+ break;
815
+ default:
816
+ consentLabel = "Unanswered (Off)";
817
+ break;
818
+ }
641
819
  console.log("LogNexus Telemetry Status:\n");
642
820
  console.log(` Globally Disabled (DO_NOT_TRACK): ${globallyDisabled ? "Yes (Forced OFF)" : "No"}`);
643
821
  console.log(` Operating Mode: ${store.mode.toUpperCase()}`);
644
822
  console.log(` Anonymous Project ID: ${store.anonymousProjectId}`);
645
- console.log(` Community Consent: ${store.consent.accepted ? "Accepted (Shared)" : "No (Local Only)"}`);
823
+ console.log(` Policy Consent: ${consentLabel}`);
646
824
  if (store.consent.acceptedAt) {
647
825
  console.log(` Consent Recorded At: ${store.consent.acceptedAt}`);
648
826
  }
827
+ if (store.consent.declinedAt) {
828
+ console.log(` Consent Declined At: ${store.consent.declinedAt}`);
829
+ }
649
830
  console.log(` Detected Stacks: ${store.detectedStacks.join(", ") || "(none)"}`);
650
831
  console.log(` Total Commits Monitored: ${store.summary.totalCommits}`);
832
+ if (store.summary.swarmCommits > 0) {
833
+ console.log(` Swarm Commits: ${store.summary.swarmCommits} (${store.summary.totalSwarmPosts} board posts, peak ${store.summary.maxSwarmWorkers} workers)`);
834
+ }
651
835
  console.log(` Estimated Cost Savings: ${store.summary.estimatedCostSavingsPct}%\n`);
652
836
  break;
653
837
  }
@@ -659,8 +843,12 @@ async function handleTelemetry(args) {
659
843
  console.error(`[FAIL] ${LOCAL_ONLY_TELEMETRY_ERROR}\n`);
660
844
  process.exit(1);
661
845
  }
846
+ if (isAgentEnvironment()) {
847
+ process.stderr.write("Confirm telemetry opt-in from an interactive human terminal (automated agent sealing is disabled).\n");
848
+ process.exit(1);
849
+ }
662
850
  try {
663
- enableTelemetry({ cwd: process.cwd() });
851
+ enableTelemetry({ cwd: process.cwd(), acceptTerms: true });
664
852
  console.log("[OK] Telemetry enabled in LOCAL mode.");
665
853
  console.log(" Metrics are stored strictly locally in .lognexus/telemetry.json.");
666
854
  console.log(" Zero network calls are made. Run 'lognexus telemetry report' to generate a report.\n");
@@ -680,8 +868,21 @@ async function handleTelemetry(args) {
680
868
  }
681
869
  case "inspect": {
682
870
  printHeader();
683
- const store = loadTelemetry();
684
- const payload = buildAnonymousCommunityPayload(store);
871
+ const { filter } = parseTelemetryScopeFlags(args.slice(1));
872
+ const store = hasFilterScope(filter)
873
+ ? syncTelemetryFromGitNotes(process.cwd(), filter)
874
+ : loadTelemetry();
875
+ const payload = buildAnonymousDiagnosticPayload(store, filter);
876
+ if (hasFilterScope(filter)) {
877
+ const scope = [
878
+ filter.issue === undefined ? null : `issue=${String(filter.issue)}`,
879
+ filter.since === undefined ? null : `since=${filter.since}`,
880
+ filter.branch === undefined ? null : `branch=${filter.branch}`,
881
+ ]
882
+ .filter((part) => part !== null)
883
+ .join(", ");
884
+ console.log(`Scoped view (in-memory only, the store is not rewritten): ${scope}\n`);
885
+ }
685
886
  console.log("Anonymous Telemetry Payload (Zero-PII Audit):\n");
686
887
  console.log(JSON.stringify(payload, null, 2));
687
888
  console.log("\nNote: No code, file paths, file names, commit messages, or identities are included.\n");
@@ -689,12 +890,8 @@ async function handleTelemetry(args) {
689
890
  }
690
891
  case "report": {
691
892
  printHeader();
692
- let outputPath;
693
- const outIdx = args.findIndex((a) => a === "--output" || a === "-o");
694
- if (outIdx !== -1 && args[outIdx + 1]) {
695
- outputPath = args[outIdx + 1];
696
- }
697
- const res = generateTelemetryReportFile(process.cwd(), outputPath);
893
+ const { filter, outputPath } = parseTelemetryScopeFlags(args.slice(1));
894
+ const res = generateTelemetryReportFile(process.cwd(), outputPath, filter);
698
895
  console.log("[OK] Telemetry & ROI Performance Report generated:");
699
896
  console.log(` Output file: ${res.filePath}`);
700
897
  console.log(" Sharing is opt-in: nothing is uploaded. Review the file, then publish it yourself with");
@@ -702,6 +899,59 @@ async function handleTelemetry(args) {
702
899
  console.log(res.content);
703
900
  break;
704
901
  }
902
+ case "snapshot": {
903
+ printHeader();
904
+ const { filter, outputPath } = parseTelemetryScopeFlags(args.slice(1));
905
+ try {
906
+ const res = exportTelemetrySnapshot(process.cwd(), outputPath, filter);
907
+ console.log("[OK] Zero-PII diagnostic snapshot exported:");
908
+ console.log(` Output file: ${res.filePath}`);
909
+ console.log(` Anonymous Project ID: ${res.payload.anonymousProjectId}`);
910
+ console.log(` Schema version: ${res.payload.schemaVersion}`);
911
+ console.log(" Scope contains no code, paths, remotes or identities.");
912
+ console.log(" Nothing was uploaded. Share the file yourself, or aggregate it with 'lognexus telemetry benchmark'.\n");
913
+ }
914
+ catch (err) {
915
+ const msg = err instanceof Error ? err.message : String(err);
916
+ console.error(`[FAIL] Snapshot export aborted: ${msg}\n`);
917
+ process.exit(1);
918
+ }
919
+ break;
920
+ }
921
+ case "benchmark": {
922
+ const { outputPath, positionals, json } = parseTelemetryScopeFlags(args.slice(1), true);
923
+ if (positionals.length === 0) {
924
+ console.error("[FAIL] telemetry benchmark requires at least one snapshot file or directory.\n");
925
+ console.error(" Run 'lognexus telemetry snapshot' first, then pass its output path.\n");
926
+ process.exit(1);
927
+ }
928
+ try {
929
+ if (outputPath !== undefined) {
930
+ const res = generateCohortBenchmarkReportFile(positionals, outputPath, process.cwd());
931
+ console.log("[OK] Cohort benchmark report generated:");
932
+ console.log(` Output file: ${res.filePath}`);
933
+ console.log(` Projects aggregated: ${res.cohort.cohortSize}`);
934
+ console.log(` Commits aggregated: ${res.cohort.totals.commits}\n`);
935
+ if (json)
936
+ console.log(JSON.stringify(res.cohort, null, 2));
937
+ break;
938
+ }
939
+ const cohort = aggregateBenchmarkCohort(positionals, process.cwd());
940
+ if (json) {
941
+ console.log(JSON.stringify(cohort, null, 2));
942
+ }
943
+ else {
944
+ printHeader();
945
+ console.log(formatCohortMarkdownReport(cohort));
946
+ }
947
+ }
948
+ catch (err) {
949
+ const msg = err instanceof Error ? err.message : String(err);
950
+ console.error(`[FAIL] Cohort benchmark aborted: ${msg}\n`);
951
+ process.exit(1);
952
+ }
953
+ break;
954
+ }
705
955
  case "clear": {
706
956
  printHeader();
707
957
  clearTelemetry();
@@ -714,9 +964,56 @@ async function handleTelemetry(args) {
714
964
  process.exit(1);
715
965
  }
716
966
  }
717
- async function main() {
718
- const args = process.argv.slice(2);
967
+ const VALUE_TAKING_FLAGS = new Set([
968
+ "-m",
969
+ "--message",
970
+ "-F",
971
+ "--file",
972
+ "--author",
973
+ "--reviewer",
974
+ "--title",
975
+ "--allowed",
976
+ "--forbidden",
977
+ "--budget",
978
+ "--verify",
979
+ "-o",
980
+ "--output",
981
+ "--issue",
982
+ "--since",
983
+ "--branch",
984
+ "--tier",
985
+ "--isolation",
986
+ "--assignee",
987
+ "--swarm-workers",
988
+ "--swarm-posts",
989
+ "--limit",
990
+ ]);
991
+ /**
992
+ * Detects standalone `--help` / `-h` flags linearly while skipping values consumed
993
+ * by value-taking flags (so `commit -m "--help"` is treated as a commit message)
994
+ * and stopping at the `--` end-of-options marker.
995
+ */
996
+ export function hasStandaloneHelpFlag(args) {
997
+ for (let i = 0; i < args.length; i += 1) {
998
+ const arg = args[i];
999
+ if (arg === "--") {
1000
+ return false;
1001
+ }
1002
+ if (arg === "--help" || arg === "-h") {
1003
+ return true;
1004
+ }
1005
+ if (VALUE_TAKING_FLAGS.has(arg)) {
1006
+ i += 1;
1007
+ }
1008
+ }
1009
+ return false;
1010
+ }
1011
+ export async function main(args = process.argv.slice(2)) {
719
1012
  const command = args[0]?.toLowerCase();
1013
+ if (command !== "mcp" && hasStandaloneHelpFlag(args)) {
1014
+ printUsage();
1015
+ return 0;
1016
+ }
720
1017
  runStartupGate(command);
721
1018
  switch (command) {
722
1019
  case "commit":
@@ -729,9 +1026,19 @@ async function main() {
729
1026
  await handleInit(args.slice(1));
730
1027
  break;
731
1028
  case "doctor":
1029
+ await maybePromptTelemetryConsent({
1030
+ command,
1031
+ args: args.slice(1),
1032
+ targetDir: process.cwd(),
1033
+ });
732
1034
  await handleDoctor();
733
1035
  break;
734
1036
  case "status":
1037
+ await maybePromptTelemetryConsent({
1038
+ command,
1039
+ args: args.slice(1),
1040
+ targetDir: process.cwd(),
1041
+ });
735
1042
  await handleStatus();
736
1043
  break;
737
1044
  case "state":
@@ -772,6 +1079,7 @@ async function main() {
772
1079
  printUsage();
773
1080
  process.exit(1);
774
1081
  }
1082
+ return 0;
775
1083
  }
776
1084
  /**
777
1085
  * True only when this module is the process entrypoint.