#include "resolve.h"
#include "platform.h"
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *const kind_names[AK_COUNT] = {
"skills", "agents", "commands", "instructions", "file", "slot",
};
// The harness key that names the folder for each kind that goes in a harness.
static const char *const folder_keys[2][AK_INSTRUCTIONS + 1] = {
{"skills.user", "agents.user", "commands.user", "instructions.user"},
{"skills.personal", "agents.personal", "commands.personal", "instructions.personal"},
};
const char *asset_kind_name(AssetKind kind)
{
ensure(kind < AK_COUNT);
return kind_names[kind];
}
bool glob_match(const char *pattern, const char *name)
{
const char *star = nullptr;
const char *resume = nullptr;
while (*name != '\0') {
if (*pattern == '*') {
star = pattern++;
resume = name;
} else if (*pattern == *name) {
pattern++;
name++;
} else if (star != nullptr) {
pattern = star + 1;
name = ++resume;
} else {
return false;
}
}
while (*pattern == '*') pattern++;
return *pattern == '\0';
}
typedef struct {
const Conf *c;
const Assets *assets;
const char *home;
const char *suit_home;
const char *store;
const char *machine;
bool limited; // the wears being placed are limited to this machine
const char *project; // the project folder being placed into; nullptr for the User scope
ProjectKind vcs;
Plan *p;
ResolveError *e;
// For resolve_why: the name asked about, and what is being looked at.
const char *why; // nullptr when resolve is not asked about a name
const char *name; // the name of the asset being placed
const char *outfit; // the outfit being placed
const char *wscope; // "user" or "personal"
const char *wkey; // the key of the wear, "" for the User scope
const char *wmachine; // the machine the wear is limited to, "" if none
Fate fate; // FATE_PENDING for a wear that applies, else why it does not
} Ctx;
__attribute__((format(printf, 2, 3)))
static bool fail(Ctx *x, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(x->e->msg, sizeof x->e->msg, fmt, ap);
va_end(ap);
return false;
}
static const char EMPTY[] = "";
// Copy A, B and C joined into the plan's text. If it does not fit, the plan is
// marked overflowed (add_placement says so) and the result is empty.
static const char *join(Plan *p, const char *a, const char *b, const char *c)
{
size_t la = strlen(a), lb = strlen(b), lc = strlen(c);
if (p->used + la + lb + lc + 1 > sizeof p->text) {
p->overflow = true;
return EMPTY;
}
char *out = p->text + p->used;
memcpy(out, a, la);
memcpy(out + la, b, lb);
memcpy(out + la + lb, c, lc + 1);
p->used += la + lb + lc + 1;
return out;
}
// "~" and "~/..." mean the home folder.
static const char *expand(Ctx *x, const char *path)
{
bool tilde = path[0] == '~' && (path[1] == '/' || path[1] == '\0');
return tilde ? join(x->p, x->home, path + 1, "") : join(x->p, path, "", "");
}
static bool plan_full(Ctx *x)
{
return fail(x, "the plan is larger than %zu bytes of paths", PLAN_TEXT_MAX);
}
// The "project" of a personal wear that no project has the key of.
static const char NOWHERE[] = "-";
static bool name_matches(const Ctx *x, AssetKind kind, const char *dest)
{
if (kind == AK_FILE || kind == AK_SLOT) return strcmp(x->why, x->name) == 0 || strcmp(x->why, dest) == 0;
if (strcmp(x->why, x->name) == 0) return true;
size_t len = strlen(x->why);
return kind != AK_INSTRUCTIONS && len > 3 && strcmp(x->why + len - 3, ".md") == 0 &&
strncmp(x->why, x->name, len - 3) == 0 && x->name[len - 3] == '\0';
}
// Remember a place that supplies the name asked about, if there is one.
static bool note(Ctx *x, AssetKind kind, const char *harness, const char *dest, const char *src,
Fate fate)
{
Plan *p = x->p;
if (x->why == nullptr || !name_matches(x, kind, dest)) return true;
if (p->nsuppliers == SUPPLIER_MAX) return fail(x, "more than %u places supply %s", SUPPLIER_MAX, x->why);
bool none = fate == FATE_NO_FOLDER || x->project == NOWHERE;
p->sup[p->nsuppliers++] = (Supplier){.scope = x->wscope, .key = x->wkey, .machine = x->wmachine,
.outfit = x->outfit, .harness = harness, .dest = none ? "-" : dest, .src = src,
.project = x->project == NOWHERE ? nullptr : x->project, .kind = kind, .fate = fate};
return true;
}
static bool add_placement(Ctx *x, const char *dest, const char *src, const char *harness,
AssetKind kind)
{
Plan *p = x->p;
if (x->fate != FATE_PENDING) return note(x, kind, harness, dest, src, x->fate);
if (p->overflow) return plan_full(x);
if (p->n == PLACE_MAX) return fail(x, "more than %u placements", PLACE_MAX);
if (dest[0] != '/')
return fail(x, "%s is not an absolute path (start it with ~ or /)", dest);
if (strpbrk(dest, " \t") != nullptr || strpbrk(src, " \t") != nullptr)
return fail(x, "a space in %s or %s: paths cannot have one", dest, src);
p->p[p->n++] = (Placement){dest, src, harness, kind, x->limited, x->project, x->vcs};
return note(x, kind, harness, dest, src, FATE_PENDING);
}
static bool add_skip(Ctx *x, const char *text)
{
Plan *p = x->p;
if (p->nskips == SKIP_MAX) return fail(x, "more than %u skipped lines", SKIP_MAX);
snprintf(p->skips[p->nskips++], SKIP_LEN, "%s", text);
return true;
}
static const Entry *find_entry(const Conf *c, const Section *s, const char *key)
{
for (uint32_t i = 0; i < s->count; i++)
if (strcmp(c->entries[s->first + i].key, key) == 0) return &c->entries[s->first + i];
return nullptr;
}
static const Section *find_outfit(const Conf *c, const char *name, size_t len)
{
for (uint32_t i = 0;; i++) {
ensure(i < c->nsections); // conf_load checked that every name given is an outfit
const Section *s = &c->sections[i];
if (s->kind == KIND_OUTFIT && strncmp(s->arg[0], name, len) == 0 && s->arg[0][len] == '\0')
return s;
}
}
// ---- which outfits ----------------------------------------------------------
typedef struct {
const Section *list[CONF_OUTFIT_MAX];
uint32_t n;
} Outfits;
static void queue_outfits(Ctx *x, Outfits *q, const char *names)
{
const char *w;
size_t len;
while (conf_list_next(&names, &w, &len)) {
const Section *s = find_outfit(x->c, w, len);
bool seen = false;
for (uint32_t i = 0; i < q->n; i++) seen |= q->list[i] == s;
if (!seen) q->list[q->n++] = s;
}
}
// What the outfits queued so far include, and so on.
static void queue_includes(Ctx *x, Outfits *q)
{
for (uint32_t head = 0; head < q->n; head++) {
const Entry *inc = find_entry(x->c, q->list[head], "include");
if (inc != nullptr) queue_outfits(x, q, inc->val);
}
}
// The outfits a scope wears (KEY is the project's key, "" for the User scope),
// each once: first the ones the wear sections name in order, then what they include, and so on. LIMITED picks the wears
// limited to this machine; otherwise the unlimited ones. A wear limited to
// another machine, or any machine when this one has no name, is ignored.
static void collect_outfits(Ctx *x, Outfits *q, const char *scope, const char *key, bool limited)
{
q->n = 0;
for (uint32_t i = 0; i < x->c->nsections; i++) {
const Section *s = &x->c->sections[i];
if (s->kind != KIND_WEAR || strcmp(s->arg[0], scope) != 0 || strcmp(s->arg[1], key) != 0) continue;
bool has_limit = s->arg[2][0] != '\0';
if (has_limit != limited || (limited && strcmp(s->arg[2], x->machine) != 0)) continue;
const Entry *outfits = find_entry(x->c, s, "outfits");
if (outfits != nullptr) queue_outfits(x, q, outfits->val);
}
queue_includes(x, q);
}
// ---- placing one asset ------------------------------------------------------
static const char *const kind_dirs[AK_COMMAND + 1] = {"/skills/", "/agents/", "/commands/"};
// True if PATH is relative and none of its parts is "..".
static bool relative_path(const char *path)
{
if (path[0] == '/' || path[0] == '~') return false;
for (const char *s = path; *s != '\0';) {
size_t len = strcspn(s, "/");
if (len == 2 && s[0] == '.' && s[1] == '.') return false;
s += len + (s[len] == '/' ? 1 : 0);
}
return true;
}
static bool place_one(Ctx *x, const Section *harness, AssetKind kind, const char *file,
const char *name)
{
const char *key = folder_keys[x->project != nullptr][kind];
const Entry *folder = find_entry(x->c, harness, key);
if (folder == nullptr) {
if (x->fate != FATE_PENDING) return note(x, kind, harness->arg[0], "", "", x->fate);
if (!note(x, kind, harness->arg[0], "", "", FATE_NO_FOLDER)) return false;
char text[SKIP_LEN];
snprintf(text, sizeof text, "skipped %s %s %s%s%s (no folder)", harness->arg[0],
kind_names[kind], name, x->project != nullptr ? " in " : "",
x->project != nullptr ? x->project : "");
return add_skip(x, text);
}
if (x->project != nullptr && !relative_path(folder->val))
return fail(x, "harness %s: %s must be a relative path with no .. part, not %s",
harness->arg[0], key, folder->val);
const char *base = x->project == nullptr ? expand(x, folder->val)
: join(x->p, x->project, "/", folder->val);
// Instructions are one file the harness names; the rest go in its folder.
bool instructions = kind == AK_INSTRUCTIONS;
const char *dest = join(x->p, base, instructions ? "" : "/", instructions ? "" : file);
const char *src = instructions ? join(x->p, x->store, "/", file)
: join(x->p, x->store, kind_dirs[kind], file);
return add_placement(x, dest, src, harness->arg[0], kind);
}
static bool eligible(const Section *harness, const char *only)
{
return only == nullptr || strcmp(harness->arg[0], only) == 0;
}
// Match each word of LIST against the names the store has, place every match
// for every harness the outfit is for.
static bool place_names(Ctx *x, const Section *outfit, const char *only, AssetKind kind,
const char *list)
{
const NameList *have = &x->assets->list[kind];
const char *w;
size_t len;
while (conf_list_next(&list, &w, &len)) {
char pattern[CONF_NAME_MAX + 1];
memcpy(pattern, w, len);
pattern[len] = '\0';
uint32_t matched = 0;
for (uint32_t i = 0; i < have->n; i++) {
if (!glob_match(pattern, have->name[i])) continue;
matched++;
x->name = have->name[i];
for (uint32_t h = 0; h < x->c->nsections; h++) {
const Section *hs = &x->c->sections[h];
if (hs->kind != KIND_HARNESS || !eligible(hs, only)) continue;
if (!place_one(x, hs, kind, have->file[i], have->name[i])) return false;
}
}
if (matched == 0)
return fail(x, "outfit %s: %s '%s' matches nothing in the store", outfit->arg[0],
kind_names[kind], pattern);
}
return true;
}
static bool place_instructions(Ctx *x, const char *only, const char *path)
{
x->name = "instructions";
for (uint32_t h = 0; h < x->c->nsections; h++) {
const Section *hs = &x->c->sections[h];
if (hs->kind != KIND_HARNESS || !eligible(hs, only)) continue;
if (!place_one(x, hs, AK_INSTRUCTIONS, path, path)) return false;
}
return true;
}
// "file DEST = SRC" and "slot NAME = SRC": one placement each, whatever the
// harnesses.
static bool place_free(Ctx *x, const Section *outfit, AssetKind kind, const char *param,
const char *src)
{
x->name = param;
if (x->project != nullptr && kind == AK_SLOT)
return fail(x, "outfit %s: slot %s is worn in a project, but a slot belongs to the User scope",
outfit->arg[0], param);
if (x->project != nullptr && !relative_path(param))
return fail(x, "outfit %s: file %s is worn in a project, so it must be a relative path with no .. part",
outfit->arg[0], param);
const char *dest = kind == AK_SLOT ? join(x->p, x->suit_home, "/slots/", param)
: x->project != nullptr ? join(x->p, x->project, "/", param)
: expand(x, param);
const char *from = join(x->p, x->store, "/", src);
return add_placement(x, dest, from, "-", kind);
}
static bool place_outfit(Ctx *x, const Section *outfit)
{
x->outfit = outfit->arg[0];
const Entry *only_entry = find_entry(x->c, outfit, "only");
const char *only = only_entry != nullptr ? only_entry->val : nullptr;
for (uint32_t i = 0; i < outfit->count; i++) {
const Entry *en = &x->c->entries[outfit->first + i];
bool ok = true;
for (int k = AK_SKILL; k <= AK_COMMAND; k++)
if (strcmp(en->key, kind_names[k]) == 0) ok = place_names(x, outfit, only, (AssetKind)k, en->val);
if (strcmp(en->key, "instructions") == 0) ok = place_instructions(x, only, en->val);
if (strncmp(en->key, "file ", 5) == 0) ok = place_free(x, outfit, AK_FILE, en->key + 5, en->val);
if (strncmp(en->key, "slot ", 5) == 0) ok = place_free(x, outfit, AK_SLOT, en->key + 5, en->val);
if (!ok) return false;
}
return true;
}
// ---- order and conflicts ----------------------------------------------------
static int cmp_placement(const void *pa, const void *pb)
{
const Placement *a = pa;
const Placement *b = pb;
int r = strcmp(a->dest, b->dest);
if (r == 0) r = strcmp(a->src, b->src);
// The same source from both is unlimited: it stays first and the rest go.
return r != 0 ? r : (int)a->limited - (int)b->limited;
}
// FNV-1a, to tell one project's joined file from another's.
static uint64_t hash_text(const char *text)
{
uint64_t h = 14695981039346656037ULL;
for (; *text != '\0'; text++) h = (h ^ (unsigned char)*text) * 1099511628211ULL;
return h;
}
// Two assets for one destination. The same source is one placement. Another
// source is an error that names both, unless one is unlimited and the other
// limited to this machine: then the limited one wins, and two instruction files
// are joined into a file of suit's own, which the destination links to.
static bool settle(Ctx *x)
{
Plan *p = x->p;
qsort(p->p, p->n, sizeof p->p[0], cmp_placement);
uint32_t out = 0;
for (uint32_t i = 0; i < p->n; i++) {
bool same = out > 0 && strcmp(p->p[out - 1].dest, p->p[i].dest) == 0 &&
strcmp(p->p[out - 1].src, p->p[i].src) == 0;
if (!same) p->p[out++] = p->p[i];
}
p->n = out;
// Now one placement per destination and source: settle each destination.
out = 0;
for (uint32_t i = 0; i < p->n;) {
uint32_t end = i + 1;
uint32_t limited = p->p[i].limited;
while (end < p->n && strcmp(p->p[end].dest, p->p[i].dest) == 0) limited += p->p[end++].limited;
uint32_t count = end - i;
if (count > 1 && (limited > 1 || count - limited > 1)) {
// Name the first two of the kind that clash.
bool clash = limited > 1;
const char *src[2];
uint32_t found = 0;
for (uint32_t k = i; found < 2; k++)
if (p->p[k].limited == clash) src[found++] = p->p[k].src;
return fail(x, "two assets want %s: %s and %s", p->p[i].dest, src[0], src[1]);
}
Placement win = p->p[i];
if (count == 2) {
const Placement *lim = &p->p[i + (p->p[i].limited ? 0 : 1)];
const Placement *unl = &p->p[i + (p->p[i].limited ? 1 : 0)];
win = *lim;
if (lim->kind == AK_INSTRUCTIONS && unl->kind == AK_INSTRUCTIONS) {
// One join for each destination, which is one a harness (User scope) or one
// a harness and project (the path carries a hash of the destination).
ensure(p->njoins < JOIN_MAX); // each join takes two of the PLACE_MAX placements
Join *j = &p->joins[p->njoins++];
// The store is inside SUIT_HOME, so a space in the path was refused earlier.
char name[CONF_NAME_MAX + 32];
if (unl->project == nullptr)
snprintf(name, sizeof name, "%s", unl->harness);
else
snprintf(name, sizeof name, "%s.%016" PRIx64, unl->harness, hash_text(unl->dest));
[[maybe_unused]] int len = snprintf(j->path, sizeof j->path, "%s/joined/%s", x->suit_home, name);
ensure(len > 0 && (size_t)len < sizeof j->path); // SUIT_HOME is shorter than a path
j->first = unl->src;
j->second = lim->src;
win.src = j->path;
}
}
p->p[out++] = win;
i = end;
}
p->n = out;
return true;
}
// Place what the outfits of one wear scope say, into PROJECT or, if null, the User scope.
static bool place_scope(Ctx *x, Outfits *q, const char *key)
{
for (int limited = 0; limited < 2; limited++) {
x->limited = limited == 1;
x->wscope = x->project == nullptr ? "user" : "personal";
x->wkey = key;
x->wmachine = x->limited ? x->machine : "";
x->fate = FATE_PENDING;
collect_outfits(x, q, x->project == nullptr ? "user" : "personal", key, x->limited);
for (uint32_t i = 0; i < q->n; i++)
if (!place_outfit(x, q->list[i])) return false;
}
return true;
}
// The wears that do not apply, as places that would supply the name asked about:
// one for another machine, or a personal one that no project has the key of.
static bool place_inert(Ctx *x, Outfits *q, const Projects *projects)
{
for (uint32_t i = 0; i < x->c->nsections; i++) {
const Section *s = &x->c->sections[i];
bool personal = s->kind == KIND_WEAR && strcmp(s->arg[0], "personal") == 0;
if (s->kind != KIND_WEAR || (!personal && strcmp(s->arg[0], "user") != 0)) continue;
bool other = s->arg[2][0] != '\0' && strcmp(s->arg[2], x->machine) != 0;
uint32_t have = 0; // projects with the key
for (uint32_t k = 0; personal && k < projects->n; k++)
have += projects->e[k].key[0] != '\0' && strcmp(projects->e[k].key, s->arg[1]) == 0;
if (!other && (!personal || have > 0)) continue;
q->n = 0;
const Entry *outfits = find_entry(x->c, s, "outfits");
if (outfits != nullptr) queue_outfits(x, q, outfits->val);
queue_includes(x, q);
x->wscope = s->arg[0];
x->wkey = s->arg[1];
x->wmachine = s->arg[2];
x->limited = false;
x->fate = other ? FATE_OTHER_MACHINE : FATE_NO_PROJECT;
for (uint32_t k = 0; k < (have > 0 ? projects->n : 1); k++) {
const ProjectEntry *pe = &projects->e[k];
if (have > 0 && (pe->key[0] == '\0' || strcmp(pe->key, s->arg[1]) != 0)) continue;
x->project = !personal ? nullptr : have > 0 ? pe->path : NOWHERE;
x->vcs = have > 0 ? pe->kind : KIND_GIT;
for (uint32_t o = 0; o < q->n; o++)
if (!place_outfit(x, q->list[o])) return false;
}
}
return true;
}
// What settle decided, for each place that applies: its destination now has its
// own source, a file of suit's that joins it with another, or another's source.
static void finish(const Ctx *x)
{
Plan *p = x->p;
char joined[JOIN_PATH_MAX];
[[maybe_unused]] int len = snprintf(joined, sizeof joined, "%s/joined/", x->suit_home);
ensure(len > 0 && (size_t)len < sizeof joined); // SUIT_HOME is shorter than a path
for (uint32_t i = 0; i < p->nsuppliers; i++) {
Supplier *su = &p->sup[i];
if (su->fate != FATE_PENDING) continue;
const Placement *win = nullptr;
for (uint32_t k = 0; k < p->n && win == nullptr; k++)
if (strcmp(p->p[k].dest, su->dest) == 0) win = &p->p[k];
ensure(win != nullptr); // settle keeps one placement for every destination
if (strcmp(win->src, su->src) == 0)
su->fate = FATE_PLACED;
else
su->fate = su->kind == AK_INSTRUCTIONS && strncmp(win->src, joined, (size_t)len) == 0 ? FATE_JOINED : FATE_DROPPED;
}
}
static bool resolve_in(Ctx *x, const Projects *projects)
{
Plan *p = x->p;
p->n = 0;
p->njoins = 0;
p->nskips = 0;
p->used = 0;
p->overflow = false;
p->nsuppliers = 0;
static Outfits outfits;
if (!place_scope(x, &outfits, "")) return false;
for (uint32_t i = 0; i < projects->n; i++) {
const ProjectEntry *pe = &projects->e[i];
if (pe->key[0] == '\0') continue;
x->project = pe->path;
x->vcs = pe->kind;
if (!place_scope(x, &outfits, pe->key)) return false;
}
x->project = nullptr;
if (x->why != nullptr && !place_inert(x, &outfits, projects)) return false;
if (!settle(x)) return false;
finish(x);
return true;
}
bool resolve(const Conf *conf, const Assets *assets, const char *home, const char *suit_home,
const char *store, const char *machine, const Projects *projects, Plan *p, ResolveError *err)
{
Ctx x = {.c = conf, .assets = assets, .home = home, .suit_home = suit_home, .store = store,
.machine = machine, .p = p, .e = err};
return resolve_in(&x, projects);
}
bool resolve_why(const Conf *conf, const Assets *assets, const char *home, const char *suit_home,
const char *store, const char *machine, const Projects *projects, const char *name, Plan *p,
ResolveError *err)
{
Ctx x = {.c = conf, .assets = assets, .home = home, .suit_home = suit_home, .store = store,
.machine = machine, .p = p, .e = err, .why = name};
return resolve_in(&x, projects);
}