@astrale-os/cli 1.0.0-beta.27 → 1.0.0-beta.28
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 +26 -3
- package/dist/astrale.js +243 -76
- package/package.json +1 -1
- package/src/commands/__tests__/domain-install-operation.test.ts +23 -0
- package/src/commands/__tests__/install-identity-override.test.ts +3 -3
- package/src/commands/domain/install.ts +19 -11
- package/src/commands/get.ts +1 -1
- package/src/commands/identity/register.ts +3 -4
- package/src/commands/logs.ts +2 -5
- package/src/commands/session/analyze.ts +26 -4
- package/src/lib/__tests__/skills.test.ts +8 -2
- package/src/program/__tests__/program.test.ts +1 -1
- package/src/telemetry/__tests__/retention.test.ts +180 -0
- package/src/telemetry/__tests__/settings.test.ts +102 -0
- package/src/telemetry/__tests__/store-scan.test.ts +128 -0
- package/src/telemetry/__tests__/trigger.test.ts +33 -4
- package/src/telemetry/recorder.ts +6 -3
- package/src/telemetry/retention.ts +129 -0
- package/src/telemetry/session.ts +18 -12
- package/src/telemetry/settings.ts +64 -11
- package/src/telemetry/store.ts +87 -9
- package/src/telemetry/trigger.ts +16 -28
- package/studio/client/dist/assets/index-BFVFs_8x.js +81 -0
- package/studio/client/dist/assets/index-DuB9iUdu.css +2 -0
- package/studio/client/dist/assets/schema-studio--a0kX3QU.css +1 -0
- package/studio/client/dist/assets/schema-studio-DH6oEWME.js +8 -0
- package/studio/client/dist/index.html +3 -3
- package/studio/server/agent/prompts/anchors.test.ts +17 -4
- package/studio/server/agent/prompts/anchors.ts +3 -2
- package/studio/server/agent/prompts/system.test.ts +2 -3
- package/studio/server/agent/prompts/system.ts +3 -3
- package/studio/server/agent/run/preparation.ts +1 -1
- package/studio/server/api/context.ts +1 -1
- package/studio/server/api/deployment.ts +1 -1
- package/studio/server/api/views.ts +2 -2
- package/studio/server/api/workspace.ts +1 -1
- package/studio/server/cache.test.ts +3 -8
- package/studio/server/cache.ts +4 -45
- package/studio/server/handoff/copy.ts +1 -1
- package/studio/server/introspect/canonical-schema.test.ts +154 -128
- package/studio/server/introspect/canonical-schema.ts +183 -302
- package/studio/server/introspect/core.ts +14 -21
- package/studio/server/introspect/extractor.ts +11 -15
- package/studio/server/introspect/overlay-tsmorph.test.ts +1 -5
- package/studio/server/introspect/overlay-tsmorph.ts +0 -1
- package/studio/server/introspect/overlay.ts +3 -24
- package/studio/server/introspect/revision.test.ts +24 -28
- package/studio/server/introspect/revision.ts +10 -21
- package/studio/server/introspect/runtime.test.ts +14 -14
- package/studio/server/introspect/runtime.ts +1 -46
- package/studio/server/lifecycle.ts +4 -1
- package/studio/server/state/documents.test.ts +69 -0
- package/studio/server/state/documents.ts +57 -10
- package/studio/shared/contracts/schema.ts +10 -26
- package/studio/shared/contracts/surface.test.ts +2 -2
- package/studio/shared/contracts/workspace.ts +3 -0
- package/studio/shared/schema/identity.ts +0 -1
- package/studio/client/dist/assets/index-C0FAnwNw.css +0 -2
- package/studio/client/dist/assets/index-CpBed0V1.js +0 -81
- package/studio/client/dist/assets/schema-studio-BilUNb6Z.css +0 -1
- package/studio/client/dist/assets/schema-studio-DJm9guI8.js +0 -8
- package/studio/server/introspect/core-extractor.ts +0 -30
- package/studio/server/introspect/overlay.test.ts +0 -44
- package/studio/server/introspect/source-overlay/annotations.ts +0 -14
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { appendFileSync } from 'node:fs'
|
|
8
8
|
|
|
9
|
+
import type { SessionScan } from './store'
|
|
9
10
|
import type { TelemetryEvent } from './types'
|
|
10
11
|
|
|
11
12
|
import { redactArgv } from './redact'
|
|
@@ -32,15 +33,17 @@ function isHelpOrVersion(args: string[]): boolean {
|
|
|
32
33
|
return args.every((a) => HELP_VERSION.has(a))
|
|
33
34
|
}
|
|
34
35
|
|
|
35
|
-
/** Begin recording an invocation; returns a finalizer to call at process end.
|
|
36
|
-
|
|
36
|
+
/** Begin recording an invocation; returns a finalizer to call at process end.
|
|
37
|
+
* `sessions` is an already-paid-for store scan the caller shares with
|
|
38
|
+
* retention — see bin/astrale.ts. */
|
|
39
|
+
export function beginInvocation(argv: string[], sessions?: readonly SessionScan[]): Finalizer {
|
|
37
40
|
try {
|
|
38
41
|
const args = argv.slice(2)
|
|
39
42
|
if (!telemetryEnabled() || isHelpOrVersion(args)) return NOOP
|
|
40
43
|
const startMs = Date.now()
|
|
41
44
|
const ts = new Date(startMs).toISOString()
|
|
42
45
|
const cwd = process.cwd()
|
|
43
|
-
const { id, root } = ensureSession(cwd)
|
|
46
|
+
const { id, root } = ensureSession(cwd, sessions)
|
|
44
47
|
return (exitCode: number, errorName?: string) => {
|
|
45
48
|
try {
|
|
46
49
|
const event: TelemetryEvent = {
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-store retention: two bounds, applied in that order.
|
|
3
|
+
*
|
|
4
|
+
* Age is a RELEVANCE bound — a session idle for a month has nothing left to
|
|
5
|
+
* say, and the harness transcripts its report would cite are long gone. It is
|
|
6
|
+
* free to enforce (scanSessions already stats every events.jsonl), so it runs
|
|
7
|
+
* on every CLI start, telemetry on or off: switching telemetry off must mean
|
|
8
|
+
* "and clean up what is already there", not "freeze the store forever".
|
|
9
|
+
*
|
|
10
|
+
* Size is a SAFETY bound — the analyzer runs with Write inside the session
|
|
11
|
+
* directory, so one pathological session can grow without limit. Enforcing it
|
|
12
|
+
* means stat-ing every file of every session, so it runs only in the detached
|
|
13
|
+
* analyzer, never on the user's critical path.
|
|
14
|
+
*
|
|
15
|
+
* Neither bound replaces the other: age bounds what is worth keeping, size
|
|
16
|
+
* bounds what can go wrong. Both are configurable — see settings.ts.
|
|
17
|
+
*/
|
|
18
|
+
import { rmSync } from 'node:fs'
|
|
19
|
+
|
|
20
|
+
import type { RetentionBudget } from './settings'
|
|
21
|
+
import type { SessionScan } from './store'
|
|
22
|
+
|
|
23
|
+
import { retentionBudget } from './settings'
|
|
24
|
+
import { scanSessions, sessionBytes, sessionDir } from './store'
|
|
25
|
+
|
|
26
|
+
/** Cap for the age sweep on the CLI's critical path, so a large backlog drains
|
|
27
|
+
* over several runs instead of stalling one command on hundreds of rmSync. */
|
|
28
|
+
export const MAX_REMOVALS_ON_START = 20
|
|
29
|
+
|
|
30
|
+
export type SweepOptions = {
|
|
31
|
+
/** Defaults to the resolved config budget. */
|
|
32
|
+
budget?: RetentionBudget
|
|
33
|
+
now?: number
|
|
34
|
+
/** Cap on removals; unbounded when omitted. */
|
|
35
|
+
limit?: number
|
|
36
|
+
/** Ids that must survive — the session being recorded or analyzed right now. */
|
|
37
|
+
protect?: ReadonlySet<string>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Session ids removed, in removal order. */
|
|
41
|
+
export type SweepResult = { removed: string[] }
|
|
42
|
+
|
|
43
|
+
function remove(id: string, into: string[]): void {
|
|
44
|
+
try {
|
|
45
|
+
rmSync(sessionDir(id), { recursive: true, force: true })
|
|
46
|
+
into.push(id)
|
|
47
|
+
} catch {
|
|
48
|
+
/* best effort — retention must never affect the CLI */
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Drop every session whose last activity predates the age bound, analyzed or
|
|
54
|
+
* not: a session that went a month without being analyzed never will be.
|
|
55
|
+
* Sessions with no events yet are exempt — one of them is the invocation
|
|
56
|
+
* running right now, created by ensureSession and not written until exit.
|
|
57
|
+
*/
|
|
58
|
+
export function sweepByAge(
|
|
59
|
+
sessions: readonly SessionScan[],
|
|
60
|
+
options: SweepOptions = {},
|
|
61
|
+
): SweepResult {
|
|
62
|
+
const { maxAgeMs } = options.budget ?? retentionBudget()
|
|
63
|
+
const cutoff = (options.now ?? Date.now()) - maxAgeMs
|
|
64
|
+
const limit = options.limit ?? Number.POSITIVE_INFINITY
|
|
65
|
+
const protect = options.protect
|
|
66
|
+
const removed: string[] = []
|
|
67
|
+
for (const session of sessions) {
|
|
68
|
+
if (removed.length >= limit) break
|
|
69
|
+
if (protect?.has(session.id)) continue
|
|
70
|
+
if (session.lastEventAt !== null && session.lastEventAt.getTime() < cutoff) {
|
|
71
|
+
remove(session.id, removed)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { removed }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Trim the store to the size bound, evicting oldest-first and analyzed before
|
|
79
|
+
* unanalyzed — an analyzed session has already handed its evidence to a report,
|
|
80
|
+
* an unanalyzed one has not. Open sessions are never touched: one of them is
|
|
81
|
+
* being recorded right now.
|
|
82
|
+
*/
|
|
83
|
+
export function sweepToBudget(
|
|
84
|
+
sessions: readonly SessionScan[],
|
|
85
|
+
options: SweepOptions = {},
|
|
86
|
+
): SweepResult {
|
|
87
|
+
const { maxBytes } = options.budget ?? retentionBudget()
|
|
88
|
+
const protect = options.protect
|
|
89
|
+
const removed: string[] = []
|
|
90
|
+
|
|
91
|
+
const sized = sessions.map((session) => ({ session, bytes: sessionBytes(session.id) }))
|
|
92
|
+
let total = sized.reduce((sum, entry) => sum + entry.bytes, 0)
|
|
93
|
+
if (total <= maxBytes) return { removed }
|
|
94
|
+
|
|
95
|
+
// Oldest first; a session with no events yet sorts to the front — it holds
|
|
96
|
+
// nothing but a meta.json, so it is the cheapest thing to lose.
|
|
97
|
+
const evictable = sized
|
|
98
|
+
.filter((entry) => entry.session.closed && !protect?.has(entry.session.id))
|
|
99
|
+
.sort(
|
|
100
|
+
(a, b) => (a.session.lastEventAt?.getTime() ?? 0) - (b.session.lastEventAt?.getTime() ?? 0),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
for (const analyzedFirst of [true, false]) {
|
|
104
|
+
for (const entry of evictable) {
|
|
105
|
+
if (total <= maxBytes) return { removed }
|
|
106
|
+
if (entry.session.analyzed !== analyzedFirst) continue
|
|
107
|
+
const before = removed.length
|
|
108
|
+
remove(entry.session.id, removed)
|
|
109
|
+
if (removed.length > before) total -= entry.bytes
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { removed }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Both bounds over the live store, for the detached analyzer: age first (cheap,
|
|
117
|
+
* and it may free enough on its own), then size over whatever survives.
|
|
118
|
+
*/
|
|
119
|
+
export function sweepStore(options: SweepOptions = {}): SweepResult {
|
|
120
|
+
const budget = options.budget ?? retentionBudget()
|
|
121
|
+
const sessions = scanSessions()
|
|
122
|
+
const byAge = sweepByAge(sessions, { ...options, budget })
|
|
123
|
+
const gone = new Set(byAge.removed)
|
|
124
|
+
const bySize = sweepToBudget(
|
|
125
|
+
sessions.filter((session) => !gone.has(session.id)),
|
|
126
|
+
{ ...options, budget },
|
|
127
|
+
)
|
|
128
|
+
return { removed: [...byAge.removed, ...bySize.removed] }
|
|
129
|
+
}
|
package/src/telemetry/session.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { dirname, join } from 'node:path'
|
|
|
10
10
|
|
|
11
11
|
import type { SessionMeta } from './types'
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import { metaPath, readMeta, scanSessions, sessionDir, type SessionScan } from './store'
|
|
14
14
|
|
|
15
15
|
export type ResolvedSession = { id: string; root: string; explicit: boolean }
|
|
16
16
|
|
|
@@ -40,12 +40,14 @@ function stamp(d = new Date()): string {
|
|
|
40
40
|
|
|
41
41
|
/** id of an open, ambient session already bucketed to `root`, else null.
|
|
42
42
|
* Analyzed sessions are never reused — a straggler event may "reopen" one
|
|
43
|
-
* after its report, and new work funneled there would never be analyzed.
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
43
|
+
* after its report, and new work funneled there would never be analyzed.
|
|
44
|
+
* Only the open, unanalyzed candidates get their meta.json read: on a store of
|
|
45
|
+
* hundreds at most a couple qualify, and this runs before every command. */
|
|
46
|
+
function findOpenAmbient(root: string, sessions: readonly SessionScan[]): string | null {
|
|
47
|
+
for (const s of sessions) {
|
|
48
|
+
if (s.closed || s.analyzed) continue
|
|
49
|
+
const meta = readMeta(s.id)
|
|
50
|
+
if (meta?.root === root && meta.explicit === false) return s.id
|
|
49
51
|
}
|
|
50
52
|
return null
|
|
51
53
|
}
|
|
@@ -55,20 +57,24 @@ function mintAmbientId(root: string): string {
|
|
|
55
57
|
return `amb-${hash8}-${stamp()}`
|
|
56
58
|
}
|
|
57
59
|
|
|
58
|
-
/** Resolve the session identity for `cwd` without creating anything on disk.
|
|
59
|
-
|
|
60
|
+
/** Resolve the session identity for `cwd` without creating anything on disk.
|
|
61
|
+
* `sessions` lets the caller hand over a scan it already paid for — the CLI
|
|
62
|
+
* start path shares one between recording and retention. */
|
|
63
|
+
export function resolveSession(cwd: string, sessions?: readonly SessionScan[]): ResolvedSession {
|
|
60
64
|
const root = findGitRoot(cwd) ?? cwd
|
|
61
65
|
const pinned = process.env.ASTRALE_SESSION
|
|
62
66
|
if (pinned) {
|
|
63
67
|
const id = sanitizeId(pinned)
|
|
64
68
|
if (id.length > 0) return { id, root, explicit: true }
|
|
65
69
|
}
|
|
66
|
-
|
|
70
|
+
// Only scan when a pinned id did not already settle it.
|
|
71
|
+
const scan = sessions ?? scanSessions()
|
|
72
|
+
return { id: findOpenAmbient(root, scan) ?? mintAmbientId(root), root, explicit: false }
|
|
67
73
|
}
|
|
68
74
|
|
|
69
75
|
/** Resolve, then create the session dir + meta.json on first sight. */
|
|
70
|
-
export function ensureSession(cwd: string): ResolvedSession {
|
|
71
|
-
const resolved = resolveSession(cwd)
|
|
76
|
+
export function ensureSession(cwd: string, sessions?: readonly SessionScan[]): ResolvedSession {
|
|
77
|
+
const resolved = resolveSession(cwd, sessions)
|
|
72
78
|
const dir = sessionDir(resolved.id)
|
|
73
79
|
if (!existsSync(dir)) {
|
|
74
80
|
try {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Telemetry kill-switch,
|
|
3
|
-
*
|
|
4
|
-
* is false; on by default.
|
|
2
|
+
* Telemetry kill-switch and retention budget, both read synchronously from
|
|
3
|
+
* `~/.astrale/config.json` with env overrides. Off when ASTRALE_TELEMETRY is
|
|
4
|
+
* 0/false/off, or when config telemetry.enabled is false; on by default.
|
|
5
|
+
* Every read silent-fails to the default — a broken config must never break
|
|
6
|
+
* the CLI, and must never leave the session store unbounded.
|
|
5
7
|
*/
|
|
6
8
|
import { readFileSync } from 'node:fs'
|
|
7
9
|
|
|
@@ -9,18 +11,69 @@ import { createPaths } from '../state/index'
|
|
|
9
11
|
|
|
10
12
|
const OFF_VALUES = new Set(['0', 'false', 'off'])
|
|
11
13
|
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
/** Sessions idle longer than this are dropped: a month-old session has nothing
|
|
15
|
+
* left to say, and the harness transcripts its report would cite are gone. */
|
|
16
|
+
export const DEFAULT_MAX_AGE_DAYS = 30
|
|
17
|
+
|
|
18
|
+
/** Hard ceiling on the whole session store. At ~35 KB per session that is some
|
|
19
|
+
* 1,400 sessions — never reached in normal use. It exists for the pathological
|
|
20
|
+
* case: the analyzer runs with Write inside the session directory, so a single
|
|
21
|
+
* session can grow without bound. */
|
|
22
|
+
export const DEFAULT_MAX_BYTES = 50 * 1024 * 1024
|
|
23
|
+
|
|
24
|
+
type TelemetryConfig = {
|
|
25
|
+
enabled?: boolean
|
|
26
|
+
maxAgeDays?: number
|
|
27
|
+
maxBytes?: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The `telemetry` block, or {} when the config is missing or unreadable. */
|
|
31
|
+
function readConfig(): TelemetryConfig {
|
|
16
32
|
try {
|
|
17
33
|
// Call-time path resolution — see sessionsRoot() in store.ts for why.
|
|
18
34
|
const parsed = JSON.parse(readFileSync(createPaths().config, 'utf-8')) as {
|
|
19
|
-
telemetry?:
|
|
35
|
+
telemetry?: TelemetryConfig
|
|
20
36
|
}
|
|
21
|
-
|
|
37
|
+
const telemetry = parsed.telemetry
|
|
38
|
+
return typeof telemetry === 'object' && telemetry !== null ? telemetry : {}
|
|
22
39
|
} catch {
|
|
23
|
-
/* missing or broken config →
|
|
40
|
+
/* missing or broken config → defaults */
|
|
41
|
+
return {}
|
|
24
42
|
}
|
|
25
|
-
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether telemetry recording is enabled for this process. */
|
|
46
|
+
export function telemetryEnabled(): boolean {
|
|
47
|
+
const env = process.env.ASTRALE_TELEMETRY
|
|
48
|
+
if (env !== undefined && OFF_VALUES.has(env.trim().toLowerCase())) return false
|
|
49
|
+
return readConfig().enabled !== false
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The two bounds on the session store — see retention.ts for how they apply. */
|
|
53
|
+
export type RetentionBudget = {
|
|
54
|
+
maxAgeMs: number
|
|
55
|
+
maxBytes: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** First finite, strictly positive candidate. Zero, negatives and garbage fall
|
|
59
|
+
* through to the next candidate (ultimately the default) rather than
|
|
60
|
+
* disabling the bound, so a typo can never make the store unbounded. */
|
|
61
|
+
function firstPositive(candidates: (number | string | undefined)[]): number | null {
|
|
62
|
+
for (const candidate of candidates) {
|
|
63
|
+
if (candidate === undefined) continue
|
|
64
|
+
const n = typeof candidate === 'string' ? Number(candidate.trim()) : candidate
|
|
65
|
+
if (Number.isFinite(n) && n > 0) return n
|
|
66
|
+
}
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Resolved retention budget: env over config over defaults. */
|
|
71
|
+
export function retentionBudget(): RetentionBudget {
|
|
72
|
+
const config = readConfig()
|
|
73
|
+
const days =
|
|
74
|
+
firstPositive([process.env.ASTRALE_TELEMETRY_MAX_AGE_DAYS, config.maxAgeDays]) ??
|
|
75
|
+
DEFAULT_MAX_AGE_DAYS
|
|
76
|
+
const bytes =
|
|
77
|
+
firstPositive([process.env.ASTRALE_TELEMETRY_MAX_BYTES, config.maxBytes]) ?? DEFAULT_MAX_BYTES
|
|
78
|
+
return { maxAgeMs: days * 24 * 60 * 60 * 1000, maxBytes: bytes }
|
|
26
79
|
}
|
package/src/telemetry/store.ts
CHANGED
|
@@ -5,8 +5,14 @@
|
|
|
5
5
|
* .analyzed AnalyzedMarker, written by the analyzer (any outcome)
|
|
6
6
|
* report.md analyzer output
|
|
7
7
|
* A session is CLOSED when events.jsonl's mtime is older than IDLE_WINDOW_MS.
|
|
8
|
+
*
|
|
9
|
+
* Two ways to read it, deliberately kept apart. scanSessions() answers the
|
|
10
|
+
* questions the CLI's start path asks — how old, open or closed, analyzed yet —
|
|
11
|
+
* from two stats per session and no file reads. listSessions() adds the parsed
|
|
12
|
+
* meta.json and marker, which only `session list` and the analyzer need. The
|
|
13
|
+
* start path runs before EVERY command, so the difference is not academic.
|
|
8
14
|
*/
|
|
9
|
-
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
15
|
+
import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
10
16
|
import { join } from 'node:path'
|
|
11
17
|
|
|
12
18
|
import type { AnalyzedMarker, SessionMeta } from './types'
|
|
@@ -42,6 +48,78 @@ export function reportPath(id: string): string {
|
|
|
42
48
|
return join(sessionDir(id), 'report.md')
|
|
43
49
|
}
|
|
44
50
|
|
|
51
|
+
/**
|
|
52
|
+
* The cheap facts about one session: enough to bucket an invocation, sweep the
|
|
53
|
+
* store, and pick an analysis target. `analyzed` records that a marker EXISTS,
|
|
54
|
+
* not what it says — a stat, not a read.
|
|
55
|
+
*/
|
|
56
|
+
export type SessionScan = {
|
|
57
|
+
id: string
|
|
58
|
+
lastEventAt: Date | null
|
|
59
|
+
closed: boolean
|
|
60
|
+
analyzed: boolean
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Session directory names, newest-first ordering applied by the callers. */
|
|
64
|
+
function sessionIds(): string[] {
|
|
65
|
+
try {
|
|
66
|
+
return readdirSync(sessionsRoot()).filter((name) => !name.startsWith('.'))
|
|
67
|
+
} catch {
|
|
68
|
+
return []
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Newest activity first. Two stats per session, no file reads, no parsing. */
|
|
73
|
+
export function scanSessions(now = Date.now()): SessionScan[] {
|
|
74
|
+
return sessionIds()
|
|
75
|
+
.map((id) => {
|
|
76
|
+
let lastEventAt: Date | null = null
|
|
77
|
+
try {
|
|
78
|
+
lastEventAt = statSync(eventsPath(id)).mtime
|
|
79
|
+
} catch {
|
|
80
|
+
/* no events yet */
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
id,
|
|
84
|
+
lastEventAt,
|
|
85
|
+
closed: lastEventAt !== null && now - lastEventAt.getTime() > IDLE_WINDOW_MS,
|
|
86
|
+
analyzed: existsSync(markerPath(id)),
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
.sort((a, b) => (b.lastEventAt?.getTime() ?? 0) - (a.lastEventAt?.getTime() ?? 0))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Bytes on disk under `dir`. Unreadable entries count as zero — a directory
|
|
93
|
+
* racing away mid-walk is normal, not an error worth propagating. */
|
|
94
|
+
function directoryBytes(dir: string): number {
|
|
95
|
+
let entries: Dirent[]
|
|
96
|
+
try {
|
|
97
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
98
|
+
} catch {
|
|
99
|
+
return 0
|
|
100
|
+
}
|
|
101
|
+
let total = 0
|
|
102
|
+
for (const entry of entries) {
|
|
103
|
+
const path = join(dir, entry.name)
|
|
104
|
+
if (entry.isDirectory()) {
|
|
105
|
+
total += directoryBytes(path)
|
|
106
|
+
} else if (entry.isFile()) {
|
|
107
|
+
try {
|
|
108
|
+
total += statSync(path).size
|
|
109
|
+
} catch {
|
|
110
|
+
/* raced away mid-walk */
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return total
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Bytes one session occupies. The analyzer runs with Write inside the session
|
|
118
|
+
* directory and may nest, so this walks rather than listing one level. */
|
|
119
|
+
export function sessionBytes(id: string): number {
|
|
120
|
+
return directoryBytes(sessionDir(id))
|
|
121
|
+
}
|
|
122
|
+
|
|
45
123
|
export type SessionInfo = {
|
|
46
124
|
id: string
|
|
47
125
|
meta: SessionMeta | null
|
|
@@ -50,6 +128,11 @@ export type SessionInfo = {
|
|
|
50
128
|
analyzed: AnalyzedMarker | null
|
|
51
129
|
}
|
|
52
130
|
|
|
131
|
+
/** One session's meta.json, or null when absent or unparseable. */
|
|
132
|
+
export function readMeta(id: string): SessionMeta | null {
|
|
133
|
+
return readJsonSafe<SessionMeta>(metaPath(id))
|
|
134
|
+
}
|
|
135
|
+
|
|
53
136
|
function readJsonSafe<T>(path: string): T | null {
|
|
54
137
|
try {
|
|
55
138
|
return JSON.parse(readFileSync(path, 'utf-8')) as T
|
|
@@ -76,15 +159,10 @@ export function inspectSession(id: string, now = Date.now()): SessionInfo | null
|
|
|
76
159
|
}
|
|
77
160
|
}
|
|
78
161
|
|
|
79
|
-
/** All sessions, newest activity first. Missing store dir → empty
|
|
162
|
+
/** All sessions, newest activity first, fully parsed. Missing store dir → empty
|
|
163
|
+
* list. Prefer scanSessions() anywhere latency matters — see the file header. */
|
|
80
164
|
export function listSessions(now = Date.now()): SessionInfo[] {
|
|
81
|
-
|
|
82
|
-
try {
|
|
83
|
-
ids = readdirSync(sessionsRoot()).filter((n) => !n.startsWith('.'))
|
|
84
|
-
} catch {
|
|
85
|
-
return []
|
|
86
|
-
}
|
|
87
|
-
return ids
|
|
165
|
+
return sessionIds()
|
|
88
166
|
.map((id) => inspectSession(id, now))
|
|
89
167
|
.filter((s): s is SessionInfo => s !== null)
|
|
90
168
|
.sort((a, b) => (b.lastEventAt?.getTime() ?? 0) - (a.lastEventAt?.getTime() ?? 0))
|
package/src/telemetry/trigger.ts
CHANGED
|
@@ -2,36 +2,18 @@
|
|
|
2
2
|
* Opportunistic analysis trigger — the `git gc --auto` model. Each CLI start
|
|
3
3
|
* cheaply scans for a closed, unanalyzed session and spawns ONE detached
|
|
4
4
|
* analyzer for it. No daemon, no cron; a lockfile keeps it single-flight.
|
|
5
|
+
* The same scan pays for the age sweep (see retention.ts), which is why the
|
|
6
|
+
* store stays bounded without anything resembling a background job.
|
|
5
7
|
*/
|
|
6
8
|
import { spawn } from 'node:child_process'
|
|
7
|
-
import { existsSync, mkdirSync, readFileSync,
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
8
10
|
import { join } from 'node:path'
|
|
9
11
|
|
|
12
|
+
import { MAX_REMOVALS_ON_START, sweepByAge } from './retention'
|
|
10
13
|
import { telemetryEnabled } from './settings'
|
|
11
|
-
import {
|
|
14
|
+
import { scanSessions, sessionsRoot, type SessionScan } from './store'
|
|
12
15
|
|
|
13
16
|
const LOCK_STALE_MS = 30 * 60 * 1000
|
|
14
|
-
const GC_AGE_MS = 30 * 24 * 60 * 60 * 1000
|
|
15
|
-
const GC_MAX_PER_RUN = 20
|
|
16
|
-
|
|
17
|
-
/** Opportunistic GC: analyzed sessions idle past the retention age are removed
|
|
18
|
-
* (capped per invocation) so the store — and the per-invocation scan — stays
|
|
19
|
-
* bounded. Evidence worth keeping has left via reports or filed issues. */
|
|
20
|
-
function gcOldSessions(sessions: SessionInfo[]): void {
|
|
21
|
-
try {
|
|
22
|
-
const cutoff = Date.now() - GC_AGE_MS
|
|
23
|
-
let removed = 0
|
|
24
|
-
for (const s of sessions) {
|
|
25
|
-
if (removed >= GC_MAX_PER_RUN) break
|
|
26
|
-
if (s.analyzed !== null && s.lastEventAt !== null && s.lastEventAt.getTime() < cutoff) {
|
|
27
|
-
rmSync(sessionDir(s.id), { recursive: true, force: true })
|
|
28
|
-
removed++
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
} catch {
|
|
32
|
-
/* best effort */
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
17
|
|
|
36
18
|
function lockPath(): string {
|
|
37
19
|
return join(sessionsRoot(), '.analyzer.lock')
|
|
@@ -76,16 +58,22 @@ export function releaseLock(): void {
|
|
|
76
58
|
* the most recently closed unanalyzed session, if any. Never throws, never
|
|
77
59
|
* blocks — worst case a few ms of directory stats.
|
|
78
60
|
*/
|
|
79
|
-
export function maybeTriggerAnalysis(argv: string[]): void {
|
|
61
|
+
export function maybeTriggerAnalysis(argv: string[], scan?: readonly SessionScan[]): void {
|
|
80
62
|
try {
|
|
81
|
-
if (!telemetryEnabled()) return
|
|
82
63
|
if (process.env.ASTRALE_TELEMETRY_NO_TRIGGER === '1') return
|
|
64
|
+
|
|
65
|
+
const sessions = scan ?? scanSessions()
|
|
66
|
+
// Retention runs ahead of the kill-switch check and on `session` commands
|
|
67
|
+
// too — turning telemetry off must still drain what is already on disk.
|
|
68
|
+
const swept = new Set(sweepByAge(sessions, { limit: MAX_REMOVALS_ON_START }).removed)
|
|
69
|
+
|
|
70
|
+
if (!telemetryEnabled()) return
|
|
83
71
|
// Never cascade off the session commands themselves.
|
|
84
72
|
if (argv[2] === 'session') return
|
|
85
73
|
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
74
|
+
const target = sessions.find(
|
|
75
|
+
(s) => s.closed && !s.analyzed && s.lastEventAt !== null && !swept.has(s.id),
|
|
76
|
+
)
|
|
89
77
|
if (!target) return
|
|
90
78
|
if (!claimLock()) return
|
|
91
79
|
|