@crafter/cli-tree 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,9 +5,12 @@ import { extractPaths, clusterIntoWorkflows } from "./workflows";
5
5
  import { computeStats } from "./stats";
6
6
  import { suggestSkills, type SkillSuggestion } from "./suggest";
7
7
  import { minedToFlowWorkflow } from "./to-flow";
8
+ import { computeActivity, formatTimeRange, type ActivityProfile } from "./activity";
9
+ import { sparkline, labeledSparkline } from "./sparkline";
10
+ import { mineCrossCli, crossCliToFlowWorkflow, type CrossCliOptions, type CrossCliResult, type CrossCliWorkflow, type CrossCliStep } from "./cross-cli";
8
11
  import type { HistoryEntry, Session, Transition, MinedWorkflow, CliUsageStats, MineOptions } from "./types";
9
- export type { HistoryEntry, Session, Transition, MinedWorkflow, CliUsageStats, MineOptions, SkillSuggestion };
10
- export { parseHistory, readHistoryFile, defaultHistoryPath, tokenize, detectHistoryFormat, segmentSessions, filterByCli, buildTransitions, normalizeTransitions, extractSubcommand, extractSubcommandPath, extractPaths, clusterIntoWorkflows, computeStats, suggestSkills, minedToFlowWorkflow, };
12
+ export type { HistoryEntry, Session, Transition, MinedWorkflow, CliUsageStats, MineOptions, SkillSuggestion, ActivityProfile, CrossCliOptions, CrossCliResult, CrossCliWorkflow, CrossCliStep, };
13
+ export { parseHistory, readHistoryFile, defaultHistoryPath, tokenize, detectHistoryFormat, segmentSessions, filterByCli, buildTransitions, normalizeTransitions, extractSubcommand, extractSubcommandPath, extractPaths, clusterIntoWorkflows, computeStats, suggestSkills, minedToFlowWorkflow, computeActivity, formatTimeRange, sparkline, labeledSparkline, mineCrossCli, crossCliToFlowWorkflow, };
11
14
  export interface MineResult {
12
15
  cli: string;
13
16
  stats: CliUsageStats;
@@ -15,5 +18,6 @@ export interface MineResult {
15
18
  workflows: MinedWorkflow[];
16
19
  suggestions: SkillSuggestion[];
17
20
  sessionsAnalyzed: number;
21
+ activity: ActivityProfile;
18
22
  }
19
23
  export declare function mineCli(cli: string, options?: MineOptions): Promise<MineResult>;
@@ -1,40 +1,52 @@
1
1
  import {
2
2
  buildTransitions,
3
3
  clusterIntoWorkflows,
4
+ computeActivity,
4
5
  computeStats,
6
+ crossCliToFlowWorkflow,
5
7
  defaultHistoryPath,
6
8
  detectHistoryFormat,
7
9
  extractPaths,
8
10
  extractSubcommand,
9
11
  extractSubcommandPath,
10
12
  filterByCli,
13
+ formatTimeRange,
14
+ labeledSparkline,
11
15
  mineCli,
16
+ mineCrossCli,
12
17
  minedToFlowWorkflow,
13
18
  normalizeTransitions,
14
19
  parseHistory,
15
20
  readHistoryFile,
16
21
  segmentSessions,
22
+ sparkline,
17
23
  suggestSkills,
18
24
  tokenize
19
- } from "../chunk-dnq2rnr7.js";
25
+ } from "../chunk-9pnqbn7b.js";
20
26
  export {
21
27
  tokenize,
22
28
  suggestSkills,
29
+ sparkline,
23
30
  segmentSessions,
24
31
  readHistoryFile,
25
32
  parseHistory,
26
33
  normalizeTransitions,
27
34
  minedToFlowWorkflow,
35
+ mineCrossCli,
28
36
  mineCli,
37
+ labeledSparkline,
38
+ formatTimeRange,
29
39
  filterByCli,
30
40
  extractSubcommandPath,
31
41
  extractSubcommand,
32
42
  extractPaths,
33
43
  detectHistoryFormat,
34
44
  defaultHistoryPath,
45
+ crossCliToFlowWorkflow,
35
46
  computeStats,
47
+ computeActivity,
36
48
  clusterIntoWorkflows,
37
49
  buildTransitions
38
50
  };
39
51
 
40
- //# debugId=34A9477E11B0A64764756E2164756E21
52
+ //# debugId=3F080486405E782764756E2164756E21
@@ -4,6 +4,6 @@
4
4
  "sourcesContent": [
5
5
  ],
6
6
  "mappings": "",
7
- "debugId": "34A9477E11B0A64764756E2164756E21",
7
+ "debugId": "3F080486405E782764756E2164756E21",
8
8
  "names": []
9
9
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Minimal Unicode sparkline for a numeric array.
3
+ *
4
+ * We could depend on @crafter/charts for this, but keeping zero deps means
5
+ * clitree stays as a single focused package. The logic is trivial: bucket each
6
+ * value into one of 8 block characters (▁▂▃▄▅▆▇█).
7
+ */
8
+ export declare function sparkline(data: number[], opts?: {
9
+ empty?: string;
10
+ }): string;
11
+ /**
12
+ * Render a labeled row like "Mon ▁▃▅█▇▅▃▂" — used for day-of-week activity.
13
+ */
14
+ export declare function labeledSparkline(label: string, data: number[], labelWidth?: number): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crafter/cli-tree",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Explore and map any CLI tool deeply. Parse --help trees, mine shell history for repeated workflows, surface hidden flags via LLM archaeology, and suggest new agent skills from your usage patterns.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/src/cli.ts CHANGED
@@ -4,13 +4,21 @@ import { printTree, treeToString, treeToHtml } from "./index";
4
4
  import type { TreeOptions } from "./types";
5
5
  import { parseWorkflow, validateWorkflow, flowToAnsi, flowToString, flowToHtml } from "./flow";
6
6
  import type { FlowRenderOptions } from "./flow/types";
7
- import { mineCli, minedToFlowWorkflow } from "./miner";
7
+ import {
8
+ mineCli,
9
+ minedToFlowWorkflow,
10
+ mineCrossCli,
11
+ crossCliToFlowWorkflow,
12
+ sparkline,
13
+ labeledSparkline,
14
+ formatTimeRange,
15
+ } from "./miner";
8
16
  import { runArchaeology, NullDelegate } from "./archaeology";
9
17
 
10
18
  const args = process.argv.slice(2);
11
19
  const subcommand = args[0];
12
20
 
13
- const HELP_SUBCOMMANDS = new Set(["flow", "mine", "archaeology", "safe-help"]);
21
+ const HELP_SUBCOMMANDS = new Set(["flow", "mine", "archaeology", "safe-help", "cross"]);
14
22
  const isHelpFlag = args.includes("--help") || args.includes("-h");
15
23
 
16
24
  if (!subcommand || (isHelpFlag && !HELP_SUBCOMMANDS.has(subcommand ?? ""))) {
@@ -23,6 +31,7 @@ if (isHelpFlag) {
23
31
  else if (subcommand === "mine") printMineHelp();
24
32
  else if (subcommand === "archaeology") printArchaeologyHelp();
25
33
  else if (subcommand === "safe-help") printSafeHelpHelp();
34
+ else if (subcommand === "cross") printCrossHelp();
26
35
  else printMainHelp();
27
36
  process.exit(0);
28
37
  }
@@ -35,6 +44,8 @@ if (subcommand === "flow") {
35
44
  await runArchaeologyCmd(args.slice(1));
36
45
  } else if (subcommand === "safe-help") {
37
46
  await runSafeHelp(args.slice(1));
47
+ } else if (subcommand === "cross") {
48
+ await runCross(args.slice(1));
38
49
  } else {
39
50
  await runTree(args);
40
51
  }
@@ -47,19 +58,22 @@ function printMainHelp() {
47
58
  clitree <binary> [options] Render command tree from --help
48
59
  clitree flow <file> [options] Render a workflow YAML as a DAG
49
60
  clitree mine <binary> [options] Mine shell history for workflows
61
+ clitree cross [options] Detect cross-CLI workflows (git + gh, docker + kubectl)
50
62
  clitree archaeology <binary> [options] Full analysis: tree + mining + (LLM)
51
63
  clitree safe-help <binary> [sub...] Fetch clean help for any CLI (no pager, no overstriking)
52
64
 
53
65
  Examples:
54
66
  clitree docker # basic tree
55
67
  clitree mine git # "what workflows do I repeat with git?"
68
+ clitree cross # cross-CLI flows across your history
56
69
  clitree archaeology bun # tree + mining + LLM archaeology
57
70
  clitree safe-help git commit # avoid the git man-page pager trap
58
71
 
59
72
  Subcommands:
60
73
  tree Parse --help output (default; passing a binary name invokes this)
61
74
  flow Render a workflow YAML file as an ASCII DAG
62
- mine Discover workflows from your shell history
75
+ mine Discover workflows from your shell history (single CLI)
76
+ cross Discover workflows that span multiple CLIs (e.g. git → gh)
63
77
  archaeology Run full analysis (tree + mine + LLM proposals when available)
64
78
  safe-help Return inline help for any CLI, handling pager/overstrike edge cases
65
79
 
@@ -67,6 +81,43 @@ function printMainHelp() {
67
81
  `);
68
82
  }
69
83
 
84
+ function printCrossHelp() {
85
+ console.log(`
86
+ clitree cross — Mine cross-CLI workflows from your shell history
87
+
88
+ Usage:
89
+ clitree cross [options]
90
+
91
+ This is mineCli's bigger sibling. Instead of filtering history to a single
92
+ binary, it looks at every command in a session and finds sequences that weave
93
+ between tools — e.g.:
94
+
95
+ git push → gh pr create
96
+ docker build → docker push → kubectl apply
97
+ bun test → git commit → git push
98
+
99
+ These patterns are invisible to 'clitree mine <cli>' because they cross boundaries.
100
+
101
+ Examples:
102
+ clitree cross # top 10 cross-CLI workflows
103
+ clitree cross --top-k 5 # just the top 5
104
+ clitree cross --only git,gh,docker # restrict to a set of CLIs
105
+ clitree cross --format json # raw data
106
+
107
+ Options:
108
+ --top-k <n> Max workflows to return (default: 10)
109
+ --min-support <n> Minimum occurrences (default: 3)
110
+ --min-path-length <n> Minimum chain length (default: 2)
111
+ --max-path-length <n> Maximum chain length (default: 5)
112
+ --min-distinct-clis <n> Require at least this many distinct CLIs (default: 2)
113
+ --only <csv> Whitelist: only include these CLIs (comma-separated)
114
+ --format <fmt> ansi (default) or json
115
+ --no-color Disable ANSI colors
116
+ --no-flow Skip DAG rendering of the top workflow
117
+ -h, --help Show this help
118
+ `);
119
+ }
120
+
70
121
  function printSafeHelpHelp() {
71
122
  console.log(`
72
123
  clitree safe-help — Fetch clean help output for any CLI
@@ -111,22 +162,26 @@ function printMineHelp() {
111
162
 
112
163
  Examples:
113
164
  clitree mine git
165
+ clitree mine git --top-k 3 # render top 3 workflows as DAGs
114
166
  clitree mine docker --min-support 5 --with-flow
115
167
  clitree mine bun --format json > bun-flows.json
116
168
  clitree mine git --no-color | tee report.txt
169
+ clitree mine git --no-activity # skip temporal sparklines
117
170
 
118
171
  Options:
119
172
  --min-support <n> Minimum occurrences to count as a workflow (default: 3)
120
173
  --history-path <p> Custom shell history path (default: ~/.zsh_history)
121
174
  --format <fmt> Output format: ansi (default), json
122
- --max-paths <n> Max workflows to show (default: 10)
123
- --with-flow Always render the top workflow as an ASCII DAG
124
- --no-flow Never render the DAG (overrides auto-detect)
175
+ --max-paths <n> Max workflows to show in text list (default: 10)
176
+ --top-k <n> Render top N workflows as DAGs (default: 1)
177
+ --with-flow Include 2-step workflows in DAG rendering
178
+ --no-flow Skip DAG rendering entirely
179
+ --no-activity Skip hour/day/30-day activity sparklines
125
180
  --no-color Disable ANSI colors (also auto-disabled when stdout is not a TTY)
126
181
  -h, --help Show this help
127
182
 
128
- By default, the top workflow is rendered as a DAG only when it has 3+ steps.
129
- Use --with-flow to force it on even for 2-step chains, or --no-flow to skip.
183
+ By default, the top 3+ step workflow is rendered as a DAG.
184
+ --top-k bumps that to N distinct workflows stacked on top of each other.
130
185
  `);
131
186
  }
132
187
 
@@ -476,6 +531,8 @@ async function runMine(args: string[]) {
476
531
  let format: "ansi" | "json" = "ansi";
477
532
  let maxPaths = 10;
478
533
  let withFlow: "auto" | "on" | "off" = "auto";
534
+ let topK = 1;
535
+ let showActivity = true;
479
536
 
480
537
  for (let i = 0; i < args.length; i++) {
481
538
  const arg = args[i]!;
@@ -487,10 +544,15 @@ async function runMine(args: string[]) {
487
544
  format = args[++i] as "ansi" | "json";
488
545
  } else if (arg === "--max-paths" && args[i + 1]) {
489
546
  maxPaths = Number.parseInt(args[++i]!, 10);
547
+ } else if (arg === "--top-k" && args[i + 1]) {
548
+ topK = Number.parseInt(args[++i]!, 10);
549
+ if (withFlow === "auto") withFlow = "on";
490
550
  } else if (arg === "--with-flow" || arg === "--flow") {
491
551
  withFlow = "on";
492
552
  } else if (arg === "--no-flow") {
493
553
  withFlow = "off";
554
+ } else if (arg === "--no-activity") {
555
+ showActivity = false;
494
556
  } else if (arg !== "--no-color" && !arg.startsWith("-")) {
495
557
  binary = arg;
496
558
  }
@@ -528,6 +590,10 @@ async function runMine(args: string[]) {
528
590
  console.log();
529
591
  }
530
592
 
593
+ if (showActivity && result.activity.total > 0) {
594
+ renderActivitySection(result.activity, C);
595
+ }
596
+
531
597
  if (result.workflows.length > 0) {
532
598
  console.log(`${C.bold}Discovered workflows:${C.reset}`);
533
599
  for (const wf of result.workflows.slice(0, maxPaths)) {
@@ -553,19 +619,23 @@ async function runMine(args: string[]) {
553
619
  console.log();
554
620
  }
555
621
 
556
- // Pick the top workflow worth visualizing as a DAG.
557
- // In "auto" mode, prefer the highest-support workflow with 3+ steps
558
- // 2-step chains are more readable as text than as boxed diagrams.
559
- // In "on" mode, render whatever is the top regardless of length.
560
- // In "off" mode, skip.
622
+ // Pick the top-K workflows worth visualizing as DAGs.
623
+ // Auto mode renders only the first 3+ step workflow.
624
+ // `--top-k N` renders up to N distinct workflows (skipping shorter 2-step ones by default).
561
625
  if (withFlow !== "off") {
562
626
  const minSteps = withFlow === "on" ? 2 : 3;
563
- const topForFlow = pickWorkflowForFlow(result.workflows, minSteps);
564
- if (topForFlow) {
565
- const flowWorkflow = minedToFlowWorkflow(topForFlow);
566
- const rendered = shouldUseColor(args) ? flowToAnsi(flowWorkflow) : flowToString(flowWorkflow);
567
- console.log(`${C.bold}Top workflow (visualized):${C.reset}`);
568
- console.log(rendered);
627
+ const topK_effective = Math.max(1, topK);
628
+ const candidates = pickWorkflowsForFlow(result.workflows, minSteps, topK_effective);
629
+
630
+ if (candidates.length > 0) {
631
+ const header = candidates.length === 1 ? "Top workflow (visualized):" : `Top ${candidates.length} workflows (visualized):`;
632
+ console.log(`${C.bold}${header}${C.reset}`);
633
+ for (let i = 0; i < candidates.length; i++) {
634
+ if (i > 0) console.log(`${C.gray}${"─".repeat(60)}${C.reset}`);
635
+ const flowWorkflow = minedToFlowWorkflow(candidates[i]!);
636
+ const rendered = shouldUseColor(args) ? flowToAnsi(flowWorkflow) : flowToString(flowWorkflow);
637
+ console.log(rendered);
638
+ }
569
639
  console.log();
570
640
  }
571
641
  }
@@ -575,15 +645,152 @@ async function runMine(args: string[]) {
575
645
  }
576
646
  }
577
647
 
648
+ function renderActivitySection(
649
+ activity: { hourOfDay: number[]; dayOfWeek: number[]; last30Days: number[]; firstSeen: number; lastSeen: number; total: number },
650
+ C: ReturnType<typeof makeColors>,
651
+ ) {
652
+ // Only show if we have timestamp data
653
+ if (activity.firstSeen === 0) return;
654
+
655
+ const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
656
+ console.log(`${C.bold}Activity:${C.reset}`);
657
+
658
+ const range = formatTimeRange(activity.firstSeen, activity.lastSeen);
659
+ console.log(` ${C.dim}Tracked over:${C.reset} ${C.cyan}${range}${C.reset}`);
660
+
661
+ // Hour-of-day sparkline (24 chars wide)
662
+ const hourSpark = sparkline(activity.hourOfDay);
663
+ console.log(` ${C.dim}Hour of day: ${C.reset}${C.cyan}${hourSpark}${C.reset} ${C.dim}(0h → 23h)${C.reset}`);
664
+
665
+ // Day-of-week mini bars
666
+ const dowMax = Math.max(...activity.dayOfWeek);
667
+ if (dowMax > 0) {
668
+ console.log(` ${C.dim}Day of week:${C.reset}`);
669
+ for (let i = 0; i < 7; i++) {
670
+ const count = activity.dayOfWeek[i]!;
671
+ const barLen = dowMax > 0 ? Math.round((count / dowMax) * 20) : 0;
672
+ const bar = "█".repeat(Math.max(count > 0 ? 1 : 0, barLen));
673
+ console.log(` ${C.gray}${dayNames[i]}${C.reset} ${C.cyan}${bar}${C.reset} ${C.dim}${count}${C.reset}`);
674
+ }
675
+ }
676
+
677
+ // Last 30 days sparkline
678
+ if (activity.last30Days.some(v => v > 0)) {
679
+ const monthSpark = sparkline(activity.last30Days);
680
+ console.log(` ${C.dim}Last 30 days:${C.reset} ${C.cyan}${monthSpark}${C.reset} ${C.dim}(30d ago → today)${C.reset}`);
681
+ }
682
+ console.log();
683
+ }
684
+
578
685
  function pickWorkflowForFlow<T extends { path: string[][]; support: number }>(
579
686
  workflows: T[],
580
687
  minSteps = 3,
581
688
  ): T | null {
689
+ const picked = pickWorkflowsForFlow(workflows, minSteps, 1);
690
+ return picked[0] ?? null;
691
+ }
692
+
693
+ function pickWorkflowsForFlow<T extends { path: string[][]; support: number }>(
694
+ workflows: T[],
695
+ minSteps: number,
696
+ topK: number,
697
+ ): T[] {
698
+ const result: T[] = [];
699
+ const signatures = new Set<string>();
582
700
  for (const wf of workflows) {
583
701
  const len = wf.path[0]?.length ?? 0;
584
- if (len >= minSteps) return wf;
702
+ if (len < minSteps) continue;
703
+ const sig = wf.path[0]!.join(" → ");
704
+ if (signatures.has(sig)) continue;
705
+ signatures.add(sig);
706
+ result.push(wf);
707
+ if (result.length >= topK) break;
708
+ }
709
+ return result;
710
+ }
711
+
712
+ async function runCross(args: string[]) {
713
+ let format: "ansi" | "json" = "ansi";
714
+ let topK = 10;
715
+ let minSupport = 3;
716
+ let minPathLength = 2;
717
+ let maxPathLength = 5;
718
+ let minDistinctCLIs = 2;
719
+ let onlyList: string[] = [];
720
+ let withFlow = true;
721
+
722
+ for (let i = 0; i < args.length; i++) {
723
+ const arg = args[i]!;
724
+ if (arg === "--top-k" && args[i + 1]) {
725
+ topK = Number.parseInt(args[++i]!, 10);
726
+ } else if (arg === "--min-support" && args[i + 1]) {
727
+ minSupport = Number.parseInt(args[++i]!, 10);
728
+ } else if (arg === "--min-path-length" && args[i + 1]) {
729
+ minPathLength = Number.parseInt(args[++i]!, 10);
730
+ } else if (arg === "--max-path-length" && args[i + 1]) {
731
+ maxPathLength = Number.parseInt(args[++i]!, 10);
732
+ } else if (arg === "--min-distinct-clis" && args[i + 1]) {
733
+ minDistinctCLIs = Number.parseInt(args[++i]!, 10);
734
+ } else if (arg === "--only" && args[i + 1]) {
735
+ onlyList = args[++i]!.split(",").map(s => s.trim()).filter(Boolean);
736
+ } else if (arg === "--format" && args[i + 1]) {
737
+ format = args[++i] as "ansi" | "json";
738
+ } else if (arg === "--no-flow") {
739
+ withFlow = false;
740
+ }
741
+ }
742
+
743
+ try {
744
+ const result = await mineCrossCli({
745
+ topK,
746
+ minSupport,
747
+ minPathLength,
748
+ maxPathLength,
749
+ minDistinctCLIs,
750
+ allowedCLIs: onlyList.length > 0 ? onlyList : undefined,
751
+ });
752
+
753
+ if (format === "json") {
754
+ console.log(JSON.stringify(result, null, 2));
755
+ return;
756
+ }
757
+
758
+ const C = makeColors(shouldUseColor(args));
759
+
760
+ console.log(`\n${C.bold}${C.magenta}cross-CLI workflow analysis${C.reset}\n`);
761
+ console.log(`${C.bold}Scope:${C.reset}`);
762
+ console.log(` ${C.dim}Sessions analyzed:${C.reset} ${C.cyan}${result.sessionsAnalyzed}${C.reset}`);
763
+ console.log(` ${C.dim}Distinct CLIs:${C.reset} ${C.cyan}${result.distinctCLIs.length}${C.reset}`);
764
+ console.log(` ${C.dim}Transitions:${C.reset} ${C.cyan}${result.totalTransitions}${C.reset}\n`);
765
+
766
+ if (result.workflows.length === 0) {
767
+ console.log(`${C.dim}No cross-CLI workflows found. Try lowering --min-support or --min-distinct-clis.${C.reset}\n`);
768
+ return;
769
+ }
770
+
771
+ console.log(`${C.bold}Cross-CLI workflows (top ${result.workflows.length}):${C.reset}`);
772
+ for (let i = 0; i < result.workflows.length; i++) {
773
+ const wf = result.workflows[i]!;
774
+ const chain = wf.path
775
+ .map(s => `${C.green}${s.cli}${C.reset} ${C.cyan}${s.subcommand}${C.reset}`)
776
+ .join(` ${C.gray}→${C.reset} `);
777
+ console.log(` ${C.dim}${(i + 1).toString().padStart(2)}.${C.reset} ${chain}`);
778
+ console.log(` ${C.dim}seen ${wf.support}×, ${wf.uniqueCLIs} distinct CLIs${C.reset}`);
779
+ }
780
+ console.log();
781
+
782
+ if (withFlow && result.workflows.length > 0) {
783
+ const top = result.workflows[0]!;
784
+ const flowWorkflow = crossCliToFlowWorkflow(top);
785
+ const rendered = shouldUseColor(args) ? flowToAnsi(flowWorkflow) : flowToString(flowWorkflow);
786
+ console.log(`${C.bold}Top cross-CLI workflow (visualized):${C.reset}`);
787
+ console.log(rendered);
788
+ console.log();
789
+ }
790
+ } catch (err: any) {
791
+ console.error(`Error: ${err.message}`);
792
+ process.exit(1);
585
793
  }
586
- return null;
587
794
  }
588
795
 
589
796
  async function runArchaeologyCmd(args: string[]) {
@@ -0,0 +1,71 @@
1
+ import type { HistoryEntry } from "./types";
2
+
3
+ export interface ActivityProfile {
4
+ /** Total invocations considered */
5
+ total: number;
6
+ /** Count per hour of day (0-23) */
7
+ hourOfDay: number[];
8
+ /** Count per day of week (0=Sun, 6=Sat) */
9
+ dayOfWeek: number[];
10
+ /** Count per day over the last N days (most recent last) */
11
+ last30Days: number[];
12
+ /** The earliest timestamp observed (unix seconds) */
13
+ firstSeen: number;
14
+ /** The latest timestamp observed (unix seconds) */
15
+ lastSeen: number;
16
+ }
17
+
18
+ /**
19
+ * Compute temporal activity histograms from a list of history entries.
20
+ * Assumes entries have unix-second timestamps; entries with timestamp 0 are ignored.
21
+ */
22
+ export function computeActivity(entries: HistoryEntry[], now: Date = new Date()): ActivityProfile {
23
+ const hourOfDay = new Array(24).fill(0);
24
+ const dayOfWeek = new Array(7).fill(0);
25
+ const last30Days = new Array(30).fill(0);
26
+
27
+ let first = Infinity;
28
+ let last = 0;
29
+ let total = 0;
30
+
31
+ const nowMs = now.getTime();
32
+ const dayMs = 24 * 60 * 60 * 1000;
33
+
34
+ for (const entry of entries) {
35
+ if (!entry.timestamp || entry.timestamp <= 0) continue;
36
+
37
+ total += 1;
38
+ if (entry.timestamp < first) first = entry.timestamp;
39
+ if (entry.timestamp > last) last = entry.timestamp;
40
+
41
+ const date = new Date(entry.timestamp * 1000);
42
+ hourOfDay[date.getHours()] += 1;
43
+ dayOfWeek[date.getDay()] += 1;
44
+
45
+ const ageDays = Math.floor((nowMs - date.getTime()) / dayMs);
46
+ if (ageDays >= 0 && ageDays < 30) {
47
+ // Index 29 = today, 0 = 29 days ago
48
+ last30Days[29 - ageDays] += 1;
49
+ }
50
+ }
51
+
52
+ return {
53
+ total,
54
+ hourOfDay,
55
+ dayOfWeek,
56
+ last30Days,
57
+ firstSeen: first === Infinity ? 0 : first,
58
+ lastSeen: last,
59
+ };
60
+ }
61
+
62
+ export function formatTimeRange(firstSeen: number, lastSeen: number): string {
63
+ if (!firstSeen || !lastSeen) return "no data";
64
+ const first = new Date(firstSeen * 1000);
65
+ const last = new Date(lastSeen * 1000);
66
+ const days = Math.round((last.getTime() - first.getTime()) / (24 * 60 * 60 * 1000));
67
+ if (days < 1) return "less than a day";
68
+ if (days < 30) return `${days} days`;
69
+ if (days < 365) return `${Math.round(days / 30)} months`;
70
+ return `${(days / 365).toFixed(1)} years`;
71
+ }