@bosun-sh/logbook 1.0.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.
- package/LICENSE +21 -0
- package/README.md +361 -0
- package/hooks/need-info-notify/config.yml +3 -0
- package/hooks/need-info-notify/script.ts +69 -0
- package/hooks/review-spawn/config.yml +3 -0
- package/hooks/review-spawn/script.ts +96 -0
- package/package.json +47 -0
- package/src/cli/init.ts +90 -0
- package/src/domain/fibonacci.ts +39 -0
- package/src/domain/kTokens.ts +65 -0
- package/src/domain/status-machine.ts +49 -0
- package/src/domain/types.ts +66 -0
- package/src/hook/hook-executor.ts +70 -0
- package/src/hook/ports.ts +16 -0
- package/src/infra/hook-config-loader.ts +111 -0
- package/src/infra/jsonl-task-repository.ts +157 -0
- package/src/infra/logger.ts +40 -0
- package/src/infra/pid-session-registry.ts +67 -0
- package/src/mcp/error-codes.ts +213 -0
- package/src/mcp/server.ts +413 -0
- package/src/mcp/session.ts +1 -0
- package/src/mcp/tool-create-task.ts +28 -0
- package/src/mcp/tool-current-task.ts +19 -0
- package/src/mcp/tool-edit-task.ts +40 -0
- package/src/mcp/tool-list-tasks.ts +34 -0
- package/src/mcp/tool-update-task.ts +55 -0
- package/src/task/create-task.ts +67 -0
- package/src/task/current-task.ts +111 -0
- package/src/task/edit-task.ts +59 -0
- package/src/task/list-tasks.ts +35 -0
- package/src/task/ports.ts +15 -0
- package/src/task/session-registry.ts +9 -0
- package/src/task/update-task.ts +160 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Effect } from "effect"
|
|
2
|
+
import type { TaskError } from "./types.js"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Validates that n is a positive Fibonacci number.
|
|
6
|
+
* Returns Effect.succeed(void) when valid,
|
|
7
|
+
* Effect.fail({ _tag: 'validation_error', message: 'estimation must be a Fibonacci number' }) otherwise.
|
|
8
|
+
*
|
|
9
|
+
* Algorithm: n is Fibonacci iff one of 5n²+4 or 5n²-4 is a perfect square.
|
|
10
|
+
*/
|
|
11
|
+
export const validateFibonacci = (n: number): Effect.Effect<void, TaskError> => {
|
|
12
|
+
// Must be a positive integer
|
|
13
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
14
|
+
return Effect.fail({
|
|
15
|
+
_tag: "validation_error",
|
|
16
|
+
message: "estimation must be a Fibonacci number",
|
|
17
|
+
})
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Check if a number is a perfect square
|
|
21
|
+
const isPerfectSquare = (num: number): boolean => {
|
|
22
|
+
if (num < 0) return false
|
|
23
|
+
const sqrt = Math.sqrt(num)
|
|
24
|
+
return sqrt === Math.floor(sqrt)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// n is Fibonacci iff 5n²+4 or 5n²-4 is a perfect square
|
|
28
|
+
const fiveSqPlusFour = 5 * n * n + 4
|
|
29
|
+
const fiveSqMinusFour = 5 * n * n - 4
|
|
30
|
+
|
|
31
|
+
if (isPerfectSquare(fiveSqPlusFour) || isPerfectSquare(fiveSqMinusFour)) {
|
|
32
|
+
return Effect.succeed(void 0)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return Effect.fail({
|
|
36
|
+
_tag: "validation_error",
|
|
37
|
+
message: "estimation must be a Fibonacci number",
|
|
38
|
+
})
|
|
39
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Effect } from "effect"
|
|
2
|
+
import type { TaskError } from "./types.js"
|
|
3
|
+
|
|
4
|
+
export interface KTokensConfig {
|
|
5
|
+
anchorPoint: number // Fibonacci number to anchor against
|
|
6
|
+
kTokensAtAnchor: number // how many kTokens map to anchorPoint
|
|
7
|
+
maxKTokens: number // cap (inclusive)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const defaultConfig: KTokensConfig = {
|
|
11
|
+
anchorPoint: 8,
|
|
12
|
+
kTokensAtAnchor: 20,
|
|
13
|
+
maxKTokens: 20,
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Fibonacci sequence for lookup
|
|
17
|
+
const FIBONACCI = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
|
|
18
|
+
|
|
19
|
+
export const estimateFromKTokens = (
|
|
20
|
+
kTokens: number,
|
|
21
|
+
config: KTokensConfig = defaultConfig
|
|
22
|
+
): Effect.Effect<number, TaskError> => {
|
|
23
|
+
// Fail if kTokens <= 0
|
|
24
|
+
if (kTokens <= 0) {
|
|
25
|
+
return Effect.fail({
|
|
26
|
+
_tag: "validation_error",
|
|
27
|
+
message: "predicted kilotokens must be positive",
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Fail if kTokens > config.maxKTokens
|
|
32
|
+
if (kTokens > config.maxKTokens) {
|
|
33
|
+
return Effect.fail({
|
|
34
|
+
_tag: "validation_error",
|
|
35
|
+
message: "predicted kilotokens exceed maximum allowed",
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Calculate ratio: kTokensAtAnchor / anchorPoint
|
|
40
|
+
const ratio = config.kTokensAtAnchor / config.anchorPoint
|
|
41
|
+
|
|
42
|
+
// Scale kTokens to estimate space
|
|
43
|
+
const scaled = kTokens / ratio
|
|
44
|
+
|
|
45
|
+
// Find nearest Fibonacci number, rounding UP on tie
|
|
46
|
+
let nearestFib: number = FIBONACCI[0] ?? 1
|
|
47
|
+
let minDistance = Math.abs(nearestFib - scaled)
|
|
48
|
+
|
|
49
|
+
for (const fib of FIBONACCI) {
|
|
50
|
+
const distance = Math.abs(fib - scaled)
|
|
51
|
+
|
|
52
|
+
// On exact match, return immediately
|
|
53
|
+
if (distance === 0) {
|
|
54
|
+
return Effect.succeed(fib)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// On tie, pick the larger value (UP)
|
|
58
|
+
if (distance < minDistance || (distance === minDistance && fib > nearestFib)) {
|
|
59
|
+
nearestFib = fib
|
|
60
|
+
minDistance = distance
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return Effect.succeed(nearestFib)
|
|
65
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Effect } from "effect"
|
|
2
|
+
import type { Status, TaskError } from "./types.js"
|
|
3
|
+
|
|
4
|
+
// Allowed state transitions: from → [to, to, ...]
|
|
5
|
+
export const allowedTransitions: Record<Status, Status[]> = {
|
|
6
|
+
backlog: ["todo"],
|
|
7
|
+
todo: ["backlog", "in_progress"],
|
|
8
|
+
in_progress: ["todo", "pending_review", "need_info", "blocked"],
|
|
9
|
+
blocked: ["in_progress"],
|
|
10
|
+
need_info: ["in_progress"],
|
|
11
|
+
pending_review: ["done", "in_progress"],
|
|
12
|
+
done: [],
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Guards a status transition, returning Effect.succeed(void) when allowed
|
|
17
|
+
* and Effect.fail({ _tag: 'transition_not_allowed', from, to }) otherwise.
|
|
18
|
+
* A same→same transition is always a no-op success.
|
|
19
|
+
* Review tasks (id starts with "review-") may go directly from in_progress to done.
|
|
20
|
+
*/
|
|
21
|
+
export const guardTransition = (
|
|
22
|
+
from: Status,
|
|
23
|
+
to: Status,
|
|
24
|
+
taskId?: string
|
|
25
|
+
): Effect.Effect<void, TaskError> => {
|
|
26
|
+
// Same→same is always a no-op success
|
|
27
|
+
if (from === to) {
|
|
28
|
+
return Effect.void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Check if transition is in the allowed map
|
|
32
|
+
const allowed = allowedTransitions[from]
|
|
33
|
+
if (allowed.includes(to)) {
|
|
34
|
+
return Effect.void
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Review tasks may skip pending_review and go directly to done
|
|
38
|
+
if (from === "in_progress" && to === "done" && taskId?.startsWith("review-")) {
|
|
39
|
+
return Effect.void
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Transition not allowed
|
|
43
|
+
return Effect.fail({
|
|
44
|
+
_tag: "transition_not_allowed",
|
|
45
|
+
from,
|
|
46
|
+
to,
|
|
47
|
+
taskId,
|
|
48
|
+
} as TaskError)
|
|
49
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { z } from "zod"
|
|
2
|
+
|
|
3
|
+
export const StatusSchema = z.enum([
|
|
4
|
+
"backlog",
|
|
5
|
+
"todo",
|
|
6
|
+
"need_info",
|
|
7
|
+
"blocked",
|
|
8
|
+
"in_progress",
|
|
9
|
+
"pending_review",
|
|
10
|
+
"done",
|
|
11
|
+
])
|
|
12
|
+
export type Status = z.infer<typeof StatusSchema>
|
|
13
|
+
|
|
14
|
+
export const CommentKindSchema = z.enum(["need_info", "regular"])
|
|
15
|
+
export type CommentKind = z.infer<typeof CommentKindSchema>
|
|
16
|
+
|
|
17
|
+
export const CommentSchema = z.object({
|
|
18
|
+
id: z.string().min(1),
|
|
19
|
+
timestamp: z.coerce.date(),
|
|
20
|
+
title: z.string().min(1),
|
|
21
|
+
content: z.string(),
|
|
22
|
+
reply: z.string(),
|
|
23
|
+
kind: CommentKindSchema,
|
|
24
|
+
})
|
|
25
|
+
export type Comment = z.infer<typeof CommentSchema>
|
|
26
|
+
|
|
27
|
+
export const AgentSchema = z.object({
|
|
28
|
+
id: z.string().min(1),
|
|
29
|
+
title: z.string().min(1),
|
|
30
|
+
description: z.string(),
|
|
31
|
+
})
|
|
32
|
+
export type Agent = z.infer<typeof AgentSchema>
|
|
33
|
+
|
|
34
|
+
export const TaskSchema = z.object({
|
|
35
|
+
project: z.string().min(1),
|
|
36
|
+
milestone: z.string().min(1),
|
|
37
|
+
id: z.string().min(1),
|
|
38
|
+
title: z.string().min(1),
|
|
39
|
+
definition_of_done: z.string().min(1),
|
|
40
|
+
description: z.string().min(1),
|
|
41
|
+
estimation: z.number().int().positive(),
|
|
42
|
+
comments: z.array(CommentSchema),
|
|
43
|
+
assignee: AgentSchema.optional(),
|
|
44
|
+
status: StatusSchema,
|
|
45
|
+
in_progress_since: z.coerce.date().optional(),
|
|
46
|
+
priority: z.number().int().min(0).default(0),
|
|
47
|
+
})
|
|
48
|
+
export type Task = z.infer<typeof TaskSchema>
|
|
49
|
+
|
|
50
|
+
// Error tags match Gherkin feature file error names
|
|
51
|
+
export type TaskError =
|
|
52
|
+
| { readonly _tag: "not_found"; readonly taskId: string }
|
|
53
|
+
| {
|
|
54
|
+
readonly _tag: "transition_not_allowed"
|
|
55
|
+
readonly from: Status
|
|
56
|
+
readonly to: Status
|
|
57
|
+
readonly taskId?: string
|
|
58
|
+
}
|
|
59
|
+
| {
|
|
60
|
+
readonly _tag: "validation_error"
|
|
61
|
+
readonly message: string
|
|
62
|
+
readonly context?: Record<string, unknown>
|
|
63
|
+
}
|
|
64
|
+
| { readonly _tag: "missing_comment"; readonly from?: Status; readonly to?: Status }
|
|
65
|
+
| { readonly _tag: "conflict"; readonly taskId: string }
|
|
66
|
+
| { readonly _tag: "no_current_task" }
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { Effect } from "effect"
|
|
2
|
+
import type { HookEvent } from "./ports.js"
|
|
3
|
+
|
|
4
|
+
export interface HookConfig {
|
|
5
|
+
event: string
|
|
6
|
+
condition?: string
|
|
7
|
+
timeout_ms?: number
|
|
8
|
+
script: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const HOOK_EVENT_NAME = "task.status_changed"
|
|
12
|
+
const DEFAULT_TIMEOUT_MS = 5000
|
|
13
|
+
|
|
14
|
+
const evaluateCondition = (condition: string, event: HookEvent): boolean => {
|
|
15
|
+
try {
|
|
16
|
+
const fn = new Function(
|
|
17
|
+
"new_status",
|
|
18
|
+
"old_status",
|
|
19
|
+
"task_id",
|
|
20
|
+
"session_id",
|
|
21
|
+
`return (${condition})`
|
|
22
|
+
)
|
|
23
|
+
return Boolean(fn(event.new_status, event.old_status, event.task_id, event.session_id))
|
|
24
|
+
} catch {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const runScript = (config: HookConfig, event: HookEvent): Promise<void> =>
|
|
30
|
+
new Promise((resolve) => {
|
|
31
|
+
const timeoutMs = config.timeout_ms ?? DEFAULT_TIMEOUT_MS
|
|
32
|
+
|
|
33
|
+
const cmd = config.script.endsWith(".ts") ? ["bun", config.script] : ["sh", "-c", config.script]
|
|
34
|
+
|
|
35
|
+
const child = Bun.spawn(cmd, {
|
|
36
|
+
env: {
|
|
37
|
+
...process.env,
|
|
38
|
+
LOGBOOK_TASK_ID: event.task_id,
|
|
39
|
+
LOGBOOK_OLD_STATUS: event.old_status,
|
|
40
|
+
LOGBOOK_NEW_STATUS: event.new_status,
|
|
41
|
+
LOGBOOK_SESSION_ID: event.session_id,
|
|
42
|
+
},
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
const timer = setTimeout(() => {
|
|
46
|
+
child.kill()
|
|
47
|
+
}, timeoutMs)
|
|
48
|
+
|
|
49
|
+
void (async () => {
|
|
50
|
+
try {
|
|
51
|
+
await child.exited
|
|
52
|
+
} finally {
|
|
53
|
+
clearTimeout(timer)
|
|
54
|
+
resolve()
|
|
55
|
+
}
|
|
56
|
+
})()
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
export const executeHooks = (
|
|
60
|
+
event: HookEvent,
|
|
61
|
+
configs: readonly HookConfig[]
|
|
62
|
+
): Effect.Effect<void, never> =>
|
|
63
|
+
Effect.promise(async () => {
|
|
64
|
+
await Promise.all(
|
|
65
|
+
configs
|
|
66
|
+
.filter((c) => c.event === HOOK_EVENT_NAME)
|
|
67
|
+
.filter((c) => !c.condition || evaluateCondition(c.condition, event))
|
|
68
|
+
.map((c) => runScript(c, event))
|
|
69
|
+
)
|
|
70
|
+
})
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Context, type Effect } from "effect"
|
|
2
|
+
import type { Comment, Status } from "../domain/types.js"
|
|
3
|
+
|
|
4
|
+
export interface HookEvent {
|
|
5
|
+
task_id: string
|
|
6
|
+
old_status: Status
|
|
7
|
+
new_status: Status
|
|
8
|
+
comment: Comment | null
|
|
9
|
+
session_id: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface HookRunner {
|
|
13
|
+
run(event: HookEvent): Effect.Effect<void, never>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const HookRunner = Context.GenericTag<HookRunner>("HookRunner")
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { z } from "zod"
|
|
4
|
+
import type { HookConfig } from "../hook/hook-executor.js"
|
|
5
|
+
import { logger } from "./logger.js"
|
|
6
|
+
|
|
7
|
+
const KNOWN_KEYS = ["event", "condition", "timeout_ms"] as const
|
|
8
|
+
|
|
9
|
+
const HookConfigFileSchema = z.object({
|
|
10
|
+
event: z.string(),
|
|
11
|
+
condition: z.string().optional(),
|
|
12
|
+
timeout_ms: z.number().optional(),
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Parses a strict subset of YAML: flat key-value pairs, no nesting.
|
|
17
|
+
* Supports quoted strings and bare integers.
|
|
18
|
+
*/
|
|
19
|
+
const parseSimpleYaml = (content: string): Record<string, unknown> => {
|
|
20
|
+
const result: Record<string, unknown> = {}
|
|
21
|
+
for (const line of content.split("\n")) {
|
|
22
|
+
const trimmed = line.trim()
|
|
23
|
+
if (!trimmed || trimmed.startsWith("#")) continue
|
|
24
|
+
const colonIdx = trimmed.indexOf(":")
|
|
25
|
+
if (colonIdx === -1) continue
|
|
26
|
+
const key = trimmed.slice(0, colonIdx).trim()
|
|
27
|
+
let value: unknown = trimmed.slice(colonIdx + 1).trim()
|
|
28
|
+
if (typeof value === "string" && value.startsWith('"') && value.endsWith('"')) {
|
|
29
|
+
value = value.slice(1, -1)
|
|
30
|
+
} else if (typeof value === "string" && value.startsWith("'") && value.endsWith("'")) {
|
|
31
|
+
value = value.slice(1, -1)
|
|
32
|
+
} else if (typeof value === "string" && /^\d+$/.test(value)) {
|
|
33
|
+
value = parseInt(value, 10)
|
|
34
|
+
}
|
|
35
|
+
result[key] = value
|
|
36
|
+
}
|
|
37
|
+
return result
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const SCRIPT_CANDIDATES = ["script.ts", "script.sh"] as const
|
|
41
|
+
|
|
42
|
+
const findScript = async (hookDir: string): Promise<string | undefined> => {
|
|
43
|
+
for (const name of SCRIPT_CANDIDATES) {
|
|
44
|
+
const candidate = join(hookDir, name)
|
|
45
|
+
try {
|
|
46
|
+
await readFile(candidate)
|
|
47
|
+
return candidate
|
|
48
|
+
} catch {
|
|
49
|
+
// try next candidate
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return undefined
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const loadHookConfigs = async (hooksDir: string): Promise<HookConfig[]> => {
|
|
56
|
+
let entries: string[]
|
|
57
|
+
try {
|
|
58
|
+
entries = await readdir(hooksDir)
|
|
59
|
+
} catch (e: unknown) {
|
|
60
|
+
if (isEnoent(e)) return []
|
|
61
|
+
throw e
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const configs: HookConfig[] = []
|
|
65
|
+
|
|
66
|
+
for (const entry of entries) {
|
|
67
|
+
const hookDir = join(hooksDir, entry)
|
|
68
|
+
try {
|
|
69
|
+
const configPath = join(hookDir, "config.yml")
|
|
70
|
+
const raw = await readFile(configPath, "utf8")
|
|
71
|
+
const parsed = parseSimpleYaml(raw)
|
|
72
|
+
const validated = HookConfigFileSchema.safeParse(parsed)
|
|
73
|
+
if (!validated.success) {
|
|
74
|
+
logger.warn("invalid hook config", { path: configPath, error: validated.error.message })
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
// Warn on unrecognized keys
|
|
78
|
+
const parsedKeys = Object.keys(parsed)
|
|
79
|
+
for (const key of parsedKeys) {
|
|
80
|
+
if (!(KNOWN_KEYS as readonly string[]).includes(key)) {
|
|
81
|
+
const validKeysStr = KNOWN_KEYS.join(", ")
|
|
82
|
+
logger.warn("unrecognized key in hook config", {
|
|
83
|
+
hook: entry,
|
|
84
|
+
key,
|
|
85
|
+
validKeys: validKeysStr,
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const script = await findScript(hookDir)
|
|
90
|
+
if (script === undefined) {
|
|
91
|
+
logger.warn("no script found in hook dir, skipping", { path: hookDir })
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
const { event, condition, timeout_ms } = validated.data
|
|
95
|
+
const config: HookConfig = {
|
|
96
|
+
event,
|
|
97
|
+
script,
|
|
98
|
+
...(condition !== undefined ? { condition } : {}),
|
|
99
|
+
...(timeout_ms !== undefined ? { timeout_ms } : {}),
|
|
100
|
+
}
|
|
101
|
+
configs.push(config)
|
|
102
|
+
} catch (e: unknown) {
|
|
103
|
+
logger.warn("failed to load hook", { hook: entry, error: String(e) })
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return configs
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const isEnoent = (e: unknown): boolean =>
|
|
111
|
+
typeof e === "object" && e !== null && (e as { code?: unknown }).code === "ENOENT"
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { appendFile, readFile, rename, writeFile } from "node:fs/promises"
|
|
2
|
+
import { Effect } from "effect"
|
|
3
|
+
import type { Status, Task, TaskError } from "../domain/types.js"
|
|
4
|
+
import { TaskSchema } from "../domain/types.js"
|
|
5
|
+
import type { TaskRepository } from "../task/ports.js"
|
|
6
|
+
import { logger } from "./logger.js"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* JSONL-backed TaskRepository.
|
|
10
|
+
* Each line is a JSON-serialized Task.
|
|
11
|
+
* Reads scan the full file; writes are append-only for save, full-rewrite for update.
|
|
12
|
+
*/
|
|
13
|
+
export class JsonlTaskRepository implements TaskRepository {
|
|
14
|
+
constructor(private readonly filePath: string) {}
|
|
15
|
+
|
|
16
|
+
save(task: Task): Effect.Effect<void, TaskError> {
|
|
17
|
+
return Effect.tryPromise<void, TaskError>({
|
|
18
|
+
try: async () => {
|
|
19
|
+
const content = await readFile(this.filePath, "utf8").catch((e: unknown) => {
|
|
20
|
+
if (isEnoent(e)) return ""
|
|
21
|
+
throw e
|
|
22
|
+
})
|
|
23
|
+
const lines = splitLines(content)
|
|
24
|
+
const conflict = lines.some((line) => {
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(line) as unknown
|
|
27
|
+
return (parsed as { id?: unknown }).id === task.id
|
|
28
|
+
} catch {
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
if (conflict) {
|
|
33
|
+
throw mkTagged<TaskError>({ _tag: "conflict", taskId: task.id })
|
|
34
|
+
}
|
|
35
|
+
await appendFile(this.filePath, `${JSON.stringify(task)}\n`, "utf8")
|
|
36
|
+
},
|
|
37
|
+
catch: (e) => asTaskError(e, task.id),
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
update(task: Task): Effect.Effect<void, TaskError> {
|
|
42
|
+
return Effect.tryPromise<void, TaskError>({
|
|
43
|
+
try: async () => {
|
|
44
|
+
const content = await readFile(this.filePath, "utf8").catch((e: unknown) => {
|
|
45
|
+
if (isEnoent(e)) return ""
|
|
46
|
+
throw e
|
|
47
|
+
})
|
|
48
|
+
const lines = splitLines(content)
|
|
49
|
+
let found = false
|
|
50
|
+
const updated = lines.map((line) => {
|
|
51
|
+
try {
|
|
52
|
+
const parsed = JSON.parse(line) as unknown
|
|
53
|
+
if ((parsed as { id?: unknown }).id === task.id) {
|
|
54
|
+
found = true
|
|
55
|
+
return JSON.stringify(task)
|
|
56
|
+
}
|
|
57
|
+
} catch {
|
|
58
|
+
// keep malformed lines as-is
|
|
59
|
+
}
|
|
60
|
+
return line
|
|
61
|
+
})
|
|
62
|
+
if (!found) {
|
|
63
|
+
throw mkTagged<TaskError>({ _tag: "not_found", taskId: task.id })
|
|
64
|
+
}
|
|
65
|
+
const tmpPath = `${this.filePath}.tmp`
|
|
66
|
+
await writeFile(tmpPath, `${updated.join("\n")}\n`, "utf8")
|
|
67
|
+
await rename(tmpPath, this.filePath)
|
|
68
|
+
},
|
|
69
|
+
catch: (e) => asTaskError(e, task.id),
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
findById(id: string): Effect.Effect<Task, TaskError> {
|
|
74
|
+
return Effect.tryPromise<Task, TaskError>({
|
|
75
|
+
try: async () => {
|
|
76
|
+
const content = await readFile(this.filePath, "utf8").catch((e: unknown) => {
|
|
77
|
+
if (isEnoent(e)) return ""
|
|
78
|
+
throw e
|
|
79
|
+
})
|
|
80
|
+
const lines = splitLines(content)
|
|
81
|
+
for (const line of lines) {
|
|
82
|
+
const result = parseLine(line)
|
|
83
|
+
if (result._tag === "error") {
|
|
84
|
+
logger.warn("skipping malformed JSONL line", { line, reason: result.reason })
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
if (result.task.id === id) return result.task
|
|
88
|
+
}
|
|
89
|
+
throw mkTagged<TaskError>({ _tag: "not_found", taskId: id })
|
|
90
|
+
},
|
|
91
|
+
catch: (e) => asTaskError(e, id),
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
findByStatus(status: Status | "*"): Effect.Effect<readonly Task[], TaskError> {
|
|
96
|
+
return Effect.tryPromise<readonly Task[], TaskError>({
|
|
97
|
+
try: async () => {
|
|
98
|
+
const content = await readFile(this.filePath, "utf8").catch((e: unknown) => {
|
|
99
|
+
if (isEnoent(e)) return ""
|
|
100
|
+
throw e
|
|
101
|
+
})
|
|
102
|
+
const lines = splitLines(content)
|
|
103
|
+
const tasks: Task[] = []
|
|
104
|
+
for (const line of lines) {
|
|
105
|
+
const result = parseLine(line)
|
|
106
|
+
if (result._tag === "error") {
|
|
107
|
+
throw mkTagged<TaskError>({ _tag: "validation_error", message: result.reason })
|
|
108
|
+
}
|
|
109
|
+
if (status === "*" || result.task.status === status) {
|
|
110
|
+
tasks.push(result.task)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return tasks
|
|
114
|
+
},
|
|
115
|
+
catch: (e) => asTaskError(e, ""),
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// Helpers (pure)
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
type ParseResult =
|
|
125
|
+
| { readonly _tag: "ok"; readonly task: Task }
|
|
126
|
+
| { readonly _tag: "error"; readonly reason: string }
|
|
127
|
+
|
|
128
|
+
const parseLine = (line: string): ParseResult => {
|
|
129
|
+
let raw: unknown
|
|
130
|
+
try {
|
|
131
|
+
raw = JSON.parse(line)
|
|
132
|
+
} catch (e) {
|
|
133
|
+
return { _tag: "error", reason: `invalid JSON: ${String(e)}` }
|
|
134
|
+
}
|
|
135
|
+
const result = TaskSchema.safeParse(raw)
|
|
136
|
+
if (!result.success) {
|
|
137
|
+
return { _tag: "error", reason: result.error.message }
|
|
138
|
+
}
|
|
139
|
+
return { _tag: "ok", task: result.data }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const splitLines = (content: string): readonly string[] =>
|
|
143
|
+
content.split("\n").filter((l) => l.trim() !== "")
|
|
144
|
+
|
|
145
|
+
const isEnoent = (e: unknown): boolean =>
|
|
146
|
+
typeof e === "object" && e !== null && (e as { code?: unknown }).code === "ENOENT"
|
|
147
|
+
|
|
148
|
+
/** Carries a typed TaskError through the tryPromise boundary. */
|
|
149
|
+
const mkTagged = <E>(value: E): E => value
|
|
150
|
+
|
|
151
|
+
const asTaskError = (e: unknown, _taskId: string): TaskError => {
|
|
152
|
+
if (isTaskError(e)) return e
|
|
153
|
+
return { _tag: "validation_error", message: String(e) } satisfies TaskError
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const isTaskError = (e: unknown): e is TaskError =>
|
|
157
|
+
typeof e === "object" && e !== null && typeof (e as { _tag?: unknown })._tag === "string"
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
type Level = "debug" | "info" | "warn" | "error"
|
|
2
|
+
type LogContext = Record<string, unknown>
|
|
3
|
+
|
|
4
|
+
interface Logger {
|
|
5
|
+
debug(msg: string, ctx?: LogContext): void
|
|
6
|
+
info(msg: string, ctx?: LogContext): void
|
|
7
|
+
warn(msg: string, ctx?: LogContext): void
|
|
8
|
+
error(msg: string, ctx?: LogContext): void
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const LEVEL_ORDER: readonly Level[] = ["debug", "info", "warn", "error"]
|
|
12
|
+
|
|
13
|
+
const levelIndex = (level: Level): number => LEVEL_ORDER.indexOf(level)
|
|
14
|
+
|
|
15
|
+
const makeLogger = (threshold: Level): Logger => {
|
|
16
|
+
const thresholdIdx = levelIndex(threshold)
|
|
17
|
+
|
|
18
|
+
const log = (level: Level, msg: string, ctx?: LogContext): void => {
|
|
19
|
+
if (levelIndex(level) < thresholdIdx) return
|
|
20
|
+
const entry = { level, ts: new Date().toISOString(), msg, ...ctx }
|
|
21
|
+
process.stderr.write(`${JSON.stringify(entry)}\n`)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
debug: (msg, ctx) => log("debug", msg, ctx),
|
|
26
|
+
info: (msg, ctx) => log("info", msg, ctx),
|
|
27
|
+
warn: (msg, ctx) => log("warn", msg, ctx),
|
|
28
|
+
error: (msg, ctx) => log("error", msg, ctx),
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const resolveThreshold = (): Level => {
|
|
33
|
+
const raw = process.env.LOGBOOK_LOG_LEVEL?.toLowerCase()
|
|
34
|
+
if (raw !== undefined && (LEVEL_ORDER as readonly string[]).includes(raw)) {
|
|
35
|
+
return raw as Level
|
|
36
|
+
}
|
|
37
|
+
return "warn"
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const logger: Logger = makeLogger(resolveThreshold())
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises"
|
|
2
|
+
import * as path from "node:path"
|
|
3
|
+
import { Effect } from "effect"
|
|
4
|
+
import type { SessionRegistry } from "../task/session-registry.js"
|
|
5
|
+
|
|
6
|
+
type SessionMap = Record<string, number>
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* PID-based session registry persisted to sessions.json alongside the tasks file.
|
|
10
|
+
*
|
|
11
|
+
* Liveness is checked via `process.kill(pid, 0)`: throws if the PID is dead, succeeds otherwise.
|
|
12
|
+
* A missing entry (clean deregistration) is also considered dead.
|
|
13
|
+
*/
|
|
14
|
+
export class PidSessionRegistry implements SessionRegistry {
|
|
15
|
+
private readonly sessionsFile: string
|
|
16
|
+
|
|
17
|
+
constructor(tasksFile: string) {
|
|
18
|
+
this.sessionsFile = path.join(path.dirname(tasksFile), "sessions.json")
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
isAlive(sessionId: string): Effect.Effect<boolean, never> {
|
|
22
|
+
return Effect.promise(async () => {
|
|
23
|
+
const map = await this.readMap()
|
|
24
|
+
const pid = map[sessionId]
|
|
25
|
+
if (pid === undefined) return false
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 0)
|
|
28
|
+
return true
|
|
29
|
+
} catch {
|
|
30
|
+
// Dead PID — lazily remove to keep the file tidy
|
|
31
|
+
await this.removeEntry(sessionId)
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
register(sessionId: string, pid: number): Effect.Effect<void, never> {
|
|
38
|
+
return Effect.promise(async () => {
|
|
39
|
+
const map = await this.readMap()
|
|
40
|
+
map[sessionId] = pid
|
|
41
|
+
await this.writeMap(map)
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
deregister(sessionId: string): Effect.Effect<void, never> {
|
|
46
|
+
return Effect.promise(() => this.removeEntry(sessionId))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private async readMap(): Promise<SessionMap> {
|
|
50
|
+
try {
|
|
51
|
+
const raw = await readFile(this.sessionsFile, "utf8")
|
|
52
|
+
return JSON.parse(raw) as SessionMap
|
|
53
|
+
} catch {
|
|
54
|
+
return {}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private async writeMap(map: SessionMap): Promise<void> {
|
|
59
|
+
await writeFile(this.sessionsFile, JSON.stringify(map), "utf8")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private async removeEntry(sessionId: string): Promise<void> {
|
|
63
|
+
const map = await this.readMap()
|
|
64
|
+
delete map[sessionId]
|
|
65
|
+
await this.writeMap(map)
|
|
66
|
+
}
|
|
67
|
+
}
|