2 Commits

Author SHA1 Message Date
2a6165ac86 Merge pull request 'feat(plugin): סגירה אוטומטית של issue שטן-מליץ אחרי ריצה מוצלחת (legal-ai #892)' (#17) from feat/devil-issue-autoclose into main
Some checks failed
INV-INT9 issue.status write-ownership / int9-guard (push) Failing after 3s
2026-10-14 15:58:47 +00:00
c51f8c36e7 feat(plugin): סגירה אוטומטית של issue שטן-מליץ אחרי ריצה מוצלחת — מעיר את ה-CEO (legal-ai #892)
Some checks failed
INV-INT9 issue.status write-ownership / int9-guard (pull_request) Failing after 6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PRePqBSqn3kjwjg9puEJZz
2026-10-14 18:56:07 +03:00
3 changed files with 328 additions and 0 deletions

138
src/devil-closer.test.ts Normal file
View File

@@ -0,0 +1,138 @@
/// <reference types="node" />
import assert from "node:assert/strict";
import { test } from "node:test";
import {
type CloseDeps,
caseNumberFromTitle,
closeDevilIssueIfDone,
DEVIL_AGENT_IDS,
} from "./devil-closer.ts";
const CMPA = "8639e837-4c9d-47fa-a76b-95788d651896";
const DEVIL = DEVIL_AGENT_IDS[CMPA];
const TITLE = "[ערר 8165-11-25] שטן-מליץ — red-team על הניתוח";
function deps(over: Partial<CloseDeps> = {}) {
const closed: string[] = [];
const d: CloseDeps = {
getIssue: async (id) => ({
id,
title: TITLE,
status: "in_progress",
assigneeAgentId: DEVIL,
createdAt: "2026-10-14T12:45:58Z",
}),
statCritique: async () => ({
size: 39261,
mtimeMs: Date.parse("2026-10-14T13:29:50Z"),
}),
closeIssue: async (id) => {
closed.push(id);
},
log: () => {},
...over,
};
return { d, closed };
}
const RUN = { agentId: DEVIL, issueId: "i1", status: "succeeded" };
test("caseNumberFromTitle", () => {
assert.equal(caseNumberFromTitle(TITLE), "8165-11-25");
assert.equal(caseNumberFromTitle("[ערר 8027/25] x"), "8027/25");
assert.equal(caseNumberFromTitle("בלי מספר"), null);
});
test("סוגר כשהכול תקין", async () => {
const { d, closed } = deps();
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "closed");
assert.deepEqual(closed, ["i1"]);
});
test("לא סוכן שטן → לא נוגע", async () => {
const { d, closed } = deps();
assert.equal(
await closeDevilIssueIfDone(CMPA, { ...RUN, agentId: "other" }, d),
"not_devil_run",
);
assert.equal(closed.length, 0);
});
test("חברה לא מוכרת → לא נוגע", async () => {
const { d } = deps();
assert.equal(await closeDevilIssueIfDone("nope", RUN, d), "not_devil_run");
});
test("ריצה שלא הצליחה → לא סוגר", async () => {
const { d, closed } = deps();
assert.equal(
await closeDevilIssueIfDone(CMPA, { ...RUN, status: "failed" }, d),
"not_devil_run",
);
assert.equal(closed.length, 0);
});
test("issue שאינו של שטן (כותרת אחרת) → לא סוגר", async () => {
const { d, closed } = deps({
getIssue: async (id) => ({
id,
title: "[ערר 1-1-1] ניתוח משפטי",
status: "in_progress",
assigneeAgentId: DEVIL,
}),
});
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "not_devil_issue");
assert.equal(closed.length, 0);
});
test("כבר סגור → לא סוגר שוב", async () => {
const { d, closed } = deps({
getIssue: async (id) => ({
id,
title: TITLE,
status: "done",
assigneeAgentId: DEVIL,
}),
});
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "already_closed");
assert.equal(closed.length, 0);
});
test("אין קובץ מזכר → נשאר פתוח", async () => {
const { d, closed } = deps({ statCritique: async () => null });
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "no_deliverable");
assert.equal(closed.length, 0);
});
test("קובץ ישן מלפני יצירת ה-issue → נשאר פתוח", async () => {
const { d, closed } = deps({
statCritique: async () => ({
size: 39261,
mtimeMs: Date.parse("2026-10-01T00:00:00Z"),
}),
});
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "no_deliverable");
assert.equal(closed.length, 0);
});
test("קובץ קצר מדי → נשאר פתוח", async () => {
const { d, closed } = deps({
statCritique: async () => ({
size: 300,
mtimeMs: Date.parse("2026-10-14T13:29:50Z"),
}),
});
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "no_deliverable");
assert.equal(closed.length, 0);
});
test("כשל גישה לקובץ → נשאר פתוח (fail-safe)", async () => {
const { d, closed } = deps({
statCritique: async () => {
throw new Error("EACCES");
},
});
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "stat_failed");
assert.equal(closed.length, 0);
});

136
src/devil-closer.ts Normal file
View File

@@ -0,0 +1,136 @@
/**
* סגירה אוטומטית של issue "שטן-מליץ" אחרי ריצה מוצלחת (legal-ai #892).
*
* הרקע: סוכן Gemini רץ בלי shell (#872) ולכן אינו יכול לסגור את ה-issue שלו.
* Paperclip מעיר את ה-CEO רק על `issue_children_completed` (ילד ב-`done`), ו-issue
* שנשאר פתוח עובר ל-`blocked` ("successful run missing disposition") — וה-CEO אינו
* מתעורר לעולם (אין לו heartbeat מחזורי). התוצאה בתיק 8165-11-25: המזכר נכתב והתהליך נתקע.
*
* הלוגיקה כאן טהורה (תלויות מוזרקות) כדי שאפשר לבדוק אותה בלי host.
*/
/** חברה → agent id של שטן-מליץ (Gemini) באותה חברה. */
export const DEVIL_AGENT_IDS: Record<string, string> = {
"42a7acd0-30c5-4cbd-ac97-7424f65df294":
"9c86e06a-5a92-4723-af6d-e8cc6ae1d45b", // CMP
"8639e837-4c9d-47fa-a76b-95788d651896":
"46cc1228-a232-410b-a36b-71a6928499a2", // CMPA
};
export const DEFAULT_CASES_DIR = "/home/chaim/legal-ai/data/cases";
/** מזכר קצר מזה = כנראה ריצה ריקה/חלקית, לא סוגרים. */
export const MIN_CRITIQUE_BYTES = 2000;
const CLOSED = new Set(["done", "cancelled"]);
export interface DevilIssueLike {
id: string;
title: string;
status: string;
assigneeAgentId?: string | null;
createdAt?: string | Date | null;
}
export interface DevilRunPayload {
agentId?: string;
issueId?: string | null;
status?: string;
}
export interface CloseDeps {
getIssue(issueId: string, companyId: string): Promise<DevilIssueLike | null>;
/** גודל + זמן-שינוי של הקובץ, או null אם אינו קיים. זורק רק על כשל-גישה. */
statCritique(
caseNumber: string,
): Promise<{ size: number; mtimeMs: number } | null>;
closeIssue(issueId: string, companyId: string): Promise<void>;
log(
level: "info" | "warn",
msg: string,
meta?: Record<string, unknown>,
): void;
}
export function caseNumberFromTitle(title: string): string | null {
const m = title.match(/\[ערר\s+([^\]\s]+)\]/);
return m ? m[1] : null;
}
export function isDevilTitle(title: string): boolean {
return title.includes("שטן-מליץ");
}
export type CloseOutcome =
| "closed"
| "not_devil_run"
| "no_issue"
| "not_devil_issue"
| "already_closed"
| "no_case_number"
| "no_deliverable"
| "stat_failed";
/**
* מופעל על `agent.run.finished` (status=succeeded בלבד). סוגר את ה-issue רק אם:
* הריצה של שטן-מליץ של אותה חברה, ה-issue שלו פתוח, וקיים `critique-gemini.md` עדכני ולא ריק.
*/
export async function closeDevilIssueIfDone(
companyId: string | undefined,
payload: DevilRunPayload | null,
deps: CloseDeps,
): Promise<CloseOutcome> {
if (!companyId || !payload) return "not_devil_run";
const devilId = DEVIL_AGENT_IDS[companyId];
if (!devilId || payload.agentId !== devilId) return "not_devil_run";
if (payload.status && payload.status !== "succeeded") return "not_devil_run";
if (!payload.issueId) return "no_issue";
const issue = await deps.getIssue(payload.issueId, companyId);
if (!issue) return "no_issue";
if (issue.assigneeAgentId !== devilId || !isDevilTitle(issue.title)) {
return "not_devil_issue";
}
if (CLOSED.has(issue.status)) return "already_closed";
const caseNumber = caseNumberFromTitle(issue.title);
if (!caseNumber) return "no_case_number";
let st: { size: number; mtimeMs: number } | null;
try {
st = await deps.statCritique(caseNumber);
} catch {
deps.log(
"warn",
"devil auto-close: critique stat failed; leaving issue open",
{
issueId: issue.id,
caseNumber,
},
);
return "stat_failed";
}
const created = issue.createdAt ? new Date(issue.createdAt).getTime() : 0;
if (!st || st.size < MIN_CRITIQUE_BYTES || st.mtimeMs < created) {
deps.log(
"warn",
"devil auto-close: no fresh critique-gemini.md; leaving issue open",
{
issueId: issue.id,
caseNumber,
size: st?.size ?? null,
},
);
return "no_deliverable";
}
await deps.closeIssue(issue.id, companyId);
deps.log(
"info",
"devil auto-close: issue closed (CEO is woken by issue_children_completed)",
{
issueId: issue.id,
caseNumber,
},
);
return "closed";
}

View File

@@ -1,3 +1,6 @@
/// <reference types="node" />
import { stat } from "node:fs/promises";
import type { import type {
PluginContext, PluginContext,
PluginWebhookInput, PluginWebhookInput,
@@ -10,6 +13,7 @@ import {
resolveApiBaseFrom, resolveApiBaseFrom,
runJobHandler, runJobHandler,
} from "./company-scope.js"; } from "./company-scope.js";
import { closeDevilIssueIfDone, DEFAULT_CASES_DIR } from "./devil-closer.js";
import type { StatusModelEntry } from "./legal-api.js"; import type { StatusModelEntry } from "./legal-api.js";
import { LegalApi } from "./legal-api.js"; import { LegalApi } from "./legal-api.js";
import { import {
@@ -739,6 +743,56 @@ const plugin = definePlugin({
} }
} }
// ── שטן-מליץ: סגירה אוטומטית אחרי ריצה מוצלחת (legal-ai #892) ──
// הסוכן רץ בלי shell ולכן אינו יכול לסגור את ה-issue שלו; בלי `done` ה-CEO
// לעולם לא מתעורר (`issue_children_completed`). ראה devil-closer.ts.
ctx.events.on("agent.run.finished", async (event) => {
try {
const casesDir = process.env.LEGAL_AI_CASES_DIR || DEFAULT_CASES_DIR;
await closeDevilIssueIfDone(
event.companyId,
(event.payload ?? null) as Parameters<
typeof closeDevilIssueIfDone
>[1],
{
getIssue: async (id, companyId) => {
const i = await ctx.issues.get(id, companyId);
return i
? {
id: i.id,
title: i.title,
status: i.status,
assigneeAgentId: i.assigneeAgentId,
createdAt: i.createdAt,
}
: null;
},
statCritique: async (caseNumber) => {
try {
const st = await stat(
`${casesDir}/${caseNumber}/documents/research/critique-gemini.md`,
);
return { size: st.size, mtimeMs: st.mtimeMs };
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT")
return null;
throw err;
}
},
// סטטוס בלבד, בלי comment: comment מעיר את ה-CEO פעם שנייה (user_commented).
closeIssue: async (id, companyId) => {
await ctx.issues.update(id, { status: "done" }, companyId);
},
log: (level, msg, meta) => ctx.logger[level](msg, meta),
},
);
} catch (err) {
ctx.logger.warn("devil auto-close handler failed", {
error: err instanceof Error ? err.name : "unknown",
});
}
});
ctx.events.on("issue.comment.created", async (event) => { ctx.events.on("issue.comment.created", async (event) => {
// Only intercept human comments — not agent comments (prevents loops) // Only intercept human comments — not agent comments (prevents loops)
if (event.actorType !== "user") return; if (event.actorType !== "user") return;