@giladbarnea/pi-simple-team 1.0.32 → 1.0.34

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.
package/README.md CHANGED
@@ -92,7 +92,7 @@ The command opens an overlay rolling recent statuses, messages, and a separate e
92
92
 
93
93
  ### 🏋️ Woken up when needed. Works freely otherwise.
94
94
 
95
- Tokens, intelligence and time are never wasted on busy-polling for messages.
95
+ **Tokens, intelligence and time are never wasted on busy-polling for messages.**
96
96
 
97
97
  Instead, `pi-simple-team` pushes messages to the recipients.
98
98
 
@@ -109,6 +109,8 @@ This is both efficient and effective:
109
109
 
110
110
  ### 🟢 Statuses everyone can see.
111
111
 
112
+ For free, at any time. Like setting a Slack status.
113
+
112
114
  Teammates publish a one-liner:
113
115
 
114
116
  > <span style="color:grey">implementer  </span> Done, 89 tests green, awaiting review.
@@ -119,74 +121,81 @@ Your main agent calls `teamstatus` and understands exactly what is going on. Mai
119
121
 
120
122
  ### 🌡️ Context window self-awareness
121
123
 
124
+ **The team manages its own context:**
125
+
122
126
  Teammates know how much free context they have left.
123
127
 
124
128
  Main agent knows its own and everyone else's too.
125
129
 
126
130
  They will hand off work autonomously when it's time to say goodbye.
127
131
 
128
- You can stop babysitting everyone's context window.
132
+ You can stop babysitting context windows.
129
133
 
130
134
  ### 📣 Interrupts, when justified.
131
135
 
132
136
  > _Situation: Late afternoon. Team finished production hotfix and started wrap up. There is one problem though._
133
137
 
134
- - 17:32:00: Security scout spots a private SSH key not covered by `.gitignore`.
135
- - 17:32:01: Release teammate sets status: _Ran `git add .`, preparing commit and push._
136
- - 17:32:02: Scout immediately interrupts. Key never leaves the machine. Developer keeps their job.
138
+ - 17:32:00: `security-guard` spots a private SSH key not covered by `.gitignore`.
139
+ - 17:32:01: `release-owner` sets status: _Ran `git add .`, preparing commit and push._
140
+ - 17:32:02: `security-guard` immediately interrupts `release-owner`. Key never leaves the machine. Developer keeps their job another day 👍
137
141
 
138
142
  ### 📡 Live, zero-cost observability
139
143
 
140
- Your main uses `teamlog` when it needs to understand the chain of events in high granularity: a timestamped, filterable timeline of messages, tool calls, and lifecycle events.
144
+ Your main uses `teamlog` when it needs to understand the chain of events in high granularity.
145
+
146
+ Provides main a timestamped, filterable, append-only record of the team’s messages, tool calls, and lifecycle events.
141
147
 
142
- ### 🪟 Herdr Mode
148
+ ### 🌅 Herdr Support
143
149
 
144
- `pi-simple-team` can give each teammate a Pi session in its own [Herdr](https://herdr.dev) pane. Just ask your main agent to do that.
150
+ `pi-simple-team` can open a teammate direct Pi session in a dedicated [Herdr](https://herdr.dev) pane. Just ask your main agent to do that.
145
151
 
146
152
  - Live view of the room.
147
153
  - Talk directly with teammates.
148
154
 
155
+ I recommend starting with “Captain here”. Feels good and the surprise on their faces is priceless.
156
+
149
157
  ### 🧱 Teammates are durable Pi sessions.
150
158
 
151
- A teammate is a normal Pi session with a team attachment.
159
+ A teammate is just a Pi session with a team attachment.
152
160
 
153
- This means teammates survive shutdown, whole team or member by member.
161
+ This means **teammates (and thus, teams) survive shutdown.**
154
162
 
155
- Have a teammate do work, exit Pi entirely, come back tomorrow in a brand-new session: main wakes that same teammate into the new conversation, everything it learned intact.
163
+ Have a teammate do work, exit Pi entirely, come back tomorrow in a brand-new session, and ask main to get you that teammate by its Pi session id. Everything it learned stays intact.
156
164
 
157
165
  You can even `/resume` a teammate session directly if you ever want a cozy one-on-one.
158
166
 
159
- The full lifecycle and persistence rules live in [ARCHITECTURE.md](ARCHITECTURE.md).
160
-
161
- ## 🪾 Teams all the way down (optionally)
167
+ ## 🪾 It’s teams all the way down (optionally)
162
168
 
163
- Tell main you want to give a teammate the ability to manage its own team(s).
169
+ Tell main you want to **have a teammate manage its own team(s).**
164
170
 
165
- This is a powerful technique to create a new layer of context breathing room.
171
+ This is a powerful technique to create a **separate layer of context.**
166
172
 
167
173
  That teammate will spawn, steer and observe its own team(s) without costing tokens to its siblings or parent.
168
174
 
169
- The tradeoff, like any higher-order delegation, is reduced control: you are moved one level further away from the action.
175
+ The tradeoff, like any higher-order delegation, is reduced control: you are moved one level further away from the trenches.
170
176
 
171
177
  This is opt-in: teammates by default can't create teams.
172
178
 
179
+ This technique plays even nicer if your main assumes the first mate[^1] or captain[^2] rank.
180
+
173
181
  ---
174
182
 
175
183
  ## 🧬 Graphs engineer themselves
176
184
 
177
- **Because** it does nothing special, `pi-simple-team` can construct any team graph you need:
185
+ **Because** it does nothing special, `pi-simple-team` can **construct any agentic graph you need:**
178
186
 
179
- You:
187
+ You tell main:
180
188
  > **Team goal:**
181
- > 1. Map all customer–product money streams in the database.
182
- > 2. Feed this knowledge into the harness.
183
- > 3. Prove the data analysis agent passes the new evals.
189
+ > 1. Map the database for all customer ⟷ purchases money streams.
190
+ > 2. Feed the new knowledge into the memory layer.
191
+ > 3. Make the data analysis agent pass the new purchases evals.
184
192
  >
185
193
  > **Note:**
186
- > - #1 and #3 are _saturation loops._ Stop only when you can't find anything new.
187
- > - Let teammates #1 and #3 create their own teams to loop until task is complete.
194
+ > - #1 is a **saturation loop.** Stop only when you can't find anything new.
195
+ > - #3 is a **hill-climbing loop.** Stop only the evals are green.
196
+ > - Teammates #1 and #3 create their own teams to loop until task is complete.
188
197
 
189
- That prompt gives you this graph:
198
+ That prompt creates this graph:
190
199
 
191
200
  ![The team graph: 1-map (Scout and Devil’s advocate) feeding subagent dispatch, feeding 3-eval (Engineer and Performance watcher)](screenshots/team-graph.png)
192
201
 
@@ -226,7 +235,13 @@ Kept minimal:
226
235
  **Functional:**
227
236
 
228
237
  - [x] Resume all or selected teammates from a dormant team.
229
- - [x] Add new teammates after a team has spawned.
238
+ - [x] Add teammates after a team has spawned.
230
239
  - [x] Let opted-in teammates create and manage teams of their own.
231
- - [ ] Main forces `/compact` on select teammate.
240
+ - [x] Remove teammates from a team.
241
+ - [ ] Main triggers `/compact` on select teammate.
232
242
  - [ ] Teammates auto-reminded to hand off on low context.
243
+
244
+ ---
245
+
246
+ [^1]: `skills/ai-to-ai/references/ranks/firstmate.md`
247
+ [^2]: `skills/ai-to-ai/references/ranks/captain.md`
package/index.ts CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  type TeamManifest,
24
24
  type TeamManifestMember,
25
25
  } from "./team-registry.ts";
26
- import { appendTeamLog, filterTeamLog, normalizeChildEvent, nowText, pageTeamLog, preview, renderTeamLogPage, type TeamLogEntry } from "./teamlog.ts";
26
+ import { appendTeamLog, filterTeamLog, normalizeChildEvent, pageTeamLog, preview, renderTeamLogPage, type TeamLogEntry } from "./teamlog.ts";
27
27
  import { renderTeamMessage, renderTeamToolCall, renderTeamToolResult, type TeamMessageDetails } from "./render.ts";
28
28
  import { openTeamOverview, type TeamSnapshot } from "./team-ui.ts";
29
29
  import { StringEnum } from "@earendil-works/pi-ai";
@@ -103,7 +103,7 @@ let callbackServer: http.Server | undefined;
103
103
  let callbackUrl = "";
104
104
 
105
105
  function status(word: string, phrase: string): TeamStatus {
106
- return { word, phrase, updated: nowText() };
106
+ return { word, phrase, updated: new Date().toISOString() };
107
107
  }
108
108
 
109
109
  function compactName(name: string): string {
@@ -169,7 +169,7 @@ async function deliverMessage(team: TeamState, from: string, recipient: Teammate
169
169
  body: JSON.stringify({
170
170
  token: callbackToken,
171
171
  tool: "deliver",
172
- args: { team: team.name, from, to: recipient.name, sentAt: nowText(), message, formattedMessage, interrupt },
172
+ args: { team: team.name, from, to: recipient.name, sentAt: new Date().toISOString(), message, formattedMessage, interrupt },
173
173
  }),
174
174
  signal: controller.signal,
175
175
  });
@@ -735,7 +735,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
735
735
 
736
736
  if (tool === "teammain") {
737
737
  const rawMessage = String(args.message ?? "");
738
- const details: TeamMessageDetails = { team: team.name, from, sentAt: nowText(), message: rawMessage };
738
+ const details: TeamMessageDetails = { team: team.name, from, sentAt: new Date().toISOString(), message: rawMessage };
739
739
  appendTeamLog(team, {
740
740
  team: team.name,
741
741
  teammate: from,
@@ -925,7 +925,7 @@ export default function (pi: ExtensionAPI) {
925
925
  mainSessionFile,
926
926
  members: new Map(),
927
927
  statuses: new Map([["main", status("available", "Main agent")]]),
928
- created: nowText(),
928
+ created: new Date().toISOString(),
929
929
  lease,
930
930
  log: [],
931
931
  nextLogSequence: 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-simple-team",
3
- "version": "1.0.32",
3
+ "version": "1.0.34",
4
4
  "description": "A flat, live team of Pi agents.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -49,6 +49,6 @@
49
49
  "extensions": [
50
50
  "./index.ts"
51
51
  ],
52
- "image": "https://raw.githubusercontent.com/giladbarnea/pi-simple-team/main/screenshots/pi-simple-team-banner.png"
52
+ "image": "https://raw.githubusercontent.com/giladbarnea/pi-simple-team/main/screenshots/abstract-tool-output-preview-640.png"
53
53
  }
54
54
  }
package/render.ts CHANGED
@@ -2,9 +2,9 @@ import { Markdown, type MarkdownTheme, truncateToWidth, wrapTextWithAnsi } from
2
2
 
3
3
  import { padVisible, stableRenderWidth, visibleLength } from "./render-support/ansi.ts";
4
4
  import { glyphs } from "./render-support/glyphs.ts";
5
- import { stackPrefix, toolLabel, treeConnector, treeGlyph, treeStem } from "./render-support/theme.ts";
5
+ import { stackPrefix, toolLabel, treeConnector, treeStem } from "./render-support/theme.ts";
6
6
  import { commandExit, plural, renderPendingCall, textContent } from "./render-support/text.ts";
7
- import { monthDay, nowText, timeOfDay, type TeamLogEntry } from "./teamlog.ts";
7
+ import { futureTime, monthDay, relativeTime, timeOfDay, type TeamLogEntry } from "./teamlog.ts";
8
8
 
9
9
  export interface ThemeLike {
10
10
  bold(text: string): string;
@@ -45,6 +45,14 @@ interface TeamLogRenderView {
45
45
  returned: number;
46
46
  nextCursor?: string;
47
47
  filters?: Record<string, unknown>;
48
+ nowMilliseconds?: number;
49
+ }
50
+
51
+ /** Sessions persisted before the ISO switch carry pre-formatted timestamps; those pass through raw. */
52
+ export function relativeTimeText(timestamp: string): string {
53
+ if (!timestamp.includes("T")) return timestamp;
54
+ const parsed = Date.parse(timestamp);
55
+ return Number.isFinite(parsed) ? relativeTime(parsed, Date.now()) : timestamp;
48
56
  }
49
57
 
50
58
  /** A rendered line with optional wrapping or right-aligned layout metadata. */
@@ -182,7 +190,7 @@ function memberRows(theme: ThemeLike, statuses: Record<string, TeamStatusView>,
182
190
  const entry = statuses[name]!;
183
191
  const branch = index === names.length - 1 ? "└" : "├";
184
192
  const left = `${indent}${treeConnector(theme, branch)}${theme.fg(actorHueToken(name, roster), padVisible(name, nameWidth))} ${theme.fg(statusWordToken(entry.word), padVisible(entry.word, wordWidth))} ${entry.phrase}`;
185
- const right = theme.fg("dim", entry.updated);
193
+ const right = theme.fg("dim", relativeTimeText(entry.updated));
186
194
  return { left, right };
187
195
  });
188
196
  }
@@ -277,8 +285,8 @@ function teamListMemberName(theme: ThemeLike, teamView: TeamListTeamView, member
277
285
  }
278
286
 
279
287
  function teamListTimestamp(teamView: TeamListTeamView): string {
280
- if (teamView.state === "dormant" && teamView.expiresAt) return `expires ${monthDay(Date.parse(teamView.expiresAt))}`;
281
- return `updated ${nowText(new Date(teamView.updatedAt))}`;
288
+ if (teamView.state === "dormant" && teamView.expiresAt) return `expires ${futureTime(Date.parse(teamView.expiresAt), Date.now())}`;
289
+ return `updated ${relativeTime(Date.parse(teamView.updatedAt), Date.now())}`;
282
290
  }
283
291
 
284
292
  export function teamListLines(theme: ThemeLike, teamViews: TeamListTeamView[], roster: string[] = []): TeamLine[] {
@@ -552,19 +560,37 @@ function renderLogDetail(theme: ThemeLike, detail: LogDetail, roster: string[]):
552
560
  return theme.fg(detail.token, detail.text);
553
561
  }
554
562
 
555
- function logChrome(theme: ThemeLike, branch: "├" | "└", sequence: number, seqWidth: number, epochMilliseconds: number): string {
556
- return theme.fg("borderMuted", `${treeGlyph(branch)}${padVisible(`#${sequence}`, seqWidth)} ${timeOfDay(epochMilliseconds)}`);
563
+ const LOG_ROW_INDENT = " ";
564
+
565
+ function logChrome(theme: ThemeLike, sequence: number, seqWidth: number, epochMilliseconds: number): string {
566
+ return theme.fg("borderMuted", `${LOG_ROW_INDENT}${padVisible(`#${sequence}`, seqWidth)} ${timeOfDay(epochMilliseconds)}`);
567
+ }
568
+
569
+ function sameLocalDay(a: number, b: number): boolean {
570
+ return new Date(a).toDateString() === new Date(b).toDateString();
571
+ }
572
+
573
+ function dayDividerLine(theme: ThemeLike, epochMilliseconds: number): string {
574
+ const rule = glyphs().line;
575
+ return `${LOG_ROW_INDENT}${theme.fg("borderMuted", `${rule.repeat(2)} ${monthDay(epochMilliseconds)} ${rule.repeat(30)}`)}`;
557
576
  }
558
577
 
559
- function actionRows(theme: ThemeLike, actions: LogAction[], roster: string[], hasFooter: boolean): string[] {
578
+ /** Log rows keep an absolute HH:MM:SS grammar; day dividers carry the date whenever a row is not from "today". */
579
+ function actionRows(theme: ThemeLike, actions: LogAction[], roster: string[], nowMilliseconds: number): string[] {
560
580
  const g = glyphs();
561
581
  const seqWidth = Math.max(...actions.map((action) => `#${action.sequence}`.length));
562
582
  const whoWidth = Math.max(...actions.map((action) => action.who.length));
563
583
  const actionWidth = Math.max(...actions.map((action) => action.action.length));
564
584
  const iconWidth = Math.max(...actions.map((action) => visibleLength(logIconGlyph(action.icon))));
585
+ const rows: string[] = [];
565
586
  let previousWho: string | undefined;
566
- return actions.map((action, index) => {
567
- const branch = index === actions.length - 1 && !hasFooter ? "└" : "├";
587
+ let previousEpoch = nowMilliseconds;
588
+ for (const action of actions) {
589
+ if (!sameLocalDay(action.epochMilliseconds, previousEpoch)) {
590
+ rows.push(dayDividerLine(theme, action.epochMilliseconds));
591
+ previousWho = undefined;
592
+ }
593
+ previousEpoch = action.epochMilliseconds;
568
594
  let whoStyled = theme.fg(actorHueToken(action.who, roster), padVisible(action.who, whoWidth));
569
595
  if (action.who === previousWho) whoStyled = `${DIM_SGR_OPEN}${whoStyled}${DIM_SGR_CLOSE}`;
570
596
  previousWho = action.who;
@@ -575,8 +601,9 @@ function actionRows(theme: ThemeLike, actions: LogAction[], roster: string[], ha
575
601
  .filter((detail) => detail.style !== "text" || detail.text.length > 0)
576
602
  .map((detail) => renderLogDetail(theme, detail, roster))
577
603
  .join(dot);
578
- return `${logChrome(theme, branch, action.sequence, seqWidth, action.epochMilliseconds)} ${whoStyled} ${icon} ${actionName}${detailText ? `${dot}${detailText}` : ""}`;
579
- });
604
+ rows.push(`${logChrome(theme, action.sequence, seqWidth, action.epochMilliseconds)} ${whoStyled} ${icon} ${actionName}${detailText ? `${dot}${detailText}` : ""}`);
605
+ }
606
+ return rows;
580
607
  }
581
608
 
582
609
  function filterStats(theme: ThemeLike, filters: Record<string, unknown>, roster: string[]): string[] {
@@ -607,24 +634,17 @@ export function teamLogLines(theme: ThemeLike, view: TeamLogRenderView): string[
607
634
  ...filterStats(theme, view.filters ?? {}, view.roster ?? []),
608
635
  ];
609
636
  const header = headerLine(theme, "Team Log", theme.fg("accent", view.team), stats);
610
- if (view.entries.length === 0) return [header, `${treeConnector(theme, "└")}${theme.fg("muted", "no matching events")}`];
637
+ if (view.entries.length === 0) return [header, `${LOG_ROW_INDENT}${theme.fg("muted", "no matching events")}`];
611
638
 
612
639
  const footer = view.nextCursor
613
- ? `${treeConnector(theme, "└")}${theme.fg("muted", `${g.ellipsis} older events${g.dot}cursor "${view.nextCursor}"`)}`
640
+ ? `${LOG_ROW_INDENT}${theme.fg("muted", `${g.ellipsis} older events${g.dot}cursor "${view.nextCursor}"`)}`
614
641
  : undefined;
615
- const rows = actionRows(theme, actions, view.roster ?? [], Boolean(footer));
642
+ const rows = actionRows(theme, actions, view.roster ?? [], view.nowMilliseconds ?? Date.now());
616
643
  return [header, ...rows, ...(footer ? [footer] : [])];
617
644
  }
618
645
 
619
646
  export function teamMessageLines(theme: ThemeLike, details: TeamMessageDetails, roster: string[] = []): TeamLine[] {
620
- const g = glyphs();
621
- const header = [
622
- theme.fg("accent", `${g.diamond} `),
623
- theme.fg(actorHueToken(details.from, roster), theme.bold(details.from)),
624
- theme.fg("muted", ` ${g.arrow} ${details.to ?? "main"}`),
625
- theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
626
- ].join("");
627
- return [header, ...quotedBody(theme, details.message, { lineLimit: Number.POSITIVE_INFINITY, barToken: "accent" })];
647
+ return [teamMessageHeader(theme, details, roster), ...quotedBody(theme, details.message, { lineLimit: Number.POSITIVE_INFINITY, barToken: "accent" })];
628
648
  }
629
649
 
630
650
  function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails, roster: string[]): string {
@@ -633,7 +653,7 @@ function teamMessageHeader(theme: ThemeLike, details: TeamMessageDetails, roster
633
653
  theme.fg("accent", `${g.diamond} `),
634
654
  theme.fg(actorHueToken(details.from, roster), theme.bold(details.from)),
635
655
  theme.fg("muted", ` ${g.arrow} ${details.to ?? "main"}`),
636
- theme.fg("dim", `${g.dot}${details.team}${g.dot}${details.sentAt}`),
656
+ theme.fg("dim", `${g.dot}${details.team}${g.dot}${relativeTimeText(details.sentAt)}`),
637
657
  ].join("");
638
658
  }
639
659
 
Binary file
package/team-ui.ts CHANGED
@@ -3,6 +3,7 @@ import { Key, matchesKey, SelectList, sliceByColumn, truncateToWidth, visibleWid
3
3
 
4
4
  import {
5
5
  actorHueToken,
6
+ relativeTimeText,
6
7
  statusWordToken,
7
8
  teamLineText,
8
9
  teamLogLines,
@@ -82,13 +83,15 @@ function statusRows(theme: ThemeLike, statuses: Array<[string, TeamStatusView]>,
82
83
  const contentWidth = Math.max(0, width - 1);
83
84
  const nameWidth = Math.max(0, ...statuses.map(([name]) => visibleWidth(name)));
84
85
  const wordWidth = Math.max(0, ...statuses.map(([, status]) => visibleWidth(status.word)));
85
- const timestampWidth = Math.max(0, ...statuses.map(([, status]) => visibleWidth(status.updated)));
86
+ const updatedTexts = statuses.map(([, status]) => relativeTimeText(status.updated));
87
+ const timestampWidth = Math.max(0, ...updatedTexts.map((text) => visibleWidth(text)));
86
88
  const phraseWidth = Math.max(0, contentWidth - nameWidth - wordWidth - timestampWidth - 6);
87
89
 
88
- return statuses.map(([name, status]) => {
90
+ return statuses.map(([name, status], index) => {
89
91
  const styledName = theme.fg(actorHueToken(name, roster), name);
90
92
  const styledWord = theme.fg(statusWordToken(status.word), status.word);
91
- const timestamp = theme.fg("dim", status.updated);
93
+ const updatedText = updatedTexts[index]!;
94
+ const timestamp = theme.fg("dim", `${" ".repeat(Math.max(0, timestampWidth - visibleWidth(updatedText)))}${updatedText}`);
92
95
  const phrase = middleTruncateToWidth(status.phrase, phraseWidth, true);
93
96
  return `${padVisible(styledName, nameWidth)} ${padVisible(styledWord, wordWidth)} ${phrase} ${timestamp}`;
94
97
  });
@@ -257,7 +260,7 @@ class TeamOverviewOverlay implements Component {
257
260
 
258
261
  const transport = team.showOnHerdrPanes ? "Herdr" : "RPC";
259
262
  const metadata = [
260
- `Created ${team.created}`,
263
+ `Created ${relativeTimeText(team.created)}`,
261
264
  `${team.roster.length} teammate${team.roster.length === 1 ? "" : "s"}`,
262
265
  transport,
263
266
  `${team.log.length} retained event${team.log.length === 1 ? "" : "s"}`,
package/teamlog.ts CHANGED
@@ -66,10 +66,6 @@ const MAX_LIMIT = 100;
66
66
  const dateFormatter = new Intl.DateTimeFormat("en-US", { month: "long", day: "2-digit" });
67
67
  const timeFormatter = new Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
68
68
 
69
- export function nowText(date: Date = new Date()): string {
70
- return `${dateFormatter.format(date)}, ${timeFormatter.format(date)}`;
71
- }
72
-
73
69
  export function timeOfDay(epochMilliseconds: number): string {
74
70
  return timeFormatter.format(new Date(epochMilliseconds));
75
71
  }
@@ -78,6 +74,44 @@ export function monthDay(epochMilliseconds: number): string {
78
74
  return dateFormatter.format(new Date(epochMilliseconds));
79
75
  }
80
76
 
77
+ const MINUTE_MILLISECONDS = 60_000;
78
+ const HOUR_MILLISECONDS = 60 * MINUTE_MILLISECONDS;
79
+ const DAY_MILLISECONDS = 24 * HOUR_MILLISECONDS;
80
+ const WEEK_MILLISECONDS = 7 * DAY_MILLISECONDS;
81
+ const MONTH_MILLISECONDS = 30 * DAY_MILLISECONDS;
82
+
83
+ /** formatElapsed(12 * 60_000) === "12m"; formatElapsed(33 * 3_600_000) === "1d 9h"; formatElapsed(5 * 86_400_000) === "5d" */
84
+ function formatElapsed(elapsedMilliseconds: number): string {
85
+ if (elapsedMilliseconds < HOUR_MILLISECONDS) return `${Math.max(1, Math.floor(elapsedMilliseconds / MINUTE_MILLISECONDS))}m`;
86
+ const hours = Math.floor(elapsedMilliseconds / HOUR_MILLISECONDS);
87
+ if (elapsedMilliseconds < 4 * HOUR_MILLISECONDS) {
88
+ const minutes = Math.floor((elapsedMilliseconds % HOUR_MILLISECONDS) / MINUTE_MILLISECONDS);
89
+ return `${hours}h ${String(minutes).padStart(2, "0")}m`;
90
+ }
91
+ if (elapsedMilliseconds < DAY_MILLISECONDS) return `${hours}h`;
92
+ if (elapsedMilliseconds < 2 * DAY_MILLISECONDS) return `1d ${Math.floor((elapsedMilliseconds % DAY_MILLISECONDS) / HOUR_MILLISECONDS)}h`;
93
+ if (elapsedMilliseconds < WEEK_MILLISECONDS) return `${Math.floor(elapsedMilliseconds / DAY_MILLISECONDS)}d`;
94
+ if (elapsedMilliseconds < MONTH_MILLISECONDS) return `${Math.floor(elapsedMilliseconds / WEEK_MILLISECONDS)}w`;
95
+ return `${Math.floor(elapsedMilliseconds / MONTH_MILLISECONDS)}mo`;
96
+ }
97
+
98
+ /**
99
+ * Elapsed-only relative time, one grammar across all tiers.
100
+ * relativeTime(now - 20_000, now) === "just now"; relativeTime(now - 12 * 60_000, now) === "12m ago"; relativeTime(now - 5 * 86_400_000, now) === "5d ago"
101
+ */
102
+ export function relativeTime(epochMilliseconds: number, nowMilliseconds: number): string {
103
+ const elapsed = Math.max(0, nowMilliseconds - epochMilliseconds);
104
+ if (elapsed < MINUTE_MILLISECONDS) return "just now";
105
+ return `${formatElapsed(elapsed)} ago`;
106
+ }
107
+
108
+ /**
109
+ * futureTime(now + 20 * 86_400_000, now) === "in 2w"
110
+ */
111
+ export function futureTime(epochMilliseconds: number, nowMilliseconds: number): string {
112
+ return `in ${formatElapsed(Math.max(0, epochMilliseconds - nowMilliseconds))}`;
113
+ }
114
+
81
115
  function safeStringify(value: unknown): string {
82
116
  try {
83
117
  return JSON.stringify(value) ?? String(value);
@@ -97,7 +131,7 @@ export function appendTeamLog(state: TeamLogState, input: TeamLogEntryInput, now
97
131
  const entry: TeamLogEntry = {
98
132
  ...input,
99
133
  sequence: state.nextLogSequence++,
100
- timestamp: nowText(now),
134
+ timestamp: now.toISOString(),
101
135
  epochMilliseconds: now.getTime(),
102
136
  };
103
137
  state.log.push(entry);