Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 66 additions & 95 deletions lib/inferenceLogUtils.ts
Original file line number Diff line number Diff line change
@@ -1,114 +1,85 @@
import fs from "fs/promises";
import path from "path";
import fs from "fs";
import { INFERENCE_LOGS_DIR } from "./constants";
import { InferenceLog } from "./types";
import { isNodeError } from "./utils";

/**
* Create (or ensure) a parent directory named "inference_summary".
*/
function ensureInferenceSummaryDir(): string {
const inferenceDir = path.join(process.cwd(), "inference_summary");
if (!fs.existsSync(inferenceDir)) {
fs.mkdirSync(inferenceDir, { recursive: true });
}
return inferenceDir;
}
export async function saveInferenceLog(log: InferenceLog): Promise<void> {
const logPath = path.join(INFERENCE_LOGS_DIR, `${log.id}.json`);

/**
* Appends a new entry to the act_summary.json file, then writes the file back out.
*/
export function appendSummary<T>(inferenceType: string, entry: T) {
const summaryPath = getSummaryJsonPath(inferenceType);
const arrayKey = `${inferenceType}_summary`;
// Security: Prevent path traversal attacks.
const resolvedPath = path.resolve(logPath);
const resolvedBaseDir = path.resolve(INFERENCE_LOGS_DIR);

const existingData = readSummaryFile<T>(inferenceType);
existingData[arrayKey].push(entry);

fs.writeFileSync(summaryPath, JSON.stringify(existingData, null, 2));
}
if (!resolvedPath.startsWith(resolvedBaseDir + path.sep)) {
// This should not happen if IDs are generated correctly, but as a safeguard:
console.error(`Path traversal attempt blocked for saving log id: ${log.id}`);
throw new Error("Invalid log ID detected.");
}

/** A simple timestamp utility for filenames. */
function getTimestamp(): string {
return new Date()
.toISOString()
.replace(/[^0-9T]/g, "")
.replace("T", "_");
await fs.writeFile(resolvedPath, JSON.stringify(log, null, 2));
}

/**
* Writes `data` as JSON into a file in `directory`, using a prefix plus timestamp.
* Returns both the file name and the timestamp used, so you can log them.
*/
export function writeTimestampedTxtFile(
directory: string,
prefix: string,
data: unknown,
): { fileName: string; timestamp: string } {
const baseDir = ensureInferenceSummaryDir();

const subDir = path.join(baseDir, directory);
if (!fs.existsSync(subDir)) {
fs.mkdirSync(subDir, { recursive: true });
export async function updateInferenceLog(
id: string,
updates: Partial<InferenceLog>,
): Promise<void> {
const log = await getInferenceLog(id);
if (!log) {
// Or throw an error, depending on desired behavior
console.warn(`Log with id ${id} not found for update.`);
return;
}

const timestamp = getTimestamp();
const fileName = `${timestamp}_${prefix}.txt`;
const filePath = path.join(subDir, fileName);

fs.writeFileSync(
filePath,
JSON.stringify(data, null, 2).replace(/\\n/g, "\n"),
);

return { fileName, timestamp };
const updatedLog = { ...log, ...updates };
await saveInferenceLog(updatedLog);
}

/**
* Returns the path to the `<inferenceType>_summary.json` file.
*
* For example, if `inferenceType = "act"`, this will be:
* `./inference_summary/act_summary/act_summary.json`
*/
function getSummaryJsonPath(inferenceType: string): string {
const baseDir = ensureInferenceSummaryDir();
const subDir = path.join(baseDir, `${inferenceType}_summary`);
if (!fs.existsSync(subDir)) {
fs.mkdirSync(subDir, { recursive: true });
export async function appendToInferenceLog(
id: string,
newContent: Partial<InferenceLog>,
): Promise<void> {
const log = await getInferenceLog(id);
if (!log) {
console.warn(`Log with id ${id} not found for appending.`);
export function getInferenceLog(id: string) {
Comment on lines +44 to +45
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

syntax: Syntax error: appendToInferenceLog function is incomplete and missing closing brace before the next export

Suggested change
console.warn(`Log with id ${id} not found for appending.`);
export function getInferenceLog(id: string) {
console.warn(`Log with id ${id} not found for appending.`);
return;
}
const updatedLog = { ...log, ...newContent };
await saveInferenceLog(updatedLog);
}
export function getInferenceLog(id: string) {
Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/inferenceLogUtils.ts
Line: 44:45

Comment:
**syntax:** Syntax error: `appendToInferenceLog` function is incomplete and missing closing brace before the next export

```suggestion
    console.warn(`Log with id ${id} not found for appending.`);
    return;
  }

  const updatedLog = { ...log, ...newContent };
  await saveInferenceLog(updatedLog);
}

export function getInferenceLog(id: string) {
```

How can I resolve this? If you propose a fix, please make it concise.

if (!id) {
return null;
}
return path.join(subDir, `${inferenceType}_summary.json`);
}

/**
* Reads the `<inferenceType>_summary.json` file, returning an object
* with the top-level array named `<inferenceType>_summary`, if it exists.
*
* E.g. if inferenceType is "act", we expect a shape like:
* {
* "act_summary": [ ... ]
* }
*
* If the file or array is missing, returns { "<inferenceType>_summary": [] }.
*/
function readSummaryFile<T>(inferenceType: string): Record<string, T[]> {
const summaryPath = getSummaryJsonPath(inferenceType);
try {
const logDir = path.resolve(INFERENCE_LOG_DIR);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Variable name inconsistency: using INFERENCE_LOG_DIR but imported INFERENCE_LOGS_DIR

Suggested change
const logDir = path.resolve(INFERENCE_LOG_DIR);
const logDir = path.resolve(INFERENCE_LOGS_DIR);
Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/inferenceLogUtils.ts
Line: 50:50

Comment:
**logic:** Variable name inconsistency: using `INFERENCE_LOG_DIR` but imported `INFERENCE_LOGS_DIR`

```suggestion
    const logDir = path.resolve(INFERENCE_LOGS_DIR);
```

How can I resolve this? If you propose a fix, please make it concise.

const logPath = path.resolve(logDir, `${id}.json`);

// The top-level array key, e.g. "act_summary", "observe_summary", "extract_summary"
const arrayKey = `${inferenceType}_summary`;
// Prevent path traversal.
if (!logPath.startsWith(logDir + path.sep)) {
console.error(`Path traversal attempt detected for id: ${id}`);
return null;
}

if (!fs.existsSync(summaryPath)) {
return { [arrayKey]: [] };
const log = fs.readFileSync(logPath, "utf-8");
return JSON.parse(log);
} catch (e) {
return null;
}
}
// Security: Prevent path traversal attacks.
// Ensure the resolved path is within the intended log directory.
const resolvedPath = path.resolve(logPath);
const resolvedBaseDir = path.resolve(INFERENCE_LOGS_DIR);

try {
const raw = fs.readFileSync(summaryPath, "utf8");
const parsed = JSON.parse(raw);
if (
parsed &&
typeof parsed === "object" &&
Array.isArray(parsed[arrayKey])
) {
return parsed;
if (!resolvedPath.startsWith(resolvedBaseDir + path.sep)) {
console.warn(`Potential path traversal attempt for id: ${id}`);
return null;
}

const data = await fs.readFile(resolvedPath, "utf-8");
return JSON.parse(data);
} catch (error) {
// It's okay if the file doesn't exist
if (isNodeError(error) && error.code === "ENOENT") {
return null;
}
} catch {
// If we fail to parse for any reason, fall back to empty array
// Re-throw other errors
throw error;
}
return { [arrayKey]: [] };
}