@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.4
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/dist/agent/channel-runner.d.ts +4 -18
- package/dist/agent/channel-runner.js +25 -120
- package/dist/agent/context-budget.js +1 -1
- package/dist/agent/job-manager.d.ts +20 -17
- package/dist/agent/job-manager.js +95 -70
- package/dist/agent/prompt/builder.d.ts +1 -1
- package/dist/agent/prompt/builder.js +2 -18
- package/dist/agent/prompt/manifest.d.ts +0 -1
- package/dist/agent/prompt/manifest.js +2 -2
- package/dist/agent/prompt/sections.js +3 -12
- package/dist/agent/prompt/types.d.ts +2 -18
- package/dist/agent/prompt/types.js +1 -1
- package/dist/agent/runner-factory.d.ts +4 -0
- package/dist/agent/session-adapter.d.ts +19 -0
- package/dist/agent/session-adapter.js +77 -0
- package/dist/app-services.d.ts +18 -0
- package/dist/app-services.js +43 -0
- package/dist/{runtime → events}/events.d.ts +1 -1
- package/dist/executor.d.ts +5 -1
- package/dist/executor.js +35 -5
- package/dist/file-store.d.ts +4 -1
- package/dist/file-store.js +5 -0
- package/dist/memory/journal.d.ts +13 -0
- package/dist/memory/journal.js +47 -4
- package/dist/memory/maintenance-gates.d.ts +0 -3
- package/dist/memory/maintenance-gates.js +2 -2
- package/dist/memory/maintenance-migration.d.ts +5 -0
- package/dist/memory/maintenance-migration.js +91 -0
- package/dist/memory/maintenance-state.js +5 -44
- package/dist/memory/migrate.js +1 -1
- package/dist/memory/reflect-job.d.ts +1 -9
- package/dist/memory/reflect-job.js +1 -3
- package/dist/memory/reflect.js +1 -1
- package/dist/memory/search.js +13 -6
- package/dist/memory/session-corpus.d.ts +11 -0
- package/dist/memory/session-corpus.js +16 -5
- package/dist/memory/session-search.d.ts +3 -0
- package/dist/memory/session-search.js +45 -8
- package/dist/memory/store.d.ts +9 -0
- package/dist/memory/store.js +26 -3
- package/dist/models/auth-cli.js +1 -1
- package/dist/playbooks/agent-delegation.md +35 -76
- package/dist/playbooks/background-jobs.md +14 -16
- package/dist/playbooks/event-scheduling.md +20 -25
- package/dist/playbooks/memory-and-learning.md +28 -61
- package/dist/playbooks/outbound-media.md +10 -12
- package/dist/playbooks/runtime-orientation.md +34 -53
- package/dist/playbooks/task-loop.md +49 -69
- package/dist/runtime/bootstrap.d.ts +5 -15
- package/dist/runtime/bootstrap.js +57 -67
- package/dist/runtime/subagent-commands.d.ts +2 -1
- package/dist/runtime/subagent-commands.js +10 -12
- package/dist/runtime/task-wake.d.ts +4 -5
- package/dist/runtime/task-wake.js +2 -12
- package/dist/security/path-guard-filter.d.ts +22 -0
- package/dist/security/path-guard-filter.js +35 -0
- package/dist/security/types.d.ts +7 -0
- package/dist/security/types.js +16 -1
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +24 -1
- package/dist/shared/exact-keys.d.ts +13 -0
- package/dist/shared/exact-keys.js +1 -0
- package/dist/shared/format.d.ts +20 -0
- package/dist/shared/format.js +64 -0
- package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
- package/dist/shared/{fs-utils.js → os.js} +8 -0
- package/dist/subagents/discovery.d.ts +18 -6
- package/dist/subagents/discovery.js +12 -8
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +1 -2
- package/dist/subagents/external/settlement.js +10 -5
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/runs.d.ts +13 -12
- package/dist/subagents/runs.js +108 -89
- package/dist/subagents/tool.d.ts +13 -7
- package/dist/subagents/tool.js +21 -13
- package/dist/tasks/brief.d.ts +1 -1
- package/dist/tasks/brief.js +12 -2
- package/dist/tasks/log.d.ts +4 -0
- package/dist/tasks/log.js +13 -1
- package/dist/tools/bash.d.ts +13 -0
- package/dist/tools/bash.js +123 -20
- package/dist/tools/command-optimizer.js +1 -1
- package/dist/tools/config.d.ts +7 -0
- package/dist/tools/config.js +16 -1
- package/dist/tools/edit.js +36 -5
- package/dist/tools/event-manage.d.ts +26 -5
- package/dist/tools/event-manage.js +84 -36
- package/dist/tools/glob.js +57 -4
- package/dist/tools/grep.d.ts +2 -0
- package/dist/tools/grep.js +188 -15
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +4 -2
- package/dist/tools/job.js +17 -5
- package/dist/tools/memory-manage.js +80 -41
- package/dist/tools/read.js +43 -6
- package/dist/tools/registry.d.ts +9 -3
- package/dist/tools/registry.js +22 -57
- package/dist/tools/send-media.js +6 -4
- package/dist/tools/session-search.js +4 -1
- package/dist/tools/skill.d.ts +2 -0
- package/dist/tools/skill.js +13 -1
- package/dist/tools/subagent-manage.d.ts +2 -0
- package/dist/tools/subagent-manage.js +8 -8
- package/dist/tools/subagent-tool-names.d.ts +11 -0
- package/dist/tools/subagent-tool-names.js +19 -0
- package/dist/tools/task-manage/log-view.js +6 -3
- package/dist/tools/task-manage/schema.d.ts +6 -6
- package/dist/tools/task-manage/schema.js +5 -12
- package/dist/tools/task-manage/shared.js +20 -11
- package/dist/tools/task-manage/step-end.js +22 -5
- package/dist/tools/task-manage/types.d.ts +4 -0
- package/dist/tools/task-manage.js +9 -1
- package/dist/tools/web-cache.d.ts +11 -3
- package/dist/tools/web-cache.js +26 -8
- package/dist/tools/web-fetch.d.ts +1 -0
- package/dist/tools/web-fetch.js +68 -15
- package/dist/tools/write.js +3 -0
- package/dist/tui/app.js +22 -7
- package/dist/web/config.js +1 -1
- package/dist/web/fetch.d.ts +5 -0
- package/dist/web/fetch.js +36 -1
- package/examples/sub-agents/README.md +14 -4
- package/examples/sub-agents/builder-hard.md +12 -34
- package/examples/sub-agents/builder.md +11 -31
- package/examples/sub-agents/explorer.md +10 -16
- package/examples/sub-agents/git-committer.md +15 -20
- package/examples/sub-agents/planner.md +11 -21
- package/examples/sub-agents/reviewer.md +10 -31
- package/examples/sub-agents/verifier.md +12 -27
- package/examples/sub-agents/worker.md +11 -35
- package/package.json +8 -3
- package/dist/shared/duration.d.ts +0 -2
- package/dist/shared/duration.js +0 -7
- package/dist/shared/file-stamp.d.ts +0 -10
- package/dist/shared/file-stamp.js +0 -19
- package/dist/shared/numeric.d.ts +0 -7
- package/dist/shared/numeric.js +0 -19
- package/dist/shared/shell-escape.d.ts +0 -5
- package/dist/shared/shell-escape.js +0 -7
- package/dist/shared/token-estimate.d.ts +0 -1
- package/dist/shared/token-estimate.js +0 -19
- /package/dist/{runtime → events}/event-commands.d.ts +0 -0
- /package/dist/{runtime → events}/event-commands.js +0 -0
- /package/dist/{runtime → events}/event-validation.d.ts +0 -0
- /package/dist/{runtime → events}/event-validation.js +0 -0
- /package/dist/{runtime → events}/events.js +0 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import * as log from "./log.js";
|
|
2
|
+
import { DEFAULT_BOOTSTRAP_PATHS } from "./runtime/app-home.js";
|
|
3
|
+
import { installLlmProxy } from "./runtime/proxy.js";
|
|
4
|
+
import { loadSecurityConfigWithDiagnostics } from "./security/config.js";
|
|
5
|
+
import { PipiclawSettingsManager } from "./settings.js";
|
|
6
|
+
import { formatConfigDiagnostic } from "./shared/config-diagnostic.js";
|
|
7
|
+
import { loadToolsConfigWithDiagnostics } from "./tools/config.js";
|
|
8
|
+
/**
|
|
9
|
+
* Transport-neutral app services shared by the DingTalk runtime, the terminal TUI, and the
|
|
10
|
+
* `pipiclaw auth` CLI: loads settings (surfacing load errors) and reports tool/security config
|
|
11
|
+
* diagnostics. Does NOT touch DingTalk config, so non-DingTalk entrypoints can call it without
|
|
12
|
+
* any DingTalk credentials.
|
|
13
|
+
*
|
|
14
|
+
* Lives at the package root rather than in `runtime/` on purpose: `models/auth-cli.ts` needs it
|
|
15
|
+
* before a runner or channel exists, and `runtime/bootstrap.ts` separately depends on `models/`
|
|
16
|
+
* (for the default model reference) — parking this function inside `bootstrap.ts` made `models`
|
|
17
|
+
* and `runtime` depend on each other. Everything this function touches (`settings.ts`,
|
|
18
|
+
* `tools/config.ts`, `security/config.ts`, `runtime/app-home.ts`, `runtime/proxy.ts`) has no
|
|
19
|
+
* import back to `models/`, so this file doesn't reintroduce the cycle it was extracted to break.
|
|
20
|
+
*/
|
|
21
|
+
export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
|
|
22
|
+
// Shared by the DingTalk daemon, the TUI, and the auth CLI (all call prepareAppServices), so
|
|
23
|
+
// this covers every entrypoint that talks to an LLM provider.
|
|
24
|
+
installLlmProxy();
|
|
25
|
+
const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
|
|
26
|
+
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
27
|
+
log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
|
|
28
|
+
}
|
|
29
|
+
// Errors already went out above with a richer message; this pass exists for the
|
|
30
|
+
// warnings, chiefly retired settings keys (spec 035 D3).
|
|
31
|
+
for (const diagnostic of settingsManager.getDiagnostics()) {
|
|
32
|
+
if (diagnostic.severity === "error")
|
|
33
|
+
continue;
|
|
34
|
+
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
35
|
+
}
|
|
36
|
+
for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
37
|
+
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
38
|
+
}
|
|
39
|
+
for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
40
|
+
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
41
|
+
}
|
|
42
|
+
return { settingsManager };
|
|
43
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
2
2
|
import type { Executor } from "../executor.js";
|
|
3
|
+
import type { DingTalkBot } from "../runtime/dingtalk.js";
|
|
3
4
|
import type { SecurityConfig } from "../security/types.js";
|
|
4
|
-
import type { DingTalkBot } from "./dingtalk.js";
|
|
5
5
|
export interface EventAction {
|
|
6
6
|
type: "bash";
|
|
7
7
|
command: string;
|
package/dist/executor.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** True when the executor found a real `bash`; `bash.ts` uses this to keep its description honest. */
|
|
2
|
+
export declare const EXECUTOR_SHELL_IS_BASH: boolean;
|
|
1
3
|
/**
|
|
2
4
|
* Create an executor that runs commands on the host machine.
|
|
3
5
|
*/
|
|
@@ -14,7 +16,9 @@ export declare class CommandTerminatedError extends Error {
|
|
|
14
16
|
readonly stderr: string;
|
|
15
17
|
readonly reason: "timeout" | "aborted";
|
|
16
18
|
readonly timeoutSeconds?: number;
|
|
17
|
-
|
|
19
|
+
/** True when the in-memory `stdout`/`stderr` here is only the head of a larger stream (D6.2). */
|
|
20
|
+
readonly captureTruncated: boolean;
|
|
21
|
+
constructor(reason: "timeout" | "aborted", stdout: string, stderr: string, timeoutSeconds?: number, captureTruncated?: boolean);
|
|
18
22
|
}
|
|
19
23
|
export interface Executor {
|
|
20
24
|
/**
|
package/dist/executor.js
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
|
-
import { createWriteStream } from "node:fs";
|
|
1
|
+
import { createWriteStream, existsSync } from "node:fs";
|
|
2
|
+
import { join as joinPath, delimiter as PATH_DELIMITER } from "node:path";
|
|
2
3
|
import { spawn } from "child_process";
|
|
4
|
+
import { logWarning } from "./log.js";
|
|
5
|
+
/**
|
|
6
|
+
* The `bash` tool's schema says "Bash command" and models write bash-only syntax (`[[ ]]`, arrays,
|
|
7
|
+
* `set -o pipefail`, process substitution). `/bin/sh` is `dash` on many hosts, so those fail with a
|
|
8
|
+
* confusing error on the model's first try. Resolve a real `bash` once at load and run commands
|
|
9
|
+
* through it; only fall back to `/bin/sh` when no `bash` exists, and say so. POSIX `shellEscape`
|
|
10
|
+
* quoting is still correct for bash, and the command guard inspects the command text either way.
|
|
11
|
+
*/
|
|
12
|
+
function resolveShell() {
|
|
13
|
+
const candidates = ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"];
|
|
14
|
+
for (const dir of (process.env.PATH ?? "").split(PATH_DELIMITER)) {
|
|
15
|
+
if (dir)
|
|
16
|
+
candidates.push(joinPath(dir, "bash"));
|
|
17
|
+
}
|
|
18
|
+
for (const candidate of candidates) {
|
|
19
|
+
if (existsSync(candidate)) {
|
|
20
|
+
return { path: candidate, isBash: true };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return { path: "/bin/sh", isBash: false };
|
|
24
|
+
}
|
|
25
|
+
const RESOLVED_SHELL = resolveShell();
|
|
26
|
+
if (!RESOLVED_SHELL.isBash) {
|
|
27
|
+
logWarning("executor: no `bash` binary found on this host; the bash tool is running commands via POSIX /bin/sh");
|
|
28
|
+
}
|
|
29
|
+
/** True when the executor found a real `bash`; `bash.ts` uses this to keep its description honest. */
|
|
30
|
+
export const EXECUTOR_SHELL_IS_BASH = RESOLVED_SHELL.isBash;
|
|
3
31
|
/**
|
|
4
32
|
* Default in-memory capture cap for a command's stdout/stderr, in bytes (spec 044, D6.1/D6.2).
|
|
5
33
|
* This is `Executor`'s own bound for *command output* -- file content never goes through it (see
|
|
@@ -21,13 +49,14 @@ export function createExecutor() {
|
|
|
21
49
|
* tail instead of losing the partial output outright.
|
|
22
50
|
*/
|
|
23
51
|
export class CommandTerminatedError extends Error {
|
|
24
|
-
constructor(reason, stdout, stderr, timeoutSeconds) {
|
|
52
|
+
constructor(reason, stdout, stderr, timeoutSeconds, captureTruncated = false) {
|
|
25
53
|
super(reason === "timeout" ? `Command timed out after ${timeoutSeconds} seconds` : "Command aborted");
|
|
26
54
|
this.name = "CommandTerminatedError";
|
|
27
55
|
this.reason = reason;
|
|
28
56
|
this.stdout = stdout;
|
|
29
57
|
this.stderr = stderr;
|
|
30
58
|
this.timeoutSeconds = timeoutSeconds;
|
|
59
|
+
this.captureTruncated = captureTruncated;
|
|
31
60
|
}
|
|
32
61
|
}
|
|
33
62
|
/** Accumulates raw chunks up to a byte cap without re-copying already-capped data on every event. */
|
|
@@ -70,7 +99,7 @@ class HostExecutor {
|
|
|
70
99
|
return new Promise((resolve, reject) => {
|
|
71
100
|
const child = (() => {
|
|
72
101
|
try {
|
|
73
|
-
return spawn(
|
|
102
|
+
return spawn(RESOLVED_SHELL.path, ["-c", command], {
|
|
74
103
|
detached: true,
|
|
75
104
|
stdio: ["pipe", "pipe", "pipe"],
|
|
76
105
|
...(options?.cwd ? { cwd: options.cwd } : {}),
|
|
@@ -179,12 +208,13 @@ class HostExecutor {
|
|
|
179
208
|
child.on("close", (code) => {
|
|
180
209
|
const stdout = stdoutAcc.toText();
|
|
181
210
|
const stderr = stderrAcc.toText();
|
|
211
|
+
const captureTruncated = stdoutAcc.truncated || stderrAcc.truncated;
|
|
182
212
|
if (options?.signal?.aborted) {
|
|
183
|
-
rejectOnce(new CommandTerminatedError("aborted", stdout, stderr));
|
|
213
|
+
rejectOnce(new CommandTerminatedError("aborted", stdout, stderr, undefined, captureTruncated));
|
|
184
214
|
return;
|
|
185
215
|
}
|
|
186
216
|
if (timedOut) {
|
|
187
|
-
rejectOnce(new CommandTerminatedError("timeout", stdout, stderr, options?.timeout));
|
|
217
|
+
rejectOnce(new CommandTerminatedError("timeout", stdout, stderr, options?.timeout, captureTruncated));
|
|
188
218
|
return;
|
|
189
219
|
}
|
|
190
220
|
resolveOnce({
|
package/dist/file-store.d.ts
CHANGED
|
@@ -81,9 +81,12 @@ export interface FileStore {
|
|
|
81
81
|
writeAtomic(path: string, data: Buffer | string, opts?: WriteAtomicOptions): Promise<void>;
|
|
82
82
|
/** Streaming atomic replace: `produce` writes to a temp file; on success it is renamed over `path`. */
|
|
83
83
|
replaceViaTemp(path: string, produce: (out: Writable) => Promise<void>, opts?: ReplaceViaTempOptions): Promise<void>;
|
|
84
|
-
/** Depth-bounded directory listing, replacing the `find -maxdepth` shell-out.
|
|
84
|
+
/** Depth-bounded directory listing, replacing the `find -maxdepth` shell-out. `maxEntries` caps
|
|
85
|
+
* the total collected so a directory with tens of thousands of children cannot be materialized
|
|
86
|
+
* whole before the caller truncates it. */
|
|
85
87
|
listDirectory(path: string, opts: {
|
|
86
88
|
maxDepth: number;
|
|
89
|
+
maxEntries?: number;
|
|
87
90
|
}): Promise<DirectoryEntry[]>;
|
|
88
91
|
/**
|
|
89
92
|
* Unbounded-depth file discovery for `glob`, replacing the `find` shell-out. Directories are
|
package/dist/file-store.js
CHANGED
|
@@ -131,9 +131,14 @@ class HostFileStore {
|
|
|
131
131
|
}
|
|
132
132
|
async listDirectory(path, opts) {
|
|
133
133
|
const results = [];
|
|
134
|
+
const cap = opts.maxEntries ?? Number.POSITIVE_INFINITY;
|
|
134
135
|
const walk = async (currentDir, relPrefix, depth) => {
|
|
136
|
+
if (results.length >= cap)
|
|
137
|
+
return;
|
|
135
138
|
const entries = await readdir(currentDir, { withFileTypes: true });
|
|
136
139
|
for (const entry of entries) {
|
|
140
|
+
if (results.length >= cap)
|
|
141
|
+
return;
|
|
137
142
|
const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
|
|
138
143
|
const isDirectory = entry.isDirectory();
|
|
139
144
|
results.push({ name: entry.name, relativePath, isDirectory });
|
package/dist/memory/journal.d.ts
CHANGED
|
@@ -7,6 +7,19 @@ export declare function getJournalDir(channelDir: string): string;
|
|
|
7
7
|
export declare function getJournalPath(channelDir: string, date: string): string;
|
|
8
8
|
export declare function readJournalDay(channelDir: string, date?: string): Promise<string>;
|
|
9
9
|
export declare function listJournalDates(channelDir: string): Promise<string[]>;
|
|
10
|
+
/** Search stays bounded even after years of journals, or one unusually busy day. */
|
|
11
|
+
export declare const JOURNAL_SEARCH_MAX_DAYS = 30;
|
|
12
|
+
export declare const JOURNAL_SEARCH_DAY_BYTES: number;
|
|
13
|
+
export interface JournalSearchWindow {
|
|
14
|
+
days: Array<{
|
|
15
|
+
date: string;
|
|
16
|
+
content: string;
|
|
17
|
+
}>;
|
|
18
|
+
omittedDays: number;
|
|
19
|
+
truncatedDates: string[];
|
|
20
|
+
}
|
|
21
|
+
/** Newest day files first; retain only whole lines when a day's older bytes are omitted. */
|
|
22
|
+
export declare function readJournalForSearch(channelDir: string): Promise<JournalSearchWindow>;
|
|
10
23
|
export interface JournalAppendResult {
|
|
11
24
|
appended: number;
|
|
12
25
|
skippedDuplicate: number;
|
package/dist/memory/journal.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { mkdir, readdir } from "node:fs/promises";
|
|
1
|
+
import { mkdir, open, readdir } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
4
|
-
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
5
4
|
import { localDayKey } from "../shared/local-time.js";
|
|
5
|
+
import { isNodeError, readOptionalTextFile } from "../shared/os.js";
|
|
6
6
|
/**
|
|
7
7
|
* Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
|
|
8
8
|
* `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
|
|
@@ -25,10 +25,53 @@ export async function listJournalDates(channelDir) {
|
|
|
25
25
|
.map((f) => f.slice(0, -3))
|
|
26
26
|
.sort();
|
|
27
27
|
}
|
|
28
|
-
catch {
|
|
29
|
-
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (isNodeError(error) && error.code === "ENOENT")
|
|
30
|
+
return [];
|
|
31
|
+
throw error;
|
|
30
32
|
}
|
|
31
33
|
}
|
|
34
|
+
/** Search stays bounded even after years of journals, or one unusually busy day. */
|
|
35
|
+
export const JOURNAL_SEARCH_MAX_DAYS = 30;
|
|
36
|
+
export const JOURNAL_SEARCH_DAY_BYTES = 64 * 1024;
|
|
37
|
+
/** Newest day files first; retain only whole lines when a day's older bytes are omitted. */
|
|
38
|
+
export async function readJournalForSearch(channelDir) {
|
|
39
|
+
const dates = (await listJournalDates(channelDir)).reverse();
|
|
40
|
+
const window = {
|
|
41
|
+
days: [],
|
|
42
|
+
omittedDays: Math.max(0, dates.length - JOURNAL_SEARCH_MAX_DAYS),
|
|
43
|
+
truncatedDates: [],
|
|
44
|
+
};
|
|
45
|
+
for (const date of dates.slice(0, JOURNAL_SEARCH_MAX_DAYS)) {
|
|
46
|
+
try {
|
|
47
|
+
const file = await open(getJournalPath(channelDir, date), "r");
|
|
48
|
+
try {
|
|
49
|
+
const stat = await file.stat();
|
|
50
|
+
if (!stat.isFile())
|
|
51
|
+
continue;
|
|
52
|
+
const start = Math.max(0, stat.size - JOURNAL_SEARCH_DAY_BYTES);
|
|
53
|
+
const buffer = Buffer.alloc(Math.min(stat.size, JOURNAL_SEARCH_DAY_BYTES));
|
|
54
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
|
|
55
|
+
let content = buffer.subarray(0, bytesRead).toString("utf-8");
|
|
56
|
+
if (start > 0) {
|
|
57
|
+
window.truncatedDates.push(date);
|
|
58
|
+
const newline = content.indexOf("\n");
|
|
59
|
+
content = newline < 0 ? "" : content.slice(newline + 1);
|
|
60
|
+
}
|
|
61
|
+
window.days.push({ date, content });
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await file.close();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
// A day can disappear between listing and opening; real IO failures must stay visible.
|
|
69
|
+
if (!isNodeError(error) || error.code !== "ENOENT")
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return window;
|
|
74
|
+
}
|
|
32
75
|
function normalizeLine(line) {
|
|
33
76
|
return line
|
|
34
77
|
.replace(/^[-*]\s*/, "")
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
|
|
2
2
|
import type { MemoryMaintenanceState } from "./maintenance-state.js";
|
|
3
|
-
/** Spec 050, D9: the three v1 jobs collapse to one. */
|
|
4
|
-
export type MaintenanceJobKind = "reflect";
|
|
5
3
|
export interface MaintenanceGateDecision {
|
|
6
4
|
allowed: boolean;
|
|
7
5
|
skipReason?: string;
|
|
8
|
-
jobKind: MaintenanceJobKind;
|
|
9
6
|
}
|
|
10
7
|
export interface ReflectMaterial {
|
|
11
8
|
hasNewEntry: boolean;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { parseLocalTime } from "../shared/local-time.js";
|
|
2
2
|
function deny(skipReason) {
|
|
3
|
-
return { allowed: false,
|
|
3
|
+
return { allowed: false, skipReason };
|
|
4
4
|
}
|
|
5
|
-
const allow = { allowed: true
|
|
5
|
+
const allow = { allowed: true };
|
|
6
6
|
function parseTime(value) {
|
|
7
7
|
if (!value) {
|
|
8
8
|
return null;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Upgrade before starting channel readers/writers. Kept through the 0.9.3 upgrade window.
|
|
2
|
+
* Canonical state wins over an obsolete nested copy; old files are removed only after a
|
|
3
|
+
* successful canonical write. Failed I/O aborts startup so no cursor is silently discarded.
|
|
4
|
+
*/
|
|
5
|
+
export declare function migrateMemoryMaintenanceStates(appHomeDir: string): Promise<void>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { readdir, readFile, rmdir, unlink } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { isChannelId } from "../channel/channel-paths.js";
|
|
4
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
6
|
+
import { getMemoryMaintenanceStateDir, getMemoryMaintenanceStatePath } from "./maintenance-state.js";
|
|
7
|
+
/** Upgrade before starting channel readers/writers. Kept through the 0.9.3 upgrade window.
|
|
8
|
+
* Canonical state wins over an obsolete nested copy; old files are removed only after a
|
|
9
|
+
* successful canonical write. Failed I/O aborts startup so no cursor is silently discarded.
|
|
10
|
+
*/
|
|
11
|
+
export async function migrateMemoryMaintenanceStates(appHomeDir) {
|
|
12
|
+
const root = getMemoryMaintenanceStateDir(appHomeDir);
|
|
13
|
+
async function files(dir) {
|
|
14
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
15
|
+
const result = [];
|
|
16
|
+
for (const entry of entries) {
|
|
17
|
+
const path = join(dir, entry.name);
|
|
18
|
+
if (entry.isDirectory())
|
|
19
|
+
result.push(...(await files(path)));
|
|
20
|
+
else if (entry.isFile() && entry.name.endsWith(".json"))
|
|
21
|
+
result.push(path);
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
let paths;
|
|
26
|
+
try {
|
|
27
|
+
paths = await files(root);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code === "ENOENT")
|
|
31
|
+
return;
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
for (const source of paths) {
|
|
35
|
+
let raw;
|
|
36
|
+
try {
|
|
37
|
+
raw = JSON.parse(await readFile(source, "utf8"));
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error instanceof SyntaxError)
|
|
41
|
+
continue; // normal reader diagnoses corrupt state
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
if (!isRecord(raw))
|
|
45
|
+
continue;
|
|
46
|
+
const channelId = typeof raw.channelId === "string" ? raw.channelId : basename(source, ".json");
|
|
47
|
+
if (!isChannelId(channelId))
|
|
48
|
+
continue;
|
|
49
|
+
const target = getMemoryMaintenanceStatePath(appHomeDir, channelId);
|
|
50
|
+
if (source !== target && source !== join(root, `${channelId}.json`))
|
|
51
|
+
continue;
|
|
52
|
+
let canonicalExists = false;
|
|
53
|
+
if (source !== target) {
|
|
54
|
+
try {
|
|
55
|
+
const existing = JSON.parse(await readFile(target, "utf8"));
|
|
56
|
+
if (!isRecord(existing) || (existing.channelId !== undefined && existing.channelId !== channelId)) {
|
|
57
|
+
throw new Error(`Invalid memory maintenance state at ${target}; repair it before restarting. Legacy state retained at ${source}.`);
|
|
58
|
+
}
|
|
59
|
+
canonicalExists = true;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code !== "ENOENT")
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const hasOldFields = "lastCheckpointAt" in raw || "lastCheckpointEntryId" in raw;
|
|
67
|
+
if (!canonicalExists && (source !== target || hasOldFields)) {
|
|
68
|
+
for (const [current, old] of [
|
|
69
|
+
["lastReflectAt", "lastCheckpointAt"],
|
|
70
|
+
["lastReflectedEntryId", "lastCheckpointEntryId"],
|
|
71
|
+
]) {
|
|
72
|
+
if (typeof raw[current] !== "string" || !raw[current].trim())
|
|
73
|
+
raw[current] = raw[old];
|
|
74
|
+
delete raw[old];
|
|
75
|
+
}
|
|
76
|
+
await writeFileAtomically(target, `${JSON.stringify({ ...raw, channelId }, null, 2)}\n`);
|
|
77
|
+
}
|
|
78
|
+
if (source !== target) {
|
|
79
|
+
await unlink(source);
|
|
80
|
+
// Empty legacy directories only; never remove unrelated state.
|
|
81
|
+
for (let dir = dirname(source); dir !== root; dir = dirname(dir)) {
|
|
82
|
+
try {
|
|
83
|
+
await rmdir(dir);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { readFile
|
|
2
|
-
import {
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
3
|
import { getChannelDirName } from "../channel/channel-paths.js";
|
|
4
4
|
import * as log from "../log.js";
|
|
5
5
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
@@ -20,19 +20,6 @@ export function getMemoryMaintenanceStateDir(appHomeDir) {
|
|
|
20
20
|
export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
|
|
21
21
|
return join(getMemoryMaintenanceStateDir(appHomeDir), `${getChannelDirName(channelId)}.json`);
|
|
22
22
|
}
|
|
23
|
-
/**
|
|
24
|
-
* Where a pre-escaping runtime put the same channel's state. Only differs for ids containing
|
|
25
|
-
* `/`, and only matters until the next write moves the state to its canonical path.
|
|
26
|
-
*
|
|
27
|
-
* RETIRE AT v0.9.3, same rationale as the header comment in `../runtime/task-migration.js`: by
|
|
28
|
-
* the stable cut, every still-running group channel with a `/` in its id will have had its state
|
|
29
|
-
* folded onto the canonical path at least once, so this fallback read finds nothing.
|
|
30
|
-
*/
|
|
31
|
-
function legacyStatePath(appHomeDir, channelId) {
|
|
32
|
-
return getChannelDirName(channelId) === channelId
|
|
33
|
-
? undefined
|
|
34
|
-
: join(getMemoryMaintenanceStateDir(appHomeDir), `${channelId}.json`);
|
|
35
|
-
}
|
|
36
23
|
function createDefaultState(channelId) {
|
|
37
24
|
return { channelId, dirty: false, failureBackoffUntil: null };
|
|
38
25
|
}
|
|
@@ -55,11 +42,8 @@ function normalizeState(channelId, value) {
|
|
|
55
42
|
dirty: typeof record.dirty === "boolean" ? record.dirty : false,
|
|
56
43
|
lastActivityAt: normalizeOptionalString(record.lastActivityAt),
|
|
57
44
|
eligibleAfter: normalizeOptionalString(record.eligibleAfter),
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
// history nor lose its due time.
|
|
61
|
-
lastReflectAt: normalizeOptionalString(record.lastReflectAt) ?? normalizeOptionalString(record.lastCheckpointAt),
|
|
62
|
-
lastReflectedEntryId: normalizeOptionalString(record.lastReflectedEntryId) ?? normalizeOptionalString(record.lastCheckpointEntryId),
|
|
45
|
+
lastReflectAt: normalizeOptionalString(record.lastReflectAt),
|
|
46
|
+
lastReflectedEntryId: normalizeOptionalString(record.lastReflectedEntryId),
|
|
63
47
|
failureBackoffUntil: normalizeOptionalNullableString(record.failureBackoffUntil) ?? null,
|
|
64
48
|
};
|
|
65
49
|
}
|
|
@@ -71,42 +55,19 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
|
|
|
71
55
|
}
|
|
72
56
|
catch (error) {
|
|
73
57
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
74
|
-
|
|
75
|
-
return legacy ?? createDefaultState(channelId);
|
|
58
|
+
return createDefaultState(channelId);
|
|
76
59
|
}
|
|
77
60
|
const message = errorMessage(error);
|
|
78
61
|
log.logWarning(`[${channelId}] Failed to read memory maintenance state; rebuilding defaults`, message);
|
|
79
62
|
return createDefaultState(channelId);
|
|
80
63
|
}
|
|
81
64
|
}
|
|
82
|
-
async function readLegacyState(appHomeDir, channelId) {
|
|
83
|
-
const path = legacyStatePath(appHomeDir, channelId);
|
|
84
|
-
if (!path)
|
|
85
|
-
return undefined;
|
|
86
|
-
try {
|
|
87
|
-
return normalizeState(channelId, JSON.parse(await readFile(path, "utf-8")));
|
|
88
|
-
}
|
|
89
|
-
catch {
|
|
90
|
-
return undefined; // absent or unreadable ⇒ the caller falls back to defaults, as before
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
65
|
export async function updateMemoryMaintenanceState(appHomeDir, channelId, update) {
|
|
94
66
|
const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
|
|
95
67
|
return stateUpdateQueue.run(path, async () => {
|
|
96
68
|
const current = await readMemoryMaintenanceState(appHomeDir, channelId);
|
|
97
69
|
const next = normalizeState(channelId, update(current));
|
|
98
70
|
await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
99
|
-
// The canonical file now holds everything the legacy one did; leaving it would keep a
|
|
100
|
-
// stale copy around forever, since reads only fall back when the canonical file is gone.
|
|
101
|
-
const legacy = legacyStatePath(appHomeDir, channelId);
|
|
102
|
-
if (legacy) {
|
|
103
|
-
await unlink(legacy).catch(() => { });
|
|
104
|
-
// ...along with the directory the raw id created, which `rmdir` leaves alone if
|
|
105
|
-
// another channel's state still lives there. Tidying only; failure changes nothing.
|
|
106
|
-
const strayDir = dirname(legacy);
|
|
107
|
-
if (strayDir !== getMemoryMaintenanceStateDir(appHomeDir))
|
|
108
|
-
await rmdir(strayDir).catch(() => { });
|
|
109
|
-
}
|
|
110
71
|
return next;
|
|
111
72
|
});
|
|
112
73
|
}
|
package/dist/memory/migrate.js
CHANGED
|
@@ -2,8 +2,8 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
6
5
|
import { localDayKey, parseLocalTime } from "../shared/local-time.js";
|
|
6
|
+
import { readOptionalTextFile } from "../shared/os.js";
|
|
7
7
|
import { dedupeMemoryName, getChannelMemoryDir, getChannelMemoryIndexPath, getMemoryEntryPath, rebuildMemoryIndex, serializeMemoryEntry, slugifyMemoryName, } from "./store.js";
|
|
8
8
|
import { hashMemoryContent } from "./tombstones.js";
|
|
9
9
|
/**
|
|
@@ -3,7 +3,6 @@ import type { Api, Model } from "@earendil-works/pi-ai";
|
|
|
3
3
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
|
|
5
5
|
import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
6
|
-
import { type MaintenanceJobKind } from "./maintenance-gates.js";
|
|
7
6
|
import { runReflect } from "./reflect.js";
|
|
8
7
|
/**
|
|
9
8
|
* Spec 050, D7/D9: the scheduler's idle-tick entry point into the reflect pass. Boundary
|
|
@@ -28,14 +27,7 @@ export interface ReflectJobInput {
|
|
|
28
27
|
sessionEntries: () => SessionEntry[];
|
|
29
28
|
queue?: ChannelMemoryQueue;
|
|
30
29
|
}
|
|
31
|
-
export
|
|
32
|
-
jobKind: MaintenanceJobKind;
|
|
33
|
-
ran: boolean;
|
|
34
|
-
skipped: boolean;
|
|
35
|
-
skipReason?: string;
|
|
36
|
-
error?: string;
|
|
37
|
-
}
|
|
38
|
-
export declare function runReflectJob(input: ReflectJobInput): Promise<ReflectJobResult>;
|
|
30
|
+
export declare function runReflectJob(input: ReflectJobInput): Promise<void>;
|
|
39
31
|
/** Shared by the idle job and `lifecycle.ts`'s boundary calls, so both write the same shape. */
|
|
40
32
|
export declare function reviewLogEntryFor(result: Awaited<ReturnType<typeof runReflect>>): {
|
|
41
33
|
actions?: unknown[];
|
|
@@ -45,7 +45,7 @@ export async function runReflectJob(input) {
|
|
|
45
45
|
reason: "reflect",
|
|
46
46
|
skipped: [{ target: "reflect", reason: decision.skipReason }],
|
|
47
47
|
});
|
|
48
|
-
return
|
|
48
|
+
return;
|
|
49
49
|
}
|
|
50
50
|
const sourceWindow = loadSourceWindow();
|
|
51
51
|
try {
|
|
@@ -71,7 +71,6 @@ export async function runReflectJob(input) {
|
|
|
71
71
|
correlationId: sourceWindow.windowId,
|
|
72
72
|
...reviewLogEntryFor(result),
|
|
73
73
|
});
|
|
74
|
-
return { jobKind: "reflect", ran: !result.skipped, skipped: result.skipped };
|
|
75
74
|
}
|
|
76
75
|
catch (error) {
|
|
77
76
|
await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
|
|
@@ -85,7 +84,6 @@ export async function runReflectJob(input) {
|
|
|
85
84
|
reason: "reflect",
|
|
86
85
|
error: message,
|
|
87
86
|
});
|
|
88
|
-
return { jobKind: "reflect", ran: false, skipped: false, error: message };
|
|
89
87
|
}
|
|
90
88
|
});
|
|
91
89
|
}
|
package/dist/memory/reflect.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { serializeConversation } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
3
2
|
import { parseJsonObject } from "../shared/llm-json.js";
|
|
4
3
|
import { localDayKey } from "../shared/local-time.js";
|
|
4
|
+
import { readOptionalTextFile } from "../shared/os.js";
|
|
5
5
|
import { clipText } from "../shared/text-utils.js";
|
|
6
6
|
import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS } from "./index-budget.js";
|
|
7
7
|
import { appendJournalEntries } from "./journal.js";
|
package/dist/memory/search.js
CHANGED
|
@@ -252,11 +252,18 @@ function scoreText(queryTokens, text) {
|
|
|
252
252
|
score += 0.5;
|
|
253
253
|
}
|
|
254
254
|
}
|
|
255
|
-
|
|
255
|
+
// Prefer the line that actually contains a query token (the hit may be in the body, not the
|
|
256
|
+
// description); fall back to the first non-empty line only when nothing matches on a line.
|
|
257
|
+
const nonEmptyLines = text
|
|
256
258
|
.split("\n")
|
|
257
|
-
.
|
|
258
|
-
|
|
259
|
-
|
|
259
|
+
.map((l) => l.trim())
|
|
260
|
+
.filter((l) => l.length > 0);
|
|
261
|
+
const matchingLine = nonEmptyLines.find((l) => {
|
|
262
|
+
const low = l.toLowerCase();
|
|
263
|
+
return [...queryTokens].some((token) => token.length >= 2 && low.includes(token));
|
|
264
|
+
});
|
|
265
|
+
const chosen = matchingLine ?? nonEmptyLines[0] ?? text.trim();
|
|
266
|
+
return { score, line: chosen.length > 200 ? `${chosen.slice(0, 197)}…` : chosen };
|
|
260
267
|
}
|
|
261
268
|
export function searchMemory(input) {
|
|
262
269
|
const queryTokens = new Set(tokenizeRecallText(input.query));
|
|
@@ -276,9 +283,9 @@ export function searchMemory(input) {
|
|
|
276
283
|
if (!line || line.startsWith("#")) {
|
|
277
284
|
continue;
|
|
278
285
|
}
|
|
279
|
-
const { score } = scoreText(queryTokens, line);
|
|
286
|
+
const { score, line: snippet } = scoreText(queryTokens, line);
|
|
280
287
|
if (score > 0) {
|
|
281
|
-
hits.push({ kind: "journal", label: day.date, date: day.date, line, score });
|
|
288
|
+
hits.push({ kind: "journal", label: day.date, date: day.date, line: snippet, score });
|
|
282
289
|
}
|
|
283
290
|
}
|
|
284
291
|
}
|
|
@@ -6,9 +6,20 @@ export interface SessionSearchDocument {
|
|
|
6
6
|
path: string;
|
|
7
7
|
timestamp?: string;
|
|
8
8
|
role: SessionSearchRole;
|
|
9
|
+
/** The full scannable message text (up to {@link SESSION_SCAN_MAX_CHARS}) — matching runs on
|
|
10
|
+
* this, display windows are cut from it at query time (fix plan §2.5). */
|
|
9
11
|
text: string;
|
|
12
|
+
/** True when even the scan text was clipped: a keyword past this point cannot be found here. */
|
|
13
|
+
scanTruncated?: boolean;
|
|
10
14
|
sessionId?: string;
|
|
11
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Ceiling on how much of one message is kept for *matching*. The old code clipped each message to
|
|
18
|
+
* the small display window at ingest, so a keyword in the middle of a long message was gone from
|
|
19
|
+
* the corpus entirely and widening the query could never bring it back. This is deliberately much
|
|
20
|
+
* larger than the display window; a single pathological message still cannot blow out memory.
|
|
21
|
+
*/
|
|
22
|
+
export declare const SESSION_SCAN_MAX_CHARS = 20000;
|
|
12
23
|
export interface BuildSessionCorpusOptions {
|
|
13
24
|
channelDir: string;
|
|
14
25
|
maxFiles: number;
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import { readdir, stat } from "node:fs/promises";
|
|
2
2
|
import { basename, join } from "node:path";
|
|
3
|
-
import { isNodeError, readOptionalTextFile } from "../shared/
|
|
4
|
-
import { clipText } from "../shared/text-utils.js";
|
|
3
|
+
import { isNodeError, readOptionalTextFile } from "../shared/os.js";
|
|
5
4
|
import { isRecord } from "../shared/type-guards.js";
|
|
5
|
+
/**
|
|
6
|
+
* Ceiling on how much of one message is kept for *matching*. The old code clipped each message to
|
|
7
|
+
* the small display window at ingest, so a keyword in the middle of a long message was gone from
|
|
8
|
+
* the corpus entirely and widening the query could never bring it back. This is deliberately much
|
|
9
|
+
* larger than the display window; a single pathological message still cannot blow out memory.
|
|
10
|
+
*/
|
|
11
|
+
export const SESSION_SCAN_MAX_CHARS = 20_000;
|
|
6
12
|
const DEFAULT_MAX_CHARS_PER_DOCUMENT = 4_000;
|
|
7
13
|
const DEFAULT_MAX_DOCUMENTS_TOTAL = 5_000;
|
|
8
14
|
const IGNORED_JSONL_FILES = new Set([
|
|
@@ -83,17 +89,22 @@ function getNestedRecord(record, key) {
|
|
|
83
89
|
return isRecord(value) ? value : null;
|
|
84
90
|
}
|
|
85
91
|
function createDocument(params) {
|
|
86
|
-
|
|
87
|
-
|
|
92
|
+
// The ingest clip is a fixed, generous scan cap — not the caller's display window. Trimming for
|
|
93
|
+
// display happens later, at query time, centered on the match (fix plan §2.5). `params.maxChars`
|
|
94
|
+
// is kept in the signature for callers that still pass it but no longer drives the clip.
|
|
95
|
+
const raw = params.text.trim();
|
|
96
|
+
if (!raw) {
|
|
88
97
|
return null;
|
|
89
98
|
}
|
|
99
|
+
const scanTruncated = raw.length > SESSION_SCAN_MAX_CHARS;
|
|
90
100
|
return {
|
|
91
101
|
id: params.id,
|
|
92
102
|
source: params.source,
|
|
93
103
|
path: params.path,
|
|
94
104
|
timestamp: params.timestamp,
|
|
95
105
|
role: params.role,
|
|
96
|
-
text,
|
|
106
|
+
text: scanTruncated ? raw.slice(0, SESSION_SCAN_MAX_CHARS) : raw,
|
|
107
|
+
...(scanTruncated ? { scanTruncated: true } : {}),
|
|
97
108
|
sessionId: params.sessionId,
|
|
98
109
|
};
|
|
99
110
|
}
|